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

TaskFolders.test.ts

944 lines39.7 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("gives two creations on one branch a folder each", () =>
252 withState((state) =>
253 Effect.gen(function* () {
254 const { fileSystem, path, tmp, repository } = yield* fixture;
255 const api = yield* repository("shop/api");
256 state.workspaceRoot = path.join(tmp, "shop");
257 state.trackedFolders = tracked(api);
258​
259 // Git gives the branch to one of them; the other's rollback must leave that one's folder.
260 const exits = yield* Effect.all(
261 [Effect.exit(create("feature")), Effect.exit(create("feature"))],
262 {
263 concurrency: 2,
264 },
265 );
266​
267 const created = exits.flatMap((exit) =>
268 Exit.isSuccess(exit) ? [exit.value.taskFolder] : [],
269 );
270 assert.isAtLeast(created.length, 1);
271 assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length);
272 for (const taskFolder of created) {
273 assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md")));
274 }
275 }),
276 ),
277);
278​
279it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])(
280 "answers an existing thread's worktree request with a task folder, project is a repository=$projectIsRepository",
281 ({ projectIsRepository }) =>
282 withState((state) =>
283 Effect.gen(function* () {
284 const { path, tmp, run, repository } = yield* fixture;
285 const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop");
286 const api = yield* repository("shop/api");
287 const web = yield* repository("web");
288 state.workspaceRoot = shop;
289 state.trackedFolders = tracked(api, web);
290 const taskFolders = yield* TaskFolders.TaskFolders;
291 const request = { cwd: shop, refName: "main", newRefName: "feature", path: null };
292​
293 const created = yield* taskFolders.createForProjectFolder(request);
294​
295 const taskFolder = yield* taskFolders.find(created!.worktree.path);
296 assert.deepEqual(created, {
297 worktree: { path: taskFolder!.projectPath, refName: "feature" },
298 });
299 assert.equal(taskFolder!.projectIsWorktree, projectIsRepository);
300 assert.sameMembers(
301 taskFolder!.repositories.map((entry) => entry.repositoryPath),
302 [api, web],
303 );
304 for (const worktree of [
305 ...(projectIsRepository ? [taskFolder!.projectPath] : []),
306 ...taskFolder!.repositories.map((entry) => entry.worktreePath),
307 ]) {
308 assert.equal(yield* run(worktree, "symbolic-ref", "--short", "HEAD"), "feature");
309 }
310 // A chosen path, an existing branch and a folder that is no project stay single worktrees.
311 for (const single of [
312 { ...request, path: path.join(tmp, "elsewhere") },
313 { cwd: shop, refName: "main", path: null },
314 { ...request, cwd: web },
315 ]) {
316 assert.isNull(yield* taskFolders.createForProjectFolder(single));
317 }
318 }),
319 ),
320);
321​
322it.live("puts a clone the project ignores inside the project's worktree", () =>
323 withState((state) =>
324 Effect.gen(function* () {
325 const { fileSystem, path, run, repository } = yield* fixture;
326 const project = yield* repository("p");
327 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
328 yield* run(project, "add", ".");
329 yield* run(project, "commit", "-m", "ignore vendor");
330 const lib = yield* repository("p/vendor/lib");
331 state.workspaceRoot = project;
332 state.trackedFolders = tracked(lib);
333​
334 const { taskFolder } = yield* create("feature");
335​
336 assert.equal(taskFolder.projectPath, taskFolder.root);
337 assert.equal(
338 taskFolder.repositories[0]?.worktreePath,
339 path.join(taskFolder.root, "vendor", "lib"),
340 );
341 assert.equal(
342 yield* run(path.join(taskFolder.root, "vendor", "lib"), "symbolic-ref", "--short", "HEAD"),
343 "feature",
344 );
345 assert.equal(yield* run(taskFolder.root, "status", "--porcelain"), "");
346 }),
347 ),
348);
349​
350it.live("creates the task folder when the project's checkout hook already linked a clone", () =>
351 withState((state) =>
352 Effect.gen(function* () {
353 const { fileSystem, path, tmp, run, repository } = yield* fixture;
354 const project = yield* repository("p");
355 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
356 yield* run(project, "add", ".");
357 yield* run(project, "commit", "-m", "ignore vendor");
358 const lib = yield* repository("p/vendor/lib");
359 // Like many projects with vendored clones, a new worktree links them back to the checkout.
360 const hooks = path.join(tmp, "hooks");
361 yield* fileSystem.makeDirectory(hooks);
362 yield* fileSystem.writeFileString(
363 path.join(hooks, "post-checkout"),
364 `#!/bin/sh\nmkdir -p vendor && ln -s "${lib}" vendor/lib\n`,
365 { mode: 0o755 },
366 );
367 yield* run(project, "config", "core.hooksPath", hooks);
368 state.workspaceRoot = project;
369 state.trackedFolders = tracked(lib);
370​
371 const created = yield* create("feature").pipe(Effect.exit);
372​
373 assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause));
374 }),
375 ),
376);
377​
378it.live("leaves a hook's link to an empty folder alone", () =>
379 withState((state) =>
380 Effect.gen(function* () {
381 const { fileSystem, path, tmp, run, repository } = yield* fixture;
382 const project = yield* repository("p");
383 yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n");
384 yield* run(project, "add", ".");
385 yield* run(project, "commit", "-m", "ignore vendor");
386 const lib = yield* repository("p/vendor/lib");
387 const target = path.join(tmp, "empty");
388 yield* fileSystem.makeDirectory(target);
389 const hooks = path.join(tmp, "hooks");
390 yield* fileSystem.makeDirectory(hooks);
391 yield* fileSystem.writeFileString(
392 path.join(hooks, "post-checkout"),
393 `#!/bin/sh\nmkdir -p vendor && ln -s "${target}" vendor/lib\n`,
394 { mode: 0o755 },
395 );
396 yield* run(project, "config", "core.hooksPath", hooks);
397 state.workspaceRoot = project;
398 state.trackedFolders = tracked(lib);
399​
400 const created = yield* create("feature").pipe(Effect.exit);
401​
402 assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause));
403 assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []);
404 }),
405 ),
406);
407​
408it.live("treats a project folder inside a larger repository as plain", () =>
409 withState((state) =>
410 Effect.gen(function* () {
411 const { fileSystem, path, repository, worktreeCount } = yield* fixture;
412 const big = yield* repository("big");
413 const pkg = path.join(big, "pkg");
414 const tool = yield* repository("big/pkg/tool");
415 yield* fileSystem.writeFileString(path.join(pkg, "notes.md"), "notes\n");
416 state.workspaceRoot = pkg;
417 state.trackedFolders = tracked(tool);
418​
419 const { taskFolder } = yield* create("feature");
420​
421 assert.isFalse(taskFolder.projectIsWorktree);
422 assert.equal(taskFolder.projectPath, taskFolder.root);
423 assert.isFalse(yield* fileSystem.exists(path.join(taskFolder.root, ".git")));
424 assert.equal(
425 yield* fileSystem.readLink(path.join(taskFolder.root, "notes.md")),
426 path.join(pkg, "notes.md"),
427 );
428 // The parent repository is never checked out.
429 assert.equal(yield* worktreeCount(big), 1);
430 assert.equal(yield* worktreeCount(tool), 2);
431 }),
432 ),
433);
434​
435it.live("adopts the checkouts a project's own layout command makes, and runs its teardown", () =>
436 withState((state) =>
437 Effect.gen(function* () {
438 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
439 const shop = path.join(tmp, "shop");
440 const api = yield* repository("shop/api");
441 const web = yield* repository("shop/web");
442 // The project checks `api` out itself, copies its build cache and leaves `web` out.
443 yield* fileSystem.writeFileString(
444 path.join(shop, "t3.json"),
445 JSON.stringify({
446 worktreeLayout: {
447 // A plain project's folder is no worktree, even when the command leaves a `.git` there.
448 create:
449 '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"',
450 // Cleanup never deletes files that exist only here, so the teardown clears its own.
451 remove:
452 'touch "$T3_PROJECT_ROOT/torn-down" && rm -rf "$T3_WORKTREE_PROJECT_PATH/cache" "$T3_WORKTREE_PROJECT_PATH/chosen" "$T3_WORKTREE_PROJECT_PATH/.git"',
453 },
454 }),
455 );
456 state.workspaceRoot = shop;
457 state.trackedFolders = tracked(api, web);
458​
459 const { taskFolder } = yield* create("feature", undefined, "main");
460​
461 assert.isFalse(taskFolder.projectIsWorktree);
462 assert.deepEqual(taskFolder.repositories, [
463 { repositoryPath: api, worktreePath: path.join(taskFolder.root, "api"), name: "api" },
464 ]);
465 assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "cache")));
466 assert.equal(
467 yield* fileSystem.readFileString(path.join(taskFolder.root, "chosen")),
468 `${api}\n${web}`,
469 );
470 assert.equal(
471 yield* run(path.join(taskFolder.root, "api"), "symbolic-ref", "--short", "HEAD"),
472 "feature",
473 );
474 assert.equal(yield* worktreeCount(web), 1);
475​
476 // Storage cleanup inspects each checkout; the teardown runs once all of them may go.
477 yield* (yield* TaskFolders.TaskFolders).remove({
478 root: taskFolder.root,
479 force: true,
480 forget: true,
481 inspect: () => Effect.succeed({ keep: null, force: true }),
482 });
483 assert.isTrue(yield* fileSystem.exists(path.join(shop, "torn-down")));
484 // What the teardown left is removed as usual.
485 assert.equal(yield* worktreeCount(api), 1);
486 assert.isFalse(yield* fileSystem.exists(taskFolder.root));
487 }),
488 ),
489);
490​
491it.live(
492 "removes what a failed layout command checked out, and refuses a checkout it cannot own",
493 () =>
494 withState((state) =>
495 Effect.gen(function* () {
496 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
497 const shop = path.join(tmp, "shop");
498 const api = yield* repository("shop/api");
499 // Not chosen, so the thread's branch name is not moved past the `feature` it has.
500 const web = yield* repository("shop/web");
501 yield* run(web, "branch", "feature");
502 state.workspaceRoot = shop;
503 const taskFolders = yield* TaskFolders.TaskFolders;
504 const attempt = Effect.fnUntraced(function* (command: string) {
505 yield* fileSystem.writeFileString(
506 path.join(shop, "t3.json"),
507 JSON.stringify({ worktreeLayout: { create: command } }),
508 );
509 const plan = yield* taskFolders.plan({ projectId, repositories: [{ path: api }] });
510 return yield* taskFolders
511 .create({
512 plan: plan!,
513 branch: "feature",
514 projectStart: { refName: "main", baseRefName: "main" },
515 startFromOrigin: false,
516 })
517 .pipe(Effect.flip);
518 });
519​
520 yield* attempt(
521 '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',
522 );
523 assert.equal(yield* worktreeCount(api), 1);
524​
525 // A clone has no worktree registration to remove, and no thread branch to rename.
526 const refused = yield* attempt(
527 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git clone -q "$T3_PROJECT_ROOT/api" "$T3_WORKTREE_PROJECT_PATH/api"',
528 );
529 assert.include(refused.detail, "is not a Git worktree of");
530​
531 // The refused checkout's folder is deleted, so its registration must go too.
532 const wrongBranch = yield* attempt(
533 'mkdir -p "$T3_WORKTREE_PROJECT_PATH" && git -C "$T3_PROJECT_ROOT/api" worktree add -q -b other "$T3_WORKTREE_PROJECT_PATH/api"',
534 );
535 assert.include(wrongBranch.detail, "is not on the branch feature");
536 assert.equal(yield* worktreeCount(api), 1);
537​
538 // A branch that was there before the command checked it out outlives the rollback.
539 yield* attempt(
540 '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',
541 );
542 assert.equal(yield* worktreeCount(web), 1);
543 assert.deepEqual((yield* run(web, "branch", "--format=%(refname:short)")).split("\n"), [
544 "feature",
545 "main",
546 ]);
547 }),
548 ),
549);
550​
551// A project that is itself a linked worktree registers its worktrees in the repository it follows.
552it.live.each([{ linked: false }, { linked: true }])(
553 "runs the layout command of a project that tracks no other repository, linked worktree=$linked",
554 ({ linked }) =>
555 withState((state) =>
556 Effect.gen(function* () {
557 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
558 const origin = yield* repository(linked ? "origin" : "mono");
559 const mono = path.join(tmp, "mono");
560 if (linked) yield* run(origin, "worktree", "add", "-q", "-b", "dev", mono);
561 yield* fileSystem.writeFileString(
562 path.join(mono, "t3.json"),
563 JSON.stringify({
564 worktreeLayout: {
565 create:
566 '(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"',
567 },
568 }),
569 );
570 state.workspaceRoot = mono;
571 state.trackedFolders = [];
572​
573 const { taskFolder } = yield* create("feature");
574​
575 assert.isTrue(taskFolder.projectIsWorktree);
576 assert.deepEqual(taskFolder.repositories, []);
577 assert.equal(
578 yield* run(taskFolder.projectPath, "symbolic-ref", "--short", "HEAD"),
579 "feature",
580 );
581 const prepared = path.join(taskFolder.projectPath, "prepared");
582 assert.isTrue(yield* fileSystem.exists(prepared));
583​
584 // A folder that went missing is rebuilt by the same command, not as a bare checkout.
585 const taskFolders = yield* TaskFolders.TaskFolders;
586 yield* fileSystem.remove(taskFolder.root, { recursive: true });
587 yield* run(mono, "worktree", "prune");
588 yield* taskFolders.restore({
589 taskFolder,
590 branch: "feature",
591 recreate: () => Effect.die("the layout command rebuilds the folder"),
592 });
593 assert.isTrue(yield* fileSystem.exists(prepared));
594​
595 yield* taskFolders.remove({ root: taskFolder.root, force: true, forget: true });
596 assert.equal(yield* worktreeCount(mono), linked ? 2 : 1);
597 }),
598 ),
599);
600​
601it.live("starts each repository from the base branch where it has one", () =>
602 withState((state) =>
603 Effect.gen(function* () {
604 const { path, tmp, run, repository } = yield* fixture;
605 const api = yield* repository("shop/api");
606 const web = yield* repository("shop/web");
607 yield* run(api, "checkout", "-b", "release");
608 yield* run(api, "commit", "--allow-empty", "-m", "release work");
609 yield* run(api, "checkout", "main");
610 state.workspaceRoot = path.join(tmp, "shop");
611 state.trackedFolders = tracked(api, web);
612​
613 const { taskFolder } = yield* create("feature", undefined, "release");
614​
615 const head = (cwd: string, ref: string) => run(cwd, "rev-parse", ref);
616 assert.equal(
617 yield* head(path.join(taskFolder.root, "api"), "HEAD"),
618 yield* head(api, "release"),
619 );
620 assert.equal(
621 yield* head(path.join(taskFolder.root, "web"), "HEAD"),
622 yield* head(web, "main"),
623 );
624 // A worktree an existing thread asks for starts its repositories from the chosen base too.
625 const requested = yield* (yield* TaskFolders.TaskFolders).createForProjectFolder({
626 cwd: state.workspaceRoot,
627 refName: "release",
628 newRefName: "later",
629 path: null,
630 });
631 assert.equal(
632 yield* head(path.join(requested!.worktree.path, "api"), "HEAD"),
633 yield* head(api, "release"),
634 );
635​
636 // `HEAD` is what a client sends for no base: the local default branch, unpushed work and
637 // all, not the remote's last-fetched one.
638 yield* run(tmp, "clone", "-q", "--bare", web, "web-origin.git");
639 yield* run(web, "remote", "add", "origin", path.join(tmp, "web-origin.git"));
640 yield* run(web, "fetch", "-q", "origin");
641 yield* run(web, "remote", "set-head", "origin", "main");
642 yield* run(web, "commit", "--allow-empty", "-m", "unpushed");
643 const unset = yield* create("no-base", [{ path: web }], "HEAD");
644 assert.equal(
645 yield* head(path.join(unset.taskFolder.root, "web"), "HEAD"),
646 yield* head(web, "main"),
647 );
648 }),
649 ),
650);
651​
652it.live("gives every repository one branch name when one of them already has it", () =>
653 withState((state) =>
654 Effect.gen(function* () {
655 const { path, tmp, run, repository } = yield* fixture;
656 const api = yield* repository("shop/api");
657 const web = yield* repository("shop/web");
658 yield* run(web, "branch", "feature");
659 state.workspaceRoot = path.join(tmp, "shop");
660 state.trackedFolders = tracked(api, web);
661​
662 const { taskFolder, branch } = yield* create("feature");
663​
664 assert.equal(branch, "feature-2");
665 for (const repositoryWorktree of taskFolder.repositories) {
666 assert.equal(
667 yield* run(repositoryWorktree.worktreePath, "symbolic-ref", "--short", "HEAD"),
668 "feature-2",
669 );
670 }
671 assert.deepEqual((yield* run(api, "branch", "--format=%(refname:short)")).split("\n"), [
672 "feature-2",
673 "main",
674 ]);
675​
676 const renamed = yield* (yield* TaskFolders.TaskFolders).renameBranch({
677 root: taskFolder.root,
678 oldBranch: "feature-2",
679 // Taken in `web` only, so every checkout moves past it together.
680 newBranch: "feature",
681 });
682 assert.equal(renamed.branch, "feature-2");
683 yield* run(api, "branch", "fix-login");
684 assert.deepEqual(
685 yield* (yield* TaskFolders.TaskFolders).renameBranch({
686 root: taskFolder.root,
687 oldBranch: "feature-2",
688 newBranch: "fix-login",
689 }),
690 { branch: "fix-login-2" },
691 );
692 assert.equal(
693 yield* run(path.join(taskFolder.root, "web"), "symbolic-ref", "--short", "HEAD"),
694 "fix-login-2",
695 );
696 }),
697 ),
698);
699​
700it.live("removes what it created when one repository fails", () =>
701 withState((state) =>
702 Effect.gen(function* () {
703 const { fileSystem, path, tmp, run, repository, worktreeCount } = yield* fixture;
704 const api = yield* repository("shop/api");
705 // Git keeps its worktrees in a folder of this name, so none can be added here.
706 const broken = yield* repository("shop/broken");
707 yield* fileSystem.writeFileString(path.join(broken, ".git", "worktrees"), "");
708 yield* fileSystem.writeFileString(path.join(tmp, "shop", "AGENTS.md"), "rules\n");
709 state.workspaceRoot = path.join(tmp, "shop");
710 state.trackedFolders = tracked(api, broken);
711 const config = yield* ServerConfig.ServerConfig;
712​
713 const error = yield* create("feature").pipe(Effect.flip);
714​
715 assert.include(String((error as { readonly detail?: string }).detail), "broken worktree");
716 assert.equal(yield* worktreeCount(api), 1);
717 assert.equal(yield* run(api, "branch", "--format=%(refname:short)"), "main");
718 assert.deepEqual(yield* fileSystem.readDirectory(path.join(config.worktreesDir, "shop")), []);
719 assert.deepEqual(yield* (yield* TaskFolderStore.TaskFolderStore).list, []);
720 assert.isTrue(yield* fileSystem.exists(path.join(tmp, "shop", "AGENTS.md")));
721 }),
722 ),
723);
724​
725it.live("selects every tracked repository up to eight and none beyond", () =>
726 withState((state) =>
727 Effect.gen(function* () {
728 const { fileSystem, path, tmp, repository } = yield* fixture;
729 const taskFolders = yield* TaskFolders.TaskFolders;
730 // Outside the project folder, so the stored list alone says which are tracked.
731 const folders = yield* Effect.forEach(
732 Array.from({ length: 9 }, (_, index) => `repos/r${index}`),
733 repository,
734 { concurrency: 3 },
735 );
736 const plain = path.join(tmp, "shop", "notes");
737 yield* fileSystem.makeDirectory(plain, { recursive: true });
738 state.workspaceRoot = path.join(tmp, "shop");
739​
740 state.trackedFolders = tracked(plain);
741 assert.isNull(yield* taskFolders.plan({ projectId }));
742 // A named choice is refused, not dropped, when the project has no repository left.
743 assert.include(
744 (yield* taskFolders.plan({ projectId, repositories: [{ path: plain }] }).pipe(Effect.flip))
745 .detail,
746 "is not a Git repository",
747 );
748​
749 state.trackedFolders = tracked(...folders.slice(0, 8), plain);
750 assert.lengthOf((yield* taskFolders.plan({ projectId }))!.repositories, 8);
751​
752 state.trackedFolders = tracked(...folders, plain);
753 assert.lengthOf((yield* taskFolders.plan({ projectId }))!.repositories, 0);
754 const chosen = yield* taskFolders.plan({
755 projectId,
756 repositories: [{ path: folders[8]! }, { path: `${folders[8]!}${path.sep}` }],
757 });
758 assert.deepEqual(chosen?.repositories, [{ name: "r8", path: folders[8]! }]);
759 assert.isFalse(chosen?.projectIsRepository);
760​
761 for (const [requested, detail] of [
762 [path.join(tmp, "shop", "untracked"), "is not a tracked folder"],
763 [plain, "is not a Git repository"],
764 ] as const) {
765 const error = yield* taskFolders
766 .plan({ projectId, repositories: [{ path: requested }] })
767 .pipe(Effect.flip);
768 assert.include(error.detail, detail);
769 }
770 }),
771 ),
772);
773​
774it.live("adds a repository to an existing task folder on the thread's branch", () =>
775 withState((state) =>
776 Effect.gen(function* () {
777 const { fileSystem, path, tmp, run, repository, isLink } = yield* fixture;
778 const taskFolders = yield* TaskFolders.TaskFolders;
779 const shop = path.join(tmp, "shop");
780 const api = yield* repository("shop/api");
781 const web = yield* repository("shop/web");
782 yield* fileSystem.makeDirectory(path.join(shop, "tools"), { recursive: true });
783 yield* fileSystem.makeDirectory(path.join(shop, "taken"), { recursive: true });
784 yield* fileSystem.makeDirectory(path.join(shop, "unborn"), { recursive: true });
785 yield* fileSystem.writeFileString(path.join(shop, "tools", "run.sh"), "#!/bin/sh\n");
786 state.workspaceRoot = shop;
787 const { taskFolder } = yield* create("feature", [{ path: api }]);
788 const root = taskFolder.root;
789 assert.isTrue(yield* isLink(path.join(root, "tools")));
790 state.thread = { worktreePath: root, branch: "feature" };
791 // `late` and `taken` become repositories only after the task folder exists.
792 const late = yield* repository("shop/tools/late");
793 const taken = yield* repository("shop/taken");
794​
795 const withWeb = yield* taskFolders.addRepository({ threadId, repositoryPath: web });
796 assert.deepEqual(
797 withWeb.repositories.map((entry) => entry.worktreePath),
798 [path.join(root, "api"), path.join(root, "web")],
799 );
800 assert.equal(
801 yield* run(path.join(root, "web"), "symbolic-ref", "--short", "HEAD"),
802 "feature",
803 );
804​
805 // The thread's record can lag a rename of its branch; the checkouts say which one it is.
806 state.thread = { worktreePath: root, branch: "name-before-the-rename" };
807 // The link that stood for `tools` becomes a folder: the worktree, and links to the rest.
808 yield* taskFolders.addRepository({ threadId, repositoryPath: late });
809 assert.isFalse(yield* isLink(path.join(root, "tools")));
810 assert.equal(
811 yield* fileSystem.readLink(path.join(root, "tools", "run.sh")),
812 path.join(shop, "tools", "run.sh"),
813 );
814 assert.equal(
815 yield* run(path.join(root, "tools", "late"), "symbolic-ref", "--short", "HEAD"),
816 "feature",
817 );
818 assert.equal(yield* run(late, "symbolic-ref", "--short", "HEAD"), "main");
819​
820 // The link to the original checkout is one this service made; a folder with files is not.
821 yield* fileSystem.remove(path.join(root, "taken"));
822 yield* fileSystem.makeDirectory(path.join(root, "taken"));
823 yield* fileSystem.writeFileString(path.join(root, "taken", "draft.md"), "mine\n");
824 for (const [repositoryPath, detail] of [
825 [taken, "already holds files"],
826 [web, "already has a worktree"],
827 [path.join(shop, "nowhere"), "is not a tracked folder"],
828 ] as const) {
829 const error = yield* taskFolders
830 .addRepository({ threadId, repositoryPath })
831 .pipe(Effect.flip);
832 assert.include(error.detail, detail);
833 }
834 assert.lengthOf((yield* taskFolders.find(root))!.repositories, 3);
835​
836 // A repository with no commit gets no worktree, and the link it stood behind comes back.
837 const unborn = path.join(shop, "unborn");
838 yield* run(unborn, "init", "-b", "main");
839 yield* taskFolders.addRepository({ threadId, repositoryPath: unborn }).pipe(Effect.flip);
840 assert.equal(yield* fileSystem.readLink(path.join(root, "unborn")), unborn);
841​
842 // A copy of a checkout Git registered elsewhere is not the thread's worktree: it is not
843 // restored over, nor resumed in.
844 const webWorktree = path.join(root, "web");
845 const moved = path.join(tmp, "web-moved");
846 yield* run(web, "worktree", "move", webWorktree, moved);
847 yield* fileSystem.copy(moved, webWorktree);
848 const refused = yield* taskFolders
849 .restore({
850 taskFolder: (yield* taskFolders.find(root))!,
851 branch: "feature",
852 recreate: () => Effect.die("an existing checkout is never recreated"),
853 })
854 .pipe(Effect.flip);
855 assert.include(refused.detail, "is not a worktree of");
856 }),
857 ),
858);
859​
860it.live("keeps a repository git will not remove and removes the rest", () =>
861 withState((state) =>
862 Effect.gen(function* () {
863 const { fileSystem, path, tmp, repository, worktreeCount } = yield* fixture;
864 const taskFolders = yield* TaskFolders.TaskFolders;
865 const shop = path.join(tmp, "shop");
866 const api = yield* repository("shop/api");
867 const web = yield* repository("shop/web");
868 yield* fileSystem.writeFileString(path.join(shop, "AGENTS.md"), "rules\n");
869 state.workspaceRoot = shop;
870 state.trackedFolders = tracked(api, web);
871 const { taskFolder } = yield* create("feature");
872 const root = taskFolder.root;
873 yield* fileSystem.writeFileString(path.join(root, "api", "README.md"), "uncommitted\n");
874​
875 const first = yield* taskFolders.remove({ root, force: false, forget: true });
876​
877 assert.deepEqual(first.removed, [path.join(root, "web")]);
878 assert.deepEqual(
879 first.kept.map((entry) => entry.path),
880 [path.join(root, "api")],
881 );
882 assert.equal(
883 yield* fileSystem.readFileString(path.join(root, "api", "README.md")),
884 "uncommitted\n",
885 );
886 assert.equal(yield* worktreeCount(web), 1);
887 // The folder stays, so the files it shares with the project stay reachable in it.
888 assert.equal(
889 yield* fileSystem.readLink(path.join(root, "AGENTS.md")),
890 path.join(shop, "AGENTS.md"),
891 );
892 // The record now lists only what is still on disk.
893 assert.deepEqual(
894 (yield* taskFolders.find(root))?.repositories.map((entry) => entry.repositoryPath),
895 [api],
896 );
897​
898 const second = yield* taskFolders.remove({ root, force: true, forget: true });
899​
900 assert.deepEqual(second.kept, []);
901 assert.isFalse(yield* fileSystem.exists(root));
902 assert.isNull(yield* taskFolders.find(root));
903 assert.equal(yield* worktreeCount(api), 1);
904 // Links went; what they pointed at did not.
905 assert.equal(yield* fileSystem.readFileString(path.join(shop, "AGENTS.md")), "rules\n");
906 }),
907 ),
908);
909​
910it.live("restores a recorded repository the project stopped tracking as its worktree", () =>
911 withState((state) =>
912 Effect.gen(function* () {
913 const { fileSystem, path, tmp, run, repository, isLink } = yield* fixture;
914 const shop = path.join(tmp, "shop");
915 const api = yield* repository("shop/api");
916 const web = yield* repository("shop/web");
917 state.workspaceRoot = shop;
918 const { taskFolder } = yield* create("feature");
919 const root = taskFolder.root;
920​
921 yield* fileSystem.remove(root, { recursive: true });
922 yield* fileSystem.writeFileString(
923 path.join(shop, "t3.json"),
924 JSON.stringify({ ignoreRepositories: ["web"] }),
925 );
926 yield* (yield* TaskFolders.TaskFolders).restore({
927 taskFolder,
928 branch: "feature",
929 recreate: ({ repositoryPath, worktreePath }) =>
930 run(repositoryPath, "worktree", "prune").pipe(
931 Effect.andThen(run(repositoryPath, "worktree", "add", "-q", worktreePath, "feature")),
932 ),
933 });
934​
935 // A link there would be the original checkout, on its own branch.
936 for (const repositoryPath of [api, web]) {
937 const worktree = path.join(root, path.basename(repositoryPath));
938 assert.isFalse(yield* isLink(worktree));
939 assert.equal(yield* run(worktree, "symbolic-ref", "--short", "HEAD"), "feature");
940 }
941 assert.isTrue(yield* isLink(path.join(root, "t3.json")));
942 }),
943 ),
944);