pi-odd-worktree 2.1.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 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  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 -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 +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 +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
@@ -1,17 +1,15 @@
1
1
  'use strict';
2
- // S6: the checkout removal for `worktree_delete` — git, and only git.
2
+ // S6: the checkout removal. Git, and only git.
3
3
  //
4
- // History worth knowing, because the file keeps its name: this module used to
5
- // reconcile Herdr workspaces around a close (closing every workspace of the
6
- // checkout's group, then opening a fresh one at the principal, because Herdr
7
- // has no path move) and could hand the removal to Herdr instead. Both are gone.
8
- // A deletion performed by this package never closes, opens or retires a Herdr
9
- // panel, and it never asks Herdr to remove a checkout — Herdr cannot be asked
10
- // to delete a worktree without retiring the workspace behind the human's back.
4
+ // The whole remover: one fixed argv, `git worktree remove
5
+ // <absolute path>`, with `--force` only when the caller asked for it. It never
6
+ // deletes the branch and never passes `--trust-repository`, and no other
7
+ // process is asked to delete a checkout.
11
8
  //
12
- // What remains is one fixed argv: `git worktree remove <absolute path>`, with
13
- // `--force` only when the caller asked for it. It never deletes the branch and
14
- // never passes `--trust-repository`.
9
+ // The caller decides WHO removes a checkout: the `/warp` panel is the person's
10
+ // surface, and a merged, clean checkout is removed by an agent with the same
11
+ // argv (docs/codebase/invariants.md invariant 5). This module is the one
12
+ // implementation both use.
15
13
  //
16
14
  // No static package imports (node builtins only), so the extension's
17
15
  // copy-to-.mjs test loaders keep working.
@@ -0,0 +1,376 @@
1
+ 'use strict';
2
+ // The background setup task of `worktree_create` (T4d, S24).
3
+ //
4
+ // `lib/worktree-setup.js` owns the closed command table and its plan. This module runs
5
+ // that plan as ONE tracked task of this process: each command is a child with a fixed
6
+ // argv, its output goes to its own log file under the system temp directory, and the
7
+ // steps run in order, one child at a time.
8
+ //
9
+ // S1/S3: nothing is written down. There is no setup record, no state file and no job
10
+ // registry to describe — the completion notice follows the CHILD PROCESS OUTCOME
11
+ // (exit code, signal, timeout, spawn error) and is the only report the chain makes. The
12
+ // create never waits for a command: `startWorktreeSetup` resolves once the first child
13
+ // is spawned, and the task settles in the background.
14
+ //
15
+ // Every external process is a binary plus a fixed argument array: the closed table's
16
+ // commands carry no quoting, so splitting one on whitespace is exact and no shell is
17
+ // ever involved. The child seam and the clock are injected, so a test answers for a
18
+ // machine it invents and no case runs a package manager.
19
+
20
+ const { spawn: spawnChild } = require('node:child_process');
21
+ const fs = require('node:fs');
22
+ const os = require('node:os');
23
+ const path = require('node:path');
24
+
25
+ const {
26
+ resolveWorktreeSetupPlan,
27
+ worktreeSetupFailureText,
28
+ worktreeSetupReadyText,
29
+ } = require('./worktree-setup.js');
30
+
31
+ /** S25: a setup that never finishes is terminated after this bound. */
32
+ const WORKTREE_SETUP_TIMEOUT_MS = 15 * 60 * 1000;
33
+
34
+ /** How long a terminated child gets before SIGKILL, and before the task settles anyway. */
35
+ const WORKTREE_SETUP_KILL_GRACE_MS = 2_000;
36
+
37
+ /** The prefix of the per-task log directory inside the system temp directory. */
38
+ const WORKTREE_SETUP_LOG_PREFIX = 'odd-worktree-setup-';
39
+
40
+ /** This process's running setup tasks, keyed by the canonical worktree path. */
41
+ const runningTasks = new Map();
42
+ let taskSequence = 0;
43
+
44
+ /** Whether this process is running a setup task for that checkout right now. */
45
+ function isWorktreeSetupRunning(worktreePath) {
46
+ return runningTasks.has(worktreePath);
47
+ }
48
+
49
+ // ---- The plan's two seams ----
50
+
51
+ /** S21: a PATH presence probe that never runs the binary. */
52
+ function binaryOnPath(command) {
53
+ const directories = (process.env.PATH || '').split(path.delimiter).filter((directory) => directory.length > 0);
54
+ if (process.platform !== 'win32') return directories.some((directory) => fs.existsSync(path.join(directory, command)));
55
+ const extensions = ['', ...(process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';')];
56
+ return directories.some((directory) => extensions.some((extension) =>
57
+ fs.existsSync(path.join(directory, `${command}${extension}`))
58
+ || fs.existsSync(path.join(directory, `${command}${extension.toLowerCase()}`))));
59
+ }
60
+
61
+ function defaultSeams() {
62
+ return {
63
+ entries: async (root) => {
64
+ try {
65
+ return await fs.promises.readdir(root);
66
+ } catch {
67
+ return [];
68
+ }
69
+ },
70
+ hasBinary: async (command) => binaryOnPath(command),
71
+ };
72
+ }
73
+
74
+ // ---- The notice ----
75
+
76
+ /** The task duration as the ported module spells it: seconds, then minutes, then hours. */
77
+ function formatSetupElapsed(ms) {
78
+ const seconds = Math.max(0, Math.round(ms / 1000));
79
+ if (seconds < 60) return `${seconds}s`;
80
+ const minutes = Math.floor(seconds / 60);
81
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
82
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
83
+ }
84
+
85
+ /**
86
+ * S1/S24: a failure sentence built only from what the child process actually answered.
87
+ * An exit code speaks for itself; a timeout, a signal or a spawn error names its own
88
+ * reason instead, and no code is ever invented.
89
+ */
90
+ function failureText(task, command, logPath, elapsed, detail) {
91
+ const headline = detail.startsWith('timed out after')
92
+ ? `worktree setup failed · ${task.name} · ${command} ${detail}`
93
+ : `worktree setup failed · ${task.name} · ${command} ${detail} (${elapsed})`;
94
+ return [
95
+ headline,
96
+ `log: ${logPath ?? ''}`,
97
+ 'worktree is not ready yet; re-run setup or inspect the log.',
98
+ ].join('\n');
99
+ }
100
+
101
+ // ---- The tracked child ----
102
+
103
+ function commandArgv(command) {
104
+ const parts = String(command).trim().split(/\s+/).filter((part) => part.length > 0);
105
+ if (parts.length === 0) throw new Error('empty setup command');
106
+ return parts;
107
+ }
108
+
109
+ function errorMessage(error) {
110
+ return error instanceof Error ? error.message : String(error);
111
+ }
112
+
113
+ function clearTimers(task) {
114
+ if (task.timeout !== undefined) {
115
+ clearTimeout(task.timeout);
116
+ task.timeout = undefined;
117
+ }
118
+ if (task.grace !== undefined) {
119
+ clearTimeout(task.grace);
120
+ task.grace = undefined;
121
+ }
122
+ }
123
+
124
+ function closeLog(job) {
125
+ if (job === undefined || job.logFd === undefined) return;
126
+ const descriptor = job.logFd;
127
+ job.logFd = undefined;
128
+ try {
129
+ fs.closeSync(descriptor);
130
+ } catch {
131
+ // A descriptor the child already saw closed is not a failure.
132
+ }
133
+ }
134
+
135
+ function logDirectoryFor(task) {
136
+ if (task.logDirectory !== undefined) return task.logDirectory;
137
+ task.logDirectory = fs.mkdtempSync(path.join(task.logRoot, WORKTREE_SETUP_LOG_PREFIX));
138
+ return task.logDirectory;
139
+ }
140
+
141
+ /** The notice and the settled value of one task, sent exactly once. */
142
+ function finalize(task, outcome) {
143
+ if (task.done) return;
144
+ task.done = true;
145
+ clearTimers(task);
146
+ runningTasks.delete(task.path);
147
+ if (task.current !== undefined) closeLog(task.current);
148
+ if (typeof task.notify === 'function') {
149
+ try {
150
+ task.notify(outcome.notice, outcome.ok ? 'info' : 'warning');
151
+ } catch {
152
+ // A UI that cannot take the notice never changes what the child did.
153
+ }
154
+ }
155
+ task.resolve(outcome);
156
+ }
157
+
158
+ function failStep(task, job, detail) {
159
+ clearTimers(task);
160
+ closeLog(job);
161
+ if (task.done) return;
162
+ const endedAt = task.now();
163
+ finalize(task, {
164
+ ok: false,
165
+ notice: failureText(
166
+ task,
167
+ job.command,
168
+ job.logPath,
169
+ formatSetupElapsed(Math.max(0, endedAt.getTime() - task.startedAt.getTime())),
170
+ detail,
171
+ ),
172
+ });
173
+ }
174
+
175
+ function timeoutJob(task, job) {
176
+ if (job.closed || task.done) return;
177
+ job.timedOut = true;
178
+ try {
179
+ job.child?.kill('SIGTERM');
180
+ } catch {
181
+ // A child that already exited has nothing left to terminate.
182
+ }
183
+ task.grace = setTimeout(() => {
184
+ task.grace = undefined;
185
+ if (job.closed || task.done) return;
186
+ try {
187
+ job.child?.kill('SIGKILL');
188
+ } catch {
189
+ // The forced kill is best effort; the task settles either way.
190
+ }
191
+ failStep(task, job, `timed out after ${task.timeoutMs}ms`);
192
+ }, task.killGraceMs);
193
+ task.grace.unref();
194
+ }
195
+
196
+ function readyTask(task) {
197
+ finalize(task, {
198
+ ok: true,
199
+ notice: worktreeSetupReadyText({
200
+ name: task.name,
201
+ steps: task.commands.length,
202
+ durationMs: Math.max(0, task.now().getTime() - task.startedAt.getTime()),
203
+ }),
204
+ });
205
+ }
206
+
207
+ /**
208
+ * Start one step's child. The task's own `settle` path moves to the next command, so a
209
+ * multi-step plan is the same code once per command and never a shell pipeline.
210
+ */
211
+ function startStep(task, index) {
212
+ if (task.done) return;
213
+ if (index >= task.commands.length) {
214
+ readyTask(task);
215
+ return;
216
+ }
217
+ const command = task.commands[index];
218
+ let argv;
219
+ try {
220
+ argv = commandArgv(command);
221
+ } catch (error) {
222
+ failStep(task, { command, logFd: undefined, closed: true }, errorMessage(error));
223
+ return;
224
+ }
225
+ const [bin, ...args] = argv;
226
+ let logPath;
227
+ let descriptor;
228
+ try {
229
+ logPath = path.join(logDirectoryFor(task), `step-${index + 1}.log`);
230
+ descriptor = fs.openSync(logPath, 'a');
231
+ } catch (error) {
232
+ failStep(task, { command, logFd: undefined, closed: true }, `could not open its log: ${errorMessage(error)}`);
233
+ return;
234
+ }
235
+ const job = {
236
+ id: `${task.id}-${index + 1}`,
237
+ command,
238
+ logPath,
239
+ logFd: descriptor,
240
+ startedAt: task.now(),
241
+ closed: false,
242
+ timedOut: false,
243
+ error: undefined,
244
+ child: undefined,
245
+ };
246
+ task.current = job;
247
+ let child;
248
+ try {
249
+ child = task.spawn(bin, args, {
250
+ cwd: task.path,
251
+ stdio: ['ignore', descriptor, descriptor],
252
+ windowsHide: true,
253
+ });
254
+ } catch (error) {
255
+ failStep(task, job, `could not start ${command}: ${errorMessage(error)}`);
256
+ return;
257
+ }
258
+ job.child = child;
259
+ child.on('error', (error) => {
260
+ job.error = error;
261
+ });
262
+ child.on('close', (code, signal) => {
263
+ if (job.closed) return;
264
+ job.closed = true;
265
+ closeLog(job);
266
+ if (task.done) return;
267
+ if (job.timedOut) {
268
+ failStep(task, job, `timed out after ${task.timeoutMs}ms`);
269
+ return;
270
+ }
271
+ if (job.error !== undefined) {
272
+ failStep(task, job, `could not start ${command}: ${errorMessage(job.error)}`);
273
+ return;
274
+ }
275
+ if (typeof code !== 'number') {
276
+ failStep(task, job, signal ? `terminated by ${signal}` : 'did not exit normally');
277
+ return;
278
+ }
279
+ if (code !== 0) {
280
+ clearTimers(task);
281
+ if (task.done) return;
282
+ const endedAt = task.now();
283
+ finalize(task, {
284
+ ok: false,
285
+ notice: worktreeSetupFailureText({
286
+ name: task.name,
287
+ command,
288
+ exitCode: code,
289
+ logPath,
290
+ }) + ` (${formatSetupElapsed(Math.max(0, endedAt.getTime() - task.startedAt.getTime()))})`,
291
+ });
292
+ return;
293
+ }
294
+ clearTimers(task);
295
+ startStep(task, index + 1);
296
+ });
297
+ task.timeout = setTimeout(() => timeoutJob(task, job), task.timeoutMs);
298
+ task.timeout.unref();
299
+ }
300
+
301
+ // ---- The start ----
302
+
303
+ function positiveMs(value, fallback) {
304
+ return Number.isFinite(value) && value > 0 ? value : fallback;
305
+ }
306
+
307
+ /**
308
+ * Resolve the plan, then start one tracked task that runs it, without waiting for the
309
+ * first command. A plan with nothing to run (no lockfile, a missing binary) starts
310
+ * nothing and sends no notice — the create does not report setup at all (S1).
311
+ *
312
+ * Returns `{ started, refused, settled }`: `started` says whether a child now runs,
313
+ * `refused` says a task for this checkout was already running, and `settled` resolves
314
+ * once — never rejects — with `{ ok, notice }`.
315
+ */
316
+ async function startWorktreeSetup(input) {
317
+ const worktreePath = input.path;
318
+ const now = typeof input.now === 'function' ? input.now : () => new Date();
319
+ const plan = await resolveWorktreeSetupPlan({
320
+ root: worktreePath,
321
+ copiedChanges: Math.max(0, Number.isInteger(input.copiedChanges) ? input.copiedChanges : 0),
322
+ seam: input.seams ?? defaultSeams(),
323
+ platform: input.platform ?? process.platform,
324
+ });
325
+
326
+ // The refusal check and the start are one synchronous region: no await sits
327
+ // between them, so two concurrent creates for one checkout cannot both start.
328
+ const running = runningTasks.get(worktreePath);
329
+ if (running !== undefined) return { started: false, refused: true, settled: running.settled };
330
+
331
+ if (plan.detail !== undefined) {
332
+ return {
333
+ started: false,
334
+ refused: false,
335
+ skipped: plan.detail,
336
+ settled: Promise.resolve({ ok: true, skipped: plan.detail, notice: undefined }),
337
+ };
338
+ }
339
+
340
+ let resolve;
341
+ const settled = new Promise((done) => {
342
+ resolve = done;
343
+ });
344
+ const task = {
345
+ id: `${process.pid}-${++taskSequence}`,
346
+ path: worktreePath,
347
+ name: input.name,
348
+ commands: plan.steps,
349
+ now,
350
+ spawn: typeof input.spawn === 'function' ? input.spawn : spawnChild,
351
+ logRoot: typeof input.logRoot === 'string' && input.logRoot.length > 0 ? input.logRoot : os.tmpdir(),
352
+ logDirectory: undefined,
353
+ timeoutMs: positiveMs(input.timeoutMs, WORKTREE_SETUP_TIMEOUT_MS),
354
+ killGraceMs: positiveMs(input.killGraceMs, WORKTREE_SETUP_KILL_GRACE_MS),
355
+ notify: typeof input.notify === 'function' ? input.notify : undefined,
356
+ startedAt: now(),
357
+ current: undefined,
358
+ timeout: undefined,
359
+ grace: undefined,
360
+ done: false,
361
+ resolve,
362
+ settled,
363
+ };
364
+ runningTasks.set(worktreePath, task);
365
+ startStep(task, 0);
366
+ return { started: true, refused: false, settled };
367
+ }
368
+
369
+ module.exports = {
370
+ WORKTREE_SETUP_TIMEOUT_MS,
371
+ WORKTREE_SETUP_KILL_GRACE_MS,
372
+ WORKTREE_SETUP_LOG_PREFIX,
373
+ isWorktreeSetupRunning,
374
+ startWorktreeSetup,
375
+ formatSetupElapsed,
376
+ };
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+ // The setup chain of `worktree_create` (S20, S21, S24).
3
+ //
4
+ // A lockfile at the worktree root selects one entry of a closed command table (S21),
5
+ // and that entry's steps run as the new checkout's own background task
6
+ // (`lib/worktree-setup-runner.js`). The create returns before a step settles and
7
+ // nothing about the chain is written down (S1, S3): the checkout's directory is the
8
+ // only record, so the chain reports itself once, in the completion notice that follows
9
+ // the child process outcome.
10
+ //
11
+ // Nothing here reads a repository file's contents or takes a command from one: the
12
+ // table below and the clone-local `setup` flag are the only sources of a command
13
+ // string. The chain reaches the world through two injected seams — the directory
14
+ // listing and the PATH probe — so a test answers for a machine it invents and no case
15
+ // runs a package manager.
16
+
17
+ /** S24: the custom message type of the one setup notification. */
18
+ const WORKTREE_SETUP_NOTICE_TYPE = 'gentle-worktree.setup';
19
+
20
+ /** S20: why a chain never ran, in the words a human reads. */
21
+ const WORKTREE_SETUP_DISABLED_DETAIL = 'setup is not enabled for this repository';
22
+
23
+ // ---- S21: the closed command table ----
24
+
25
+ /** S21: `.venv` keeps pip from touching the machine's interpreter, and its layout is platform-specific. */
26
+ function venvPython(platform) {
27
+ return platform === 'win32' ? '.venv/Scripts/python' : '.venv/bin/python';
28
+ }
29
+
30
+ /**
31
+ * S21: one entry of the closed table. `lockfiles` are the exact names at the worktree
32
+ * root and `suffixes` are the .NET solution and project files; the first matching entry
33
+ * wins, so a repository that carries two lockfiles gets the earlier one and never a
34
+ * merge of both. `binaries` are the commands the steps run, and the first missing one
35
+ * skips the chain. No entry is reachable from a repository file.
36
+ */
37
+ const WORKTREE_SETUP_RULES = [
38
+ { lockfiles: ['pnpm-lock.yaml'], binaries: ['pnpm'], steps: () => ['pnpm install'] },
39
+ {
40
+ lockfiles: ['yarn.lock'],
41
+ binaries: ['yarn'],
42
+ steps: ({ copiedChanges }) => [copiedChanges === 0 ? 'yarn install --immutable' : 'yarn install'],
43
+ },
44
+ {
45
+ lockfiles: ['package-lock.json', 'npm-shrinkwrap.json'],
46
+ binaries: ['npm'],
47
+ steps: ({ copiedChanges }) => [copiedChanges === 0 ? 'npm ci' : 'npm install'],
48
+ },
49
+ { lockfiles: ['bun.lock', 'bun.lockb'], binaries: ['bun'], steps: () => ['bun install --frozen-lockfile'] },
50
+ { lockfiles: ['Cargo.toml'], binaries: ['cargo'], steps: () => ['cargo fetch'] },
51
+ { lockfiles: ['go.mod'], binaries: ['go'], steps: () => ['go mod download'] },
52
+ { lockfiles: ['uv.lock'], binaries: ['uv'], steps: () => ['uv sync'] },
53
+ { lockfiles: ['poetry.lock'], binaries: ['poetry'], steps: () => ['poetry install'] },
54
+ { lockfiles: ['Pipfile.lock'], binaries: ['pipenv'], steps: () => ['pipenv install'] },
55
+ {
56
+ lockfiles: ['requirements.txt'],
57
+ binaries: ['python3'],
58
+ steps: ({ platform }) => ['python3 -m venv .venv', `${venvPython(platform)} -m pip install -r requirements.txt`],
59
+ },
60
+ { lockfiles: ['Gemfile.lock'], binaries: ['bundle'], steps: () => ['bundle install'] },
61
+ { lockfiles: ['composer.lock'], binaries: ['composer'], steps: () => ['composer install'] },
62
+ { lockfiles: ['mix.lock'], binaries: ['mix'], steps: () => ['mix deps.get'] },
63
+ { lockfiles: ['pubspec.lock'], binaries: ['flutter'], steps: () => ['flutter pub get'] },
64
+ {
65
+ lockfiles: [],
66
+ suffixes: ['.sln', '.csproj', '.fsproj', '.vbproj'],
67
+ binaries: ['dotnet'],
68
+ steps: () => ['dotnet restore'],
69
+ },
70
+ ];
71
+
72
+ /** The entry this root selects, or nothing when no lockfile or project file matched. */
73
+ function worktreeSetupRuleFor(entries) {
74
+ for (const rule of WORKTREE_SETUP_RULES) {
75
+ if (rule.lockfiles.some((name) => entries.includes(name))) return rule;
76
+ const suffixes = rule.suffixes ?? [];
77
+ if (suffixes.some((suffix) => entries.some((name) => name.toLowerCase().endsWith(suffix)))) return rule;
78
+ }
79
+ return undefined;
80
+ }
81
+
82
+ // ---- S21: resolving one plan ----
83
+
84
+ /**
85
+ * S21: the first matching entry, its binary checked, or the reason it cannot run. A
86
+ * missing binary stops here instead of trying the next entry, because a lockfile from
87
+ * one package manager installed by another is not the project's setup. The filesystem
88
+ * seam answers what the root holds and whether a command resolves on the PATH.
89
+ */
90
+ async function resolveWorktreeSetupPlan(input) {
91
+ const entries = await input.seam.entries(input.root);
92
+ const rule = worktreeSetupRuleFor(entries);
93
+ if (rule === undefined) return { steps: [], detail: 'no lockfile at root' };
94
+ for (const binary of rule.binaries) {
95
+ if (!(await input.seam.hasBinary(binary))) return { steps: [], detail: `${binary} not found` };
96
+ }
97
+ return {
98
+ steps: rule.steps({
99
+ copiedChanges: Math.max(0, input.copiedChanges),
100
+ platform: input.platform ?? process.platform,
101
+ }),
102
+ };
103
+ }
104
+
105
+ // ---- S24: the two sentences ----
106
+
107
+ /** The task duration as the notices spell it: seconds, then minutes, then hours. */
108
+ function formatJobDuration(ms) {
109
+ const seconds = Math.max(0, Math.round(ms / 1000));
110
+ if (seconds < 60) return `${seconds}s`;
111
+ const minutes = Math.floor(seconds / 60);
112
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
113
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
114
+ }
115
+
116
+ /** S24: the one sentence a chain that ended well sends. */
117
+ function worktreeSetupReadyText(input) {
118
+ const steps = `${input.steps} step${input.steps === 1 ? '' : 's'}`;
119
+ return `worktree setup ready · ${input.name} · ${steps} (${formatJobDuration(input.durationMs)})`;
120
+ }
121
+
122
+ /** S24: the one sentence a chain that failed sends, with the log a human would read. */
123
+ function worktreeSetupFailureText(input) {
124
+ return [
125
+ `worktree setup failed · ${input.name} · ${input.command} exited ${input.exitCode}`,
126
+ `log: ${input.logPath}`,
127
+ 'worktree is not ready yet; re-run setup or inspect the log.',
128
+ ].join('\n');
129
+ }
130
+
131
+ module.exports = {
132
+ WORKTREE_SETUP_NOTICE_TYPE,
133
+ WORKTREE_SETUP_DISABLED_DETAIL,
134
+ WORKTREE_SETUP_RULES,
135
+ worktreeSetupRuleFor,
136
+ resolveWorktreeSetupPlan,
137
+ formatJobDuration,
138
+ worktreeSetupReadyText,
139
+ worktreeSetupFailureText,
140
+ };