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

TaskFolders.test.ts

947 lines40.0 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodePath from "@effect/platform-node/NodePath";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import { type ProjectTrackedFolder, ThreadId } from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import type * as Scope from "effect/Scope";
13​
14import * as ServerConfig from "../config.ts";
15import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
16import * as TaskFolders from "./TaskFolders.ts";
17import * as TaskFolderStore from "./TaskFolderStore.ts";
18import {
19 layerTaskFoldersWithGit,
20 taskFoldersTestProjectId as projectId,
21 type TaskFoldersTestState,
22} from "./TaskFolders.testkit.ts";
23​
24const threadId = ThreadId.make("thread:task-folders");
25​
26const layerFor = (state: TaskFoldersTestState) =>
27 layerTaskFoldersWithGit(state).pipe(
28 Layer.provideMerge(
29 GitVcsDriver.layer.pipe(
30 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-task-folders-" })),
31 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
32 ),
33 ),
34 );
35​
36const fixture = Effect.gen(function* () {
37 const fileSystem = yield* FileSystem.FileSystem;
38 const path = yield* Path.Path;
39 const git = yield* GitVcsDriver.GitVcsDriver;
40 const tmp = yield* fileSystem.realPath(
41 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-task-folders-" }),
42 );
43 const run = (cwd: string, ...args: ReadonlyArray<string>) =>
44 git
45 .execute({ operation: "task-folders-test", cwd, args })
46 .pipe(Effect.map((result) => result.stdout.trim()));
47 const repository = Effect.fnUntraced(function* (relative: string) {
48 const folder = path.join(tmp, relative);
49 yield* fileSystem.makeDirectory(folder, { recursive: true });
50 yield* run(folder, "init", "-b", "main");
51 yield* run(folder, "config", "user.email", "task-folders@example.test");
52 yield* run(folder, "config", "user.name", "Task folders");
53 yield* fileSystem.writeFileString(path.join(folder, "README.md"), `${relative}\n`);
54 yield* run(folder, "add", ".");
55 yield* run(folder, "commit", "-m", "initial");
56 return folder;
57 });
58 const isLink = (target: string) =>
59 fileSystem.readLink(target).pipe(Effect.option, Effect.map(Option.isSome));
60 const worktreeCount = (folder: string) =>
61 run(folder, "worktree", "list", "--porcelain").pipe(
62 Effect.map((listed) => listed.split("\n").filter((line) => line.startsWith("worktree "))),
63 Effect.map((worktrees) => worktrees.length),
64 );
65 return { fileSystem, path, tmp, run, repository, isLink, worktreeCount };
66});
67​
68const tracked = (...folders: ReadonlyArray<string>): ReadonlyArray<ProjectTrackedFolder> =>
69 folders.map((folder) => ({ path: folder, name: folder.split(/[\\/]/).at(-1)! }));
70​
71const create = Effect.fnUntraced(function* (
72 branch: string,
73 repositories?: ReadonlyArray<{ readonly path: string }>,
74 baseBranch?: string,
75) {
76 const taskFolders = yield* TaskFolders.TaskFolders;
77 const plan = yield* taskFolders.plan({ projectId, repositories });
78 assert.isNotNull(plan);
79 return yield* taskFolders.create({
80 plan: plan!,
81 branch,
82 projectStart: { refName: "main", baseRefName: "main" },
83 baseBranch,
84 startFromOrigin: false,
85 });
86});
87​
88const withState = <A, E>(
89 test: (
90 state: TaskFoldersTestState,
91 ) => Effect.Effect<A, E, Layer.Success<ReturnType<typeof layerFor>> | Scope.Scope>,
92) => {
93 const state: TaskFoldersTestState = { workspaceRoot: "/unset", trackedFolders: [], thread: null };
94 return test(state).pipe(Effect.provide(layerFor(state)), Effect.scoped);
95};
96​
97it.live("lays a plain wrapper out as links around its repositories' worktrees", () =>
98 withState((state) =>
99 Effect.gen(function* () {
100 const { fileSystem, path, tmp, run, repository, isLink } = yield* fixture;
101 const shop = path.join(tmp, "shop");
102 const api = yield* repository("shop/services/api");
103 const web = yield* repository("shop/web");
104 const unpicked = yield* repository("shop/unpicked");
105 yield* fileSystem.makeDirectory(path.join(shop, "notes"));
106 yield* fileSystem.makeDirectory(path.join(shop, ".git-not"));
107 yield* fileSystem.writeFileString(path.join(shop, "AGENTS.md"), "root rules\n");
108 yield* fileSystem.writeFileString(path.join(shop, "services", "README.md"), "services\n");
109 const unborn = path.join(shop, "unborn");
110 yield* fileSystem.makeDirectory(unborn);
111 yield* run(unborn, "init", "-b", "main");
112 state.workspaceRoot = shop;
113 state.trackedFolders = tracked(api, web, unpicked, unborn, path.join(shop, "notes"));
114​
115 const { taskFolder, branch } = yield* create("feature", [
116 { path: api },
117 { path: web },
118 { path: unborn },
119 ]);
120 const root = taskFolder.root;
121​
122 assert.equal(branch, "feature");
123 assert.deepEqual(
124 { ...taskFolder, repositories: taskFolder.repositories.toSorted(byName) },
125 {
126 root,
127 projectId,
128 projectRoot: shop,
129 anchor: shop,
130 projectPath: root,
131 projectIsWorktree: false,
132 repositories: [
133 {
134 repositoryPath: api,
135 worktreePath: path.join(root, "services", "api"),
136 name: "api",
137 },
138 { repositoryPath: web, worktreePath: path.join(root, "web"), name: "web" },
139 ],
140 },
141 );
142 // Shared with the original, never copied.
143 assert.equal(
144 yield* fileSystem.readLink(path.join(root, "AGENTS.md")),
145 path.join(shop, "AGENTS.md"),
146 );
147 assert.isTrue(yield* isLink(path.join(root, "notes")));
148 // The folder leading to a repository is real, and still shows what else it holds.
149 assert.isFalse(yield* isLink(path.join(root, "services")));
150 assert.isTrue(yield* isLink(path.join(root, "services", "README.md")));
151 // A tracked repository that was not chosen is absent: a link would be the original checkout.
152 assert.isFalse(yield* fileSystem.exists(path.join(root, "unpicked")));
153 // So is a chosen one with no commit yet, which has nothing to branch from.
154 assert.isFalse(yield* fileSystem.exists(path.join(root, "unborn")));
155 assert.isFalse(yield* fileSystem.exists(path.join(root, ".git")));
156 for (const worktree of [path.join(root, "services", "api"), path.join(root, "web")]) {
157 assert.equal(yield* run(worktree, "symbolic-ref", "--short", "HEAD"), "feature");
158 }
159 const taskFolders = yield* TaskFolders.TaskFolders;
160 assert.deepEqual(yield* taskFolders.find(path.join(root, "web", "src")), taskFolder);
161​
162 // A file of the thread's own keeps the folder, and a folder that stays keeps its links.
163 yield* fileSystem.writeFileString(path.join(root, "draft.md"), "mine\n");
164 yield* taskFolders.remove({ root, force: false, forget: true });
165 assert.equal(
166 yield* fileSystem.readLink(path.join(root, "AGENTS.md")),
167 path.join(shop, "AGENTS.md"),
168 );
169 }),
170 ),
171);
172​
173const byName = (left: { readonly name: string }, right: { readonly name: string }) =>
174 left.name.localeCompare(right.name);
175​
176it.live("keeps a Git project and its sibling repository side by side", () =>
177 withState((state) =>
178 Effect.gen(function* () {
179 const { fileSystem, path, run, repository, worktreeCount } = yield* fixture;
180 const ctx = yield* repository("x/ctx");
181 const app = yield* repository("x/app");
182 // A submodule comes with its repository's worktree, however that repository sets it up.
183 const lib = yield* repository("x/app/vendor/lib");
184 yield* fileSystem.writeFileString(
185 path.join(app, ".gitmodules"),
186 '[submodule "lib"]\n\tpath = vendor/lib\n',
187 );
188 state.workspaceRoot = ctx;
189 state.trackedFolders = tracked(app, lib);
190​
191 // Named by a client that cannot tell it apart, the submodule is left to its repository.
192 const { taskFolder } = yield* create("feature", [{ path: app }, { path: lib }]);
193​
194 assert.equal(taskFolder.anchor, path.dirname(ctx));
195 assert.equal(taskFolder.projectPath, path.join(taskFolder.root, "ctx"));
196 assert.isTrue(taskFolder.projectIsWorktree);
197 assert.deepEqual(taskFolder.repositories, [
198 { repositoryPath: app, worktreePath: path.join(taskFolder.root, "app"), name: "app" },
199 ]);
200 // `../app` from the thread's folder is the thread's own checkout of it.
201 assert.equal(
202 yield* run(
203 path.join(taskFolder.projectPath, "..", "app"),
204 "symbolic-ref",
205 "--short",
206 "HEAD",
207 ),
208 "feature",
209 );
210 assert.equal(
211 yield* run(taskFolder.projectPath, "symbolic-ref", "--short", "HEAD"),
212 "feature",
213 );
214 assert.equal(yield* worktreeCount(ctx), 2);
215 assert.equal(yield* worktreeCount(lib), 1);
216​
217 // A file the thread left beside its checkouts keeps the folder, and the record of it.
218 const taskFolders = yield* TaskFolders.TaskFolders;
219 const { root } = taskFolder;
220 yield* fileSystem.writeFileString(path.join(root, "notes.md"), "mine\n");
221 const first = yield* taskFolders.remove({ root, force: false, forget: true });
222 assert.deepEqual(
223 first.kept.map((entry) => entry.path),
224 [root],
225 );
226 assert.isNotNull(yield* taskFolders.find(root));
227 const second = yield* taskFolders.remove({ root, force: true, forget: true });
228 assert.deepEqual(second.kept, []);
229 assert.isFalse(yield* fileSystem.exists(root));
230 assert.isNull(yield* taskFolders.find(root));
231 }),
232 ),
233);
234​
235it.effect("finds no common folder for two Windows drives instead of climbing forever", () =>
236 Effect.gen(function* () {
237 const path = yield* Path.Path;
238 assert.equal(
239 TaskFolders.commonAncestor(path, ["C:\\work\\shop", "C:\\work\\libs\\api"]),
240 "C:\\work",
241 );
242 assert.isNull(TaskFolders.commonAncestor(path, ["C:\\work\\shop", "D:\\api"]));
243 // A repository on another drive is left out of the layout, not in the way of the rest.
244 assert.deepEqual(
245 TaskFolders.layoutAnchor(path, "C:\\work\\shop", ["D:\\api", "C:\\work\\libs\\api"]),
246 { anchor: "C:\\work", unreachable: ["D:\\api"] },
247 );
248 }).pipe(Effect.provide(NodePath.layerWin32)),
249);
250​
251it.live.each([{ projectIsRepository: false }, { projectIsRepository: true }])(
252 "gives two creations on one branch a folder each, project is a repository=$projectIsRepository",
253 ({ projectIsRepository }) =>
254 withState((state) =>
255 Effect.gen(function* () {
256 const { fileSystem, path, tmp, repository } = yield* fixture;
257 const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop");
258 const api = yield* repository("shop/api");
259 state.workspaceRoot = shop;
260 state.trackedFolders = tracked(api);
261​
262 // Git gives the branch to one of them; the other's rollback must leave that one's folder.
263 const exits = yield* Effect.all(
264 [Effect.exit(create("feature")), Effect.exit(create("feature"))],
265 {
266 concurrency: 2,
267 },
268 );
269​
270 const created = exits.flatMap((exit) =>
271 Exit.isSuccess(exit) ? [exit.value.taskFolder] : [],
272 );
273 assert.isAtLeast(created.length, 1);
274 assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length);
275 for (const taskFolder of created) {
276 assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md")));
277 }
278 }),
279 ),
280);
281​
282it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])(
283 "answers an existing thread's worktree request with a task folder, project is a repository=$projectIsRepository",
284 ({ projectIsRepository }) =>
285 withState((state) =>
286 Effect.gen(function* () {
287 const { path, tmp, run, repository } = yield* fixture;
288 const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop");
289 const api = yield* repository("shop/api");
290 const web = yield* repository("web");
291 state.workspaceRoot = shop;
292 state.trackedFolders = tracked(api, web);
293 const taskFolders = yield* TaskFolders.TaskFolders;
294 const request = { cwd: shop, refName: "main", newRefName: "feature", path: null };
295​
296 const created = yield* taskFolders.createForProjectFolder(request);
297​
298 const taskFolder = yield* taskFolders.find(created!.worktree.path);
299 assert.deepEqual(created, {
300 worktree: { path: taskFolder!.projectPath, refName: "feature" },
301 });
302 assert.equal(taskFolder!.projectIsWorktree, projectIsRepository);
303 assert.sameMembers(
304 taskFolder!.repositories.map((entry) => entry.repositoryPath),
305 [api, web],
306 );
307 for (const worktree of [
308 ...(projectIsRepository ? [taskFolder!.projectPath] : []),
309 ...taskFolder!.repositories.map((entry) => entry.worktreePath),
310 ]) {
311 assert.equal(yield* run(worktree, "symbolic-ref", "--short", "HEAD"), "feature");
312 }
313 // A chosen path, an existing branch and a folder that is no project stay single worktrees.
314 for (const single of [
315 { ...request, path: path.join(tmp, "elsewhere") },
316 { cwd: shop, refName: "main", path: null },
317 { ...request, cwd: web },
318 ]) {
319 assert.isNull(yield* taskFolders.createForProjectFolder(single));
320 }
321 }),
322 ),
323);
324​
325it.live("puts a clone the project ignores inside the project's worktree", () =>
326 withState((state) =>
327 Effect.gen(function* () {
328 const { fileSystem, path, run, repository } = yield* fixture;
329 const project = yield* repository("p");
330 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
331 yield* run(project, "add", ".");
332 yield* run(project, "commit", "-m", "ignore vendor");
333 const lib = yield* repository("p/vendor/lib");
334 state.workspaceRoot = project;
335 state.trackedFolders = tracked(lib);
336​
337 const { taskFolder } = yield* create("feature");
338​
339 assert.equal(taskFolder.projectPath, taskFolder.root);
340 assert.equal(
341 taskFolder.repositories[0]?.worktreePath,
342 path.join(taskFolder.root, "vendor", "lib"),
343 );
344 assert.equal(
345 yield* run(path.join(taskFolder.root, "vendor", "lib"), "symbolic-ref", "--short", "HEAD"),
346 "feature",
347 );
348 assert.equal(yield* run(taskFolder.root, "status", "--porcelain"), "");
349 }),
350 ),
351);
352​
353it.live("creates the task folder when the project's checkout hook already linked a clone", () =>
354 withState((state) =>
355 Effect.gen(function* () {
356 const { fileSystem, path, tmp, run, repository } = yield* fixture;
357 const project = yield* repository("p");
358 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
359 yield* run(project, "add", ".");
360 yield* run(project, "commit", "-m", "ignore vendor");
361 const lib = yield* repository("p/vendor/lib");
362 // Like many projects with vendored clones, a new worktree links them back to the checkout.
363 const hooks = path.join(tmp, "hooks");
364 yield* fileSystem.makeDirectory(hooks);
365 yield* fileSystem.writeFileString(
366 path.join(hooks, "post-checkout"),
367 `#!/bin/sh\nmkdir -p vendor && ln -s "${lib}" vendor/lib\n`,
368 { mode: 0o755 },
369 );
370 yield* run(project, "config", "core.hooksPath", hooks);
371 state.workspaceRoot = project;
372 state.trackedFolders = tracked(lib);
373​
374 const created = yield* create("feature").pipe(Effect.exit);
375​
376 assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause));
377 }),
378 ),
379);
380​
381it.live("leaves a hook's link to an empty folder alone", () =>
382 withState((state) =>
383 Effect.gen(function* () {
384 const { fileSystem, path, tmp, run, repository } = yield* fixture;
385 const project = yield* repository("p");
386 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
387 yield* run(project, "add", ".");
388 yield* run(project, "commit", "-m", "ignore vendor");
389 const lib = yield* repository("p/vendor/lib");
390 const target = path.join(tmp, "empty");
391 yield* fileSystem.makeDirectory(target);
392 const hooks = path.join(tmp, "hooks");
393 yield* fileSystem.makeDirectory(hooks);
394 yield* fileSystem.writeFileString(
395 path.join(hooks, "post-checkout"),
396 `#!/bin/sh\nmkdir -p vendor && ln -s "${target}" vendor/lib\n`,
397 { mode: 0o755 },
398 );
399 yield* run(project, "config", "core.hooksPath", hooks);
400 state.workspaceRoot = project;
401 state.trackedFolders = tracked(lib);
402​
403 const created = yield* create("feature").pipe(Effect.exit);
404​
405 assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause));
406 assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []);
407 }),
408 ),
409);
410​
411it.live("treats a project folder inside a larger repository as plain", () =>
412 withState((state) =>
413 Effect.gen(function* () {
414 const { fileSystem, path, repository, worktreeCount } = yield* fixture;
415 const big = yield* repository("big");
416 const pkg = path.join(big, "pkg");
417 const tool = yield* repository("big/pkg/tool");
418 yield* fileSystem.writeFileString(path.join(pkg, "notes.md"), "notes\n");
419 state.workspaceRoot = pkg;
420 state.trackedFolders = tracked(tool);
421​
422 const { taskFolder } = yield* create("feature");
423​
424 assert.isFalse(taskFolder.projectIsWorktree);
425 assert.equal(taskFolder.projectPath, taskFolder.root);
426 assert.isFalse(yield* fileSystem.exists(path.join(taskFolder.root, ".git")));
427 assert.equal(
428 yield* fileSystem.readLink(path.join(taskFolder.root, "notes.md")),
429 path.join(pkg, "notes.md"),
430 );
431 // The parent repository is never checked out.
432 assert.equal(yield* worktreeCount(big), 1);
433 assert.equal(yield* worktreeCount(tool), 2);
434 }),
435 ),
436);
437​
438it.live("adopts the checkouts a project's own layout command makes, and runs its teardown", () =>
439 withState((state) =>
440 Effect.gen(function* () {
441 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
442 const shop = path.join(tmp, "shop");
443 const api = yield* repository("shop/api");
444 const web = yield* repository("shop/web");
445 // The project checks `api` out itself, copies its build cache and leaves `web` out.
446 yield* fileSystem.writeFileString(
447 path.join(shop, "t3.json"),
448 JSON.stringify({
449 worktreeLayout: {
450 // A plain project's folder is no worktree, even when the command leaves a `.git` there.
451 create:
452 'mkdir -p "$T3_WORKTREE_PROJECT_PATH/cache" && git init -q "$T3_WORKTREE_PROJECT_PATH" && printf %s "$T3_WORKTREE_REPOSITORIES" > "$T3_WORKTREE_PROJECT_PATH/chosen" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH/api" "$T3_WORKTREE_BASE"',
453 // Cleanup never deletes files that exist only here, so the teardown clears its own.
454 remove:
455 'touch "$T3_PROJECT_ROOT/torn-down" && rm -rf "$T3_WORKTREE_PROJECT_PATH/cache" "$T3_WORKTREE_PROJECT_PATH/chosen" "$T3_WORKTREE_PROJECT_PATH/.git"',
456 },
457 }),
458 );
459 state.workspaceRoot = shop;
460 state.trackedFolders = tracked(api, web);
461​
462 const { taskFolder } = yield* create("feature", undefined, "main");
463​
464 assert.isFalse(taskFolder.projectIsWorktree);
465 assert.deepEqual(taskFolder.repositories, [
466 { repositoryPath: api, worktreePath: path.join(taskFolder.root, "api"), name: "api" },
467 ]);
468 assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "cache")));
469 assert.equal(
470 yield* fileSystem.readFileString(path.join(taskFolder.root, "chosen")),
471 `${api}\n${web}`,
472 );
473 assert.equal(
474 yield* run(path.join(taskFolder.root, "api"), "symbolic-ref", "--short", "HEAD"),
475 "feature",
476 );
477 assert.equal(yield* worktreeCount(web), 1);
478​
479 // Storage cleanup inspects each checkout; the teardown runs once all of them may go.
480 yield* (yield* TaskFolders.TaskFolders).remove({
481 root: taskFolder.root,
482 force: true,
483 forget: true,
484 inspect: () => Effect.succeed({ keep: null, force: true }),
485 });
486 assert.isTrue(yield* fileSystem.exists(path.join(shop, "torn-down")));
487 // What the teardown left is removed as usual.
488 assert.equal(yield* worktreeCount(api), 1);
489 assert.isFalse(yield* fileSystem.exists(taskFolder.root));
490 }),
491 ),
492);
493​
494it.live(
495 "removes what a failed layout command checked out, and refuses a checkout it cannot own",
496 () =>
497 withState((state) =>
498 Effect.gen(function* () {
499 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
500 const shop = path.join(tmp, "shop");
501 const api = yield* repository("shop/api");
502 // Not chosen, so the thread's branch name is not moved past the `feature` it has.
503 const web = yield* repository("shop/web");
504 yield* run(web, "branch", "feature");
505 state.workspaceRoot = shop;
506 const taskFolders = yield* TaskFolders.TaskFolders;
507 const attempt = Effect.fnUntraced(function* (command: string) {
508 yield* fileSystem.writeFileString(
509 path.join(shop, "t3.json"),
510 JSON.stringify({ worktreeLayout: { create: command } }),
511 );
512 const plan = yield* taskFolders.plan({ projectId, repositories: [{ path: api }] });
513 return yield* taskFolders
514 .create({
515 plan: plan!,
516 branch: "feature",
517 projectStart: { refName: "main", baseRefName: "main" },
518 startFromOrigin: false,
519 })
520 .pipe(Effect.flip);
521 });
522​
523 yield* attempt(
524 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH/api" && exit 1',
525 );
526 assert.equal(yield* worktreeCount(api), 1);
527​
528 // A clone has no worktree registration to remove, and no thread branch to rename.
529 const refused = yield* attempt(
530 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git clone -q "$T3_PROJECT_ROOT/api" "$T3_WORKTREE_PROJECT_PATH/api"',
531 );
532 assert.include(refused.detail, "is not a Git worktree of");
533​
534 // The refused checkout's folder is deleted, so its registration must go too.
535 const wrongBranch = yield* attempt(
536 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b other "$T3_WORKTREE_PROJECT_PATH/api"',
537 );
538 assert.include(wrongBranch.detail, "is not on the branch feature");
539 assert.equal(yield* worktreeCount(api), 1);
540​
541 // A branch that was there before the command checked it out outlives the rollback.
542 yield* attempt(
543 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git -C "$T3_PROJECT_ROOT/web" worktree add -q "$T3_WORKTREE_PROJECT_PATH/web" "$T3_WORKTREE_BRANCH" && exit 1',
544 );
545 assert.equal(yield* worktreeCount(web), 1);
546 assert.deepEqual((yield* run(web, "branch", "--format=%(refname:short)")).split("\n"), [
547 "feature",
548 "main",
549 ]);
550 }),
551 ),
552);
553​
554// A project that is itself a linked worktree registers its worktrees in the repository it follows.
555it.live.each([{ linked: false }, { linked: true }])(
556 "runs the layout command of a project that tracks no other repository, linked worktree=$linked",
557 ({ linked }) =>
558 withState((state) =>
559 Effect.gen(function* () {
560 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
561 const origin = yield* repository(linked ? "origin" : "mono");
562 const mono = path.join(tmp, "mono");
563 if (linked) yield* run(origin, "worktree", "add", "-q", "-b", "dev", mono);
564 yield* fileSystem.writeFileString(
565 path.join(mono, "t3.json"),
566 JSON.stringify({
567 worktreeLayout: {
568 create:
569 '(git worktree add -q "$T3_WORKTREE_PROJECT_PATH" "$T3_WORKTREE_BRANCH" 2>/dev/null || git worktree add -q -b "$T3_WORKTREE_BRANCH" "$T3_WORKTREE_PROJECT_PATH") && touch "$T3_WORKTREE_PROJECT_PATH/prepared"',
570 },
571 }),
572 );
573 state.workspaceRoot = mono;
574 state.trackedFolders = [];
575​
576 const { taskFolder } = yield* create("feature");
577​
578 assert.isTrue(taskFolder.projectIsWorktree);
579 assert.deepEqual(taskFolder.repositories, []);
580 assert.equal(
581 yield* run(taskFolder.projectPath, "symbolic-ref", "--short", "HEAD"),
582 "feature",
583 );
584 const prepared = path.join(taskFolder.projectPath, "prepared");
585 assert.isTrue(yield* fileSystem.exists(prepared));
586​
587 // A folder that went missing is rebuilt by the same command, not as a bare checkout.
588 const taskFolders = yield* TaskFolders.TaskFolders;
589 yield* fileSystem.remove(taskFolder.root, { recursive: true });
590 yield* run(mono, "worktree", "prune");
591 yield* taskFolders.restore({
592 taskFolder,
593 branch: "feature",
594 recreate: () => Effect.die("the layout command rebuilds the folder"),
595 });
596 assert.isTrue(yield* fileSystem.exists(prepared));
597​
598 yield* taskFolders.remove({ root: taskFolder.root, force: true, forget: true });
599 assert.equal(yield* worktreeCount(mono), linked ? 2 : 1);
600 }),
601 ),
602);
603​
604it.live("starts each repository from the base branch where it has one", () =>
605 withState((state) =>
606 Effect.gen(function* () {
607 const { path, tmp, run, repository } = yield* fixture;
608 const api = yield* repository("shop/api");
609 const web = yield* repository("shop/web");
610 yield* run(api, "checkout", "-b", "release");
611 yield* run(api, "commit", "--allow-empty", "-m", "release work");
612 yield* run(api, "checkout", "main");
613 state.workspaceRoot = path.join(tmp, "shop");
614 state.trackedFolders = tracked(api, web);
615​
616 const { taskFolder } = yield* create("feature", undefined, "release");
617​
618 const head = (cwd: string, ref: string) => run(cwd, "rev-parse", ref);
619 assert.equal(
620 yield* head(path.join(taskFolder.root, "api"), "HEAD"),
621 yield* head(api, "release"),
622 );
623 assert.equal(
624 yield* head(path.join(taskFolder.root, "web"), "HEAD"),
625 yield* head(web, "main"),
626 );
627 // A worktree an existing thread asks for starts its repositories from the chosen base too.
628 const requested = yield* (yield* TaskFolders.TaskFolders).createForProjectFolder({
629 cwd: state.workspaceRoot,
630 refName: "release",
631 newRefName: "later",
632 path: null,
633 });
634 assert.equal(
635 yield* head(path.join(requested!.worktree.path, "api"), "HEAD"),
636 yield* head(api, "release"),
637 );
638​
639 // `HEAD` is what a client sends for no base: the local default branch, unpushed work and
640 // all, not the remote's last-fetched one.
641 yield* run(tmp, "clone", "-q", "--bare", web, "web-origin.git");
642 yield* run(web, "remote", "add", "origin", path.join(tmp, "web-origin.git"));
643 yield* run(web, "fetch", "-q", "origin");
644 yield* run(web, "remote", "set-head", "origin", "main");
645 yield* run(web, "commit", "--allow-empty", "-m", "unpushed");
646 const unset = yield* create("no-base", [{ path: web }], "HEAD");
647 assert.equal(
648 yield* head(path.join(unset.taskFolder.root, "web"), "HEAD"),
649 yield* head(web, "main"),
650 );
651 }),
652 ),
653);
654​
655it.live("gives every repository one branch name when one of them already has it", () =>
656 withState((state) =>
657 Effect.gen(function* () {
658 const { path, tmp, run, repository } = yield* fixture;
659 const api = yield* repository("shop/api");
660 const web = yield* repository("shop/web");
661 yield* run(web, "branch", "feature");
662 state.workspaceRoot = path.join(tmp, "shop");
663 state.trackedFolders = tracked(api, web);
664​
665 const { taskFolder, branch } = yield* create("feature");
666​
667 assert.equal(branch, "feature-2");
668 for (const repositoryWorktree of taskFolder.repositories) {
669 assert.equal(
670 yield* run(repositoryWorktree.worktreePath, "symbolic-ref", "--short", "HEAD"),
671 "feature-2",
672 );
673 }
674 assert.deepEqual((yield* run(api, "branch", "--format=%(refname:short)")).split("\n"), [
675 "feature-2",
676 "main",
677 ]);
678​
679 const renamed = yield* (yield* TaskFolders.TaskFolders).renameBranch({
680 root: taskFolder.root,
681 oldBranch: "feature-2",
682 // Taken in `web` only, so every checkout moves past it together.
683 newBranch: "feature",
684 });
685 assert.equal(renamed.branch, "feature-2");
686 yield* run(api, "branch", "fix-login");
687 assert.deepEqual(
688 yield* (yield* TaskFolders.TaskFolders).renameBranch({
689 root: taskFolder.root,
690 oldBranch: "feature-2",
691 newBranch: "fix-login",
692 }),
693 { branch: "fix-login-2" },
694 );
695 assert.equal(
696 yield* run(path.join(taskFolder.root, "web"), "symbolic-ref", "--short", "HEAD"),
697 "fix-login-2",
698 );
699 }),
700 ),
701);
702​
703it.live("removes what it created when one repository fails", () =>
704 withState((state) =>
705 Effect.gen(function* () {
706 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
707 const api = yield* repository("shop/api");
708 // Git keeps its worktrees in a folder of this name, so none can be added here.
709 const broken = yield* repository("shop/broken");
710 yield* fileSystem.writeFileString(path.join(broken, ".git", "worktrees"), "");
711 yield* fileSystem.writeFileString(path.join(tmp, "shop", "AGENTS.md"), "rules\n");
712 state.workspaceRoot = path.join(tmp, "shop");
713 state.trackedFolders = tracked(api, broken);
714 const config = yield* ServerConfig.ServerConfig;
715​
716 const error = yield* create("feature").pipe(Effect.flip);
717​
718 assert.include(String((error as { readonly detail?: string }).detail), "broken worktree");
719 assert.equal(yield* worktreeCount(api), 1);
720 assert.equal(yield* run(api, "branch", "--format=%(refname:short)"), "main");
721 assert.deepEqual(yield* fileSystem.readDirectory(path.join(config.worktreesDir, "shop")), []);
722 assert.deepEqual(yield* (yield* TaskFolderStore.TaskFolderStore).list, []);
723 assert.isTrue(yield* fileSystem.exists(path.join(tmp, "shop", "AGENTS.md")));
724 }),
725 ),
726);
727​
728it.live("selects every tracked repository up to eight and none beyond", () =>
729 withState((state) =>
730 Effect.gen(function* () {
731 const { fileSystem, path, tmp, repository } = yield* fixture;
732 const taskFolders = yield* TaskFolders.TaskFolders;
733 // Outside the project folder, so the stored list alone says which are tracked.
734 const folders = yield* Effect.forEach(
735 Array.from({ length: 9 }, (_, index) => `repos/r${index}`),
736 repository,
737 { concurrency: 3 },
738 );
739 const plain = path.join(tmp, "shop", "notes");
740 yield* fileSystem.makeDirectory(plain, { recursive: true });
741 state.workspaceRoot = path.join(tmp, "shop");
742​
743 state.trackedFolders = tracked(plain);
744 assert.isNull(yield* taskFolders.plan({ projectId }));
745 // A named choice is refused, not dropped, when the project has no repository left.
746 assert.include(
747 (yield* taskFolders.plan({ projectId, repositories: [{ path: plain }] }).pipe(Effect.flip))
748 .detail,
749 "is not a Git repository",
750 );
751​
752 state.trackedFolders = tracked(...folders.slice(0, 8), plain);
753 assert.lengthOf((yield* taskFolders.plan({ projectId }))!.repositories, 8);
754​
755 state.trackedFolders = tracked(...folders, plain);
756 assert.lengthOf((yield* taskFolders.plan({ projectId }))!.repositories, 0);
757 const chosen = yield* taskFolders.plan({
758 projectId,
759 repositories: [{ path: folders[8]! }, { path: `${folders[8]!}${path.sep}` }],
760 });
761 assert.deepEqual(chosen?.repositories, [{ name: "r8", path: folders[8]! }]);
762 assert.isFalse(chosen?.projectIsRepository);
763​
764 for (const [requested, detail] of [
765 [path.join(tmp, "shop", "untracked"), "is not a tracked folder"],
766 [plain, "is not a Git repository"],
767 ] as const) {
768 const error = yield* taskFolders
769 .plan({ projectId, repositories: [{ path: requested }] })
770 .pipe(Effect.flip);
771 assert.include(error.detail, detail);
772 }
773 }),
774 ),
775);
776​
777it.live("adds a repository to an existing task folder on the thread's branch", () =>
778 withState((state) =>
779 Effect.gen(function* () {
780 const { fileSystem, path, tmp, run, repository, isLink } = yield* fixture;
781 const taskFolders = yield* TaskFolders.TaskFolders;
782 const shop = path.join(tmp, "shop");
783 const api = yield* repository("shop/api");
784 const web = yield* repository("shop/web");
785 yield* fileSystem.makeDirectory(path.join(shop, "tools"), { recursive: true });
786 yield* fileSystem.makeDirectory(path.join(shop, "taken"), { recursive: true });
787 yield* fileSystem.makeDirectory(path.join(shop, "unborn"), { recursive: true });
788 yield* fileSystem.writeFileString(path.join(shop, "tools", "run.sh"), "#!/bin/sh\n");
789 state.workspaceRoot = shop;
790 const { taskFolder } = yield* create("feature", [{ path: api }]);
791 const root = taskFolder.root;
792 assert.isTrue(yield* isLink(path.join(root, "tools")));
793 state.thread = { worktreePath: root, branch: "feature" };
794 // `late` and `taken` become repositories only after the task folder exists.
795 const late = yield* repository("shop/tools/late");
796 const taken = yield* repository("shop/taken");
797​
798 const withWeb = yield* taskFolders.addRepository({ threadId, repositoryPath: web });
799 assert.deepEqual(
800 withWeb.repositories.map((entry) => entry.worktreePath),
801 [path.join(root, "api"), path.join(root, "web")],
802 );
803 assert.equal(
804 yield* run(path.join(root, "web"), "symbolic-ref", "--short", "HEAD"),
805 "feature",
806 );
807​
808 // The thread's record can lag a rename of its branch; the checkouts say which one it is.
809 state.thread = { worktreePath: root, branch: "name-before-the-rename" };
810 // The link that stood for `tools` becomes a folder: the worktree, and links to the rest.
811 yield* taskFolders.addRepository({ threadId, repositoryPath: late });
812 assert.isFalse(yield* isLink(path.join(root, "tools")));
813 assert.equal(
814 yield* fileSystem.readLink(path.join(root, "tools", "run.sh")),
815 path.join(shop, "tools", "run.sh"),
816 );
817 assert.equal(
818 yield* run(path.join(root, "tools", "late"), "symbolic-ref", "--short", "HEAD"),
819 "feature",
820 );
821 assert.equal(yield* run(late, "symbolic-ref", "--short", "HEAD"), "main");
822​
823 // The link to the original checkout is one this service made; a folder with files is not.
824 yield* fileSystem.remove(path.join(root, "taken"));
825 yield* fileSystem.makeDirectory(path.join(root, "taken"));
826 yield* fileSystem.writeFileString(path.join(root, "taken", "draft.md"), "mine\n");
827 for (const [repositoryPath, detail] of [
828 [taken, "already holds files"],
829 [web, "already has a worktree"],
830 [path.join(shop, "nowhere"), "is not a tracked folder"],
831 ] as const) {
832 const error = yield* taskFolders
833 .addRepository({ threadId, repositoryPath })
834 .pipe(Effect.flip);
835 assert.include(error.detail, detail);
836 }
837 assert.lengthOf((yield* taskFolders.find(root))!.repositories, 3);
838​
839 // A repository with no commit gets no worktree, and the link it stood behind comes back.
840 const unborn = path.join(shop, "unborn");
841 yield* run(unborn, "init", "-b", "main");
842 yield* taskFolders.addRepository({ threadId, repositoryPath: unborn }).pipe(Effect.flip);
843 assert.equal(yield* fileSystem.readLink(path.join(root, "unborn")), unborn);
844​
845 // A copy of a checkout Git registered elsewhere is not the thread's worktree: it is not
846 // restored over, nor resumed in.
847 const webWorktree = path.join(root, "web");
848 const moved = path.join(tmp, "web-moved");
849 yield* run(web, "worktree", "move", webWorktree, moved);
850 yield* fileSystem.copy(moved, webWorktree);
851 const refused = yield* taskFolders
852 .restore({
853 taskFolder: (yield* taskFolders.find(root))!,
854 branch: "feature",
855 recreate: () => Effect.die("an existing checkout is never recreated"),
856 })
857 .pipe(Effect.flip);
858 assert.include(refused.detail, "is not a worktree of");
859 }),
860 ),
861);
862​
863it.live("keeps a repository git will not remove and removes the rest", () =>
864 withState((state) =>
865 Effect.gen(function* () {
866 const { fileSystem, path, tmp, repository, worktreeCount } = yield* fixture;
867 const taskFolders = yield* TaskFolders.TaskFolders;
868 const shop = path.join(tmp, "shop");
869 const api = yield* repository("shop/api");
870 const web = yield* repository("shop/web");
871 yield* fileSystem.writeFileString(path.join(shop, "AGENTS.md"), "rules\n");
872 state.workspaceRoot = shop;
873 state.trackedFolders = tracked(api, web);
874 const { taskFolder } = yield* create("feature");
875 const root = taskFolder.root;
876 yield* fileSystem.writeFileString(path.join(root, "api", "README.md"), "uncommitted\n");
877​
878 const first = yield* taskFolders.remove({ root, force: false, forget: true });
879​
880 assert.deepEqual(first.removed, [path.join(root, "web")]);
881 assert.deepEqual(
882 first.kept.map((entry) => entry.path),
883 [path.join(root, "api")],
884 );
885 assert.equal(
886 yield* fileSystem.readFileString(path.join(root, "api", "README.md")),
887 "uncommitted\n",
888 );
889 assert.equal(yield* worktreeCount(web), 1);
890 // The folder stays, so the files it shares with the project stay reachable in it.
891 assert.equal(
892 yield* fileSystem.readLink(path.join(root, "AGENTS.md")),
893 path.join(shop, "AGENTS.md"),
894 );
895 // The record now lists only what is still on disk.
896 assert.deepEqual(
897 (yield* taskFolders.find(root))?.repositories.map((entry) => entry.repositoryPath),
898 [api],
899 );
900​
901 const second = yield* taskFolders.remove({ root, force: true, forget: true });
902​
903 assert.deepEqual(second.kept, []);
904 assert.isFalse(yield* fileSystem.exists(root));
905 assert.isNull(yield* taskFolders.find(root));
906 assert.equal(yield* worktreeCount(api), 1);
907 // Links went; what they pointed at did not.
908 assert.equal(yield* fileSystem.readFileString(path.join(shop, "AGENTS.md")), "rules\n");
909 }),
910 ),
911);
912​
913it.live("restores a recorded repository the project stopped tracking as its worktree", () =>
914 withState((state) =>
915 Effect.gen(function* () {
916 const { fileSystem, path, tmp, run, repository, isLink } = yield* fixture;
917 const shop = path.join(tmp, "shop");
918 const api = yield* repository("shop/api");
919 const web = yield* repository("shop/web");
920 state.workspaceRoot = shop;
921 const { taskFolder } = yield* create("feature");
922 const root = taskFolder.root;
923​
924 yield* fileSystem.remove(root, { recursive: true });
925 yield* fileSystem.writeFileString(
926 path.join(shop, "t3.json"),
927 JSON.stringify({ ignoreRepositories: ["web"] }),
928 );
929 yield* (yield* TaskFolders.TaskFolders).restore({
930 taskFolder,
931 branch: "feature",
932 recreate: ({ repositoryPath, worktreePath }) =>
933 run(repositoryPath, "worktree", "prune").pipe(
934 Effect.andThen(run(repositoryPath, "worktree", "add", "-q", worktreePath, "feature")),
935 ),
936 });
937​
938 // A link there would be the original checkout, on its own branch.
939 for (const repositoryPath of [api, web]) {
940 const worktree = path.join(root, path.basename(repositoryPath));
941 assert.isFalse(yield* isLink(worktree));
942 assert.equal(yield* run(worktree, "symbolic-ref", "--short", "HEAD"), "feature");
943 }
944 assert.isTrue(yield* isLink(path.join(root, "t3.json")));
945 }),
946 ),
947);