pi-odd-worktree 2.0.0 → 3.0.0

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 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -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 +1416 -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 +308 -14
  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 -711
  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 +1419 -0
  75. package/tools/bash-design.test.js +1091 -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 +610 -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 +1871 -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 +391 -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 +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -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 +2569 -308
  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 +477 -93
  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,318 @@
1
+ 'use strict';
2
+ // S6/T9b: a removal uses `git worktree remove` and NOTHING else. The module is
3
+ // `lib/worktree-remove.js`, so the suite is named after the removal it covers;
4
+ // the cases below drive the extension's own close (the seam the warp panel's
5
+ // ctrl+d calls — the `worktree_delete` tool that used to wrap it is unregistered,
6
+ // T6/S4).
7
+ //
8
+ // What is pinned here, with teeth:
9
+ // - the removal argv is git's, fixed, absolute, with `--force` only when the
10
+ // caller asked for it, and a relative target is refused before any child;
11
+ // - a real close spawns `git` and no other binary, exactly one
12
+ // `worktree remove <absolute target>` argv, with the caller's root and the
13
+ // helper's own timeout;
14
+ // - the removal is awaited, so the host event loop keeps turning while git
15
+ // runs (a blocking spawn would fail the argv assertions above as well);
16
+ // - a failing git leaves the checkout AND the branch in place and reports
17
+ // git's own refusal to the caller;
18
+ // - the helper itself never throws and never loses the backend's reason.
19
+
20
+ const { test, describe, before, after } = require('node:test');
21
+ const assert = require('node:assert/strict');
22
+ const fs = require('node:fs');
23
+ const os = require('node:os');
24
+ const path = require('node:path');
25
+ const { spawnSync } = require('node:child_process');
26
+ const { pathToFileURL } = require('node:url');
27
+ const { LIB_DIR, loadExtension, stubbedSource } = require('./fixtures/load-extension.js');
28
+
29
+ const lib = require('../lib/worktree-remove.js');
30
+
31
+ const TARGET = '/tmp/repo-worktrees/feat-doomed';
32
+ const PRINCIPAL = '/tmp/repo';
33
+
34
+ const roots = [];
35
+ after(() => {
36
+ for (const dir of roots) {
37
+ fs.rmSync(dir, { recursive: true, force: true });
38
+ }
39
+ });
40
+
41
+ function track(dir) {
42
+ roots.push(dir);
43
+ return dir;
44
+ }
45
+
46
+ describe('the removal argv is git\'s, fixed and absolute', () => {
47
+ test('the removal argv is git worktree remove with the absolute target', () => {
48
+ assert.deepEqual(lib.gitRemovalArgv(TARGET, false), ['worktree', 'remove', TARGET]);
49
+ assert.deepEqual(lib.gitRemovalArgv(TARGET, true), ['worktree', 'remove', '--force', TARGET]);
50
+ // Neither the branch nor `--trust-repository` is ever part of it.
51
+ assert.equal(lib.gitRemovalArgv(TARGET, true).includes('--force'), true);
52
+ assert.equal(lib.gitRemovalArgv(TARGET, true).length, 4);
53
+ assert.throws(() => lib.gitRemovalArgv('relative/path', false), TypeError);
54
+ });
55
+
56
+ test('the module exposes one remover and nothing that reconciles anything else', () => {
57
+ assert.deepEqual(Object.keys(lib).sort(), ['REMOVE_TIMEOUT_MS', 'gitRemovalArgv', 'removeCheckout']);
58
+ });
59
+ });
60
+
61
+ describe('removeCheckout asks one awaited git child', () => {
62
+ test('a removal asks git exactly once, with the caller root and timeout', async () => {
63
+ const calls = [];
64
+ const out = await lib.removeCheckout({
65
+ runAsync: async (bin, argv, options) => {
66
+ calls.push({ bin, argv, options });
67
+ return { status: 0, stdout: '', stderr: '' };
68
+ },
69
+ repoRoot: PRINCIPAL,
70
+ resolvedTarget: TARGET,
71
+ force: true,
72
+ });
73
+ assert.equal(calls.length, 1);
74
+ assert.equal(calls[0].bin, 'git');
75
+ assert.deepEqual(calls[0].argv, ['worktree', 'remove', '--force', TARGET]);
76
+ assert.equal(calls[0].options.cwd, PRINCIPAL);
77
+ assert.equal(calls[0].options.timeoutMs, lib.REMOVE_TIMEOUT_MS);
78
+ assert.deepEqual(out, { removed: true, removedBy: 'git' });
79
+ });
80
+
81
+ test('the backend reason travels back verbatim, and no failure ever throws', async () => {
82
+ const failed = await lib.removeCheckout({
83
+ runAsync: async () => ({ status: 1, stdout: '', stderr: "fatal: '/x' contains modified or untracked files\nsecond line\n" }),
84
+ repoRoot: PRINCIPAL,
85
+ resolvedTarget: TARGET,
86
+ force: false,
87
+ });
88
+ assert.equal(failed.removed, false);
89
+ assert.equal(failed.error, "fatal: '/x' contains modified or untracked files\nsecond line");
90
+
91
+ const noRunner = await lib.removeCheckout({ runAsync: null, repoRoot: PRINCIPAL, resolvedTarget: TARGET, force: false });
92
+ assert.equal(noRunner.removed, false);
93
+ assert.match(noRunner.error, /runner/);
94
+
95
+ const thrown = await lib.removeCheckout({
96
+ runAsync: () => { throw new Error('spawn exploded'); },
97
+ repoRoot: PRINCIPAL,
98
+ resolvedTarget: TARGET,
99
+ force: false,
100
+ });
101
+ assert.equal(thrown.removed, false);
102
+ assert.equal(thrown.error, 'spawn exploded');
103
+ });
104
+ });
105
+
106
+ describe('a real close removes with git alone', () => {
107
+ const savedEnv = { ...process.env };
108
+ const HOOK_BIN = track(fs.mkdtempSync(path.join(os.tmpdir(), 'wt-remove-hookbin-')));
109
+ const AGENT_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'wt-remove-agent-home-')));
110
+
111
+ let tools;
112
+ let mod;
113
+ before(async () => {
114
+ delete process.env.GENTLE_PI_AGENT_HOME;
115
+ process.env.PI_CODING_AGENT_DIR = AGENT_HOME;
116
+ process.env.PATH = `${HOOK_BIN}${path.delimiter}${savedEnv.PATH || ''}`;
117
+ // The refusal asserted below is git's OWN sentence, so the child's locale is
118
+ // pinned instead of matching a translation.
119
+ process.env.LC_ALL = 'C';
120
+ process.env.LANG = 'C';
121
+ ({ tools } = await loadExtension({}));
122
+ mod = await loadStubbedModule();
123
+ });
124
+
125
+ // The removal the panel's ctrl+d drives is an exported seam of the extension
126
+ // module, not a registered tool (T6/S4), so this file keeps that namespace
127
+ // beside the registrations: same stubs, same lib override, same copy.
128
+ async function loadStubbedModule() {
129
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
130
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-remove-mod-'));
131
+ try {
132
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
133
+ fs.writeFileSync(copy, stubbedSource());
134
+ return await import(pathToFileURL(copy).href);
135
+ } finally {
136
+ fs.rmSync(dir, { recursive: true, force: true });
137
+ }
138
+ }
139
+
140
+ after(() => {
141
+ for (const key of Object.keys(process.env)) {
142
+ if (!(key in savedEnv)) delete process.env[key];
143
+ }
144
+ for (const [key, value] of Object.entries(savedEnv)) process.env[key] = value;
145
+ });
146
+
147
+ function git(cwd, args) {
148
+ const out = spawnSync('git', args, { cwd, encoding: 'utf8' });
149
+ if (out.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${out.stderr}`);
150
+ return out.stdout.trim();
151
+ }
152
+
153
+ function makeRepo() {
154
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'wt-remove-repo-')));
155
+ git(dir, ['init', '-b', 'main']);
156
+ git(dir, ['config', 'user.email', 'test@example.test']);
157
+ git(dir, ['config', 'user.name', 'Test']);
158
+ fs.writeFileSync(path.join(dir, 'README.md'), '# fixture\n');
159
+ git(dir, ['add', 'README.md']);
160
+ git(dir, ['commit', '-m', 'init']);
161
+ return fs.realpathSync(dir);
162
+ }
163
+
164
+ function makeCtx(repoRoot) {
165
+ return {
166
+ cwd: repoRoot,
167
+ hasUI: false,
168
+ mode: 'tui',
169
+ sessionManager: { getSessionId: () => 'remove-session' },
170
+ ui: { confirm: async () => true, notify: () => {} },
171
+ };
172
+ }
173
+
174
+ function resultText(result) {
175
+ return (result.content || []).map((part) => (part && part.text) || '').join('\n');
176
+ }
177
+
178
+ function branches(root) {
179
+ return git(root, ['branch', '--format=%(refname:short)']).split('\n').filter(Boolean).sort();
180
+ }
181
+
182
+ // The checkout git itself reports for a branch, so the test never guesses the
183
+ // flattened directory the create front derived.
184
+ function checkoutFor(root, branch) {
185
+ return git(root, ['worktree', 'list', '--porcelain'])
186
+ .split('\n')
187
+ .filter((line) => line.startsWith('worktree '))
188
+ .map((line) => line.slice('worktree '.length))
189
+ .find((entry) => entry !== root && fs.existsSync(entry) && git(entry, ['rev-parse', '--abbrev-ref', 'HEAD']) === branch);
190
+ }
191
+
192
+ async function createCheckout(toolsByName, repo, branch) {
193
+ // S7: the checkout's directory is the ODD, so it is the branch's own last
194
+ // segment — one ODD per create, and the branch lookup below still finds the
195
+ // checkout the create wrote.
196
+ const odd = branch.slice(branch.lastIndexOf('/') + 1);
197
+ const created = await toolsByName.get('worktree_create').execute(
198
+ 'remove-create', { branch, odd }, undefined, undefined, makeCtx(repo),
199
+ );
200
+ assert.notEqual(created.isError, true, resultText(created));
201
+ const target = checkoutFor(repo, branch);
202
+ assert.ok(target, `the create made no checkout for ${branch}`);
203
+ return target;
204
+ }
205
+
206
+ // Every child the close spawns is recorded through the one async argv runner
207
+ // the extension hands the removal module. A blocking spawn would bypass this
208
+ // seam entirely, which is what makes the argv assertions below meaningful.
209
+ function recordChildren() {
210
+ // The git seam the extension itself loaded: one load compiles its own lib
211
+ // modules, so the fake goes on THAT instance (the extension's libModule seam).
212
+ const gitLib = mod.libModule('worktree-git.js');
213
+ const original = gitLib.runArgvAsync;
214
+ const calls = [];
215
+ gitLib.runArgvAsync = async (bin, argv, options) => {
216
+ calls.push({ bin, argv, options });
217
+ return original(bin, argv, options);
218
+ };
219
+ return {
220
+ calls,
221
+ restore() { gitLib.runArgvAsync = original; },
222
+ };
223
+ }
224
+
225
+ test('a close spawns git only, with one fixed worktree remove argv', async () => {
226
+ const repo = makeRepo();
227
+ const target = await createCheckout(tools, repo, 'feat/doomed');
228
+
229
+ const recorder = recordChildren();
230
+ let closed;
231
+ try {
232
+ closed = await mod.executeWorktreeClose({ name: 'feat-doomed' }, makeCtx(repo));
233
+ } finally {
234
+ recorder.restore();
235
+ }
236
+
237
+ assert.notEqual(closed.isError, true, resultText(closed));
238
+ assert.equal(fs.existsSync(target), false, 'git removed the checkout');
239
+ assert.ok(branches(repo).includes('feat/doomed'), 'the branch is kept');
240
+
241
+ const binaries = [...new Set(recorder.calls.map((call) => call.bin))];
242
+ assert.deepEqual(binaries, ['git'], 'the removal path runs git and nothing else');
243
+ const removals = recorder.calls.filter((call) => call.argv[0] === 'worktree' && call.argv[1] === 'remove');
244
+ assert.equal(removals.length, 1, 'exactly one remover invocation');
245
+ assert.deepEqual(removals[0].argv, ['worktree', 'remove', target], 'the argv is fixed: no branch, no --force, no --trust-repository');
246
+ assert.equal(fs.realpathSync(removals[0].options.cwd), repo, 'the remover runs in the repository root');
247
+ assert.equal(removals[0].options.timeoutMs, lib.REMOVE_TIMEOUT_MS);
248
+ });
249
+
250
+ test('the removal is awaited, so the host keeps turning while git runs', async () => {
251
+ const repo = makeRepo();
252
+ const target = await createCheckout(tools, repo, 'feat/slow');
253
+
254
+ const gitLib = mod.libModule('worktree-git.js');
255
+ const original = gitLib.runArgvAsync;
256
+ const order = [];
257
+ gitLib.runArgvAsync = async (bin, argv, options) => {
258
+ if (argv[0] === 'worktree' && argv[1] === 'remove') {
259
+ order.push('remover:start');
260
+ // A slow remover: the window only the caller's own event loop can use.
261
+ const ticks = await new Promise((resolve) => {
262
+ let fired = 0;
263
+ const interval = setInterval(() => { fired += 1; }, 1);
264
+ setTimeout(() => { clearInterval(interval); resolve(fired); }, 25);
265
+ });
266
+ order.push(ticks > 0 ? 'host:turned' : 'host:blocked');
267
+ const out = await original(bin, argv, options);
268
+ order.push('remover:end');
269
+ return out;
270
+ }
271
+ return original(bin, argv, options);
272
+ };
273
+ try {
274
+ const closing = mod.executeWorktreeClose({ name: 'feat-slow' }, makeCtx(repo));
275
+ // Yield once so the close reaches the remover before the assertion below.
276
+ await new Promise((resolve) => setTimeout(resolve, 5));
277
+ assert.ok(fs.existsSync(target), 'the await means the checkout survives until git answers');
278
+ const closed = await closing;
279
+ assert.notEqual(closed.isError, true, resultText(closed));
280
+ assert.deepEqual(order, ['remover:start', 'host:turned', 'remover:end'], 'the event loop kept turning while the remover ran');
281
+ } finally {
282
+ gitLib.runArgvAsync = original;
283
+ }
284
+ assert.equal(fs.existsSync(target), false, 'the awaited removal then completes');
285
+ assert.ok(branches(repo).includes('feat/slow'), 'the branch is kept');
286
+ });
287
+
288
+ test('a failing git leaves the checkout and the branch and reports the refusal', async () => {
289
+ const repo = makeRepo();
290
+ const target = await createCheckout(tools, repo, 'feat/dirty');
291
+ // Real git refuses this removal: an untracked file in the checkout and no
292
+ // force. No shim decides the failure, so the refusal is the backend's own.
293
+ fs.writeFileSync(path.join(target, 'uncommitted.txt'), 'work in progress\n');
294
+
295
+ const recorder = recordChildren();
296
+ let refused;
297
+ try {
298
+ refused = await mod.executeWorktreeClose({ name: 'feat-dirty' }, makeCtx(repo));
299
+ } finally {
300
+ recorder.restore();
301
+ }
302
+
303
+ assert.equal(refused.isError, true, 'a refusal is an error result');
304
+ assert.match(resultText(refused), /contains modified or untracked files/);
305
+ assert.match(resultText(refused), /use --force/);
306
+ assert.ok(resultText(refused).includes(target), `the refusal names the checkout git refused: ${resultText(refused)}`);
307
+ assert.equal(fs.existsSync(target), true, 'the checkout survives');
308
+ assert.equal(fs.existsSync(path.join(target, 'uncommitted.txt')), true, 'the pending work survives');
309
+ assert.ok(branches(repo).includes('feat/dirty'), 'the branch survives');
310
+ const removals = recorder.calls.filter((call) => call.argv[0] === 'worktree' && call.argv[1] === 'remove');
311
+ assert.equal(removals.length, 1);
312
+ assert.deepEqual(removals[0].argv, ['worktree', 'remove', target], 'no --force was added on the caller\'s behalf');
313
+ // The registry entry stays: the checkout is still a registered worktree, so
314
+ // the next listing still finds it instead of silently forgetting it.
315
+ const listed = await tools.get('worktree_list').execute('remove-4', {}, undefined, undefined, makeCtx(repo));
316
+ assert.match(resultText(listed), /feat-dirty|feat\/dirty/);
317
+ });
318
+ });
@@ -0,0 +1,276 @@
1
+ 'use strict';
2
+ // T4d: the create's own background setup task.
3
+ //
4
+ // `lib/worktree-setup.js` owns the closed command table and its plan;
5
+ // `lib/worktree-setup-runner.js` owns the task: one tracked child per planned command,
6
+ // its own log under the system temp directory, and the ONE completion notice built
7
+ // from the child process outcome. S1/S3: nothing is persisted — there is no record to
8
+ // read back, so every assertion is about the child, its log and the notice.
9
+ // Everything below injects the child-process seam and the clock, so no package manager
10
+ // is ever spawned and nothing reaches the network.
11
+
12
+ const assert = require('node:assert/strict');
13
+ const { EventEmitter } = require('node:events');
14
+ const fs = require('node:fs');
15
+ const os = require('node:os');
16
+ const path = require('node:path');
17
+ const { after, test } = require('node:test');
18
+
19
+ const {
20
+ WORKTREE_SETUP_TIMEOUT_MS,
21
+ isWorktreeSetupRunning,
22
+ startWorktreeSetup,
23
+ } = require('../lib/worktree-setup-runner.js');
24
+ const { worktreeSetupReadyText } = require('../lib/worktree-setup.js');
25
+
26
+ const scratch = [];
27
+ function track(dir) {
28
+ scratch.push(dir);
29
+ return dir;
30
+ }
31
+ after(() => {
32
+ for (const dir of scratch) {
33
+ try {
34
+ fs.rmSync(dir, { recursive: true, force: true });
35
+ } catch {
36
+ // A removed scratch directory is already what the test wanted.
37
+ }
38
+ }
39
+ });
40
+
41
+ function makeClone(tag) {
42
+ const root = track(fs.mkdtempSync(path.join(os.tmpdir(), `odd-wt-runner-${tag}-`)));
43
+ return {
44
+ logRoot: track(fs.mkdtempSync(path.join(os.tmpdir(), `odd-wt-runner-logs-${tag}-`))),
45
+ worktreePath: path.join(root, 'repo-worktrees', 'demo'),
46
+ };
47
+ }
48
+
49
+ // The injected child seam: every call is recorded, and the test decides when the
50
+ // child ends. `stdio` carries the real log descriptor the runner opened, so a test
51
+ // can write the output a real command would have produced.
52
+ function fakeSpawn() {
53
+ const calls = [];
54
+ const spawn = (bin, args, options) => {
55
+ const child = new EventEmitter();
56
+ child.killed = [];
57
+ child.kill = (signal) => {
58
+ child.killed.push(signal);
59
+ return true;
60
+ };
61
+ child.pid = 4000 + calls.length;
62
+ calls.push({ bin, args, options, child });
63
+ return child;
64
+ };
65
+ return { spawn, calls };
66
+ }
67
+
68
+ // A deterministic clock: the runner reads it for the start, the end and the elapsed.
69
+ function clock() {
70
+ let value = Date.UTC(2026, 0, 1, 0, 0, 0);
71
+ return {
72
+ now: () => new Date(value),
73
+ advance: (ms) => {
74
+ value += ms;
75
+ },
76
+ };
77
+ }
78
+
79
+ // The timeout path settles through the runner's own unref'd timer: a background
80
+ // setup task must never keep the host process alive. A test awaiting such a
81
+ // settlement would leave the event loop empty while its promise is still pending,
82
+ // and the runner on Node 18/20/22 refuses that. One ref'd keep-alive, held only for
83
+ // the duration of the await, keeps those runners honest.
84
+ async function holdLoop(promise) {
85
+ const keepAlive = setInterval(() => {}, 1_000);
86
+ try {
87
+ return await promise;
88
+ } finally {
89
+ clearInterval(keepAlive);
90
+ }
91
+ }
92
+
93
+ const NPM_SEAMS = {
94
+ entries: async () => ['package-lock.json'],
95
+ hasBinary: async (command) => command === 'npm',
96
+ };
97
+
98
+ function start(clone, overrides = {}) {
99
+ return startWorktreeSetup({
100
+ path: clone.worktreePath,
101
+ name: 'demo',
102
+ logRoot: clone.logRoot,
103
+ seams: overrides.seams ?? NPM_SEAMS,
104
+ spawn: overrides.spawn,
105
+ now: overrides.now,
106
+ notify: overrides.notify,
107
+ timeoutMs: overrides.timeoutMs,
108
+ killGraceMs: overrides.killGraceMs,
109
+ copiedChanges: overrides.copiedChanges ?? 0,
110
+ });
111
+ }
112
+
113
+ // ---- S1/S24: the create never waits, and the notice follows the child ----
114
+
115
+ test('a lockfile starts the ported install, and the create returns before it finishes', async () => {
116
+ const clone = makeClone('start');
117
+ const { spawn, calls } = fakeSpawn();
118
+ const notices = [];
119
+ const started = await start(clone, { spawn, notify: (text, level) => notices.push([level, text]), now: clock().now });
120
+
121
+ assert.equal(started.started, true);
122
+ assert.equal(started.refused, false);
123
+ assert.equal(calls.length, 1, 'one child is spawned before the call resolves');
124
+ assert.equal(calls[0].bin, 'npm');
125
+ assert.deepEqual(calls[0].args, ['ci']);
126
+ assert.equal(calls[0].options.cwd, clone.worktreePath);
127
+ assert.equal(isWorktreeSetupRunning(clone.worktreePath), true);
128
+ assert.deepEqual(notices, [], 'nothing is announced while the child runs');
129
+
130
+ calls[0].child.emit('close', 0, null);
131
+ const settled = await started.settled;
132
+ assert.equal(settled.ok, true);
133
+ assert.equal(isWorktreeSetupRunning(clone.worktreePath), false);
134
+ assert.deepEqual(notices, [['info', worktreeSetupReadyText({ name: 'demo', steps: 1, durationMs: 0 })]]);
135
+ });
136
+
137
+ test('the child’s output goes to its own log under the injected root', async () => {
138
+ const clone = makeClone('log');
139
+ const { spawn, calls } = fakeSpawn();
140
+ const started = await start(clone, { spawn, now: clock().now });
141
+ const entry = calls[0];
142
+ assert.ok(entry.options.stdio[1] !== 'ignore', 'stdout is a real descriptor');
143
+ const fd = entry.options.stdio[1];
144
+ fs.writeSync(fd, 'installed 42 packages\n');
145
+ entry.child.emit('close', 0, null);
146
+ await started.settled;
147
+
148
+ const directories = fs.readdirSync(clone.logRoot);
149
+ assert.equal(directories.length, 1);
150
+ const logs = fs.readdirSync(path.join(clone.logRoot, directories[0]));
151
+ assert.deepEqual(logs, ['step-1.log']);
152
+ assert.equal(fs.readFileSync(path.join(clone.logRoot, directories[0], 'step-1.log'), 'utf8'), 'installed 42 packages\n');
153
+ });
154
+
155
+ test('a multi-step plan runs one child per step and announces once, after the last', async () => {
156
+ const clone = makeClone('steps');
157
+ const { spawn, calls } = fakeSpawn();
158
+ const notices = [];
159
+ const now = clock();
160
+ const started = await start(clone, {
161
+ spawn,
162
+ now: now.now,
163
+ notify: (text, level) => notices.push([level, text]),
164
+ seams: { entries: async () => ['requirements.txt'], hasBinary: async (command) => command === 'python3' },
165
+ });
166
+
167
+ assert.equal(calls.length, 1);
168
+ calls[0].child.emit('close', 0, null);
169
+ await new Promise((resolve) => setImmediate(resolve));
170
+ assert.equal(calls.length, 2, 'the second step starts only after the first passed');
171
+ assert.deepEqual(calls[1].args, ['-m', 'pip', 'install', '-r', 'requirements.txt']);
172
+ assert.deepEqual(notices, [], 'a passing step that starts the next one is not the end of the task');
173
+
174
+ now.advance(3_000);
175
+ calls[1].child.emit('close', 0, null);
176
+ const settled = await started.settled;
177
+ assert.equal(settled.ok, true);
178
+ assert.deepEqual(notices, [['info', worktreeSetupReadyText({ name: 'demo', steps: 2, durationMs: 3_000 })]]);
179
+ });
180
+
181
+ test('a failing step stops the chain and sends one failure notice naming the log', async () => {
182
+ const clone = makeClone('fail');
183
+ const { spawn, calls } = fakeSpawn();
184
+ const notices = [];
185
+ const started = await start(clone, { spawn, now: clock().now, notify: (text, level) => notices.push([level, text]) });
186
+
187
+ calls[0].child.emit('close', 1, null);
188
+ const settled = await started.settled;
189
+ assert.equal(settled.ok, false);
190
+ assert.equal(calls.length, 1, 'nothing follows a failed step');
191
+ assert.equal(notices.length, 1);
192
+ assert.equal(notices[0][0], 'warning');
193
+ assert.match(notices[0][1], /^worktree setup failed · demo · npm ci exited 1/);
194
+ assert.match(notices[0][1], /log: .*step-1\.log/);
195
+ assert.match(notices[0][1], /worktree is not ready yet; re-run setup or inspect the log\./);
196
+ });
197
+
198
+ test('a root with no lockfile starts nothing and sends no notice', async () => {
199
+ const clone = makeClone('skip');
200
+ const { spawn, calls } = fakeSpawn();
201
+ const notices = [];
202
+ const started = await start(clone, {
203
+ spawn,
204
+ notify: (text, level) => notices.push([level, text]),
205
+ seams: { entries: async () => ['README.md'], hasBinary: async () => true },
206
+ });
207
+
208
+ assert.equal(started.started, false);
209
+ assert.equal(started.skipped, 'no lockfile at root');
210
+ const settled = await started.settled;
211
+ assert.equal(settled.ok, true);
212
+ assert.equal(settled.notice, undefined);
213
+ assert.deepEqual(calls, [], 'no child runs for a plan with no steps');
214
+ assert.deepEqual(notices, []);
215
+ assert.equal(isWorktreeSetupRunning(clone.worktreePath), false);
216
+ });
217
+
218
+ test('a second start for one checkout refuses instead of running two installs', async () => {
219
+ const clone = makeClone('twice');
220
+ const { spawn, calls } = fakeSpawn();
221
+ const now = clock();
222
+ const first = await start(clone, { spawn, now: now.now });
223
+ const second = await start(clone, { spawn, now: now.now });
224
+
225
+ assert.equal(second.started, false);
226
+ assert.equal(second.refused, true);
227
+ assert.equal(calls.length, 1, 'the second start spawns nothing');
228
+ assert.equal(second.settled, first.settled, 'both callers wait on the same task');
229
+
230
+ calls[0].child.emit('close', 0, null);
231
+ await first.settled;
232
+ });
233
+
234
+ test('a child that never finishes is terminated at the bound and reports its reason', async () => {
235
+ const clone = makeClone('timeout');
236
+ const { spawn, calls } = fakeSpawn();
237
+ const notices = [];
238
+ const started = await start(clone, {
239
+ spawn,
240
+ now: clock().now,
241
+ notify: (text, level) => notices.push([level, text]),
242
+ timeoutMs: 20,
243
+ killGraceMs: 20,
244
+ });
245
+
246
+ const settled = await holdLoop(started.settled);
247
+ assert.equal(settled.ok, false);
248
+ assert.deepEqual(calls[0].child.killed, ['SIGTERM', 'SIGKILL']);
249
+ assert.equal(notices.length, 1);
250
+ assert.match(notices[0][1], /npm ci timed out after 20ms/);
251
+ });
252
+
253
+ test('a spawn error is reported as what the child answered, never as a fake code', async () => {
254
+ const clone = makeClone('spawn-error');
255
+ const spawn = (bin, args, options) => {
256
+ const child = new EventEmitter();
257
+ child.kill = () => true;
258
+ child.options = options;
259
+ setImmediate(() => {
260
+ child.emit('error', new Error('spawn npm ENOENT'));
261
+ child.emit('close', null, null);
262
+ });
263
+ return child;
264
+ };
265
+ const notices = [];
266
+ const started = await start(clone, { spawn, now: clock().now, notify: (text, level) => notices.push([level, text]) });
267
+ const settled = await started.settled;
268
+
269
+ assert.equal(settled.ok, false);
270
+ assert.equal(notices.length, 1);
271
+ assert.match(notices[0][1], /npm ci could not start npm ci: spawn npm ENOENT/);
272
+ });
273
+
274
+ test('the default bound is fifteen minutes', () => {
275
+ assert.equal(WORKTREE_SETUP_TIMEOUT_MS, 15 * 60 * 1000);
276
+ });