Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TaskFolders.ts

1,427 lines59.7 KB

1import {
2 type ProjectId,
3 type ProjectTrackedFolder,
4 TASK_FOLDER_DEFAULT_REPOSITORIES_MAX,
5 type TaskFolder,
6 TaskFolderError,
7 type TaskFolderRepository,
8 type ThreadId,
9 type VcsCreateWorktreeInput,
10 type VcsCreateWorktreeResult,
11 T3_PROJECT_FILE_NAME,
12} from "@t3tools/contracts";
13import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
14import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as KeyedLock from "@t3tools/shared/KeyedLock";
17import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
18import * as Context from "effect/Context";
19import * as Digest from "effect/crypto/Digest";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Hex from "effect/encoding/Hex";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Path from "effect/Path";
27import type * as PlatformError from "effect/PlatformError";
28import * as Schema from "effect/Schema";
29​
30import * as ServerConfig from "../config.ts";
31import * as GitWorkflowService from "../git/GitWorkflowService.ts";
32import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
33import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
36import * as VcsProcess from "../vcs/VcsProcess.ts";
37import {
38 removeEmptyDirectory,
39 type RemoveEmptyDirectoryError,
40} from "../vcs/removeEmptyDirectory.ts";
41import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
42import { isWithinRoot } from "./KnownWorkspaces.ts";
43import * as TaskFolderStore from "./TaskFolderStore.ts";
44import { projectFolders, parseGitmodulesPaths } from "./WorkspaceFolders.ts";
45import { withWorkspaceLease } from "./workspaceLease.ts";
46​
47// Each worktree is a checkout: enough at once to finish four repositories together, few enough
48// to leave Git's server-wide process slots to running threads.
49const REPOSITORY_CONCURRENCY = 4;
50const LAYOUT_COMMAND_TIMEOUT_MS = 600_000;
51const BRANCH_NAME_ATTEMPTS = 50;
52​
53/** What a new task folder will hold, decided before anything is created. */
54export interface TaskFolderPlan {
55 readonly projectId: ProjectId;
56 readonly projectRoot: string;
57 readonly projectIsRepository: boolean;
58 readonly anchor: string;
59 /** The tracked Git folders that get a worktree. */
60 readonly repositories: ReadonlyArray<ProjectTrackedFolder>;
61 /** Every tracked Git folder. None is linked into a plain project folder: a link is the original. */
62 readonly trackedRepositories: ReadonlyArray<string>;
64​
65interface TaskFolderRemoval {
66 readonly removed: ReadonlyArray<string>;
67 readonly kept: ReadonlyArray<{ readonly path: string; readonly reason: string }>;
69​
70/** One checkout of a task folder, as removal sees it. */
71interface TaskFolderCheckout {
72 readonly worktreePath: string;
73 /** The checkout this is a worktree of. */
74 readonly repositoryPath: string;
76​
77export class TaskFolders extends Context.Service<
78 TaskFolders,
79 {
80 /**
81 * Null when the project tracks no Git folder: its worktree is then a single checkout, made as
82 * it always was. Omitted `repositories` selects every tracked Git folder up to
83 * `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, and none beyond that.
84 */
85 readonly plan: (input: {
86 readonly projectId: ProjectId;
87 readonly repositories?: ReadonlyArray<{ readonly path: string }> | undefined;
88 }) => Effect.Effect<TaskFolderPlan | null, TaskFolderError>;
89 /**
90 * Creates the folder and every worktree on one branch name, which is `branch` unless a
91 * selected repository already has it. A failure removes what this call created.
92 */
93 readonly create: (input: {
94 readonly plan: TaskFolderPlan;
95 readonly branch: string;
96 /** Where the project folder's branch starts; unused when it is not a repository. */
97 readonly projectStart: { readonly refName: string; readonly baseRefName: string };
98 /**
99 * The branch the thread starts from. A repository that has it starts there; one that does
100 * not starts from its own default branch.
101 */
102 readonly baseBranch?: string | undefined;
103 readonly startFromOrigin: boolean;
104 readonly projectProgress?: GitVcsDriver.CreateWorktreeProgress;
105 /** As soon as the folder is recorded, so a cancelled caller knows what to remove. */
106 readonly onClaimed?: (taskFolder: TaskFolder, branch: string) => Effect.Effect<void>;
107 readonly onRepository?: (progress: {
108 readonly name: string;
109 readonly done: number;
110 readonly total: number;
111 }) => Effect.Effect<void>;
112 }) => Effect.Effect<
113 {
114 readonly taskFolder: TaskFolder;
115 readonly branch: string;
116 /** The project's own command made the checkouts, from whatever start it chose. */
117 readonly laidOutByProject: boolean;
118 /** A repository's worktree starts from the commit just fetched from its remote. */
119 readonly repositoriesStartedFromOrigin: boolean;
120 },
121 TaskFolderError
122 >;
123 /**
124 * The worktree an existing thread asks for in its project folder: a task folder with the
125 * default repositories when the project there tracks Git folders. Null otherwise, and for a
126 * request that names its path or checks out an existing branch, which stay a single worktree.
127 */
128 readonly createForProjectFolder: (
129 input: VcsCreateWorktreeInput,
130 ) => Effect.Effect<VcsCreateWorktreeResult | null, TaskFolderError>;
131 /**
132 * Gives a tracked Git folder its worktree in a thread's task folder, on the thread's branch.
133 * `startFromOrigin` defaults to the project's setting for new worktrees.
134 */
135 readonly addRepository: (input: {
136 readonly threadId: ThreadId;
137 readonly repositoryPath: string;
138 readonly startFromOrigin?: boolean | undefined;
139 }) => Effect.Effect<TaskFolder, TaskFolderError>;
140 /** The task folder that is, or contains, `target`. */
141 readonly find: (target: string) => Effect.Effect<TaskFolder | null, TaskFolderError>;
142 /**
143 * Removes repository worktrees, then the project folder, then the links and the folder.
144 * `inspect` may keep a checkout, with the reason to report, or allow forcing it; without it
145 * every checkout is removed with `force`. `forget` drops the record, shrinking it to what was
146 * kept; otherwise the record stays so the folder can be restored when its thread resumes.
147 */
148 readonly remove: (input: {
149 readonly root: string;
150 readonly force: boolean;
151 readonly forget: boolean;
152 readonly deleteBranch?: string | undefined;
153 readonly inspect?: (
154 checkout: TaskFolderCheckout,
155 ) => Effect.Effect<{ readonly keep: string | null; readonly force: boolean }>;
156 }) => Effect.Effect<TaskFolderRemoval, TaskFolderError>;
157 /**
158 * Removes the task folder `path` is the root or the project folder of, for good. False when
159 * it is neither, and a failure naming what could not be removed.
160 */
161 readonly removeIfTaskFolder: (input: {
162 readonly path: string;
163 readonly force: boolean;
164 }) => Effect.Effect<boolean, TaskFolderError>;
165 /** Renames the branch in every checkout to one name free in all of them. */
166 readonly renameBranch: (input: {
167 readonly root: string;
168 readonly oldBranch: string;
169 readonly newBranch: string;
170 readonly exactName?: boolean;
171 }) => Effect.Effect<{ readonly branch: string }, TaskFolderError>;
172 /** Puts back whatever is missing; `recreate` checks a branch out again at a path. */
173 readonly restore: <E>(input: {
174 readonly taskFolder: TaskFolder;
175 /** The thread's branch, for a project that lays its folder out with its own command. */
176 readonly branch: string;
177 readonly recreate: (checkout: TaskFolderCheckout) => Effect.Effect<void, E>;
178 }) => Effect.Effect<void, TaskFolderError | E>;
179 }
180>()("t3/workspace/TaskFolders") {}
181​
182const isTaskFolderError = Schema.is(TaskFolderError);
183​
184const failureDetail = (cause: unknown) =>
185 typeof cause === "object" &&
186 cause !== null &&
187 "detail" in cause &&
188 typeof cause.detail === "string"
189 ? cause.detail
190 : cause instanceof Error
191 ? cause.message
192 : String(cause);
193​
194/** The deepest folder that holds every one of `folders`, or null when they share none. */
195export const commonAncestor = (path: Path.Path, folders: ReadonlyArray<string>) => {
196 let ancestor = folders[0]!;
197 for (const folder of folders.slice(1)) {
198 while (!isWithinRoot(path, folder, ancestor)) {
199 const parent = path.dirname(ancestor);
200 // Two Windows drives meet nowhere, and a drive root is its own parent.
201 if (parent === ancestor) return null;
202 ancestor = parent;
203 }
204 }
205 return ancestor;
206};
207​
208/**
209 * The folder a task folder mirrors: the deepest one holding the project and every tracked
210 * repository that shares a root with it. The rest are `unreachable` and cannot be laid out.
211 */
212export const layoutAnchor = (
213 path: Path.Path,
214 projectRoot: string,
215 repositories: ReadonlyArray<string>,
216) => {
217 let anchor = projectRoot;
218 const unreachable: string[] = [];
219 for (const repository of repositories) {
220 const shared = commonAncestor(path, [anchor, repository]);
221 if (shared === null) unreachable.push(repository);
222 else anchor = shared;
223 }
224 return { anchor, unreachable };
225};
226​
227const make = Effect.gen(function* () {
228 const fileSystem = yield* FileSystem.FileSystem;
229 const path = yield* Path.Path;
230 const digest = yield* Digest.Digest;
231 const config = yield* ServerConfig.ServerConfig;
232 const settings = yield* ServerSettings.ServerSettingsService;
233 const projects = yield* ProjectStore.ProjectStoreV2;
234 const git = yield* GitWorkflowService.GitWorkflowService;
235 const gitDriver = yield* GitVcsDriver.GitVcsDriver;
236 const store = yield* TaskFolderStore.TaskFolderStore;
237 const processes = yield* VcsProcess.VcsProcess;
238 const hostEnvironment = yield* HostProcess.Environment;
239 const hostPlatform = yield* HostProcess.Platform;
240 const onWindows = yield* HostProcess.isWindows;
241 const projections = yield* ProjectionStore.ProjectionStoreV2;
242​
243 const exists = (target: string) =>
244 fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
245 const isRepository = (folder: string) => exists(path.join(folder, ".git"));
246 const occupied = Effect.fnUntraced(function* (target: string) {
247 if (!(yield* exists(target))) return false;
248 const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe(
249 Option.exists((info) => info.type === "Directory"),
250 );
251 if (!isDirectory) return true;
252 return (
253 (yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0
254 );
255 });
256 const trackedFolders = (project: {
257 readonly workspaceRoot: string;
258 readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
259 }) =>
260 projectFolders(project).pipe(
261 Effect.provideService(FileSystem.FileSystem, fileSystem),
262 Effect.provideService(Path.Path, path),
263 );
264 // The repository that pins a submodule owns its checkout: Git, a hook or a setup script puts it
265 // in that repository's worktree, so it never gets one of its own here.
266 const isSubmodule = Effect.fnUntraced(function* (folder: string) {
267 for (
268 let owner = path.dirname(folder);
269 owner !== path.dirname(owner);
270 owner = path.dirname(owner)
271 ) {
272 if (!(yield* isRepository(owner))) continue;
273 const declared = yield* fileSystem
274 .readFileString(path.join(owner, ".gitmodules"))
275 .pipe(Effect.orElseSucceed(() => ""));
276 return parseGitmodulesPaths(declared).includes(
277 path.relative(owner, folder).split(path.sep).join("/"),
278 );
279 }
280 return false;
281 });
282 const fail =
283 (operation: TaskFolderError["operation"], prefix: string) =>
284 (cause: unknown): TaskFolderError =>
285 new TaskFolderError({ operation, detail: `${prefix}: ${failureDetail(cause)}`, cause });
286​
287 // A project that lays its own thread folder out says so in its `t3.json`.
288 const worktreeLayout = (projectRoot: string) =>
289 fileSystem.readFileString(path.join(projectRoot, T3_PROJECT_FILE_NAME)).pipe(
290 Effect.map((contents) => parseT3ProjectFile(contents)?.worktreeLayout ?? null),
291 Effect.orElseSucceed(() => null),
292 );
293 // One at a time per project: the commands share the project folder, and its workspace files.
294 const layoutLocks = yield* KeyedLock.make<string>();
295 const runLayoutCommand = (
296 operation: TaskFolderError["operation"],
297 command: string,
298 taskFolder: Pick<TaskFolder, "root" | "projectRoot" | "projectPath">,
299 branch: string,
300 baseBranch: string | undefined,
301 repositories: ReadonlyArray<string>,
302 ) =>
303 layoutLocks.withLock(
304 taskFolder.projectRoot,
305 processes
306 .run({
307 operation: "TaskFolders.worktreeLayout",
308 command: onWindows ? "cmd.exe" : "sh",
309 args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command],
310 cwd: taskFolder.projectRoot,
311 env: {
312 ...hostEnvironment,
313 // A `GIT_DIR` the server inherited would point the command's Git at another repository.
314 ...VcsProcess.unsetInheritedRepositoryEnv(hostEnvironment, hostPlatform),
315 T3_PROJECT_ROOT: taskFolder.projectRoot,
316 T3_WORKTREE_ROOT: taskFolder.root,
317 T3_WORKTREE_PROJECT_PATH: taskFolder.projectPath,
318 T3_WORKTREE_BRANCH: branch,
319 T3_WORKTREE_BASE: baseBranch ?? "",
320 T3_WORKTREE_REPOSITORIES: repositories.join("\n"),
321 },
322 timeoutMs: LAYOUT_COMMAND_TIMEOUT_MS,
323 })
324 .pipe(Effect.mapError(fail(operation, "The project's worktree layout command failed"))),
325 );
326​
327 /** Where a folder's `.git` file points, or null when `.git` is a directory or absent. */
328 const gitDirPointer = Effect.fnUntraced(function* (folder: string) {
329 const pointer = yield* fileSystem
330 .readFileString(path.join(folder, ".git"))
331 .pipe(Effect.orElseSucceed(() => ""));
332 const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
333 return gitDir === undefined ? null : path.resolve(folder, gitDir);
334 });
335 // A repository that is itself a linked worktree registers worktrees under the Git dir it shares.
336 const commonGitDir = Effect.fnUntraced(function* (repositoryPath: string) {
337 const gitDir = yield* gitDirPointer(repositoryPath);
338 if (gitDir === null) return path.join(repositoryPath, ".git");
339 const common = (yield* fileSystem
340 .readFileString(path.join(gitDir, "commondir"))
341 .pipe(Effect.orElseSucceed(() => ""))).trim();
342 return common === "" ? gitDir : path.resolve(gitDir, common);
343 });
344​
345 // What a layout command leaves must be a checkout this service can later remove, restore and
346 // rename: a worktree linked to the repository, on the thread's branch. Null when it is.
347 /** The checkout's own Git directory when it is a worktree linked to its repository. */
348 const linkedGitDir = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
349 const real = (target: string) =>
350 fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
351 const resolved = yield* gitDirPointer(checkout.worktreePath);
352 if (
353 resolved === null ||
354 !isWithinRoot(
355 path,
356 yield* real(resolved),
357 path.join(yield* real(yield* commonGitDir(checkout.repositoryPath)), "worktrees"),
358 )
359 )
360 return null;
361 // Git registers one path per worktree: a copy of the checkout elsewhere points here too.
362 const registered = (yield* fileSystem
363 .readFileString(path.join(resolved, "gitdir"))
364 .pipe(Effect.orElseSucceed(() => ""))).trim();
365 return registered !== "" &&
366 (yield* real(path.dirname(registered))) === (yield* real(checkout.worktreePath))
367 ? resolved
368 : null;
369 });
370 const unadoptable = Effect.fnUntraced(function* (checkout: TaskFolderCheckout, branch: string) {
371 const resolved = yield* linkedGitDir(checkout);
372 if (resolved === null)
373 return `${checkout.worktreePath} is not a Git worktree of ${checkout.repositoryPath}`;
374 const head = (yield* fileSystem
375 .readFileString(path.join(resolved, "HEAD"))
376 .pipe(Effect.orElseSucceed(() => ""))).trim();
377 return head === `ref: refs/heads/${branch}`
378 ? null
379 : `${checkout.worktreePath} is not on the branch ${branch}`;
380 });
381​
382 const mapped = (taskFolder: Pick<TaskFolder, "root" | "anchor">, source: string) =>
383 path.join(taskFolder.root, path.relative(taskFolder.anchor, source));
384 const depth = (target: string) => path.resolve(target).split(path.sep).length;
385​
386 const readProject = Effect.fn("TaskFolders.readProject")(function* (
387 operation: TaskFolderError["operation"],
388 projectId: ProjectId,
389 ) {
390 const row = yield* projects
391 .get(projectId)
392 .pipe(Effect.mapError(fail(operation, "Could not read the project")));
393 if (Option.isNone(row)) {
394 return yield* new TaskFolderError({
395 operation,
396 detail: `Project ${projectId} was not found.`,
397 });
398 }
399 return row.value;
400 });
401​
402 const plan: TaskFolders["Service"]["plan"] = Effect.fn("TaskFolders.plan")(function* (input) {
403 const project = yield* readProject("plan", input.projectId);
404 const projectRoot = path.resolve(project.workspaceRoot);
405 const classified = yield* Effect.forEach(
406 yield* trackedFolders(project),
407 (folder) => {
408 const folderPath = path.resolve(folder.path);
409 return Effect.all([isRepository(folderPath), isSubmodule(folderPath)]).pipe(
410 Effect.map(([git, submodule]) => ({
411 name: folder.name,
412 path: folderPath,
413 git,
414 submodule,
415 })),
416 );
417 },
418 { concurrency: 8 },
419 );
420 const tracked = classified.filter(
421 (folder) => folder.git && !folder.submodule && folder.path !== projectRoot,
422 );
423 // A project that lays its own thread folder out gets one even with nothing else to check out.
424 // An explicit choice still goes through the checks below, so it is refused, not dropped.
425 if (
426 tracked.length === 0 &&
427 (input.repositories ?? []).length === 0 &&
428 (yield* worktreeLayout(projectRoot)) === null
429 )
430 return null;
431 // A repository on another Windows drive has no place in the folder; only choosing it fails.
432 const { anchor, unreachable } = layoutAnchor(
433 path,
434 projectRoot,
435 tracked.map((folder) => folder.path),
436 );
437 const reachable = tracked.filter((folder) => !unreachable.includes(folder.path));
438 let repositories: ReadonlyArray<ProjectTrackedFolder>;
439 if (input.repositories === undefined) {
440 repositories = reachable.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX ? reachable : [];
441 } else {
442 const selected = new Map<string, ProjectTrackedFolder>();
443 for (const requested of input.repositories) {
444 const requestedPath = path.resolve(requested.path);
445 const folder = classified.find((candidate) => candidate.path === requestedPath);
446 // A submodule comes with its repository's worktree; clients cannot tell one apart.
447 if (folder?.submodule === true) continue;
448 if (folder === undefined || !folder.git || folder.path === projectRoot) {
449 return yield* new TaskFolderError({
450 operation: "plan",
451 detail:
452 folder === undefined
453 ? `"${requested.path}" is not a tracked folder of project "${project.title}".`
454 : `"${requested.path}" is not a Git repository, so it cannot get a worktree.`,
455 });
456 }
457 if (unreachable.includes(folder.path)) {
458 return yield* new TaskFolderError({
459 operation: "plan",
460 detail: `"${folder.path}" shares no common root with the project folder ${projectRoot}, so the two cannot be laid out in one worktree folder.`,
461 });
462 }
463 selected.set(folder.path, folder);
464 }
465 repositories = [...selected.values()];
466 }
467 // A repository with no commit yet has nothing to branch from, so it is left out.
468 repositories = yield* Effect.filter(
469 repositories,
470 (folder) =>
471 git.hasCommit({ cwd: folder.path, refName: "HEAD" }).pipe(Effect.orElseSucceed(() => true)),
472 { concurrency: REPOSITORY_CONCURRENCY },
473 );
474 return {
475 projectId: project.projectId,
476 projectRoot,
477 projectIsRepository: yield* isRepository(projectRoot),
478 anchor,
479 repositories: repositories.map(({ name, path: folderPath }) => ({ name, path: folderPath })),
480 trackedRepositories: reachable.map((folder) => folder.path),
481 };
482 });
483​
484 const branchNames = (cwds: ReadonlyArray<string>) =>
485 Effect.forEach(cwds, (cwd) => git.listLocalBranchNames(cwd), {
486 concurrency: REPOSITORY_CONCURRENCY,
487 });
488 // Git stores branches as files, so a name also collides with one it nests under or contains.
489 const collides = (existing: string, candidate: string) =>
490 existing === candidate ||
491 existing.startsWith(`${candidate}/`) ||
492 candidate.startsWith(`${existing}/`);
493​
494 const freeBranchName = (
495 operation: TaskFolderError["operation"],
496 branch: string,
497 names: ReadonlyArray<ReadonlyArray<string>>,
498 ) => {
499 for (let attempt = 1; attempt <= BRANCH_NAME_ATTEMPTS; attempt++) {
500 const candidate = attempt === 1 ? branch : `${branch}-${attempt}`;
501 if (!names.some((list) => list.some((existing) => collides(existing, candidate))))
502 return Effect.succeed(candidate);
503 }
504 return Effect.fail(
505 new TaskFolderError({
506 operation,
507 detail: `No branch name based on "${branch}" is free in every repository.`,
508 }),
509 );
510 };
511​
512 /**
513 * Where a repository's branch starts: `baseBranch` when the repository has it, else its
514 * default branch. The remote commit of either when starting from origin.
515 */
516 const repositoryStart = Effect.fn("TaskFolders.repositoryStart")(function* (
517 cwd: string,
518 startFromOrigin: boolean,
519 baseBranch?: string,
520 ) {
521 // Clients send `HEAD` when no base was chosen; as a name it would match `origin/HEAD`.
522 const wanted = baseBranch?.replace(/^refs\/heads\//, "").replace(/^origin\//, "");
523 const defaultBranch =
524 wanted !== undefined &&
525 wanted !== "" &&
526 wanted !== "HEAD" &&
527 ((yield* git.hasCommit({ cwd, refName: `refs/heads/${wanted}` })) ||
528 (yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${wanted}` })))
529 ? wanted
530 : ((yield* gitDriver.resolveDefaultBranchName(cwd, "origin")) ??
531 (yield* git.currentBranch(cwd)));
532 let baseRef = "HEAD";
533 if (defaultBranch !== null) {
534 if (yield* git.hasCommit({ cwd, refName: `refs/heads/${defaultBranch}` }))
535 baseRef = defaultBranch;
536 else if (yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${defaultBranch}` }))
537 baseRef = `origin/${defaultBranch}`;
538 }
539 const remoteBase =
540 startFromOrigin && baseRef !== "HEAD"
541 ? yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef })
542 : null;
543 return remoteBase === null
544 ? { refName: baseRef, baseRefName: baseRef }
545 : { refName: remoteBase.commitSha, baseRefName: `refs/remotes/${remoteBase.remoteRefName}` };
546 });
547​
548 /**
549 * Stands in for a folder that is not a repository: every entry links to the original, so
550 * nothing is copied, except the folders that lead to a tracked repository, which are real so a
551 * worktree can sit in them.
552 */
553 const linkFolder: (
554 source: string,
555 target: string,
556 trackedRepositories: ReadonlyArray<string>,
557 skip?: string,
558 ) => Effect.Effect<void, PlatformError.PlatformError> = Effect.fnUntraced(
559 function* (source, target, trackedRepositories, skip) {
560 yield* fileSystem.makeDirectory(target, { recursive: true });
561 for (const name of yield* fileSystem.readDirectory(source)) {
562 const entry = path.join(source, name);
563 const link = path.join(target, name);
564 if (name === ".git" || name === skip || trackedRepositories.includes(entry)) continue;
565 if (yield* exists(link)) continue;
566 if (trackedRepositories.some((repository) => isWithinRoot(path, repository, entry))) {
567 yield* linkFolder(entry, link, trackedRepositories);
568 } else {
569 yield* fileSystem.symlink(entry, link);
570 }
571 }
572 },
573 );
574​
575 /**
576 * Makes room for a worktree at `relative` inside a linked folder: a link on the way becomes a
577 * real folder linking its other entries. Anything there that this service did not link stays.
578 */
579 const openLinkedPath = Effect.fnUntraced(function* (
580 source: string,
581 target: string,
582 relative: string,
583 ) {
584 const segments = relative.split(path.sep);
585 for (const [index, segment] of segments.entries()) {
586 source = path.join(source, segment);
587 target = path.join(target, segment);
588 const last = index === segments.length - 1;
589 const link = yield* fileSystem.readLink(target).pipe(Effect.option);
590 if (Option.isSome(link)) {
591 if (path.resolve(path.dirname(target), link.value) !== source) return false;
592 yield* fileSystem.remove(target);
593 if (!last) yield* linkFolder(source, target, [], segments[index + 1]);
594 } else if (!last) {
595 yield* fileSystem.makeDirectory(target, { recursive: true });
596 }
597 }
598 return true;
599 });
600​
601 /** Unlinks links and removes the folders that leaves empty; files and checkouts stay. */
602 const removeLinks: (
603 target: string,
604 ) => Effect.Effect<boolean, PlatformError.PlatformError | RemoveEmptyDirectoryError> =
605 Effect.fnUntraced(function* (target) {
606 if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
607 yield* fileSystem.remove(target);
608 return true;
609 }
610 if (!(yield* exists(target))) return true;
611 if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
612 if (yield* isRepository(target)) return false;
613 let empty = true;
614 for (const name of yield* fileSystem.readDirectory(target)) {
615 if (!(yield* removeLinks(path.join(target, name)))) empty = false;
616 }
617 return empty && (yield* removeEmptyDirectory(target));
618 });
619​
620 /** Whether `removeLinks` would leave nothing: only links and folders of links are inside. */
621 const holdsOnlyLinks: (target: string) => Effect.Effect<boolean, PlatformError.PlatformError> =
622 Effect.fnUntraced(function* (target) {
623 if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) return true;
624 if (!(yield* exists(target))) return true;
625 if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
626 if (yield* isRepository(target)) return false;
627 for (const name of yield* fileSystem.readDirectory(target)) {
628 if (!(yield* holdsOnlyLinks(path.join(target, name)))) return false;
629 }
630 return true;
631 });
632​
633 const allocateRoot = Effect.fn("TaskFolders.allocateRoot")(function* (
634 taskPlan: TaskFolderPlan,
635 branch: string,
636 ) {
637 const parent = resolveWorktreesDirectory(
638 (yield* settings.getSettings.pipe(Effect.orElseSucceed(() => ({ worktreesDirectory: "" }))))
639 .worktreesDirectory,
640 config.worktreesDir,
641 path,
642 yield* HostProcess.HomeDirectory,
643 );
644 if (parent === null) {
645 return yield* new TaskFolderError({
646 operation: "create",
647 detail:
648 "The worktree location must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.",
649 });
650 }
651 const hash = yield* digest.digest(
652 Digest.sha256,
653 new TextEncoder().encode(`${taskPlan.projectId}\0${taskPlan.anchor}\0${branch}`),
654 );
655 // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows.
656 let prefix = "";
657 for (const character of branch.replace(/\//g, "-")) {
658 if (Buffer.byteLength(prefix + character) > 23) break;
659 prefix += character;
660 }
661 const base = path.join(
662 parent,
663 path.basename(taskPlan.anchor) || "workspace",
664 `${prefix}-${Hex.encode(hash).slice(0, 16)}`,
665 );
666 const allocateFailed = fail("create", "Could not create the worktree folder");
667 yield* fileSystem
668 .makeDirectory(path.dirname(base), { recursive: true })
669 .pipe(Effect.mapError(allocateFailed));
670 // Made here, not just found free: two creations on one branch must not share a folder.
671 for (let suffix = 1; ; suffix++) {
672 const root = suffix === 1 ? base : `${base}-${suffix}`;
673 const claimed = yield* fileSystem.makeDirectory(root).pipe(
674 Effect.as(true),
675 Effect.catchIf(
676 (cause) => cause.reason._tag === "AlreadyExists",
677 () => Effect.succeed(false),
678 ),
679 Effect.mapError(allocateFailed),
680 );
681 if (claimed) return root;
682 }
683 });
684​
685 const removeCheckout = Effect.fnUntraced(function* (
686 checkout: TaskFolderCheckout,
687 force: boolean,
688 deleteBranch: string | undefined,
689 ) {
690 yield* git.removeWorktree({
691 cwd: checkout.repositoryPath,
692 path: checkout.worktreePath,
693 force,
694 });
695 if (deleteBranch !== undefined) {
696 yield* git
697 .deleteLocalBranch({ cwd: checkout.repositoryPath, refName: deleteBranch, force: true })
698 .pipe(Effect.ignoreCause({ log: true }));
699 }
700 });
701​
702 const removeLocked = Effect.fn("TaskFolders.remove")(function* (
703 taskFolder: TaskFolder,
704 input: Omit<Parameters<TaskFolders["Service"]["remove"]>[0], "root">,
705 /** Repositories whose `deleteBranch` is not this folder's to delete. */
706 keepBranchIn: ReadonlySet<string> = new Set(),
707 /** False when the folder never got as far as its layout command: nothing to tear down. */
708 laidOut = true,
709 ) {
710 const removed: string[] = [];
711 const kept: Array<{ path: string; reason: string }> = [];
712 let remaining = taskFolder.repositories;
713 const verdicts = new Map<string, { readonly keep: string | null; readonly force: boolean }>();
714 const verdict = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
715 const known = verdicts.get(checkout.worktreePath);
716 if (known !== undefined) return known;
717 const decided =
718 input.inspect === undefined
719 ? { keep: null, force: input.force }
720 : yield* input.inspect(checkout);
721 verdicts.set(checkout.worktreePath, decided);
722 return decided;
723 });
724 // The project's own teardown goes first; what it leaves is removed below as usual. Only when
725 // every checkout may go: the command cannot be told which ones to keep.
726 const layout = laidOut ? yield* worktreeLayout(taskFolder.projectRoot) : null;
727 if (layout?.remove !== undefined) {
728 const checkouts = [
729 ...taskFolder.repositories,
730 ...(taskFolder.projectIsWorktree
731 ? [{ worktreePath: taskFolder.projectPath, repositoryPath: taskFolder.projectRoot }]
732 : []),
733 ];
734 let allGo = true;
735 for (const checkout of checkouts) {
736 if (!(yield* exists(checkout.worktreePath))) continue;
737 if ((yield* verdict(checkout)).keep === null) continue;
738 allGo = false;
739 break;
740 }
741 if (allGo) {
742 yield* runLayoutCommand(
743 "remove",
744 layout.remove,
745 taskFolder,
746 input.deleteBranch ?? "",
747 undefined,
748 taskFolder.repositories.map((repository) => repository.repositoryPath),
749 ).pipe(Effect.ignoreCause({ log: true }));
750 // The command took its time: what it left is looked at again before it is removed.
751 verdicts.clear();
752 }
753 }
754 const removeOne = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
755 if (!(yield* exists(checkout.worktreePath))) {
756 yield* git
757 .pruneWorktrees({ cwd: checkout.repositoryPath })
758 .pipe(Effect.ignoreCause({ log: true }));
759 return true;
760 }
761 const { keep, force } = yield* verdict(checkout);
762 if (keep !== null) {
763 kept.push({ path: checkout.worktreePath, reason: keep });
764 return false;
765 }
766 return yield* removeCheckout(
767 checkout,
768 force,
769 keepBranchIn.has(checkout.repositoryPath) ? undefined : input.deleteBranch,
770 ).pipe(
771 Effect.as(true),
772 Effect.tap(() => Effect.sync(() => removed.push(checkout.worktreePath))),
773 Effect.catch((cause) =>
774 Effect.sync(() => {
775 kept.push({ path: checkout.worktreePath, reason: failureDetail(cause) });
776 return false;
777 }),
778 ),
779 );
780 });
781 // Children first: a worktree nested in another must go before the one that holds it.
782 for (const repository of taskFolder.repositories.toSorted(
783 (left, right) => depth(right.worktreePath) - depth(left.worktreePath),
784 )) {
785 const holdsKept = kept.some((entry) =>
786 isWithinRoot(path, entry.path, repository.worktreePath),
787 );
788 if (holdsKept) {
789 kept.push({ path: repository.worktreePath, reason: "holds a repository that was kept" });
790 continue;
791 }
792 if (!(yield* removeOne(repository))) continue;
793 remaining = remaining.filter((entry) => entry.worktreePath !== repository.worktreePath);
794 // After each one, so a crash leaves a record that matches the disk.
795 if (input.forget) yield* store.put({ ...taskFolder, repositories: remaining });
796 }
797 const projectPath = taskFolder.projectPath;
798 const projectHoldsKept = kept.some((entry) => isWithinRoot(path, entry.path, projectPath));
799 let projectGone = false;
800 if (taskFolder.projectIsWorktree) {
801 if (projectHoldsKept) {
802 if (yield* exists(projectPath))
803 kept.push({ path: projectPath, reason: "holds a repository that was kept" });
804 } else {
805 projectGone = yield* removeOne({
806 worktreePath: projectPath,
807 repositoryPath: taskFolder.projectRoot,
808 });
809 }
810 } else if (!projectHoldsKept) {
811 // A folder that stays keeps its links: restoring relinks only a folder that is gone.
812 projectGone = yield* holdsOnlyLinks(projectPath).pipe(
813 Effect.flatMap((onlyLinks) =>
814 onlyLinks ? removeLinks(projectPath) : Effect.succeed(false),
815 ),
816 Effect.orElseSucceed(() => false),
817 );
818 if (!projectGone && input.force && input.inspect === undefined) {
819 // Forced: what is left are files the thread wrote beside the links.
820 projectGone = yield* fileSystem.remove(projectPath, { recursive: true, force: true }).pipe(
821 Effect.as(true),
822 Effect.orElseSucceed(() => false),
823 );
824 }
825 if (projectGone) removed.push(projectPath);
826 else kept.push({ path: projectPath, reason: "has files that exist only in this folder" });
827 }
828 if (kept.length === 0) {
829 let rootGone = yield* removeLinks(taskFolder.root).pipe(Effect.orElseSucceed(() => false));
830 if (!rootGone && input.force && input.inspect === undefined) {
831 rootGone = yield* fileSystem.remove(taskFolder.root, { recursive: true, force: true }).pipe(
832 Effect.as(true),
833 Effect.orElseSucceed(() => false),
834 );
835 }
836 if (!rootGone) {
837 kept.push({ path: taskFolder.root, reason: "has files that exist only in this folder" });
838 } else if (input.forget) yield* store.remove(taskFolder.root);
839 }
840 return { removed, kept } satisfies TaskFolderRemoval;
841 });
842​
843 const requireTaskFolder = Effect.fnUntraced(function* (
844 operation: TaskFolderError["operation"],
845 target: string,
846 ) {
847 const taskFolder = yield* store.findContaining(target);
848 if (taskFolder === null) {
849 return yield* new TaskFolderError({
850 operation,
851 detail: `"${target}" is not inside a task folder.`,
852 });
853 }
854 return taskFolder;
855 });
856 // The same lease storage cleanup and file rewind take: the thread's worktree path.
857 const locked = <A, E>(taskFolder: Pick<TaskFolder, "projectPath">, effect: Effect.Effect<A, E>) =>
858 withWorkspaceLease(path.resolve(taskFolder.projectPath), effect);
859​
860 const createRepositoryWorktree = Effect.fnUntraced(function* (
861 taskFolder: TaskFolder,
862 repository: ProjectTrackedFolder,
863 branch: string,
864 startFromOrigin: boolean,
865 baseBranch: string | undefined,
866 ) {
867 const worktreePath = mapped(taskFolder, repository.path);
868 // The project's own checkout (a post-checkout hook, say) already provided this repository.
869 // A link counts even to an empty folder: Git would write the worktree through it.
870 if (
871 Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option)) ||
872 (yield* occupied(worktreePath))
873 )
874 return null;
875 yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true });
876 const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch);
877 yield* git.createWorktree({
878 cwd: repository.path,
879 refName: start.refName,
880 newRefName: branch,
881 baseRefName: start.baseRefName,
882 path: worktreePath,
883 });
884 return {
885 repository: {
886 repositoryPath: repository.path,
887 worktreePath,
888 name: repository.name,
889 } satisfies TaskFolderRepository,
890 fromOrigin: start.refName !== start.baseRefName,
891 };
892 });
893​
894 const create: TaskFolders["Service"]["create"] = Effect.fn("TaskFolders.create")(
895 function* (input) {
896 const taskPlan = input.plan;
897 const listFailed = fail("create", "Could not list branches");
898 const names = yield* branchNames(
899 taskPlan.repositories.map((repository) => repository.path),
900 ).pipe(Effect.mapError(listFailed));
901 const projectNames = taskPlan.projectIsRepository
902 ? yield* git.listLocalBranchNames(taskPlan.projectRoot).pipe(Effect.mapError(listFailed))
903 : [];
904 // A temporary name nests under its prefix, which a repository may hold as a branch.
905 const requested =
906 isTemporaryWorktreeBranch(input.branch) &&
907 [...names, projectNames].some((list) =>
908 list.some((existing) => input.branch.startsWith(`${existing}/`)),
909 )
910 ? flattenTemporaryWorktreeBranchName(input.branch)
911 : input.branch;
912 // A name the project folder already has is Git's to refuse, as for a single worktree.
913 const branch = projectNames.some((existing) => collides(existing, requested))
914 ? requested
915 : yield* freeBranchName("create", requested, [...names, projectNames]);
916 const root = yield* allocateRoot(taskPlan, branch);
917 const empty: TaskFolder = {
918 root,
919 projectId: taskPlan.projectId,
920 projectRoot: taskPlan.projectRoot,
921 anchor: taskPlan.anchor,
922 projectPath: path.join(root, path.relative(taskPlan.anchor, taskPlan.projectRoot)),
923 projectIsWorktree: taskPlan.projectIsRepository,
924 repositories: [],
925 };
926 const created: TaskFolderRepository[] = [];
927 let repositoriesStartedFromOrigin = false;
928 const current = (): TaskFolder => ({ ...empty, repositories: [...created] });
929 const checkedOutFrom = [
930 ...(taskPlan.projectIsRepository ? [taskPlan.projectRoot] : []),
931 ...taskPlan.trackedRepositories,
932 ];
933 // A layout command may check out a branch that was already there; a rollback leaves it.
934 const hadBranch = new Set<string>();
935 let layoutStarted = false;
936 // Where this attempt makes the branch: a checkout that fails halfway leaves it behind.
937 let branchMadeIn = [
938 ...taskPlan.repositories
939 .filter((_, index) => !names[index]!.includes(branch))
940 .map((repository) => repository.path),
941 ...(taskPlan.projectIsRepository && !projectNames.includes(branch)
942 ? [taskPlan.projectRoot]
943 : []),
944 ];
945 return yield* Effect.gen(function* () {
946 yield* fileSystem.makeDirectory(root, { recursive: true });
947 // Recorded before any checkout, so an interrupted creation is still found and removed.
948 yield* store.put(empty);
949 if (input.onClaimed !== undefined) yield* input.onClaimed(empty, branch);
950 const layout = yield* worktreeLayout(taskPlan.projectRoot);
951 if (layout !== null) {
952 const before = yield* branchNames(checkedOutFrom).pipe(Effect.mapError(listFailed));
953 for (const [index, repositoryPath] of checkedOutFrom.entries()) {
954 if (before[index]!.includes(branch)) hadBranch.add(repositoryPath);
955 }
956 branchMadeIn = checkedOutFrom.filter((repositoryPath) => !hadBranch.has(repositoryPath));
957 layoutStarted = true;
958 const ran = yield* Effect.exit(
959 runLayoutCommand(
960 "create",
961 layout.create,
962 empty,
963 branch,
964 input.baseBranch,
965 taskPlan.repositories.map((repository) => repository.path),
966 ),
967 );
968 // Whatever the command checked out where a repository belongs is the thread's. Adopted
969 // even when the command failed, so the rollback removes it instead of leaking it.
970 const refused: string[] = [];
971 for (const repositoryPath of taskPlan.trackedRepositories) {
972 const checkout = { repositoryPath, worktreePath: mapped(empty, repositoryPath) };
973 if (!(yield* isRepository(checkout.worktreePath))) continue;
974 const reason = yield* unadoptable(checkout, branch);
975 if (reason === null) created.push({ ...checkout, name: path.basename(repositoryPath) });
976 else refused.push(reason);
977 }
978 if (Exit.isFailure(ran)) return yield* Effect.failCause(ran.cause);
979 if (!(yield* exists(empty.projectPath))) {
980 return yield* new TaskFolderError({
981 operation: "create",
982 detail: `The project's worktree layout command left no folder at ${empty.projectPath}.`,
983 });
984 }
985 if (taskPlan.projectIsRepository && (yield* isRepository(empty.projectPath))) {
986 const reason = yield* unadoptable(
987 { repositoryPath: taskPlan.projectRoot, worktreePath: empty.projectPath },
988 branch,
989 );
990 if (reason !== null) refused.push(reason);
991 }
992 if (refused.length > 0) {
993 return yield* new TaskFolderError({
994 operation: "create",
995 detail: `The project's worktree layout command must make each checkout with git worktree add on the thread's branch: ${refused.join("; ")}.`,
996 });
997 }
998 const taskFolder: TaskFolder = {
999 ...current(),
1000 projectIsWorktree:
1001 taskPlan.projectIsRepository && (yield* isRepository(empty.projectPath)),
1002 };
1003 yield* store.put(taskFolder);
1004 return {
1005 taskFolder,
1006 branch,
1007 laidOutByProject: true,
1008 repositoriesStartedFromOrigin: false,
1009 };
1011 if (taskPlan.projectIsRepository) {
1012 yield* fileSystem.makeDirectory(path.dirname(empty.projectPath), { recursive: true });
1013 yield* git.createWorktree(
1015 cwd: taskPlan.projectRoot,
1016 refName: input.projectStart.refName,
1017 newRefName: branch,
1018 baseRefName: input.projectStart.baseRefName,
1019 path: empty.projectPath,
1020 },
1021 input.projectProgress === undefined ? {} : { progress: input.projectProgress },
1022 );
1023 } else {
1024 yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories);
1026 let finished = 0;
1027 // Whatever the project put at a skipped path also stands for the repositories inside it.
1028 const skipped: string[] = [];
1029 // A repository inside another waits for the one that holds it.
1030 const levels = Map.groupBy(
1031 taskPlan.repositories,
1032 (repository) =>
1033 taskPlan.repositories.filter(
1034 (other) =>
1035 other.path !== repository.path && isWithinRoot(path, repository.path, other.path),
1036 ).length,
1037 );
1038 for (const level of [...levels.keys()].toSorted((left, right) => left - right)) {
1039 // Every checkout runs to its end: one stopped halfway is registered in its repository
1040 // without being known here, so nothing would remove it.
1041 const exits = yield* Effect.forEach(
1042 levels.get(level)!,
1043 (repository) =>
1044 (skipped.some((outer) => isWithinRoot(path, repository.path, outer))
1045 ? Effect.succeed(null)
1046 : createRepositoryWorktree(
1047 empty,
1048 repository,
1049 branch,
1050 input.startFromOrigin,
1051 input.baseBranch,
1053 ).pipe(
1054 Effect.tap((worktree) =>
1055 Effect.suspend(() => {
1056 finished += 1;
1057 if (worktree === null) skipped.push(repository.path);
1058 else {
1059 created.push(worktree.repository);
1060 repositoriesStartedFromOrigin ||= worktree.fromOrigin;
1062 return (
1063 input.onRepository?.({
1064 name: repository.name,
1065 done: finished,
1066 total: taskPlan.repositories.length,
1067 }) ?? Effect.void
1068 );
1069 }),
1070 ),
1071 Effect.mapError(fail("create", `Could not create the ${repository.name} worktree`)),
1072 Effect.exit,
1073 ),
1074 { concurrency: REPOSITORY_CONCURRENCY },
1075 ).pipe(Effect.uninterruptible);
1076 const failed = exits.find(Exit.isFailure);
1077 if (failed !== undefined) return yield* Effect.failCause(failed.cause);
1079 const taskFolder = current();
1080 yield* store.put(taskFolder);
1081 return { taskFolder, branch, laidOutByProject: false, repositoriesStartedFromOrigin };
1082 }).pipe(
1083 Effect.onError(() =>
1084 // Recorded first: a checkout the rollback cannot remove must still be known afterwards.
1085 store.put(current()).pipe(
1086 Effect.ignoreCause({ log: true }),
1087 Effect.andThen(
1088 removeLocked(
1089 current(),
1090 { force: true, forget: true, deleteBranch: branch },
1091 hadBranch,
1092 layoutStarted,
1093 ),
1094 ),
1095 Effect.tap(({ kept }) =>
1096 kept.length === 0
1097 ? Effect.void
1098 : Effect.logWarning("A failed task folder was not fully removed", { root, kept }),
1099 ),
1100 Effect.ignoreCause({ log: true }),
1101 // A checkout the layout command made and this service refused was deleted as files.
1102 Effect.andThen(
1103 Effect.forEach(
1104 checkedOutFrom,
1105 (cwd) => git.pruneWorktrees({ cwd }).pipe(Effect.ignoreCause({ log: true })),
1106 { concurrency: REPOSITORY_CONCURRENCY, discard: true },
1107 ),
1108 ),
1109 // Only now that no checkout is registered on it; most went with their checkout.
1110 Effect.andThen(
1111 Effect.forEach(
1112 branchMadeIn,
1113 (cwd) =>
1114 git.deleteLocalBranch({ cwd, refName: branch, force: true }).pipe(Effect.ignore),
1115 { concurrency: REPOSITORY_CONCURRENCY, discard: true },
1116 ),
1117 ),
1118 ),
1119 ),
1120 Effect.mapError((cause) =>
1121 isTaskFolderError(cause)
1122 ? cause
1123 : fail("create", "Could not create the worktrees")(cause),
1124 ),
1125 );
1126 },
1127 );
1128​
1129 /** The project's setting for where new worktrees start. */
1130 const startsFromOrigin = (operation: TaskFolderError["operation"], projectId: ProjectId) =>
1131 settings.getSettings.pipe(
1132 Effect.mapError(fail(operation, "Could not read settings")),
1133 Effect.map(
1134 (current) =>
1135 resolveProjectSettings(current, projectId).settings.newWorktreesStartFromOrigin,
1136 ),
1137 );
1138​
1139 const createForProjectFolder: TaskFolders["Service"]["createForProjectFolder"] = Effect.fn(
1140 "TaskFolders.createForProjectFolder",
1141 )(function* (input) {
1142 if (input.path !== null || input.newRefName === undefined) return null;
1143 const project = yield* projects
1144 .findActiveByWorkspaceRoot(input.cwd)
1145 .pipe(Effect.mapError(fail("plan", "Could not read the project")));
1146 if (Option.isNone(project)) return null;
1147 const { projectId } = project.value;
1148 const taskPlan = yield* plan({ projectId });
1149 if (taskPlan === null) return null;
1150 const { taskFolder, branch } = yield* create({
1151 plan: taskPlan,
1152 branch: input.newRefName,
1153 projectStart: { refName: input.refName, baseRefName: input.baseRefName ?? input.refName },
1154 baseBranch: input.baseRefName ?? input.refName,
1155 startFromOrigin: yield* startsFromOrigin("create", projectId),
1156 });
1157 return { worktree: { path: taskFolder.projectPath, refName: branch } };
1158 });
1159​
1160 const addRepository: TaskFolders["Service"]["addRepository"] = Effect.fn(
1161 "TaskFolders.addRepository",
1162 )(function* (input) {
1163 const refuse = (detail: string) => new TaskFolderError({ operation: "add-repository", detail });
1164 const thread = yield* projections
1165 .getThreadShell(input.threadId)
1166 .pipe(Effect.mapError(fail("add-repository", "Could not read the thread")));
1167 if (thread === null || thread.worktreePath === null || thread.branch === null)
1168 return yield* refuse("This thread does not work in a worktree.");
1169 const recordedBranch = thread.branch;
1170 const startFromOrigin =
1171 input.startFromOrigin ?? (yield* startsFromOrigin("add-repository", thread.projectId));
1172 const found = yield* requireTaskFolder("add-repository", thread.worktreePath);
1173 return yield* locked(
1174 found,
1175 Effect.gen(function* () {
1176 // Read again under the lease: another add may have landed.
1177 const taskFolder = yield* requireTaskFolder("add-repository", found.root);
1178 // The thread's record lags a rename of its branch, so a checkout says which one it is.
1179 const checkedOut = taskFolder.projectIsWorktree
1180 ? taskFolder.projectPath
1181 : taskFolder.repositories[0]?.worktreePath;
1182 const branch =
1183 (checkedOut === undefined
1184 ? null
1185 : yield* git.currentBranch(checkedOut).pipe(Effect.orElseSucceed(() => null))) ??
1186 recordedBranch;
1187 const project = yield* readProject("add-repository", taskFolder.projectId);
1188 const repositoryPath = path.resolve(input.repositoryPath);
1189 const folder = (yield* trackedFolders(project)).find(
1190 (candidate) => path.resolve(candidate.path) === repositoryPath,
1191 );
1192 if (folder === undefined)
1193 return yield* refuse(`"${input.repositoryPath}" is not a tracked folder of the project.`);
1194 if (!(yield* isRepository(repositoryPath)))
1195 return yield* refuse(`"${input.repositoryPath}" is not a Git repository.`);
1196 if (yield* isSubmodule(repositoryPath))
1197 return yield* refuse(`${folder.name} is a submodule, so it comes with its repository.`);
1198 if (taskFolder.repositories.some((entry) => entry.repositoryPath === repositoryPath))
1199 return yield* refuse(`${folder.name} already has a worktree in this thread.`);
1200 if (!isWithinRoot(path, repositoryPath, taskFolder.anchor))
1201 return yield* refuse(
1202 `${folder.name} lies outside the folders this thread's worktree was laid out for. Start a new worktree thread to include it.`,
1203 );
1204 const worktreePath = mapped(taskFolder, repositoryPath);
1205 const insideLinkedProject =
1206 !taskFolder.projectIsWorktree &&
1207 isWithinRoot(path, repositoryPath, taskFolder.projectRoot) &&
1208 repositoryPath !== taskFolder.projectRoot;
1209 const wasLinked =
1210 insideLinkedProject &&
1211 Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option));
1212 const opened = insideLinkedProject
1213 ? yield* openLinkedPath(
1214 taskFolder.projectRoot,
1215 taskFolder.projectPath,
1216 path.relative(taskFolder.projectRoot, repositoryPath),
1217 ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder")))
1218 : true;
1219 if (!opened || (yield* occupied(worktreePath)))
1220 return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`);
1221 // The link the worktree took the place of comes back when the worktree does not stay.
1222 const relink = wasLinked
1223 ? // Git may or may not have left an empty folder where the link was.
1224 removeEmptyDirectory(worktreePath).pipe(
1225 Effect.ignore,
1226 Effect.andThen(fileSystem.symlink(repositoryPath, worktreePath)),
1227 Effect.ignoreCause({ log: true }),
1229 : Effect.void;
1230 const existing = (yield* git
1231 .listLocalBranchNames(repositoryPath)
1232 .pipe(Effect.mapError(fail("add-repository", "Could not list branches")))).includes(
1233 branch,
1234 );
1235 yield* Effect.gen(function* () {
1236 yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true });
1237 if (existing) {
1238 // The thread's branch is already there, so it is checked out, not started again.
1239 yield* git.createWorktree({
1240 cwd: repositoryPath,
1241 refName: branch,
1242 path: worktreePath,
1243 });
1244 } else {
1245 const start = yield* repositoryStart(repositoryPath, startFromOrigin);
1246 yield* git.createWorktree({
1247 cwd: repositoryPath,
1248 refName: start.refName,
1249 newRefName: branch,
1250 baseRefName: start.baseRefName,
1251 path: worktreePath,
1252 });
1254 }).pipe(
1255 Effect.onError(() => relink),
1256 Effect.mapError(fail("add-repository", `Could not create the ${folder.name} worktree`)),
1257 );
1258 const updated: TaskFolder = {
1259 ...taskFolder,
1260 repositories: [
1261 ...taskFolder.repositories,
1262 { repositoryPath, worktreePath, name: folder.name },
1263 ],
1264 };
1265 yield* store
1266 .put(updated)
1267 .pipe(
1268 Effect.onError(() =>
1269 removeCheckout(
1270 { repositoryPath, worktreePath },
1271 true,
1272 existing ? undefined : branch,
1273 ).pipe(Effect.ignoreCause({ log: true }), Effect.andThen(relink)),
1274 ),
1275 );
1276 return updated;
1277 }),
1278 );
1279 });
1280​
1281 const remove: TaskFolders["Service"]["remove"] = Effect.fnUntraced(function* (input) {
1282 const taskFolder = yield* store.findContaining(input.root);
1283 if (taskFolder === null || taskFolder.root !== input.root) return { removed: [], kept: [] };
1284 return yield* removeLocked(taskFolder, input);
1285 });
1286​
1287 const removeIfTaskFolder: TaskFolders["Service"]["removeIfTaskFolder"] = Effect.fn(
1288 "TaskFolders.removeIfTaskFolder",
1289 )(function* (input) {
1290 const taskFolder = yield* store.findContaining(input.path);
1291 const target = path.resolve(input.path);
1292 if (taskFolder === null || (target !== taskFolder.root && target !== taskFolder.projectPath))
1293 return false;
1294 const { kept } = yield* removeLocked(taskFolder, { force: input.force, forget: true });
1295 if (kept.length > 0) {
1296 return yield* new TaskFolderError({
1297 operation: "remove",
1298 detail: `Kept ${kept.map((entry) => `${entry.path} (${entry.reason})`).join(", ")}.`,
1299 });
1301 return true;
1302 });
1303​
1304 const renameBranch: TaskFolders["Service"]["renameBranch"] = Effect.fn(
1305 "TaskFolders.renameBranch",
1306 )(function* (input) {
1307 const taskFolder = yield* requireTaskFolder("create", input.root);
1308 const cwds = [
1309 ...(taskFolder.projectIsWorktree ? [taskFolder.projectPath] : []),
1310 ...taskFolder.repositories.map((repository) => repository.worktreePath),
1311 ];
1312 if (cwds.length === 0 || input.oldBranch === input.newBranch)
1313 return { branch: input.oldBranch };
1314 const renameFailed = fail("create", "Could not rename the branch");
1315 const branch =
1316 input.exactName === true
1317 ? input.newBranch
1318 : yield* freeBranchName(
1319 "create",
1320 input.newBranch,
1321 (yield* branchNames(cwds).pipe(Effect.mapError(renameFailed))).map((list) =>
1322 list.filter((existing) => existing !== input.oldBranch),
1323 ),
1324 );
1325 const renamed: string[] = [];
1326 yield* Effect.forEach(
1327 cwds,
1328 (cwd) =>
1329 git
1330 .renameBranch({ cwd, oldBranch: input.oldBranch, newBranch: branch, exactName: true })
1331 .pipe(Effect.tap(() => Effect.sync(() => renamed.push(cwd)))),
1332 { discard: true },
1333 ).pipe(
1334 // One name everywhere or the old one everywhere.
1335 Effect.onError(() =>
1336 Effect.forEach(
1337 renamed,
1338 (cwd) =>
1339 git
1340 .renameBranch({ cwd, oldBranch: branch, newBranch: input.oldBranch, exactName: true })
1341 .pipe(Effect.ignoreCause({ log: true })),
1342 { discard: true },
1343 ),
1344 ),
1345 Effect.mapError(renameFailed),
1346 );
1347 return { branch };
1348 });
1349​
1350 const restore: TaskFolders["Service"]["restore"] = Effect.fn("TaskFolders.restore")(function* ({
1351 taskFolder,
1352 branch,
1353 recreate,
1354 }) {
1355 const restoreFailed = fail("create", "Could not restore the worktrees");
1356 // A project that lays its own folder out rebuilds it; whatever is still missing after that
1357 // comes back as a plain checkout below.
1358 const layout = yield* worktreeLayout(taskFolder.projectRoot);
1359 const present = yield* Effect.forEach(
1360 [taskFolder.projectPath, ...taskFolder.repositories.map((entry) => entry.worktreePath)],
1361 exists,
1362 );
1363 if (layout !== null && present.includes(false)) {
1364 yield* fileSystem
1365 .makeDirectory(taskFolder.root, { recursive: true })
1366 .pipe(Effect.mapError(restoreFailed));
1367 yield* runLayoutCommand(
1368 "create",
1369 layout.create,
1370 taskFolder,
1371 branch,
1372 undefined,
1373 taskFolder.repositories.map((repository) => repository.repositoryPath),
1374 ).pipe(Effect.ignoreCause({ log: true }));
1376 const recreateMissing = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
1377 if (yield* isRepository(checkout.worktreePath)) {
1378 // Another checkout in its place is not the thread's: resuming there would work on it.
1379 if ((yield* linkedGitDir(checkout)) !== null) return;
1380 return yield* new TaskFolderError({
1381 operation: "create",
1382 detail: `${checkout.worktreePath} holds a checkout that is not a worktree of ${checkout.repositoryPath}. Move it away to restore the thread's worktree.`,
1383 });
1385 yield* fileSystem
1386 .makeDirectory(path.dirname(checkout.worktreePath), { recursive: true })
1387 .pipe(Effect.mapError(restoreFailed));
1388 yield* recreate(checkout);
1389 });
1390 if (taskFolder.projectIsWorktree) {
1391 yield* recreateMissing({
1392 worktreePath: taskFolder.projectPath,
1393 repositoryPath: taskFolder.projectRoot,
1394 });
1395 } else if (!(yield* exists(taskFolder.projectPath))) {
1396 const project = yield* readProject("create", taskFolder.projectId);
1397 const tracked = yield* Effect.filter(
1398 (yield* trackedFolders(project)).map((folder) => path.resolve(folder.path)),
1399 isRepository,
1400 );
1401 // A recorded repository the project no longer tracks still gets its worktree, never a link.
1402 yield* linkFolder(taskFolder.projectRoot, taskFolder.projectPath, [
1403 ...tracked,
1404 ...taskFolder.repositories.map((repository) => repository.repositoryPath),
1405 ]).pipe(Effect.mapError(restoreFailed));
1407 for (const repository of taskFolder.repositories.toSorted(
1408 (left, right) => depth(left.worktreePath) - depth(right.worktreePath),
1409 )) {
1410 yield* recreateMissing(repository);
1412 });
1413​
1414 return TaskFolders.of({
1415 plan,
1416 create,
1417 createForProjectFolder,
1418 addRepository,
1419 find: store.findContaining,
1420 remove,
1421 removeIfTaskFolder,
1422 renameBranch,
1423 restore,
1424 });
1425});
1426​
1427export const layer = Layer.effect(TaskFolders, make);