pi-odd-worktree 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,905 @@
1
+ 'use strict';
2
+ // The preparation hooks of `worktree_create` (S19, S20): the ordered chain, what it
3
+ // links and copies, the skip rules, the local configuration and the summary the
4
+ // create output prints. Every filesystem case uses a real temporary clone with an
5
+ // isolated HOME and Git configuration, removed in teardown; the Windows and
6
+ // refusal cases use an injected seam so no test depends on the host's link
7
+ // privileges or writes outside its own tree.
8
+
9
+ const assert = require('node:assert/strict');
10
+ const { execFileSync } = require('node:child_process');
11
+ const { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } = require('node:fs');
12
+ const { copyFile, lstat, mkdir, readdir, readFile, symlink } = require('node:fs/promises');
13
+ const { tmpdir } = require('node:os');
14
+ const { dirname, join } = require('node:path');
15
+ const test = require('node:test');
16
+
17
+ const {
18
+ WORKTREE_ASSET_LINKS,
19
+ WORKTREE_BUILD_CACHE_LINKS,
20
+ WORKTREE_HOOKS_FILENAME,
21
+ WORKTREE_INPUT_PREFIX,
22
+ WORKTREE_NEVER_LINKED,
23
+ copyChangesHook,
24
+ defaultWorktreeHooks,
25
+ emptyWorktreeHooksConfig,
26
+ inputsHook,
27
+ parseWorktreeHooksConfig,
28
+ runWorktreeHooks,
29
+ submodulesHook,
30
+ symlinksHook,
31
+ worktreeCopyChangesLine,
32
+ worktreeHookRecords,
33
+ worktreeHooksFilePath,
34
+ worktreeHooksSummary,
35
+ } = require('../lib/worktree-hooks.js');
36
+
37
+ const ENV_MARKER = 'FIXTURE_ENV_VALUE\n';
38
+
39
+ // ---- A real clone with a worktree ----
40
+
41
+ /** The real seams the extension wires, written here so the tests check the contract from outside. */
42
+ function realSeams(git) {
43
+ return {
44
+ git,
45
+ async kind(path) {
46
+ try {
47
+ const stats = await lstat(path);
48
+ if (stats.isSymbolicLink()) return 'symlink';
49
+ return stats.isDirectory() ? 'directory' : 'file';
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ },
54
+ async readdir(path) {
55
+ try {
56
+ return await readdir(path);
57
+ } catch {
58
+ return [];
59
+ }
60
+ },
61
+ async readText(path) {
62
+ try {
63
+ return await readFile(path, 'utf8');
64
+ } catch {
65
+ return undefined;
66
+ }
67
+ },
68
+ async copyFile(from, to) {
69
+ await copyFile(from, to);
70
+ },
71
+ async mkdir(path) {
72
+ await mkdir(path, { recursive: true });
73
+ },
74
+ async symlink(target, path, type) {
75
+ await symlink(target, path, type);
76
+ },
77
+ platform: process.platform,
78
+ };
79
+ }
80
+
81
+ function hooksFixture(t, options = {}) {
82
+ const fixture = realpathSync(mkdtempSync(join(tmpdir(), 'worktree-hooks-')));
83
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
84
+ const empty = join(fixture, 'empty');
85
+ mkdirSync(empty);
86
+ writeFileSync(join(empty, 'config'), '');
87
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
88
+ Object.assign(env, { HOME: fixture, GIT_CONFIG_GLOBAL: join(empty, 'config'), GIT_CONFIG_NOSYSTEM: '1' });
89
+ const git = (cwd, args) =>
90
+ execFileSync(
91
+ 'git',
92
+ ['-C', cwd, '-c', `core.hooksPath=${empty}`, '-c', 'commit.gpgsign=false', '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', ...args],
93
+ { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
94
+ );
95
+ const main = join(fixture, 'repo');
96
+ git(fixture, ['init', '--initial-branch=main', `--template=${empty}`, main]);
97
+ writeFileSync(join(main, 'tracked.txt'), 'fixture\n');
98
+ const write = (rel, text) => {
99
+ mkdirSync(dirname(join(main, rel)), { recursive: true });
100
+ writeFileSync(join(main, rel), text);
101
+ };
102
+ for (const [rel, text] of Object.entries(options.tracked ?? {})) write(rel, text);
103
+ git(main, ['add', '-A']);
104
+ git(main, ['commit', '-m', 'Fixture']);
105
+ for (const rel of options.directories ?? []) mkdirSync(join(main, rel), { recursive: true });
106
+ for (const [rel, text] of Object.entries(options.files ?? {})) write(rel, text);
107
+ for (const [rel, text] of Object.entries(options.unstaged ?? {})) write(rel, text);
108
+ for (const [rel, text] of Object.entries(options.staged ?? {})) {
109
+ write(rel, text);
110
+ git(main, ['add', '--', rel]);
111
+ }
112
+ const commonDir = realpathSync(git(main, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim());
113
+ git(main, ['worktree', 'add', '-b', 'feat/hooks', join(fixture, 'repo-worktrees', 'hooks')]);
114
+ const worktree = realpathSync(join(fixture, 'repo-worktrees', 'hooks'));
115
+ return {
116
+ fixture,
117
+ main,
118
+ worktree,
119
+ commonDir,
120
+ git,
121
+ async run(runOptions = {}) {
122
+ const gitCalls = [];
123
+ const runner = async (cwd, args) => {
124
+ gitCalls.push({ cwd, args });
125
+ try {
126
+ return { code: 0, stdout: git(cwd, [...args]) };
127
+ } catch (error) {
128
+ const failure = error;
129
+ return { code: failure.status ?? 1, stdout: typeof failure.stdout === 'string' ? failure.stdout : '' };
130
+ }
131
+ };
132
+ const input = {
133
+ mainRoot: main,
134
+ // The checkout whose uncommitted delta a copy reads is the one the caller
135
+ // stands in, so the fixture names it explicitly and defaults to main.
136
+ changesRoot: runOptions.changesRoot ?? main,
137
+ path: runOptions.path ?? worktree,
138
+ odd: 'worktree-tools',
139
+ copyChanges: runOptions.copyChanges === true,
140
+ seams: { ...realSeams(runner), ...runOptions.seams },
141
+ configPath: runOptions.configPath ?? worktreeHooksFilePath(commonDir),
142
+ };
143
+ if (runOptions.hooks !== undefined) input.hooks = runOptions.hooks;
144
+ const result = await runWorktreeHooks(input);
145
+ return { ...result, gitCalls };
146
+ },
147
+ };
148
+ }
149
+
150
+ /** The S20 file, written into `<git-common-dir>/gentle-ai/`, which Git never versions. */
151
+ function writeLocalHooks(fixture, value) {
152
+ const path = worktreeHooksFilePath(fixture.commonDir);
153
+ mkdirSync(dirname(path), { recursive: true });
154
+ writeFileSync(path, typeof value === 'string' ? value : JSON.stringify(value));
155
+ return path;
156
+ }
157
+
158
+ // ---- An injected seam for the cases no host can promise ----
159
+
160
+ function fakeWorld(options = {}) {
161
+ const mainRoot = '/main';
162
+ const worktree = '/worktree';
163
+ const kinds = new Map();
164
+ for (const rel of options.directories ?? []) kinds.set(join(mainRoot, rel), 'directory');
165
+ const links = [];
166
+ const copies = [];
167
+ const relative = (path) => path.slice(mainRoot.length + 1);
168
+ const seams = {
169
+ async git(_cwd, args) {
170
+ const rel = args[args.length - 1];
171
+ if (args[0] === 'ls-files') return { code: (options.tracked ?? []).includes(rel) ? 0 : 1, stdout: '' };
172
+ if (args[0] === 'check-ignore') return { code: (options.ignored ?? []).includes(rel) ? 0 : 1, stdout: '' };
173
+ return undefined;
174
+ },
175
+ async kind(path) {
176
+ return kinds.get(path) ?? (relative(path).length > 0 ? undefined : 'directory');
177
+ },
178
+ async readdir() {
179
+ return [];
180
+ },
181
+ async readText() {
182
+ return undefined;
183
+ },
184
+ async copyFile(from, to) {
185
+ copies.push({ from, to });
186
+ },
187
+ async mkdir() {},
188
+ async symlink(target, path, type) {
189
+ const refusal = (options.fails ?? {})[type];
190
+ if (refusal !== undefined) throw new Error(refusal);
191
+ links.push({ target, path, type });
192
+ kinds.set(path, 'symlink');
193
+ },
194
+ platform: options.platform ?? 'linux',
195
+ };
196
+ return { seams, links, copies, mainRoot, worktree };
197
+ }
198
+
199
+ // ---- S19: the chain ----
200
+
201
+ test('S19/S18: the default chain is ordered and puts copy_changes between the inputs and the links', () => {
202
+ assert.deepEqual(defaultWorktreeHooks().map((hook) => hook.name), ['submodules', 'inputs', 'copy_changes', 'symlinks']);
203
+ const chain = defaultWorktreeHooks();
204
+ chain.splice(2, 1);
205
+ assert.deepEqual(
206
+ defaultWorktreeHooks().map((hook) => hook.name),
207
+ ['submodules', 'inputs', 'copy_changes', 'symlinks'],
208
+ "a caller's edit stays with the caller's chain",
209
+ );
210
+ });
211
+
212
+ test('S19: build caches main has and does not track are linked into the worktree', async (t) => {
213
+ const fixture = hooksFixture(t, {
214
+ tracked: { '.gitignore': '.turbo\n.next/cache\n' },
215
+ directories: ['.turbo/cache', '.next/cache/build'],
216
+ });
217
+ const run = await fixture.run({ hooks: [symlinksHook] });
218
+
219
+ for (const rel of ['.turbo', '.next/cache']) {
220
+ const link = join(fixture.worktree, rel);
221
+ assert.ok(existsSync(link), `${rel} exists in the worktree`);
222
+ assert.ok(lstatSync(link).isSymbolicLink(), `${rel} is a link, not a copy`);
223
+ assert.equal(realpathSync(link), realpathSync(join(fixture.main, rel)), `${rel} points at main's directory`);
224
+ }
225
+ assert.equal(lstatSync(join(fixture.worktree, '.next')).isSymbolicLink(), false, 'only the cache directory is linked');
226
+ assert.deepEqual(run.results, [
227
+ { name: 'symlink .turbo', status: 'applied' },
228
+ { name: 'symlink .next/cache', status: 'applied' },
229
+ { name: 'symlink .parcel-cache', status: 'skipped', detail: '.parcel-cache not in main' },
230
+ { name: 'symlink .pytest_cache', status: 'skipped', detail: '.pytest_cache not in main' },
231
+ { name: 'symlink .ruff_cache', status: 'skipped', detail: '.ruff_cache not in main' },
232
+ { name: 'symlink .agents', status: 'skipped', detail: '.agents not in main' },
233
+ { name: 'symlink .atl', status: 'skipped', detail: '.atl not in main' },
234
+ { name: 'symlink .claude', status: 'skipped', detail: '.claude not in main' },
235
+ { name: 'symlink odd', status: 'skipped', detail: 'odd not in main' },
236
+ ]);
237
+ assert.equal(run.summary, 'hooks: 2 applied, 7 skipped');
238
+ });
239
+
240
+ test('S19: local asset directories are linked only when main has them untracked', async (t) => {
241
+ const fixture = hooksFixture(t, {
242
+ tracked: { '.gitignore': '.claude\n.agents\n', '.atl/note.md': 'tracked\n' },
243
+ directories: ['.claude/skills', '.agents/notes'],
244
+ });
245
+ const run = await fixture.run({ hooks: [symlinksHook] });
246
+
247
+ assert.ok(lstatSync(join(fixture.worktree, '.claude')).isSymbolicLink(), '.claude is linked');
248
+ assert.ok(lstatSync(join(fixture.worktree, '.agents')).isSymbolicLink(), '.agents is linked');
249
+ assert.equal(lstatSync(join(fixture.worktree, '.atl')).isSymbolicLink(), false, '.atl is tracked, so it arrives with the checkout');
250
+ assert.equal(existsSync(join(fixture.worktree, 'odd')), false);
251
+ assert.deepEqual(
252
+ run.results.filter((result) => result.status === 'applied').map((result) => result.name),
253
+ ['symlink .agents', 'symlink .claude'],
254
+ );
255
+ assert.deepEqual(
256
+ run.results.filter((result) => result.status === 'skipped' && result.detail === 'tracked').map((result) => result.name),
257
+ ['symlink .atl'],
258
+ );
259
+ assert.deepEqual(run.results.at(-1), { name: 'symlink odd', status: 'skipped', detail: 'odd not in main' });
260
+ });
261
+
262
+ test('S19: the .env family is copied, never read, and never linked', async (t) => {
263
+ const fixture = hooksFixture(t, {
264
+ tracked: { '.env.example': 'EXAMPLE\n' },
265
+ files: { '.env.local': ENV_MARKER },
266
+ });
267
+ const run = await fixture.run({ hooks: [inputsHook] });
268
+
269
+ const copied = join(fixture.worktree, '.env.local');
270
+ assert.ok(existsSync(copied), '.env.local reached the worktree');
271
+ assert.equal(lstatSync(copied).isSymbolicLink(), false, 'an input is copied, never linked');
272
+ assert.equal(readFileSync(copied, 'utf8'), ENV_MARKER, 'the copy is byte-identical');
273
+ assert.equal(lstatSync(join(fixture.worktree, '.env.example')).isSymbolicLink(), false, 'a tracked input keeps its checkout copy');
274
+ assert.deepEqual(run.results, [
275
+ { name: 'copy .env.example', status: 'skipped', detail: 'tracked' },
276
+ { name: 'copy .env.local', status: 'applied', warning: '.env.local is not ignored; add .env.local to .gitignore' },
277
+ ]);
278
+ assert.equal(run.summary, 'hooks: 1 applied, 1 skipped, warning: .env.local is not ignored; add .env.local to .gitignore');
279
+ });
280
+
281
+ test('S19: a path package managers own is never linked, whatever main holds', async (t) => {
282
+ const fixture = hooksFixture(t, {
283
+ tracked: { '.gitignore': 'node_modules/\nvendor/\n.venv/\ntarget/\ndeps/\n.pi/gentle-ai/\n.gentle-ai/\n' },
284
+ directories: ['node_modules/pkg', 'vendor/gem', '.venv/lib', 'target/debug', 'deps/cache', '.pi/gentle-ai/x', '.gentle-ai/y'],
285
+ });
286
+ const run = await fixture.run({ hooks: [symlinksHook] });
287
+
288
+ for (const rel of ['node_modules', 'vendor', '.venv', 'target', 'deps', '.pi/gentle-ai', '.gentle-ai']) {
289
+ assert.equal(existsSync(join(fixture.worktree, rel)), false, `${rel} is never linked`);
290
+ }
291
+ assert.equal(run.results.filter((result) => result.status === 'applied').length, 0, 'the 7 forbidden directories are not candidates at all');
292
+ });
293
+
294
+ test('S19: an untracked path .gitignore does not silence is still linked, with a warning', async (t) => {
295
+ const fixture = hooksFixture(t, { directories: ['.agents/notes'] });
296
+ const run = await fixture.run({ hooks: [symlinksHook] });
297
+
298
+ assert.ok(lstatSync(join(fixture.worktree, '.agents')).isSymbolicLink(), 'the directory is still linked');
299
+ assert.deepEqual(run.results[5], {
300
+ name: 'symlink .agents',
301
+ status: 'applied',
302
+ warning: '.agents is not ignored; add .agents to .gitignore',
303
+ });
304
+ assert.equal(run.summary, 'hooks: 1 applied, 8 skipped, warning: .agents is not ignored; add .agents to .gitignore');
305
+ });
306
+
307
+ test('S19: a failing hook is reported and the chain keeps going', async (t) => {
308
+ const fixture = hooksFixture(t, {
309
+ tracked: { '.gitignore': '.turbo\n.next/cache\n' },
310
+ directories: ['.turbo/cache', '.next/cache/build'],
311
+ });
312
+ const run = await fixture.run({
313
+ seams: {
314
+ async symlink(target, path, type) {
315
+ if (path.endsWith('.turbo')) throw new Error('EPERM: operation not permitted');
316
+ await symlink(target, path, type);
317
+ },
318
+ },
319
+ });
320
+
321
+ const turbo = run.results.find((result) => result.name === 'symlink .turbo');
322
+ assert.deepEqual(turbo, { name: 'symlink .turbo', status: 'failed', detail: 'could not link .turbo: EPERM: operation not permitted' });
323
+ assert.ok(lstatSync(join(fixture.worktree, '.next/cache')).isSymbolicLink(), 'the next hook still ran');
324
+ assert.equal(existsSync(join(fixture.worktree, '.turbo')), false, 'a failed link is never replaced by a copy');
325
+ assert.ok(existsSync(join(fixture.worktree, 'tracked.txt')), 'the worktree is still usable');
326
+ assert.equal(fixture.git(fixture.worktree, ['status', '--porcelain']).trim(), '', 'the failed hook left no partial state');
327
+ assert.equal(run.summary, 'hooks: 1 applied, 9 skipped, 1 failed: symlink .turbo (could not link .turbo: EPERM: operation not permitted)');
328
+ });
329
+
330
+ test('S19: a link the platform refuses falls back to a junction, and never to a copy', async () => {
331
+ const world = fakeWorld({ directories: ['.turbo'], ignored: ['.turbo'], fails: { dir: 'EPERM: operation not permitted' } });
332
+ const run = await runWorktreeHooks({
333
+ mainRoot: world.mainRoot,
334
+ path: world.worktree,
335
+ odd: 'worktree-tools',
336
+ seams: world.seams,
337
+ configPath: '/main/.git/gentle-ai/worktree-hooks.json',
338
+ hooks: [symlinksHook],
339
+ });
340
+
341
+ assert.deepEqual(run.results[0], { name: 'symlink .turbo', status: 'applied', detail: 'junction' });
342
+ assert.deepEqual(world.links, [{ target: '/main/.turbo', path: '/worktree/.turbo', type: 'junction' }]);
343
+ assert.deepEqual(world.copies, [], 'a refused link is never silently copied');
344
+ });
345
+
346
+ test('S19: on Windows the junction is the first attempt', async () => {
347
+ const world = fakeWorld({ platform: 'win32', directories: ['.turbo'], ignored: ['.turbo'] });
348
+ const run = await runWorktreeHooks({
349
+ mainRoot: world.mainRoot,
350
+ path: world.worktree,
351
+ odd: 'worktree-tools',
352
+ seams: world.seams,
353
+ configPath: '/main/.git/gentle-ai/worktree-hooks.json',
354
+ hooks: [symlinksHook],
355
+ });
356
+
357
+ assert.deepEqual(run.results[0], { name: 'symlink .turbo', status: 'applied', detail: 'junction' });
358
+ assert.deepEqual(world.links.map((link) => link.type), ['junction'], 'Windows prefers the junction that needs no privilege');
359
+ });
360
+
361
+ test('S19: a link refused twice is reported as failed, never replaced by a copy', async () => {
362
+ const world = fakeWorld({
363
+ platform: 'win32',
364
+ directories: ['.turbo'],
365
+ ignored: ['.turbo'],
366
+ fails: { dir: 'EPERM: symlink refused', junction: 'EPERM: junction refused' },
367
+ });
368
+ const run = await runWorktreeHooks({
369
+ mainRoot: world.mainRoot,
370
+ path: world.worktree,
371
+ odd: 'worktree-tools',
372
+ seams: world.seams,
373
+ configPath: '/main/.git/gentle-ai/worktree-hooks.json',
374
+ hooks: [symlinksHook],
375
+ });
376
+
377
+ assert.deepEqual(run.results[0], { name: 'symlink .turbo', status: 'failed', detail: 'could not link .turbo: EPERM: junction refused' });
378
+ assert.deepEqual(world.links, []);
379
+ assert.deepEqual(world.copies, [], 'the failure is reported instead of a copy that pretends to be a link');
380
+ assert.equal(run.summary, 'hooks: 8 skipped, 1 failed: symlink .turbo (could not link .turbo: EPERM: junction refused)');
381
+ });
382
+
383
+ // ---- S20: the local configuration ----
384
+
385
+ test('S20: the local file extends the copy and link lists and enables setup', async (t) => {
386
+ const fixture = hooksFixture(t, {
387
+ files: { 'config/local.json': '{}\n' },
388
+ directories: ['.cache/data'],
389
+ });
390
+ writeLocalHooks(fixture, { version: 1, copy: ['config/local.json'], link: ['.cache'], setup: true });
391
+ const run = await fixture.run();
392
+
393
+ assert.deepEqual(run.config, { copy: ['config/local.json'], link: ['.cache'], setup: true });
394
+ assert.ok(existsSync(join(fixture.worktree, 'config/local.json')), 'the configured input was copied');
395
+ assert.ok(lstatSync(join(fixture.worktree, '.cache')).isSymbolicLink(), 'the configured directory was linked');
396
+ assert.deepEqual(
397
+ run.results.filter((result) => result.status === 'applied').map((result) => result.name),
398
+ ['copy config/local.json', 'symlink .cache'],
399
+ );
400
+ assert.deepEqual(
401
+ [run.results[1]?.warning, run.results.at(-1)?.warning],
402
+ ['config/local.json is not ignored; add config/local.json to .gitignore', '.cache is not ignored; add .cache to .gitignore'],
403
+ );
404
+ assert.deepEqual(run.results.find((result) => result.name === 'submodules'), {
405
+ name: 'submodules',
406
+ status: 'skipped',
407
+ detail: 'no submodules',
408
+ });
409
+ });
410
+
411
+ test('S20: entries that would leave the worktree or cross the never-linked list are refused', async (t) => {
412
+ assert.deepEqual(parseWorktreeHooksConfig('{"version":1,"link":["node_modules","../escape","/absolute",".cache"]}'), {
413
+ copy: [],
414
+ link: ['node_modules', '.cache'],
415
+ setup: false,
416
+ });
417
+ assert.deepEqual(parseWorktreeHooksConfig('{"copy":["../escape","node_modules/x"],"setup":"pnpm install"}'), {
418
+ copy: ['node_modules/x'],
419
+ link: [],
420
+ setup: false,
421
+ });
422
+ assert.deepEqual(parseWorktreeHooksConfig('not json at all'), { copy: [], link: [], setup: false }, 'an unreadable file keeps the defaults');
423
+ assert.deepEqual(parseWorktreeHooksConfig(undefined), { copy: [], link: [], setup: false }, 'an absent file keeps the defaults');
424
+
425
+ const fixture = hooksFixture(t, {
426
+ tracked: { '.gitignore': 'node_modules/\n' },
427
+ directories: ['node_modules/pkg'],
428
+ });
429
+ writeLocalHooks(fixture, { link: ['node_modules', '.pi/gentle-ai'], copy: ['../escape', 'node_modules/pkg'] });
430
+ const run = await fixture.run({ hooks: [symlinksHook, inputsHook] });
431
+
432
+ assert.equal(existsSync(join(fixture.worktree, 'node_modules')), false, 'a package-manager directory is never linked');
433
+ assert.equal(existsSync(join(fixture.fixture, 'escape')), false, 'an entry cannot reach outside the worktree');
434
+ assert.deepEqual(run.results.slice(9, 11), [
435
+ { name: 'symlink node_modules', status: 'skipped', detail: 'node_modules is never linked' },
436
+ { name: 'symlink .pi/gentle-ai', status: 'skipped', detail: '.pi/gentle-ai is never linked' },
437
+ ]);
438
+ assert.deepEqual(run.results.filter((result) => result.name.startsWith('copy ')), [
439
+ { name: 'copy node_modules/pkg', status: 'skipped', detail: 'node_modules/pkg is not a file' },
440
+ ]);
441
+ });
442
+
443
+ test('S20: commands in any versioned repository file are never executed', async (t) => {
444
+ const command = `node -e "require('node:fs').writeFileSync('pwned','1')"`;
445
+ const fixture = hooksFixture(t, {
446
+ tracked: {
447
+ 'worktree-hooks.json': JSON.stringify({ copy: ['config/versioned.json'], commands: [command] }),
448
+ '.gentle-ai/worktree-hooks.json': JSON.stringify({ link: ['.cache-assets'], commands: [command] }),
449
+ },
450
+ files: { 'config/versioned.json': '{}\n' },
451
+ directories: ['.cache-assets/data'],
452
+ });
453
+ const versioned = await fixture.run({ hooks: [inputsHook, symlinksHook] });
454
+
455
+ assert.ok(!existsSync(join(fixture.worktree, 'config/versioned.json')), 'a versioned copy list is never read');
456
+ assert.equal(existsSync(join(fixture.worktree, '.cache-assets')), false, 'a versioned link list is never read');
457
+ assert.deepEqual(versioned.config, { copy: [], link: [], setup: false });
458
+ assert.equal(existsSync(join(fixture.fixture, 'pwned')), false);
459
+
460
+ writeLocalHooks(fixture, { version: 1, copy: [], commands: [command], setup: true });
461
+ const local = await fixture.run({ hooks: [inputsHook, symlinksHook] });
462
+
463
+ assert.deepEqual(local.config, { copy: [], link: [], setup: true }, 'only the boolean setup flag is read, never a command');
464
+ assert.equal(existsSync(join(fixture.fixture, 'pwned')), false, 'a command in the local file is never executed');
465
+ assert.ok(
466
+ local.gitCalls.every((call) => call.args[0] === 'ls-files' || call.args[0] === 'check-ignore'),
467
+ "the chain runs no command but Git's own queries",
468
+ );
469
+ });
470
+
471
+ // ---- S18: copy_changes ----
472
+
473
+ test('S18: true copies the staged, unstaged and untracked changes and counts files', async (t) => {
474
+ const fixture = hooksFixture(t, {
475
+ tracked: { '.gitignore': 'ignored.log\n', 'modified.txt': 'base\n' },
476
+ staged: { 'added.txt': 'added\n' },
477
+ unstaged: { 'modified.txt': 'changed\n' },
478
+ files: { 'ignored.log': 'ignored\n', 'untracked.txt': 'untracked\n' },
479
+ });
480
+ const run = await fixture.run({ copyChanges: true });
481
+
482
+ assert.equal(readFileSync(join(fixture.worktree, 'modified.txt'), 'utf8'), 'changed\n', 'an unstaged edit reaches the worktree');
483
+ assert.equal(readFileSync(join(fixture.worktree, 'added.txt'), 'utf8'), 'added\n', 'a staged addition reaches the worktree');
484
+ assert.equal(readFileSync(join(fixture.worktree, 'untracked.txt'), 'utf8'), 'untracked\n', 'an untracked file is copied');
485
+ assert.equal(existsSync(join(fixture.worktree, 'ignored.log')), false, 'an ignored file is never copied');
486
+ assert.deepEqual(
487
+ fixture
488
+ .git(fixture.worktree, ['status', '--porcelain'])
489
+ .trim()
490
+ .split('\n')
491
+ .map((line) => line.slice(3))
492
+ .sort(),
493
+ ['added.txt', 'modified.txt', 'untracked.txt'],
494
+ 'exactly the copied paths changed in the worktree',
495
+ );
496
+
497
+ assert.equal(readFileSync(join(fixture.main, 'modified.txt'), 'utf8'), 'changed\n', 'main keeps its unstaged edit');
498
+ assert.deepEqual(
499
+ fixture
500
+ .git(fixture.main, ['status', '--porcelain'])
501
+ .trimEnd()
502
+ .split('\n')
503
+ .map((line) => line.slice(3))
504
+ .sort(),
505
+ ['added.txt', 'modified.txt', 'untracked.txt'],
506
+ 'main keeps every uncommitted change; the ignored file is not one Git reports',
507
+ );
508
+
509
+ assert.deepEqual(run.results.find((result) => result.name === 'copy_changes'), {
510
+ name: 'copy_changes',
511
+ status: 'applied',
512
+ copyChanges: { copied: 3, failed: [] },
513
+ });
514
+ assert.equal(worktreeCopyChangesLine(run.results), 'copy_changes: 3 changes copied');
515
+ assert.equal(run.summary, 'hooks: 1 applied, 11 skipped', 'the step is part of the one hooks summary');
516
+ assert.ok(
517
+ run.gitCalls.some((call) => call.cwd === fixture.main && call.args.join(' ') === 'diff --name-only --no-renames -z HEAD'),
518
+ 'the changed paths come from Git, never from a directory walk',
519
+ );
520
+ assert.ok(
521
+ run.gitCalls.some((call) => call.cwd === fixture.main && call.args[0] === 'diff' && call.args.includes('--binary')),
522
+ 'the patch is the binary diff of HEAD against both the index and the worktree',
523
+ );
524
+ assert.ok(
525
+ run.gitCalls.some((call) => call.cwd === fixture.worktree && call.args[0] === 'apply' && call.args.includes('--3way')),
526
+ 'the patch is applied in the new worktree with --3way',
527
+ );
528
+ });
529
+
530
+ test('S18: the delta is read from the asking checkout, never from main', async (t) => {
531
+ const fixture = hooksFixture(t, { tracked: { 'shared.txt': 'base\n' }, files: { 'main-only.txt': 'main\n' } });
532
+ fixture.git(fixture.main, ['worktree', 'add', '-b', 'feat/destination', join(fixture.fixture, 'repo-worktrees', 'destination')]);
533
+ const destination = realpathSync(join(fixture.fixture, 'repo-worktrees', 'destination'));
534
+ writeFileSync(join(fixture.worktree, 'asking-only.txt'), 'asking\n');
535
+ writeFileSync(join(fixture.worktree, 'shared.txt'), 'asking edit\n');
536
+
537
+ const run = await fixture.run({
538
+ copyChanges: true,
539
+ changesRoot: fixture.worktree,
540
+ path: destination,
541
+ hooks: [copyChangesHook],
542
+ });
543
+
544
+ assert.equal(readFileSync(join(destination, 'asking-only.txt'), 'utf8'), 'asking\n', "the asking checkout's untracked file travels");
545
+ assert.equal(readFileSync(join(destination, 'shared.txt'), 'utf8'), 'asking edit\n', "the asking checkout's edit travels");
546
+ assert.equal(existsSync(join(destination, 'main-only.txt')), false, "main's uncommitted file stays behind");
547
+ assert.deepEqual(run.results, [{ name: 'copy_changes', status: 'applied', copyChanges: { copied: 2, failed: [] } }]);
548
+ assert.equal(readFileSync(join(fixture.worktree, 'asking-only.txt'), 'utf8'), 'asking\n', 'the asking checkout keeps its own change');
549
+ assert.equal(readFileSync(join(fixture.main, 'main-only.txt'), 'utf8'), 'main\n', 'main keeps its own change');
550
+ assert.ok(
551
+ run.gitCalls.some((call) => call.cwd === fixture.worktree && call.args.join(' ') === 'diff --name-only --no-renames -z HEAD'),
552
+ 'the changed paths are read in the asking checkout',
553
+ );
554
+ assert.ok(
555
+ run.gitCalls.some((call) => call.cwd === fixture.worktree && call.args[0] === 'diff' && call.args.includes('--binary')),
556
+ 'the patch is read in the asking checkout',
557
+ );
558
+ assert.ok(
559
+ run.gitCalls.some((call) => call.cwd === destination && call.args[0] === 'apply'),
560
+ 'the patch still lands in the new worktree',
561
+ );
562
+ });
563
+
564
+ test("S18: a staged rename copies its deletion and its addition", async (t) => {
565
+ const fixture = hooksFixture(t, { tracked: { 'old.txt': 'content\n' } });
566
+ fixture.git(fixture.main, ['mv', 'old.txt', 'new.txt']);
567
+ const run = await fixture.run({ copyChanges: true, hooks: [copyChangesHook] });
568
+
569
+ assert.equal(existsSync(join(fixture.worktree, 'old.txt')), false, "the rename's deletion reaches the worktree");
570
+ assert.equal(readFileSync(join(fixture.worktree, 'new.txt'), 'utf8'), 'content\n', "the rename's addition reaches the worktree");
571
+ assert.deepEqual(run.results, [{ name: 'copy_changes', status: 'applied', copyChanges: { copied: 2, failed: [] } }]);
572
+ assert.equal(worktreeCopyChangesLine(run.results), 'copy_changes: 2 changes copied');
573
+ });
574
+
575
+ test('S18: an omitted or false copy_changes copies nothing and prints nothing', async (t) => {
576
+ const fixture = hooksFixture(t, {
577
+ tracked: { 'modified.txt': 'base\n' },
578
+ unstaged: { 'modified.txt': 'changed\n' },
579
+ files: { 'untracked.txt': 'untracked\n' },
580
+ });
581
+ for (const copyChanges of [undefined, false]) {
582
+ const run = await fixture.run(copyChanges === undefined ? {} : { copyChanges });
583
+ assert.equal(run.results.some((result) => result.name === 'copy_changes'), false, 'the step reports nothing when it was not requested');
584
+ assert.equal(worktreeCopyChangesLine(run.results), undefined, 'there is no line to print');
585
+ assert.equal(readFileSync(join(fixture.worktree, 'modified.txt'), 'utf8'), 'base\n', 'the worktree keeps its checkout copy');
586
+ assert.equal(existsSync(join(fixture.worktree, 'untracked.txt')), false, 'no untracked file was carried over');
587
+ }
588
+ });
589
+
590
+ test('S18: true with no uncommitted changes is not an error', async (t) => {
591
+ const fixture = hooksFixture(t);
592
+ const run = await fixture.run({ copyChanges: true });
593
+
594
+ assert.deepEqual(run.results.find((result) => result.name === 'copy_changes'), {
595
+ name: 'copy_changes',
596
+ status: 'skipped',
597
+ detail: 'no uncommitted changes',
598
+ copyChanges: { copied: 0, failed: [] },
599
+ });
600
+ assert.equal(worktreeCopyChangesLine(run.results), 'copy_changes: no uncommitted changes to copy');
601
+ assert.equal(fixture.git(fixture.worktree, ['status', '--porcelain']).trim(), '', 'the worktree stays clean');
602
+ });
603
+
604
+ test('S18: a conflicting change reports its paths and leaves the worktree clean', async (t) => {
605
+ const fixture = hooksFixture(t, { tracked: { 'clean.txt': 'base\n', 'conflict.txt': 'base\n' } });
606
+ writeFileSync(join(fixture.worktree, 'conflict.txt'), 'branch\n');
607
+ fixture.git(fixture.worktree, ['commit', '-am', 'Branch edit']);
608
+ writeFileSync(join(fixture.main, 'clean.txt'), 'main clean\n');
609
+ writeFileSync(join(fixture.main, 'conflict.txt'), 'main\n');
610
+ const run = await fixture.run({ copyChanges: true, hooks: [copyChangesHook] });
611
+
612
+ assert.deepEqual(run.results, [
613
+ {
614
+ name: 'copy_changes',
615
+ status: 'failed',
616
+ detail: 'could not copy: conflict.txt',
617
+ copyChanges: { copied: 1, failed: ['conflict.txt'] },
618
+ },
619
+ ]);
620
+ assert.equal(
621
+ worktreeCopyChangesLine(run.results),
622
+ 'copy_changes: 1 changes copied; failed: conflict.txt',
623
+ );
624
+ assert.equal(run.summary, 'hooks: 1 failed: copy_changes (could not copy: conflict.txt)');
625
+ assert.equal(readFileSync(join(fixture.worktree, 'conflict.txt'), 'utf8'), 'branch\n', "the conflicted path keeps the branch's content");
626
+ assert.equal(readFileSync(join(fixture.worktree, 'clean.txt'), 'utf8'), 'main clean\n', 'the clean change still landed');
627
+ assert.equal(fixture.git(fixture.worktree, ['status', '--porcelain']).trimEnd(), ' M clean.txt', 'no conflict state survives in the worktree');
628
+ assert.equal(readFileSync(join(fixture.main, 'conflict.txt'), 'utf8'), 'main\n', 'main is untouched by the failure');
629
+ assert.ok(existsSync(join(fixture.worktree, 'tracked.txt')), 'the worktree is still usable');
630
+ });
631
+
632
+ // ---- The branches the fixed lists and the pure helpers decide ----
633
+
634
+ /** A seam set that answers nothing; each case overrides exactly what it exercises. */
635
+ function seamWorld(overrides = {}) {
636
+ return {
637
+ async git() {
638
+ return { code: 0, stdout: '' };
639
+ },
640
+ async kind() {
641
+ return undefined;
642
+ },
643
+ async readdir() {
644
+ return [];
645
+ },
646
+ async readText() {
647
+ return undefined;
648
+ },
649
+ async copyFile() {},
650
+ async mkdir() {},
651
+ async symlink() {},
652
+ platform: 'linux',
653
+ ...overrides,
654
+ };
655
+ }
656
+
657
+ function runSeams(seams, hooks, extra = {}) {
658
+ return runWorktreeHooks({
659
+ mainRoot: '/main',
660
+ path: '/worktree',
661
+ odd: 'worktree-tools',
662
+ seams,
663
+ configPath: '/main/.git/gentle-ai/worktree-hooks.json',
664
+ hooks,
665
+ ...extra,
666
+ });
667
+ }
668
+
669
+ test('S19/S20: the fixed lists are the ones the contract names', () => {
670
+ assert.equal(WORKTREE_HOOKS_FILENAME, 'worktree-hooks.json');
671
+ assert.equal(worktreeHooksFilePath('/clone/.git'), '/clone/.git/gentle-ai/worktree-hooks.json');
672
+ assert.deepEqual(WORKTREE_NEVER_LINKED, ['node_modules', 'vendor', '.venv', 'target', 'deps', '.pi/gentle-ai', '.gentle-ai']);
673
+ assert.deepEqual(WORKTREE_BUILD_CACHE_LINKS, ['.turbo', '.next/cache', '.parcel-cache', '.pytest_cache', '.ruff_cache']);
674
+ assert.deepEqual(WORKTREE_ASSET_LINKS, ['.agents', '.atl', '.claude', 'odd']);
675
+ assert.equal(WORKTREE_INPUT_PREFIX, '.env');
676
+ assert.deepEqual(emptyWorktreeHooksConfig(), { copy: [], link: [], setup: false });
677
+ });
678
+
679
+ test('S20: the parser refuses an array, a control character and duplicates, and normalises a trailing slash', () => {
680
+ assert.deepEqual(parseWorktreeHooksConfig('[]'), { copy: [], link: [], setup: false }, 'an array is not a configuration');
681
+ assert.deepEqual(parseWorktreeHooksConfig('null'), { copy: [], link: [], setup: false });
682
+ assert.deepEqual(parseWorktreeHooksConfig('{"copy":["a\\u0000b"]}'), { copy: [], link: [], setup: false }, 'a control character is refused');
683
+ assert.deepEqual(parseWorktreeHooksConfig('{"link":[".cache/",".cache","./x","../y","/z"]}'), {
684
+ copy: [],
685
+ link: ['.cache'],
686
+ setup: false,
687
+ });
688
+ });
689
+
690
+ test('S19: submodules are updated when main has .gitmodules, and a refused update is reported', async () => {
691
+ const calls = [];
692
+ const applied = await runSeams(
693
+ seamWorld({
694
+ async kind(path) {
695
+ return path === '/main/.gitmodules' ? 'file' : undefined;
696
+ },
697
+ async git(cwd, args) {
698
+ calls.push({ cwd, args });
699
+ return { code: 0, stdout: '' };
700
+ },
701
+ }),
702
+ [submodulesHook],
703
+ );
704
+ assert.deepEqual(applied.results, [{ name: 'submodules', status: 'applied' }]);
705
+ assert.deepEqual(calls, [{ cwd: '/worktree', args: ['submodule', 'update', '--init', '--recursive'] }]);
706
+
707
+ const withGitmodules = (result) =>
708
+ seamWorld({
709
+ async kind(path) {
710
+ return path === '/main/.gitmodules' ? 'file' : undefined;
711
+ },
712
+ async git() {
713
+ return result;
714
+ },
715
+ });
716
+ const refused = await runSeams(withGitmodules({ code: 1, stdout: '' }), [submodulesHook]);
717
+ assert.deepEqual(refused.results, [
718
+ { name: 'submodules', status: 'failed', detail: 'git submodule update --init --recursive exited 1' },
719
+ ]);
720
+ const silent = await runSeams(withGitmodules(undefined), [submodulesHook]);
721
+ assert.deepEqual(silent.results, [
722
+ { name: 'submodules', status: 'failed', detail: 'git submodule update --init --recursive exited without a result' },
723
+ ]);
724
+ });
725
+
726
+ test('S19: the inputs step reports an empty main, a path already in the worktree and a refused copy', async () => {
727
+ const none = await runSeams(seamWorld(), [inputsHook]);
728
+ assert.deepEqual(none.results, [{ name: 'inputs', status: 'skipped', detail: 'no .env files in main' }]);
729
+ assert.equal(none.summary, undefined, 'a step that skipped and applied nothing prints no summary');
730
+
731
+ const existing = await runSeams(
732
+ seamWorld({
733
+ async readdir() {
734
+ return ['.env.local'];
735
+ },
736
+ async kind(path) {
737
+ return path === '/main/.env.local' || path === '/worktree/.env.local' ? 'file' : undefined;
738
+ },
739
+ async git() {
740
+ return { code: 1, stdout: '' };
741
+ },
742
+ }),
743
+ [inputsHook],
744
+ );
745
+ assert.deepEqual(existing.results, [
746
+ { name: 'copy .env.local', status: 'skipped', detail: '.env.local already exists in the worktree' },
747
+ ]);
748
+
749
+ const refused = await runSeams(
750
+ seamWorld({
751
+ async readdir() {
752
+ return ['.env.local'];
753
+ },
754
+ async kind(path) {
755
+ return path === '/main/.env.local' ? 'file' : undefined;
756
+ },
757
+ async git() {
758
+ return { code: 1, stdout: '' };
759
+ },
760
+ async copyFile() {
761
+ throw new Error('EACCES: permission denied');
762
+ },
763
+ }),
764
+ [inputsHook],
765
+ );
766
+ assert.deepEqual(refused.results, [
767
+ { name: 'copy .env.local', status: 'failed', detail: 'could not copy .env.local: EACCES: permission denied' },
768
+ ]);
769
+ });
770
+
771
+ test('S18: an unreadable change list and an unreadable administrative directory are failures', async () => {
772
+ const unreadable = await runSeams(seamWorld({ async git() { return undefined; } }), [copyChangesHook], { copyChanges: true });
773
+ assert.deepEqual(unreadable.results, [{ name: 'copy_changes', status: 'failed', detail: 'could not read the uncommitted changes' }]);
774
+ assert.equal(worktreeCopyChangesLine(unreadable.results), 'copy_changes: could not read the uncommitted changes');
775
+
776
+ const noAdminDir = await runSeams(
777
+ seamWorld({
778
+ async git(_cwd, args) {
779
+ if (args[0] === 'diff') return { code: 0, stdout: 'a.txt\0' };
780
+ if (args[0] === 'ls-files') return { code: 0, stdout: '' };
781
+ return { code: 1, stdout: '' };
782
+ },
783
+ }),
784
+ [copyChangesHook],
785
+ { copyChanges: true },
786
+ );
787
+ assert.deepEqual(noAdminDir.results, [
788
+ {
789
+ name: 'copy_changes',
790
+ status: 'failed',
791
+ detail: "could not read the worktree's administrative directory",
792
+ copyChanges: { copied: 0, failed: ['a.txt'] },
793
+ },
794
+ ]);
795
+ });
796
+
797
+ test('S18: an untracked path already in the worktree is left alone, and a refused copy is reported', async () => {
798
+ const untrackedWorld = (path, destinationKind, copyFile) =>
799
+ seamWorld({
800
+ async git(_cwd, args) {
801
+ if (args[0] === 'diff') return { code: 0, stdout: '' };
802
+ if (args[0] === 'ls-files') return { code: 0, stdout: `${path}\0` };
803
+ if (args[0] === 'rev-parse') return { code: 0, stdout: '/admin' };
804
+ return { code: 1, stdout: '' };
805
+ },
806
+ async kind(candidate) {
807
+ return candidate === `/worktree/${path}` ? destinationKind : undefined;
808
+ },
809
+ copyFile,
810
+ });
811
+
812
+ const present = await runSeams(
813
+ untrackedWorld('present.txt', 'file', async () => {
814
+ throw new Error('a present path is never copied');
815
+ }),
816
+ [copyChangesHook],
817
+ { copyChanges: true },
818
+ );
819
+ assert.deepEqual(present.results, [{ name: 'copy_changes', status: 'applied', copyChanges: { copied: 0, failed: [] } }]);
820
+ assert.equal(worktreeCopyChangesLine(present.results), 'copy_changes: no uncommitted changes to copy');
821
+
822
+ const refused = await runSeams(
823
+ untrackedWorld('blocked.txt', undefined, async () => {
824
+ throw new Error('EACCES: permission denied');
825
+ }),
826
+ [copyChangesHook],
827
+ { copyChanges: true },
828
+ );
829
+ assert.deepEqual(refused.results, [
830
+ { name: 'copy_changes', status: 'failed', detail: 'could not copy: blocked.txt', copyChanges: { copied: 0, failed: ['blocked.txt'] } },
831
+ ]);
832
+ });
833
+
834
+ test('S19: an existing path in the worktree is skipped, never overwritten', async () => {
835
+ const run = await runSeams(
836
+ seamWorld({
837
+ async kind(path) {
838
+ if (path === '/main/.agents') return 'directory';
839
+ if (path === '/worktree/.agents') return 'symlink';
840
+ return undefined;
841
+ },
842
+ async git() {
843
+ return { code: 1, stdout: '' };
844
+ },
845
+ }),
846
+ [symlinksHook],
847
+ );
848
+ assert.deepEqual(run.results[5], { name: 'symlink .agents', status: 'skipped', detail: '.agents already exists in the worktree' });
849
+ });
850
+
851
+ test('S19: a hook that throws is recorded under its own name and the chain keeps going', async () => {
852
+ const run = await runSeams(seamWorld(), [
853
+ {
854
+ name: 'explode',
855
+ async run() {
856
+ throw new Error('kaboom');
857
+ },
858
+ },
859
+ submodulesHook,
860
+ ]);
861
+
862
+ assert.deepEqual(run.results, [
863
+ { name: 'explode', status: 'failed', detail: 'kaboom' },
864
+ { name: 'submodules', status: 'skipped', detail: 'no submodules' },
865
+ ]);
866
+ assert.equal(run.summary, 'hooks: 1 skipped, 1 failed: explode (kaboom)');
867
+ });
868
+
869
+ // ---- S16 and S7: what the create flow stores and prints ----
870
+
871
+ test('S19: the stored records carry the hook name, status and reason', () => {
872
+ assert.deepEqual(
873
+ worktreeHookRecords([
874
+ { name: 'symlink .turbo', status: 'applied', warning: '.turbo is not ignored; add .turbo to .gitignore' },
875
+ { name: 'submodules', status: 'skipped', detail: 'no submodules' },
876
+ ]),
877
+ [
878
+ { name: 'symlink .turbo', status: 'applied', detail: '.turbo is not ignored; add .turbo to .gitignore' },
879
+ { name: 'submodules', status: 'skipped', detail: 'no submodules' },
880
+ ],
881
+ );
882
+ assert.deepEqual(worktreeHookRecords([{ name: 'symlink .atl', status: 'applied' }]), [{ name: 'symlink .atl', status: 'applied' }]);
883
+ });
884
+
885
+ test('S16: the hooks summary is absent when nothing applied and nothing failed', () => {
886
+ assert.equal(worktreeHooksSummary([]), undefined);
887
+ assert.equal(worktreeHooksSummary([{ name: 'submodules', status: 'skipped', detail: 'no submodules' }]), undefined);
888
+ assert.equal(
889
+ worktreeHooksSummary([
890
+ { name: 'a', status: 'applied' },
891
+ { name: 'b', status: 'skipped', detail: 'tracked' },
892
+ ]),
893
+ 'hooks: 1 applied, 1 skipped',
894
+ );
895
+ assert.equal(
896
+ worktreeHooksSummary([
897
+ { name: 'copy .env.local', status: 'applied', warning: '.env.local is not ignored; add .env.local to .gitignore' },
898
+ { name: 'symlink .turbo', status: 'failed', detail: 'EPERM' },
899
+ { name: 'submodules', status: 'skipped', detail: 'no submodules' },
900
+ ]),
901
+ 'hooks: 1 applied, 1 skipped, 1 failed: symlink .turbo (EPERM), warning: .env.local is not ignored; add .env.local to .gitignore',
902
+ );
903
+ assert.equal(worktreeHooksSummary([{ name: 'symlink .turbo', status: 'failed', detail: 'EPERM' }]), 'hooks: 1 failed: symlink .turbo (EPERM)');
904
+ assert.equal(worktreeHooksSummary([{ name: 'explode', status: 'failed' }]), 'hooks: 1 failed: explode (no reason)');
905
+ });