Open History to see the last commit
1import {
2 GitCommandError,
3 type OrchestrationV2ThreadShell,
4 type ProjectId,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7
8import * as GitWorkflowService from "./GitWorkflowService.ts";
9import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
10import * as ProjectService from "../project/ProjectService.ts";
11
12type CheckoutThread = Pick<
13 OrchestrationV2ThreadShell,
14 "id" | "title" | "projectId" | "worktreePath" | "activityRunStatus"
15>;
16
17/** Threads with an active run whose working directory is one of `checkoutPaths`. */
18export function busyThreadsInCheckout<T extends CheckoutThread>(input: {
19 readonly checkoutPaths: ReadonlyArray<string>;
20 readonly projectIds: ReadonlySet<ProjectId>;
21 readonly threads: ReadonlyArray<T>;
22}): ReadonlyArray<T> {
23 return input.threads.filter(
24 (thread) =>
25 (thread.activityRunStatus ?? null) !== null &&
26 (thread.worktreePath === null
27 ? input.projectIds.has(thread.projectId)
28 : input.checkoutPaths.includes(thread.worktreePath)),
29 );
30}
31
32function describeBusyCheckout(titles: ReadonlyArray<string>): string {
33 const quoted = titles.map((title) => `'${title}'`);
34 const names =
35 quoted.length <= 2
36 ? quoted.join(" and ")
37 : `${quoted.slice(0, 2).join(", ")} and ${quoted.length - 2} more`;
38 return `${names} ${quoted.length === 1 ? "is" : "are"} still working in this checkout. Wait for ${quoted.length === 1 ? "it" : "them"} to finish, or use a worktree for a separate branch.`;
39}
40
41/** Switching a shared checkout's ref moves every thread working in it, mid-turn included. */
42export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutIdle")(function* (
43 operation: string,
44 cwd: string,
45) {
46 const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
47 const projectService = yield* ProjectService.ProjectService;
48 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
49 // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling.
50 const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null));
51 const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])];
52 const projects = yield* projectService.snapshot.pipe(
53 Effect.map((snapshot) => snapshot.projects),
54 Effect.orElseSucceed(() => []),
55 );
56 // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its
57 // own repository nested there.
58 const nested = yield* Effect.forEach(
59 projects.filter(
60 ({ workspaceRoot }) =>
61 root !== null &&
62 !checkoutPaths.includes(workspaceRoot) &&
63 workspaceRoot.startsWith(`${root}/`),
64 ),
65 (project) =>
66 gitWorkflow.repositoryRoot(project.workspaceRoot).pipe(
67 Effect.map((projectRoot) => (projectRoot === root ? [project] : [])),
68 Effect.orElseSucceed(() => []),
69 ),
70 { concurrency: "unbounded" },
71 );
72 const projectIds = new Set(
73 [
74 ...projects.filter(({ workspaceRoot }) => checkoutPaths.includes(workspaceRoot)),
75 ...nested.flat(),
76 ].map(({ id }) => id),
77 );
78 // Archiving does not stop a run, so archived threads can still be working. Each lookup fails
79 // open on its own, so one failure keeps what the others found.
80 const snapshots = yield* Effect.forEach(
81 [
82 ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })),
83 ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })),
84 ],
85 (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))),
86 { concurrency: "unbounded" },
87 );
88 const busy = busyThreadsInCheckout({
89 checkoutPaths,
90 projectIds,
91 threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]),
92 });
93 const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()];
94 if (titles.length === 0) return;
95 return yield* new GitCommandError({
96 operation,
97 command: "git checkout",
98 cwd,
99 detail: describeBusyCheckout(titles),
100 });
101});