@mycompbox/compbox-cli 1.21.9 → 1.21.11

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 (85) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/list.js +1 -1
  3. package/commands/list.js.map +1 -1
  4. package/commands/machines.d.ts +4 -0
  5. package/commands/machines.d.ts.map +1 -1
  6. package/commands/machines.js +61 -2
  7. package/commands/machines.js.map +1 -1
  8. package/commands/run.d.ts +27 -1
  9. package/commands/run.d.ts.map +1 -1
  10. package/commands/run.js +182 -36
  11. package/commands/run.js.map +1 -1
  12. package/commands/update.d.ts +19 -0
  13. package/commands/update.d.ts.map +1 -1
  14. package/commands/update.js +124 -7
  15. package/commands/update.js.map +1 -1
  16. package/commands/workspace.d.ts.map +1 -1
  17. package/commands/workspace.js +13 -1
  18. package/commands/workspace.js.map +1 -1
  19. package/index.js +4983 -1505
  20. package/index.js.map +1 -1
  21. package/package.json +1 -1
  22. package/utils/agent-invoker.d.ts +264 -31
  23. package/utils/agent-invoker.d.ts.map +1 -1
  24. package/utils/agent-invoker.js +1013 -372
  25. package/utils/agent-invoker.js.map +1 -1
  26. package/utils/brew.d.ts +10 -0
  27. package/utils/brew.d.ts.map +1 -1
  28. package/utils/brew.js +14 -0
  29. package/utils/brew.js.map +1 -1
  30. package/utils/cli-version.d.ts +3 -0
  31. package/utils/cli-version.d.ts.map +1 -0
  32. package/utils/cli-version.js +18 -0
  33. package/utils/cli-version.js.map +1 -0
  34. package/utils/cloud-preflight.d.ts +68 -0
  35. package/utils/cloud-preflight.d.ts.map +1 -0
  36. package/utils/cloud-preflight.js +287 -0
  37. package/utils/cloud-preflight.js.map +1 -0
  38. package/utils/config-store.d.ts +29 -0
  39. package/utils/config-store.d.ts.map +1 -1
  40. package/utils/config-store.js +30 -0
  41. package/utils/config-store.js.map +1 -1
  42. package/utils/install-cache.d.ts +105 -0
  43. package/utils/install-cache.d.ts.map +1 -0
  44. package/utils/install-cache.js +184 -0
  45. package/utils/install-cache.js.map +1 -0
  46. package/utils/mailbox-client.d.ts +130 -3
  47. package/utils/mailbox-client.d.ts.map +1 -1
  48. package/utils/mailbox-client.js +140 -6
  49. package/utils/mailbox-client.js.map +1 -1
  50. package/utils/merge-guard.d.ts +66 -0
  51. package/utils/merge-guard.d.ts.map +1 -0
  52. package/utils/merge-guard.js +271 -0
  53. package/utils/merge-guard.js.map +1 -0
  54. package/utils/merge-policy.d.ts +68 -0
  55. package/utils/merge-policy.d.ts.map +1 -0
  56. package/utils/merge-policy.js +129 -0
  57. package/utils/merge-policy.js.map +1 -0
  58. package/utils/progress-watcher.d.ts +53 -0
  59. package/utils/progress-watcher.d.ts.map +1 -0
  60. package/utils/progress-watcher.js +109 -0
  61. package/utils/progress-watcher.js.map +1 -0
  62. package/utils/project-checks.d.ts +72 -0
  63. package/utils/project-checks.d.ts.map +1 -0
  64. package/utils/project-checks.js +276 -0
  65. package/utils/project-checks.js.map +1 -0
  66. package/utils/run-timings.d.ts +59 -0
  67. package/utils/run-timings.d.ts.map +1 -0
  68. package/utils/run-timings.js +130 -0
  69. package/utils/run-timings.js.map +1 -0
  70. package/utils/run-workspace.d.ts +200 -2
  71. package/utils/run-workspace.d.ts.map +1 -1
  72. package/utils/run-workspace.js +898 -136
  73. package/utils/run-workspace.js.map +1 -1
  74. package/utils/self-update.d.ts +104 -0
  75. package/utils/self-update.d.ts.map +1 -0
  76. package/utils/self-update.js +391 -0
  77. package/utils/self-update.js.map +1 -0
  78. package/utils/usage-limit.d.ts +30 -0
  79. package/utils/usage-limit.d.ts.map +1 -0
  80. package/utils/usage-limit.js +186 -0
  81. package/utils/usage-limit.js.map +1 -0
  82. package/utils/wrap-up.d.ts +109 -0
  83. package/utils/wrap-up.d.ts.map +1 -0
  84. package/utils/wrap-up.js +260 -0
  85. package/utils/wrap-up.js.map +1 -0
@@ -24,19 +24,22 @@
24
24
  * Every git/gh/install call goes through an injectable runner so tests never
25
25
  * touch a real repository.
26
26
  */
27
- import { spawn } from 'node:child_process';
28
- import { copyFileSync, existsSync, mkdirSync } from 'node:fs';
29
- import { basename, dirname, join } from 'node:path';
30
- import { claudeChildEnvPath } from './claude-runtime.js';
31
- import { getConfigDir } from './config-store.js';
27
+ import { spawn } from "node:child_process";
28
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
29
+ import { basename, dirname, join } from "node:path";
30
+ import { formatNeedsInputText } from "@mycompbox/shared";
31
+ import { claudeChildEnvPath } from "./claude-runtime.js";
32
+ import { installPrePushGuard } from "./merge-guard.js";
33
+ import { DEFAULT_RUN_RETENTION_DAYS, getConfigDir, getRunRetentionMs } from "./config-store.js";
34
+ import { activeMarkerPath, activeMarkerProtects, detectLockfile, formatActiveMarker, orphanMarkers, parseActiveMarker, pidAlive, hashLockfile, installArgs, markerMatches, parseWorktreeList, readInstallMarker, selectStaleRuns, storeDirFor, waitingMarkerPath, writeInstallMarker, } from "./install-cache.js";
32
35
  /** Set to "0" to keep finished runs local: no push, no pull request. */
33
- export const RUN_PUSH_ENV = 'COMPBOX_RUN_PUSH';
36
+ export const RUN_PUSH_ENV = "COMPBOX_RUN_PUSH";
34
37
  /** Install deps can take a while on a cold cache. */
35
38
  const INSTALL_TIMEOUT_MS = 20 * 60 * 1_000;
36
39
  const GIT_TIMEOUT_MS = 5 * 60 * 1_000;
37
40
  export const defaultCommandRunner = (command, args, cwd) => new Promise((resolve) => {
38
- let stdout = '';
39
- let stderr = '';
41
+ let stdout = "";
42
+ let stderr = "";
40
43
  let settled = false;
41
44
  const done = (result) => {
42
45
  if (settled)
@@ -47,70 +50,110 @@ export const defaultCommandRunner = (command, args, cwd) => new Promise((resolve
47
50
  };
48
51
  const child = spawn(command, args, {
49
52
  cwd,
50
- stdio: ['ignore', 'pipe', 'pipe'],
51
- env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH), GIT_TERMINAL_PROMPT: '0' },
53
+ stdio: ["ignore", "pipe", "pipe"],
54
+ env: { ...process.env, PATH: claudeChildEnvPath(process.env.PATH), GIT_TERMINAL_PROMPT: "0" },
52
55
  });
53
56
  const timer = setTimeout(() => {
54
- child.kill('SIGKILL');
57
+ child.kill("SIGKILL");
55
58
  done({ status: 1, stdout, stderr: `${command} timed out` });
56
- }, command === 'git' || command === 'gh' ? GIT_TIMEOUT_MS : INSTALL_TIMEOUT_MS);
57
- child.stdout.on('data', (chunk) => {
58
- stdout += chunk.toString('utf-8');
59
+ }, command === "git" || command === "gh" ? GIT_TIMEOUT_MS : INSTALL_TIMEOUT_MS);
60
+ child.stdout.on("data", (chunk) => {
61
+ stdout += chunk.toString("utf-8");
59
62
  });
60
- child.stderr.on('data', (chunk) => {
61
- stderr += chunk.toString('utf-8');
63
+ child.stderr.on("data", (chunk) => {
64
+ stderr += chunk.toString("utf-8");
62
65
  });
63
- child.on('error', (error) => {
66
+ child.on("error", (error) => {
64
67
  done({ status: 1, stdout, stderr: error.message });
65
68
  });
66
- child.on('close', (code) => {
69
+ child.on("close", (code) => {
67
70
  done({ status: code ?? 1, stdout, stderr });
68
71
  });
69
72
  });
73
+ /** Longest question text put into a pull request body (GitHub caps bodies at 65,536). */
74
+ const PR_QUESTION_MAX_CHARS = 20_000;
75
+ /**
76
+ * ENG-337: the "Waiting for your reply" block at the top of a draft pull
77
+ * request. The request is untrusted agent output, so it goes in a code fence
78
+ * longer than any backtick run inside it: no markdown, links, HTML or
79
+ * @-mentions are rendered from it. Pure — exported for unit testing.
80
+ */
81
+ export function waitingPrBodyBlock(request) {
82
+ let text = formatNeedsInputText(request);
83
+ if (text.length > PR_QUESTION_MAX_CHARS)
84
+ text = `${text.slice(0, PR_QUESTION_MAX_CHARS)}\n…(cut short)`;
85
+ const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), (m) => m[0].length));
86
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
87
+ return [
88
+ "Waiting for your reply",
89
+ "",
90
+ "The build stopped to ask you something. Answer it in CompBox and the build continues from here.",
91
+ "",
92
+ `${fence}text`,
93
+ text,
94
+ fence,
95
+ ].join("\n");
96
+ }
70
97
  /** Local-only files a run needs that git doesn't carry into a new worktree. */
71
98
  export function isLocalConfigFile(path) {
72
- if (path.split('/').includes('node_modules'))
99
+ if (path.split("/").includes("node_modules"))
73
100
  return false;
74
101
  const name = basename(path);
75
- return (name === '.mcp.json' ||
76
- name === 'CLAUDE.local.md' ||
77
- path === '.claude/settings.local.json');
102
+ return (name === ".mcp.json" || name === "CLAUDE.local.md" || path === ".claude/settings.local.json");
78
103
  // Never .env files: they can hold production credentials. On 2026-10-21 a
79
104
  // build's test run read the copied packages/api/.env and wiped the prod
80
105
  // database.
81
106
  }
82
107
  /** `ENG-E12` → `ENG-E12`; anything unusual becomes dashes. */
83
108
  export function slugForBranch(value) {
84
- return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'run';
109
+ return (value
110
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
111
+ .replace(/^-+|-+$/g, "")
112
+ .slice(0, 40) || "run");
85
113
  }
86
114
  function stamp(now) {
87
- const pad = (n) => String(n).padStart(2, '0');
115
+ const pad = (n) => String(n).padStart(2, "0");
88
116
  return `${String(now.getFullYear())}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
89
117
  }
118
+ /** The real path of `path` (git prints worktrees by real path), or `path` itself. */
119
+ function realpathOr(path) {
120
+ try {
121
+ return realpathSync(path);
122
+ }
123
+ catch {
124
+ return path;
125
+ }
126
+ }
127
+ /** ENG-337: the note for a paused run whose folder is kept for the reply. */
128
+ function keptForReplyNote(ws) {
129
+ return `The run is waiting for your reply. Its folder is kept for the reply: ${ws.dir} (branch ${ws.branch}).`;
130
+ }
90
131
  /** Git's well-known empty tree (SHA-1 repositories). */
91
- const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
132
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
92
133
  /**
93
134
  * The line of git's stderr that says what went wrong. Git prints progress
94
135
  * ("Preparing worktree (new branch …)", "HEAD is now at …") before the actual
95
136
  * `fatal:`/`error:` line, so the first line alone hid the reason.
96
137
  */
97
138
  export function gitReason(text) {
98
- const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
139
+ const lines = text
140
+ .split("\n")
141
+ .map((l) => l.trim())
142
+ .filter(Boolean);
99
143
  const failure = lines.find((l) => /^(fatal|error):/i.test(l));
100
144
  if (failure)
101
145
  return failure;
102
146
  const notProgress = lines.filter((l) => !/^(Preparing worktree|HEAD is now at|Updating files)/.test(l));
103
- return notProgress.at(-1) ?? lines.at(-1) ?? '';
147
+ return notProgress.at(-1) ?? lines.at(-1) ?? "";
104
148
  }
105
- /** Picks the install command for the repo's lockfile, or null when there is none. */
106
- export function installCommand(dir, exists = existsSync) {
107
- if (exists(join(dir, 'pnpm-lock.yaml')))
108
- return ['pnpm', ['install', '--frozen-lockfile', '--prefer-offline']];
109
- if (exists(join(dir, 'package-lock.json')))
110
- return ['npm', ['ci', '--prefer-offline']];
111
- if (exists(join(dir, 'yarn.lock')))
112
- return ['yarn', ['install', '--frozen-lockfile']];
113
- return null;
149
+ /**
150
+ * Picks the install command for the repo's lockfile, or null when there is
151
+ * none. `opts.storeDir` points the package manager at a shared per-project
152
+ * store (ENG-349); `opts.offline` installs only from it. Pure.
153
+ */
154
+ export function installCommand(dir, exists = existsSync, opts = {}) {
155
+ const found = detectLockfile(dir, exists);
156
+ return found ? [found.pm, installArgs(found.pm, opts)] : null;
114
157
  }
115
158
  /**
116
159
  * GitHub "compare" link for a remote URL, so the person can open the pull
@@ -122,7 +165,7 @@ export function githubCompareUrl(remoteUrl, baseBranch, branch) {
122
165
  /^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(remoteUrl.trim());
123
166
  if (!m)
124
167
  return null;
125
- return `https://github.com/${m[1] ?? ''}/${m[2] ?? ''}/compare/${encodeURIComponent(baseBranch)}...${encodeURIComponent(branch)}?expand=1`;
168
+ return `https://github.com/${m[1] ?? ""}/${m[2] ?? ""}/compare/${encodeURIComponent(baseBranch)}...${encodeURIComponent(branch)}?expand=1`;
126
169
  }
127
170
  /**
128
171
  * Git commands that write to the same repository (fetch, worktree add/remove,
@@ -150,11 +193,18 @@ export class RunWorkspaceManager {
150
193
  copyFile;
151
194
  env;
152
195
  openPullRequest;
196
+ storesRoot;
197
+ retentionMs;
198
+ activeRunDirs;
199
+ mtimeMs;
200
+ readFile;
201
+ isPidAlive;
202
+ pid;
153
203
  constructor(deps = {}) {
154
204
  this.openPullRequest = deps.openPullRequest;
155
205
  this.run = deps.run ?? defaultCommandRunner;
156
206
  this.now = deps.now ?? (() => new Date());
157
- this.runsRoot = deps.runsRoot ?? join(getConfigDir(), 'runs');
207
+ this.runsRoot = deps.runsRoot ?? join(getConfigDir(), "runs");
158
208
  this.exists = deps.exists ?? existsSync;
159
209
  this.copyFile =
160
210
  deps.copyFile ??
@@ -163,9 +213,95 @@ export class RunWorkspaceManager {
163
213
  copyFileSync(from, to);
164
214
  });
165
215
  this.env = deps.env ?? process.env;
216
+ this.storesRoot = deps.storesRoot ?? join(dirname(this.runsRoot), "stores");
217
+ this.retentionMs = deps.retentionMs;
218
+ this.activeRunDirs = deps.activeRunDirs;
219
+ this.mtimeMs =
220
+ deps.mtimeMs ??
221
+ ((path) => {
222
+ try {
223
+ return statSync(path).mtimeMs;
224
+ }
225
+ catch {
226
+ return null;
227
+ }
228
+ });
229
+ this.isPidAlive = deps.isPidAlive ?? pidAlive;
230
+ this.pid = deps.pid ?? process.pid;
231
+ this.readFile =
232
+ deps.readFile ??
233
+ ((path) => {
234
+ try {
235
+ return readFileSync(path);
236
+ }
237
+ catch {
238
+ return null;
239
+ }
240
+ });
166
241
  }
167
242
  git(args, cwd) {
168
- return this.run('git', args, cwd);
243
+ return this.run("git", args, cwd);
244
+ }
245
+ /**
246
+ * Marks a run folder as in use (`<dir>.active`: pid + startedAt) and touches
247
+ * the folder, so a prune from another process never removes it. Called
248
+ * inside the repo lock. Best-effort.
249
+ */
250
+ markActive(dir) {
251
+ try {
252
+ writeFileSync(activeMarkerPath(dir), formatActiveMarker({ pid: this.pid, startedAt: this.now().toISOString() }));
253
+ }
254
+ catch {
255
+ // Prune also skips recently touched folders.
256
+ }
257
+ try {
258
+ const now = this.now();
259
+ utimesSync(dir, now, now);
260
+ }
261
+ catch {
262
+ // A folder we can't touch just keeps its old age.
263
+ }
264
+ }
265
+ clearActive(dir) {
266
+ rmSync(activeMarkerPath(dir), { force: true });
267
+ }
268
+ /** Whether a `.active` marker still protects this folder from pruning. */
269
+ activeByMarker(dir) {
270
+ const path = activeMarkerPath(dir);
271
+ let text = null;
272
+ try {
273
+ text = readFileSync(path, "utf-8");
274
+ }
275
+ catch {
276
+ text = null;
277
+ }
278
+ const exists = text !== null || this.exists(path);
279
+ const touched = Math.max(this.mtimeMs(path) ?? 0, this.mtimeMs(dir) ?? 0);
280
+ return activeMarkerProtects({
281
+ exists,
282
+ marker: parseActiveMarker(text),
283
+ markerMtimeMs: touched === 0 ? null : touched,
284
+ nowMs: this.now().getTime(),
285
+ isAlive: this.isPidAlive,
286
+ });
287
+ }
288
+ /** Removes `.active`/`.waiting` markers whose run folder is gone. Best-effort. */
289
+ clearOrphanMarkers() {
290
+ let entries;
291
+ try {
292
+ entries = readdirSync(this.runsRoot);
293
+ }
294
+ catch {
295
+ return;
296
+ }
297
+ for (const name of orphanMarkers(entries)) {
298
+ try {
299
+ rmSync(join(this.runsRoot, name), { force: true });
300
+ }
301
+ catch {
302
+ // Harmless leftover.
303
+ }
304
+ }
169
305
  }
170
306
  /** Creates the branch + worktree for a run. Never touches the person's checkout. */
171
307
  /**
@@ -174,31 +310,146 @@ export class RunWorkspaceManager {
174
310
  * rather than fall back to a fresh branch when it can't be checked out.
175
311
  */
176
312
  async prepare(projectDir, epicId, opts = {}) {
177
- const created = await withRepoLock(projectDir, () => this.createWorktree(projectDir, epicId, opts));
313
+ const active = [...(opts.activeRunDirs ?? []), ...((await this.activeRunDirs?.()) ?? [])];
314
+ const created = await withRepoLock(projectDir, async () => {
315
+ // ENG-349: clear out old, clean, pushed run folders first.
316
+ const pruned = await this.pruneStaleRuns(projectDir, active);
317
+ const result = await this.createWorktree(projectDir, epicId, opts);
318
+ if (result.ok)
319
+ this.markActive(result.workspace.dir);
320
+ if (result.ok && pruned > 0) {
321
+ result.notes.push(`Removed ${String(pruned)} old run folder${pruned === 1 ? "" : "s"} that ${pruned === 1 ? "was" : "were"} no longer used.`);
322
+ }
323
+ return result;
324
+ });
178
325
  if (!created.ok)
179
326
  return created;
180
327
  const { workspace, notes } = created;
181
328
  const { dir, branch } = workspace;
182
- const install = installCommand(dir, this.exists);
183
- if (install) {
184
- const [command, args] = install;
185
- const res = await this.run(command, args, dir);
329
+ // ENG-346: the agent can't push to the default branch from this run copy.
330
+ await this.guardPushes(projectDir, dir, workspace.baseBranch);
331
+ const installed = await this.installDeps(projectDir, dir);
332
+ if (installed) {
333
+ const { command, args, res } = installed;
186
334
  if (res.status !== 0) {
187
335
  await withRepoLock(projectDir, async () => {
188
- await this.git(['worktree', 'remove', '--force', dir], projectDir);
189
- await this.git(['branch', '-D', branch], projectDir);
336
+ await this.git(["worktree", "remove", "--force", dir], projectDir);
337
+ await this.git(["branch", "-D", branch], projectDir);
338
+ this.clearActive(dir);
190
339
  });
191
340
  return {
192
341
  ok: false,
193
342
  error: [
194
- `Installing the project's dependencies failed (${command} ${args.join(' ')}): ${gitReason(res.stderr) || gitReason(res.stdout) || 'unknown error'}`,
195
- 'The run was not started. Check that the same command works in your project folder.',
196
- ].join('\n'),
343
+ `Installing the project's dependencies failed (${command} ${args.join(" ")}): ${gitReason(res.stderr) || gitReason(res.stdout) || "unknown error"}`,
344
+ "The run was not started. Check that the same command works in your project folder.",
345
+ ].join("\n"),
197
346
  };
198
347
  }
348
+ workspace.install = { ms: installed.ms, cacheHit: installed.cacheHit };
199
349
  }
200
350
  return { ok: true, workspace, notes };
201
351
  }
352
+ /**
353
+ * ENG-349: installs dependencies through a shared per-project store. When the
354
+ * store's marker matches this lockfile and package-manager version, installs
355
+ * offline from it (hard links for pnpm); if that fails, or there is no
356
+ * match, runs the full frozen install. The marker is read and written under
357
+ * the repo lock and only updated after a successful install.
358
+ */
359
+ async installDeps(projectDir, dir) {
360
+ const found = detectLockfile(dir, this.exists);
361
+ if (!found)
362
+ return null;
363
+ const storeDir = storeDirFor(this.storesRoot, projectDir);
364
+ const lock = this.readFile(found.lockfile);
365
+ const lockHash = lock ? hashLockfile(lock) : "";
366
+ const version = await this.run(found.pm, ["--version"], dir);
367
+ const pmVersion = version.status === 0 ? version.stdout.trim() : "";
368
+ const marker = await withRepoLock(projectDir, () => Promise.resolve(readInstallMarker(storeDir)));
369
+ const started = Date.now();
370
+ let cacheHit = false;
371
+ let res = null;
372
+ let args = installArgs(found.pm, { storeDir, pmVersion });
373
+ const fastArgs = installArgs(found.pm, { storeDir, offline: true, pmVersion });
374
+ // No offline variant (e.g. Yarn Berry): there is no separate fast path.
375
+ const hasFastPath = fastArgs.join(" ") !== args.join(" ");
376
+ if (hasFastPath && lockHash && markerMatches(marker, lockHash, pmVersion)) {
377
+ const fast = await this.run(found.pm, fastArgs, dir);
378
+ if (fast.status === 0) {
379
+ cacheHit = true;
380
+ res = fast;
381
+ args = fastArgs;
382
+ }
383
+ }
384
+ // No match, or the fast path failed: the full install (silently).
385
+ res ??= await this.run(found.pm, args, dir);
386
+ const ms = Date.now() - started;
387
+ if (res.status === 0 && lockHash && pmVersion) {
388
+ await withRepoLock(projectDir, () => {
389
+ try {
390
+ writeInstallMarker(storeDir, { lockHash, pmVersion, at: this.now().toISOString() });
391
+ }
392
+ catch {
393
+ // A marker that can't be written only costs the next run its fast path.
394
+ }
395
+ return Promise.resolve();
396
+ });
397
+ }
398
+ return { command: found.pm, args, res, ms, cacheHit };
399
+ }
400
+ /**
401
+ * ENG-349: removes run folders under the runs folder that nothing uses any
402
+ * more. Runs inside the repo lock. A folder is removed only when it is older
403
+ * than the retention window, not used by a running job, not kept for a
404
+ * waiting job's reply, clean, and has no unpushed commits — and only with
405
+ * `git worktree remove` (never a plain delete). Returns how many went.
406
+ */
407
+ async pruneStaleRuns(projectDir, activeRunDirs) {
408
+ const list = await this.git(["worktree", "list", "--porcelain"], projectDir);
409
+ if (list.status !== 0)
410
+ return 0;
411
+ const roots = [this.runsRoot, realpathOr(this.runsRoot)];
412
+ const inRuns = (dir) => roots.some((root) => dir.startsWith(`${root}/`));
413
+ const active = new Set(activeRunDirs.flatMap((d) => [d.replace(/\/+$/, ""), realpathOr(d)]));
414
+ const candidates = parseWorktreeList(list.stdout)
415
+ .filter((dir) => inRuns(dir) && !dir.split("/").includes(".."))
416
+ .map((dir) => ({
417
+ dir,
418
+ mtimeMs: this.mtimeMs(dir),
419
+ waiting: this.exists(waitingMarkerPath(dir)),
420
+ active: active.has(dir) || active.has(realpathOr(dir)) || this.activeByMarker(dir),
421
+ }));
422
+ // Markers left behind by folders that are already gone.
423
+ this.clearOrphanMarkers();
424
+ if (candidates.length === 0)
425
+ return 0;
426
+ let retention = this.retentionMs;
427
+ if (retention === undefined) {
428
+ try {
429
+ retention = getRunRetentionMs();
430
+ }
431
+ catch {
432
+ retention = DEFAULT_RUN_RETENTION_DAYS * 86_400_000;
433
+ }
434
+ }
435
+ let pruned = 0;
436
+ for (const dir of selectStaleRuns(candidates, this.now().getTime(), retention)) {
437
+ if (await this.isDirty(dir))
438
+ continue;
439
+ // Commits on this branch that no remote has yet.
440
+ const unpushed = await this.git(["rev-list", "--count", "HEAD", "--not", "--remotes"], dir);
441
+ if (unpushed.status !== 0 || unpushed.stdout.trim() !== "0")
442
+ continue;
443
+ // --force only skips git's own ignored-file check; the folder is verified clean.
444
+ const removed = await this.git(["worktree", "remove", "--force", dir], projectDir);
445
+ if (removed.status === 0) {
446
+ pruned += 1;
447
+ this.clearActive(dir);
448
+ rmSync(waitingMarkerPath(dir), { force: true });
449
+ }
450
+ }
451
+ return pruned;
452
+ }
202
453
  /**
203
454
  * When neither the folder nor its remote has any commit, records one empty
204
455
  * commit on `main` (and pushes it) so runs can branch and open pull requests.
@@ -206,63 +457,62 @@ export class RunWorkspaceManager {
206
457
  * the folder is swept in: the person's files stay exactly as they were.
207
458
  */
208
459
  async startEmptyRepository(projectDir, remote) {
209
- if ((await this.git(['rev-parse', '--verify', '--quiet', 'HEAD'], projectDir)).status === 0)
460
+ if ((await this.git(["rev-parse", "--verify", "--quiet", "HEAD"], projectDir)).status === 0)
210
461
  return { ok: true };
211
462
  if (remote) {
212
- const heads = await this.git(['ls-remote', '--heads', remote], projectDir);
463
+ const heads = await this.git(["ls-remote", "--heads", remote], projectDir);
213
464
  // Unreachable remote, or it already has branches: leave it to the usual path.
214
- if (heads.status !== 0 || heads.stdout.trim() !== '')
465
+ if (heads.status !== 0 || heads.stdout.trim() !== "")
215
466
  return { ok: true };
216
467
  }
217
468
  const fail = (what, res) => ({
218
469
  ok: false,
219
470
  error: [
220
- `This repository has no commits yet, and CompBox couldn't ${what}: ${gitReason(res.stderr) || 'unknown error'}`,
221
- 'The run was not started. Make a first commit on main in your project folder (or push one to GitHub), then try again.',
222
- ].join('\n'),
471
+ `This repository has no commits yet, and CompBox couldn't ${what}: ${gitReason(res.stderr) || "unknown error"}`,
472
+ "The run was not started. Make a first commit on main in your project folder (or push one to GitHub), then try again.",
473
+ ].join("\n"),
223
474
  });
224
- const commit = await this.git(['commit-tree', EMPTY_TREE, '-m', 'Start the project'], projectDir);
475
+ const commit = await this.git(["commit-tree", EMPTY_TREE, "-m", "Start the project"], projectDir);
225
476
  if (commit.status !== 0)
226
- return fail('make its first commit', commit);
477
+ return fail("make its first commit", commit);
227
478
  const sha = commit.stdout.trim();
228
- const ref = await this.git(['update-ref', 'refs/heads/main', sha, ''], projectDir);
479
+ const ref = await this.git(["update-ref", "refs/heads/main", sha, ""], projectDir);
229
480
  if (ref.status !== 0)
230
- return fail('create the main branch', ref);
231
- await this.git(['symbolic-ref', 'HEAD', 'refs/heads/main'], projectDir);
481
+ return fail("create the main branch", ref);
482
+ await this.git(["symbolic-ref", "HEAD", "refs/heads/main"], projectDir);
232
483
  if (!remote)
233
484
  return {
234
485
  ok: true,
235
- note: 'The repository had no commits, so CompBox started main with an empty first commit.',
486
+ note: "The repository had no commits, so CompBox started main with an empty first commit.",
236
487
  };
237
- const push = await this.git(['push', remote, 'main'], projectDir);
488
+ const push = await this.git(["push", remote, "main"], projectDir);
238
489
  if (push.status !== 0)
239
490
  return fail(`push its first commit to ${remote}`, push);
240
- return { ok: true, note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.` };
491
+ return {
492
+ ok: true,
493
+ note: `The repository had no commits, so CompBox started main with an empty first commit and pushed it to ${remote}.`,
494
+ };
241
495
  }
242
- async createWorktree(projectDir, epicId, opts = {}) {
243
- const notes = [];
244
- const remotes = (await this.git(['remote'], projectDir)).stdout.split('\n').map((r) => r.trim()).filter(Boolean);
245
- const remote = remotes.includes('origin') ? 'origin' : (remotes[0] ?? null);
246
- // A brand-new repository has no commits, so there is nothing to branch from
247
- // and no base for a pull request. Give it one empty starting commit on main.
248
- const started = await this.startEmptyRepository(projectDir, remote);
249
- if (!started.ok)
250
- return started;
251
- if (started.note)
252
- notes.push(started.note);
253
- let baseBranch = '';
254
- let baseRef = 'HEAD';
496
+ /** The repository's remote: `origin`, else the first one, else null. */
497
+ async resolveRemote(projectDir) {
498
+ const remotes = (await this.git(["remote"], projectDir)).stdout
499
+ .split("\n")
500
+ .map((r) => r.trim())
501
+ .filter(Boolean);
502
+ return remotes.includes("origin") ? "origin" : (remotes[0] ?? null);
503
+ }
504
+ /** The branch pull requests target and the ref new branches start from. */
505
+ async resolveBase(projectDir, remote) {
506
+ let baseBranch = "";
507
+ let baseRef = "HEAD";
255
508
  if (remote) {
256
- if ((await this.git(['fetch', remote, '--quiet'], projectDir)).status !== 0) {
257
- notes.push(`Couldn't fetch from ${remote}, so the run starts from the last fetched copy.`);
258
- }
259
- const head = await this.git(['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote}/HEAD`], projectDir);
509
+ const head = await this.git(["symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`], projectDir);
260
510
  if (head.status === 0 && head.stdout.trim().startsWith(`${remote}/`)) {
261
511
  baseBranch = head.stdout.trim().slice(remote.length + 1);
262
512
  }
263
513
  else {
264
- for (const candidate of ['main', 'master']) {
265
- if ((await this.git(['rev-parse', '--verify', '--quiet', `${remote}/${candidate}`], projectDir)).status === 0) {
514
+ for (const candidate of ["main", "master"]) {
515
+ if ((await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${candidate}`], projectDir)).status === 0) {
266
516
  baseBranch = candidate;
267
517
  break;
268
518
  }
@@ -272,9 +522,143 @@ export class RunWorkspaceManager {
272
522
  baseRef = `${remote}/${baseBranch}`;
273
523
  }
274
524
  if (!baseBranch) {
275
- baseBranch = (await this.git(['rev-parse', '--abbrev-ref', 'HEAD'], projectDir)).stdout.trim() || 'main';
276
- baseRef = 'HEAD';
525
+ baseBranch =
526
+ (await this.git(["rev-parse", "--abbrev-ref", "HEAD"], projectDir)).stdout.trim() || "main";
527
+ baseRef = "HEAD";
528
+ }
529
+ return { baseBranch, baseRef };
530
+ }
531
+ /**
532
+ * ENG-339: reopens the run copy a paused run kept (by its stored path, not
533
+ * by looking for an unfinished pushed branch: a copy with no commits sits
534
+ * on a branch that was never pushed). Verifies the folder is a worktree of
535
+ * this repository, inside CompBox's run folders, on the expected branch.
536
+ * When the folder was removed, re-creates it at the SAME path (Claude keys
537
+ * sessions by folder) from the local branch, or the pushed one. Runs the
538
+ * git steps inside the repo lock. Fails (so the caller runs fresh) rather
539
+ * than guessing.
540
+ */
541
+ async reopen(input) {
542
+ const reopened = await withRepoLock(input.projectDir, async () => {
543
+ const result = await this.reopenLocked(input);
544
+ if (result.ok) {
545
+ // In use again before the lock is released, so no prune can take it.
546
+ this.markActive(result.workspace.dir);
547
+ // ENG-349: the reply arrived; the folder is a normal run folder again.
548
+ rmSync(waitingMarkerPath(result.workspace.dir), { force: true });
549
+ }
550
+ return result;
551
+ });
552
+ // ENG-346: a re-created (or older) run copy gets the push guard too.
553
+ if (reopened.ok) {
554
+ await this.guardPushes(input.projectDir, reopened.workspace.dir, reopened.workspace.baseBranch);
555
+ }
556
+ return reopened;
557
+ }
558
+ /**
559
+ * ENG-346: installs the pre-push hook that refuses pushes to the default
560
+ * branch, in this run copy only (per-worktree core.hooksPath; see
561
+ * installPrePushGuard). Best-effort: a guard that can't be installed never
562
+ * stops a run (the agent's disallowed tools and gh shim still apply).
563
+ */
564
+ async guardPushes(projectDir, dir, baseBranch) {
565
+ // The repo lock: extensions.worktreeConfig is written to the shared config.
566
+ await withRepoLock(projectDir, () => installPrePushGuard(dir, baseBranch || null, (args, cwd) => this.git(args, cwd)));
567
+ }
568
+ async reopenLocked(input) {
569
+ const { projectDir } = input;
570
+ const fail = (why) => ({
571
+ ok: false,
572
+ error: `Couldn't reopen the paused run's folder ${input.runDir}: ${why}`,
573
+ });
574
+ const runDir = input.runDir.replace(/\/+$/, "");
575
+ if (!runDir.startsWith("/") || runDir.split("/").includes("..")) {
576
+ return fail("it isn't an absolute path.");
577
+ }
578
+ // Never a folder outside the runs folder (e.g. the person's own checkout).
579
+ const roots = [this.runsRoot, realpathOr(this.runsRoot)];
580
+ const inRuns = (dir) => roots.some((root) => dir.startsWith(`${root}/`));
581
+ // Both the literal path AND its real path (symlinks resolved) must be inside.
582
+ if (!inRuns(runDir) || !inRuns(realpathOr(runDir))) {
583
+ return fail("it isn't inside CompBox's run folders.");
584
+ }
585
+ const remote = await this.resolveRemote(projectDir);
586
+ const { baseBranch, baseRef } = await this.resolveBase(projectDir, remote);
587
+ const notes = [];
588
+ const given = input.branch?.trim() ?? "";
589
+ let branch = given === "" ? null : given;
590
+ // The branch comes from the job's result: never let it reach git as an
591
+ // option or an invalid ref.
592
+ if (branch && !(await this.isValidBranchName(branch, projectDir))) {
593
+ return fail(`the run's branch name ${JSON.stringify(branch)} isn't a valid branch name.`);
594
+ }
595
+ if (this.exists(runDir)) {
596
+ // Must be the top of a worktree of THIS repository, not just any folder.
597
+ const top = await this.git(["rev-parse", "--show-toplevel"], runDir);
598
+ if (top.status !== 0 || realpathOr(top.stdout.trim()) !== realpathOr(runDir)) {
599
+ return fail("it isn't a git worktree.");
600
+ }
601
+ const mine = await this.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], runDir);
602
+ const theirs = await this.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], projectDir);
603
+ if (mine.status !== 0 ||
604
+ theirs.status !== 0 ||
605
+ realpathOr(mine.stdout.trim()) !== realpathOr(theirs.stdout.trim())) {
606
+ return fail("it belongs to a different repository.");
607
+ }
608
+ const current = (await this.git(["symbolic-ref", "--quiet", "--short", "HEAD"], runDir)).stdout.trim();
609
+ if (!current)
610
+ return fail("it isn't on a branch.");
611
+ if (branch && current !== branch) {
612
+ return fail(`it is on ${current}, not ${branch}.`);
613
+ }
614
+ branch = current;
615
+ notes.push(`Resuming in the kept run folder ${runDir} on ${branch}.`);
616
+ }
617
+ else {
618
+ if (!branch)
619
+ return fail("the folder is gone and the run's branch is unknown.");
620
+ // Drop git's record of the removed folder so the path can be reused.
621
+ await this.git(["worktree", "prune"], projectDir);
622
+ const local = await this.git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], projectDir);
623
+ const add = local.status === 0
624
+ ? await this.git(["worktree", "add", runDir, branch], projectDir)
625
+ : remote &&
626
+ (await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${branch}`], projectDir)).status === 0
627
+ ? await this.git(["worktree", "add", "-B", branch, runDir, `${remote}/${branch}`], projectDir)
628
+ : null;
629
+ if (!add)
630
+ return fail(`the folder is gone and the branch ${branch} no longer exists.`);
631
+ if (add.status !== 0)
632
+ return fail(gitReason(add.stderr) || "git worktree add failed.");
633
+ notes.push(`The paused run's folder was gone, so it was re-created at ${runDir} on ${branch}.`);
277
634
  }
635
+ return {
636
+ ok: true,
637
+ workspace: { dir: runDir, projectDir, branch, baseRef, baseBranch, remote, continued: true },
638
+ notes,
639
+ };
640
+ }
641
+ /** A plain branch name: no leading '-', safe characters, and accepted by `git check-ref-format --branch`. */
642
+ async isValidBranchName(branch, cwd) {
643
+ if (branch.startsWith("-") || !/^[A-Za-z0-9._/-]+$/.test(branch))
644
+ return false;
645
+ const check = await this.git(["check-ref-format", "--branch", branch], cwd);
646
+ return check.status === 0;
647
+ }
648
+ async createWorktree(projectDir, epicId, opts = {}) {
649
+ const notes = [];
650
+ const remote = await this.resolveRemote(projectDir);
651
+ // A brand-new repository has no commits, so there is nothing to branch from
652
+ // and no base for a pull request. Give it one empty starting commit on main.
653
+ const started = await this.startEmptyRepository(projectDir, remote);
654
+ if (!started.ok)
655
+ return started;
656
+ if (started.note)
657
+ notes.push(started.note);
658
+ if (remote && (await this.git(["fetch", remote, "--quiet"], projectDir)).status !== 0) {
659
+ notes.push(`Couldn't fetch from ${remote}, so the run starts from the last fetched copy.`);
660
+ }
661
+ const { baseBranch, baseRef } = await this.resolveBase(projectDir, remote);
278
662
  const when = stamp(this.now());
279
663
  const dir = join(this.runsRoot, `${slugForBranch(basename(projectDir))}-${slugForBranch(epicId)}-${when}`);
280
664
  mkdirSync(this.runsRoot, { recursive: true });
@@ -289,46 +673,64 @@ export class RunWorkspaceManager {
289
673
  ok: false,
290
674
  error: [
291
675
  `Couldn't open the pull request's branch ${target}: ${why}`,
292
- 'The fix was not started, and your project folder was not changed.',
293
- ].join('\n'),
676
+ "The fix was not started, and your project folder was not changed.",
677
+ ].join("\n"),
294
678
  });
295
679
  if (!remote)
296
- return missing('this project folder has no remote to fetch it from.');
297
- if ((await this.git(['rev-parse', '--verify', '--quiet', `${remote}/${target}`], projectDir)).status !== 0) {
680
+ return missing("this project folder has no remote to fetch it from.");
681
+ // ENG-337: a paused run may still hold this branch in its kept folder.
682
+ await this.releaseKeptWorktree(target, remote, projectDir, notes);
683
+ if ((await this.git(["rev-parse", "--verify", "--quiet", `${remote}/${target}`], projectDir))
684
+ .status !== 0) {
298
685
  return missing(`it isn't on ${remote} (was the pull request closed or the branch deleted?).`);
299
686
  }
300
- const checkout = await this.git(['worktree', 'add', '-B', target, dir, `${remote}/${target}`], projectDir);
687
+ const checkout = await this.git(["worktree", "add", "-B", target, dir, `${remote}/${target}`], projectDir);
301
688
  if (checkout.status !== 0)
302
- return missing(gitReason(checkout.stderr) || 'unknown error');
689
+ return missing(gitReason(checkout.stderr) || "unknown error");
303
690
  branch = target;
304
691
  continued = true;
305
692
  }
306
- const previous = !opts.branch && remote ? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir) : null;
307
- if (remote && previous) {
308
- const resume = await this.git(['worktree', 'add', '-B', previous, dir, `${remote}/${previous}`], projectDir);
693
+ // ER-130: the owner merged the last run's branch (a squash merge leaves it
694
+ // looking unfinished to git), so start a new one from the base.
695
+ const previous = !opts.branch && !opts.fresh && remote
696
+ ? await this.unfinishedBranch(remote, slugForBranch(epicId), baseRef, projectDir)
697
+ : null;
698
+ // ENG-337: a run that paused for a reply kept its folder, which holds the
699
+ // branch checked out; a clean one is removed first so the branch can be
700
+ // checked out again. A dirty one is never touched (the fallback below runs).
701
+ if (remote && previous && !(await this.releaseKeptWorktree(previous, remote, projectDir, notes))) {
702
+ notes.push(`The earlier run on ${previous} is kept as it is, so this run starts a new branch.`);
703
+ }
704
+ else if (remote && previous) {
705
+ const resume = await this.git(["worktree", "add", "-B", previous, dir, `${remote}/${previous}`], projectDir);
309
706
  if (resume.status === 0) {
310
707
  branch = previous;
311
708
  continued = true;
312
709
  notes.push(`Continuing the earlier unfinished work on ${previous}.`);
313
710
  }
314
711
  else {
315
- notes.push(`Couldn't continue the earlier unfinished branch ${previous} (${gitReason(resume.stderr) || 'unknown error'}), so the run starts a new branch.`);
712
+ notes.push(`Couldn't continue the earlier unfinished branch ${previous} (${gitReason(resume.stderr) || "unknown error"}), so the run starts a new branch.`);
316
713
  }
317
714
  }
318
- const add = continued ? null : await this.git(['worktree', 'add', '-b', branch, dir, baseRef], projectDir);
715
+ const add = continued
716
+ ? null
717
+ : await this.git(["worktree", "add", "-b", branch, dir, baseRef], projectDir);
319
718
  if (add && add.status !== 0) {
320
719
  return {
321
720
  ok: false,
322
721
  error: [
323
- `Couldn't create a separate workspace for this run (git worktree add failed): ${gitReason(add.stderr) || 'unknown error'}`,
324
- 'The run was not started, and your project folder was not changed.',
325
- ].join('\n'),
722
+ `Couldn't create a separate workspace for this run (git worktree add failed): ${gitReason(add.stderr) || "unknown error"}`,
723
+ "The run was not started, and your project folder was not changed.",
724
+ ].join("\n"),
326
725
  };
327
726
  }
328
727
  // Local-only config the agents need (.mcp.json for CompBox tools, .env files for tests).
329
- const ignored = await this.git(['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], projectDir);
330
- const untracked = await this.git(['ls-files', '--others', '--exclude-standard'], projectDir);
331
- const candidates = new Set(`${ignored.stdout}\n${untracked.stdout}`.split('\n').map((p) => p.trim()).filter((p) => p && !p.endsWith('/')));
728
+ const ignored = await this.git(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"], projectDir);
729
+ const untracked = await this.git(["ls-files", "--others", "--exclude-standard"], projectDir);
730
+ const candidates = new Set(`${ignored.stdout}\n${untracked.stdout}`
731
+ .split("\n")
732
+ .map((p) => p.trim())
733
+ .filter((p) => p && !p.endsWith("/")));
332
734
  for (const path of candidates) {
333
735
  if (!isLocalConfigFile(path))
334
736
  continue;
@@ -345,19 +747,76 @@ export class RunWorkspaceManager {
345
747
  notes,
346
748
  };
347
749
  }
750
+ /**
751
+ * ENG-337: removes kept run folders (worktrees) that still have `branch`
752
+ * checked out, so a later run can check the branch out again. Runs inside
753
+ * the repo lock (from prepare). Only a folder that is clean, and whose branch
754
+ * has nothing unpushed, is removed; returns false (with a note) when a
755
+ * folder had to stay.
756
+ */
757
+ async releaseKeptWorktree(branch, remote, projectDir, notes) {
758
+ const list = await this.git(["worktree", "list", "--porcelain"], projectDir);
759
+ if (list.status !== 0)
760
+ return true;
761
+ const holders = [];
762
+ let path = null;
763
+ for (const line of list.stdout.split("\n")) {
764
+ if (line.startsWith("worktree "))
765
+ path = line.slice("worktree ".length).trim();
766
+ else if (line.trim() === `branch refs/heads/${branch}` && path)
767
+ holders.push(path);
768
+ }
769
+ // Never a folder outside the runs folder (e.g. the person's own checkout).
770
+ const roots = [this.runsRoot, realpathOr(this.runsRoot)];
771
+ const kept = holders.filter((dir) => roots.some((root) => dir.startsWith(`${root}/`)));
772
+ if (kept.length < holders.length) {
773
+ notes.push(`The branch ${branch} is checked out outside CompBox's run folders, so it was left alone.`);
774
+ return false;
775
+ }
776
+ if (kept.length === 0)
777
+ return true;
778
+ const unpushed = await this.git(["rev-list", "--count", `${remote}/${branch}..refs/heads/${branch}`], projectDir);
779
+ if (unpushed.status !== 0 || unpushed.stdout.trim() !== "0") {
780
+ notes.push(`The earlier run folder ${kept.join(", ")} has commits on ${branch} that aren't pushed, so it was kept.`);
781
+ return false;
782
+ }
783
+ for (const dir of kept) {
784
+ if (await this.isDirty(dir)) {
785
+ notes.push(`The earlier run folder ${dir} still has uncommitted changes, so it was kept (branch ${branch}).`);
786
+ return false;
787
+ }
788
+ // --force only skips git's own ignored-file check; the folder is verified clean.
789
+ const removed = await this.git(["worktree", "remove", "--force", dir], projectDir);
790
+ if (removed.status !== 0) {
791
+ notes.push(`Couldn't remove the earlier run folder ${dir}: ${gitReason(removed.stderr) || "unknown error"}.`);
792
+ return false;
793
+ }
794
+ }
795
+ return true;
796
+ }
348
797
  /** The newest pushed run branch for this epic that isn't merged into the base yet, if any. */
349
798
  async unfinishedBranch(remote, epicSlug, baseRef, projectDir) {
350
- const refs = await this.git(['for-each-ref', '--sort=-refname', '--format=%(refname:short)', `refs/remotes/${remote}/compbox/epic-${epicSlug}-*`], projectDir);
351
- const latest = refs.stdout.split('\n').map((r) => r.trim()).find(Boolean);
799
+ const refs = await this.git([
800
+ "for-each-ref",
801
+ "--sort=-refname",
802
+ "--format=%(refname:short)",
803
+ `refs/remotes/${remote}/compbox/epic-${epicSlug}-*`,
804
+ ], projectDir);
805
+ const latest = refs.stdout
806
+ .split("\n")
807
+ .map((r) => r.trim())
808
+ .find(Boolean);
352
809
  if (!latest?.startsWith(`${remote}/`))
353
810
  return null;
354
- if ((await this.git(['merge-base', '--is-ancestor', latest, baseRef], projectDir)).status === 0)
811
+ if ((await this.git(["merge-base", "--is-ancestor", latest, baseRef], projectDir)).status === 0)
355
812
  return null;
356
813
  return latest.slice(remote.length + 1);
357
814
  }
358
815
  /** A cancelled run's result: the branch and worktree are kept locally, untouched. */
359
816
  async keepCancelled(ws, notes, commits) {
360
- const count = commits ?? (Number.parseInt((await this.git(['rev-list', '--count', `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0);
817
+ const count = commits ??
818
+ (Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) ||
819
+ 0);
361
820
  notes.push(`The run was cancelled, so nothing was pushed. Its work is kept in ${ws.dir} on branch ${ws.branch}.`);
362
821
  return {
363
822
  branch: ws.branch,
@@ -369,8 +828,28 @@ export class RunWorkspaceManager {
369
828
  };
370
829
  }
371
830
  /** Commits, pushes and opens the pull request; then cleans up the worktree. */
372
- finish(input) {
373
- return withRepoLock(input.workspace.projectDir, () => this.finishLocked(input));
831
+ async finish(input) {
832
+ return withRepoLock(input.workspace.projectDir, async () => {
833
+ const result = await this.finishLocked(input);
834
+ // ENG-349: a folder kept for a waiting job's reply is never pruned. The
835
+ // marker is written before the lock is released, so no prune slips in.
836
+ if (input.waiting?.keepRunCopy && result.keptWorktree) {
837
+ try {
838
+ writeFileSync(waitingMarkerPath(result.keptWorktree), `${input.jobId}\n`);
839
+ }
840
+ catch {
841
+ // Best-effort; prune also skips recent folders.
842
+ }
843
+ }
844
+ // The run is over: the folder is no longer in use by this job.
845
+ try {
846
+ this.clearActive(input.workspace.dir);
847
+ }
848
+ catch {
849
+ // A leftover marker only protects the folder for the grace window.
850
+ }
851
+ return result;
852
+ });
374
853
  }
375
854
  async finishLocked(input) {
376
855
  const { workspace: ws } = input;
@@ -384,17 +863,22 @@ export class RunWorkspaceManager {
384
863
  const dirtyBefore = await this.isDirty(ws.dir);
385
864
  let commitFailed = false;
386
865
  if (dirtyBefore) {
387
- await this.git(['add', '-A'], ws.dir);
866
+ await this.git(["add", "-A"], ws.dir);
388
867
  // --no-verify: these are the run's own commits, not the person's; review
389
868
  // happens on the pull request. A repo pre-commit hook (e.g. one running
390
869
  // the full test suite) once failed this commit and the work was lost.
391
- const commit = await this.git(['commit', '--no-verify', '-m', `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`], ws.dir);
870
+ const commit = await this.git([
871
+ "commit",
872
+ "--no-verify",
873
+ "-m",
874
+ `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`,
875
+ ], ws.dir);
392
876
  if (commit.status !== 0) {
393
877
  commitFailed = true;
394
- notes.push(`Couldn't commit the remaining changes: ${gitReason(commit.stderr) || gitReason(commit.stdout) || 'unknown error'}`);
878
+ notes.push(`Couldn't commit the remaining changes: ${gitReason(commit.stderr) || gitReason(commit.stdout) || "unknown error"}`);
395
879
  }
396
880
  }
397
- const commits = Number.parseInt((await this.git(['rev-list', '--count', `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
881
+ const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
398
882
  const base = { branch: ws.branch, commits, pushed: false, notes };
399
883
  // Never remove a worktree that still holds uncommitted work: keep it, say
400
884
  // where it is, and flag the run for attention.
@@ -402,22 +886,32 @@ export class RunWorkspaceManager {
402
886
  notes.push(`The run's changes couldn't all be committed, so nothing was removed. They are safe in ${ws.dir} on branch ${ws.branch}.`);
403
887
  return { ...base, keptWorktree: ws.dir, needsAttention: true };
404
888
  }
889
+ const keepRunCopy = input.waiting?.keepRunCopy === true;
405
890
  if (commits === 0) {
891
+ if (!dirtyBefore && keepRunCopy) {
892
+ // ENG-337: nothing to push yet, but the paused session lives here.
893
+ notes.push(keptForReplyNote(ws));
894
+ return { ...base, keptWorktree: ws.dir };
895
+ }
406
896
  if (!dirtyBefore) {
407
897
  if (await this.removeWorktree(ws, notes)) {
408
- await this.git(['branch', '-D', ws.branch], ws.projectDir);
898
+ await this.git(["branch", "-D", ws.branch], ws.projectDir);
409
899
  }
410
900
  else {
411
901
  return { ...base, keptWorktree: ws.dir, needsAttention: true };
412
902
  }
413
- notes.push('The run made no code changes, so there is nothing to review.');
903
+ notes.push("The run made no code changes, so there is nothing to review.");
414
904
  return base;
415
905
  }
416
906
  // Changes existed but no commit landed — keep everything.
417
907
  notes.push(`The run's changes didn't end up in a commit, so nothing was removed. Check ${ws.dir} on branch ${ws.branch}.`);
418
908
  return { ...base, keptWorktree: ws.dir, needsAttention: true };
419
909
  }
420
- if (!ws.remote || this.env[RUN_PUSH_ENV] === '0') {
910
+ if (!ws.remote || this.env[RUN_PUSH_ENV] === "0") {
911
+ if (keepRunCopy) {
912
+ notes.push(keptForReplyNote(ws));
913
+ return { ...base, keptWorktree: ws.dir };
914
+ }
421
915
  if (!(await this.removeWorktree(ws, notes))) {
422
916
  return { ...base, keptWorktree: ws.dir, needsAttention: true };
423
917
  }
@@ -428,51 +922,172 @@ export class RunWorkspaceManager {
428
922
  }
429
923
  if (input.signal?.aborted)
430
924
  return this.keepCancelled(ws, notes, commits);
431
- const push = await this.git(['push', '--set-upstream', ws.remote, ws.branch], ws.dir);
925
+ // ENG-327: bring the latest base into a completed run's branch before it
926
+ // is pushed. A clean merge becomes an ordinary merge commit on top, so the
927
+ // push below stays a fast-forward (never forced).
928
+ let baseMerge;
929
+ if (input.mergeBase && !input.waiting) {
930
+ if (!input.completed) {
931
+ baseMerge = {
932
+ outcome: "skipped",
933
+ reason: "The run stopped early, so the base branch was not merged in.",
934
+ };
935
+ }
936
+ else {
937
+ baseMerge = await this.mergeBaseLocked(ws, input.mergeBase.resolveConflicts, input.signal);
938
+ if (input.signal?.aborted)
939
+ return this.keepCancelled(ws, notes, commits);
940
+ if (baseMerge.outcome === "merged") {
941
+ base.commits =
942
+ Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || commits;
943
+ }
944
+ else if (baseMerge.outcome === "conflict") {
945
+ notes.push(`Merging the latest ${ws.baseBranch} hit conflicts that need a decision: ${baseMerge.files.join(", ") || "unknown files"}. ${baseMerge.reason}`);
946
+ // The merge was aborted; anything left behind means it isn't safe to clean up.
947
+ if (await this.isDirty(ws.dir)) {
948
+ notes.push(`The merge couldn't be fully undone, so nothing was pushed. Check ${ws.dir} on branch ${ws.branch}.`);
949
+ return { ...base, keptWorktree: ws.dir, needsAttention: true, baseMerge };
950
+ }
951
+ }
952
+ else if (baseMerge.outcome === "skipped") {
953
+ notes.push(baseMerge.reason);
954
+ }
955
+ }
956
+ base.baseMerge = baseMerge;
957
+ }
958
+ // A branch that still conflicts with its base isn't ready to merge.
959
+ const ready = input.completed && baseMerge?.outcome !== "conflict";
960
+ // ENG-327: checks, completeness and migrations, recorded as a wrap-up attempt.
961
+ let verdict;
962
+ if (input.wrapUp && input.completed && !input.waiting) {
963
+ try {
964
+ verdict = await input.wrapUp({
965
+ dir: ws.dir,
966
+ branch: ws.branch,
967
+ baseBranch: ws.baseBranch,
968
+ baseRef: ws.baseRef,
969
+ ...(baseMerge ? { baseMerge } : {}),
970
+ });
971
+ base.wrapUp = { status: verdict.status, ready: verdict.ready, reasons: verdict.reasons };
972
+ if (!verdict.ready) {
973
+ notes.push(`The wrap-up didn't pass, so the pull request stays a draft: ${verdict.reasons.join(" ")}`);
974
+ }
975
+ }
976
+ catch (error) {
977
+ const reason = `The wrap-up couldn't run: ${error instanceof Error ? error.message : String(error)}.`;
978
+ base.wrapUp = { status: "failed", ready: false, reasons: [reason] };
979
+ notes.push(`${reason} The pull request stays a draft.`);
980
+ }
981
+ // The checks may leave build output or formatting changes behind. The
982
+ // run's work is already committed, so put the worktree back to HEAD.
983
+ await this.discardCheckLeftovers(ws, notes);
984
+ if (input.signal?.aborted)
985
+ return this.keepCancelled(ws, notes, commits);
986
+ }
987
+ // With a wrap-up, the pull request opens as a draft; the review marks it ready.
988
+ const draft = !ready || input.wrapUp !== undefined || input.waiting !== undefined;
989
+ const push = await this.git(["push", "--set-upstream", ws.remote, ws.branch], ws.dir);
432
990
  if (push.status !== 0) {
433
- notes.push(`Couldn't push the branch to ${ws.remote}: ${gitReason(push.stderr) || 'unknown error'}. The work is safe in ${ws.dir} on branch ${ws.branch}.`);
991
+ notes.push(`Couldn't push the branch to ${ws.remote}: ${gitReason(push.stderr) || "unknown error"}. The work is safe in ${ws.dir} on branch ${ws.branch}.`);
434
992
  return { ...base, keptWorktree: ws.dir };
435
993
  }
436
- const title = `CompBox: epic ${input.epicId}${input.completed ? '' : ' (stopped early, needs review)'}`;
994
+ const title = `CompBox: epic ${input.epicId}${input.waiting
995
+ ? " (waiting for your reply)"
996
+ : input.completed
997
+ ? ""
998
+ : " (stopped early, needs review)"}`;
437
999
  const body = [
1000
+ ...(input.waiting ? [waitingPrBodyBlock(input.waiting.request), "", "---", ""] : []),
438
1001
  `Code written by the CompBox orchestrator for epic **${input.epicId}** (job \`${input.jobId}\`).`,
439
- '',
440
- input.completed
441
- ? 'The orchestrator finished every phase. Review the changes, check that CI passes, then merge.'
442
- : `The orchestrator stopped before finishing${input.stopReason ? `: ${input.stopReason}` : '.'} This is a draft so the partial work can be reviewed.`,
443
- '',
444
- `${String(commits)} commit${commits === 1 ? '' : 's'} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`,
445
- ].join('\n');
1002
+ "",
1003
+ input.waiting
1004
+ ? "The orchestrator paused to ask the question above. This is a draft until the build finishes."
1005
+ : !input.completed
1006
+ ? `The orchestrator stopped before finishing${input.stopReason ? `: ${input.stopReason}` : "."} This is a draft so the partial work can be reviewed.`
1007
+ : baseMerge?.outcome === "conflict"
1008
+ ? `The orchestrator finished every phase, but merging the latest \`${ws.baseBranch}\` hit conflicts that need a decision (${baseMerge.files.map((f) => `\`${f}\``).join(", ")}). This is a draft until they are resolved.`
1009
+ : input.wrapUp
1010
+ ? "The orchestrator finished every phase. The CompBox wrap-up review below says whether it's ready to merge."
1011
+ : "The orchestrator finished every phase. Review the changes, check that CI passes, then merge.",
1012
+ "",
1013
+ `${String(base.commits)} commit${base.commits === 1 ? "" : "s"} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`,
1014
+ ].join("\n");
446
1015
  // CompBox's GitHub app first (no local GitHub CLI needed), then `gh`.
447
1016
  let prUrl;
1017
+ let prNumber;
448
1018
  if (this.openPullRequest) {
449
1019
  try {
450
- prUrl = (await this.openPullRequest({ branch: ws.branch, base: ws.baseBranch, title, body, draft: !input.completed })).url;
1020
+ const opened = await this.openPullRequest({
1021
+ branch: ws.branch,
1022
+ base: ws.baseBranch,
1023
+ title,
1024
+ body,
1025
+ draft,
1026
+ });
1027
+ prUrl = opened.url;
1028
+ prNumber = opened.number;
451
1029
  }
452
1030
  catch {
453
1031
  prUrl = undefined;
454
1032
  }
455
1033
  }
456
- let pr = { status: 0, stdout: '', stderr: '' };
1034
+ let pr = { status: 0, stdout: "", stderr: "" };
457
1035
  if (!prUrl) {
458
- const prArgs = ['pr', 'create', '--base', ws.baseBranch, '--head', ws.branch, '--title', title, '--body', body];
459
- if (!input.completed)
460
- prArgs.push('--draft');
461
- pr = await this.run('gh', prArgs, ws.dir);
1036
+ const prArgs = [
1037
+ "pr",
1038
+ "create",
1039
+ "--base",
1040
+ ws.baseBranch,
1041
+ "--head",
1042
+ ws.branch,
1043
+ "--title",
1044
+ title,
1045
+ "--body",
1046
+ body,
1047
+ ];
1048
+ if (draft)
1049
+ prArgs.push("--draft");
1050
+ pr = await this.run("gh", prArgs, ws.dir);
462
1051
  prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : undefined;
463
1052
  if (!prUrl && ws.continued) {
464
1053
  // The continued branch usually has its pull request already.
465
- const existing = await this.run('gh', ['pr', 'view', ws.branch, '--json', 'url', '--jq', '.url'], ws.dir);
1054
+ const existing = await this.run("gh", ["pr", "view", ws.branch, "--json", "url", "--jq", ".url"], ws.dir);
466
1055
  if (existing.status === 0)
467
1056
  prUrl = /https:\/\/\S+/.exec(existing.stdout)?.[0];
468
1057
  }
469
1058
  }
470
1059
  let compareUrl;
471
1060
  if (!prUrl) {
472
- const remoteUrl = (await this.git(['remote', 'get-url', ws.remote], ws.dir)).stdout.trim();
1061
+ const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
473
1062
  compareUrl = githubCompareUrl(remoteUrl, ws.baseBranch, ws.branch) ?? undefined;
474
- notes.push(`The branch was pushed, but the pull request couldn't be opened automatically${gitReason(pr.stderr) ? ` (${gitReason(pr.stderr)})` : ''}.` +
475
- (compareUrl ? ' Use the link to open it.' : ` Open a pull request for ${ws.branch} on your git host.`));
1063
+ notes.push(`The branch was pushed, but the pull request couldn't be opened automatically${gitReason(pr.stderr) ? ` (${gitReason(pr.stderr)})` : ""}.` +
1064
+ (compareUrl
1065
+ ? " Use the link to open it."
1066
+ : ` Open a pull request for ${ws.branch} on your git host.`));
1067
+ }
1068
+ if (verdict && prUrl) {
1069
+ const problems = await verdict.publish({
1070
+ url: prUrl,
1071
+ ...(prNumber !== undefined ? { number: prNumber } : {}),
1072
+ });
1073
+ notes.push(...problems);
1074
+ if (problems.length > 0 && base.wrapUp) {
1075
+ base.wrapUp = { status: "failed", ready: false, reasons: [...base.wrapUp.reasons, ...problems] };
1076
+ }
1077
+ }
1078
+ else if (verdict) {
1079
+ notes.push("The wrap-up review couldn't be posted because there is no pull request yet.");
1080
+ }
1081
+ // ENG-337: a paused run keeps its folder so the reply can resume there.
1082
+ if (keepRunCopy) {
1083
+ notes.push(keptForReplyNote(ws));
1084
+ return {
1085
+ ...base,
1086
+ pushed: true,
1087
+ ...(prUrl ? { prUrl } : {}),
1088
+ ...(compareUrl ? { compareUrl } : {}),
1089
+ keptWorktree: ws.dir,
1090
+ };
476
1091
  }
477
1092
  // The branch is pushed, so the worktree can go (removeWorktree still
478
1093
  // re-checks it is clean first).
@@ -485,9 +1100,156 @@ export class RunWorkspaceManager {
485
1100
  ...(removed ? {} : { keptWorktree: ws.dir, needsAttention: true }),
486
1101
  };
487
1102
  }
1103
+ /**
1104
+ * Puts a run's worktree back to its last commit after the wrap-up checks
1105
+ * (ENG-327). Only check output can be there: the run's work was committed
1106
+ * before the checks ran. Ignored files (node_modules, build caches) stay.
1107
+ */
1108
+ async discardCheckLeftovers(ws, notes) {
1109
+ if (!(await this.isDirty(ws.dir)))
1110
+ return;
1111
+ await this.git(["checkout", "--", "."], ws.dir);
1112
+ await this.git(["clean", "-fd"], ws.dir);
1113
+ notes.push("The project checks changed some files; those changes were discarded.");
1114
+ }
1115
+ /**
1116
+ * Merges the latest base branch into the run's branch (ENG-327). Runs under
1117
+ * the repo lock (from finish). Never rewrites history: a clean merge is a
1118
+ * normal merge commit; conflicts go to one time-boxed agent turn limited to
1119
+ * the conflicted files, and anything it doesn't settle — conflicts left,
1120
+ * markers left, other files touched, or the commit failing — aborts the merge.
1121
+ */
1122
+ async mergeBaseLocked(ws, resolveConflicts, signal) {
1123
+ if (!ws.remote)
1124
+ return {
1125
+ outcome: "skipped",
1126
+ reason: "The repository has no remote, so the base branch was not merged in.",
1127
+ };
1128
+ const fetch = await this.git(["fetch", ws.remote, ws.baseBranch], ws.dir);
1129
+ if (fetch.status !== 0) {
1130
+ return {
1131
+ outcome: "skipped",
1132
+ reason: `Couldn't fetch the latest ${ws.baseBranch} to merge it in: ${gitReason(fetch.stderr) || "unknown error"}.`,
1133
+ };
1134
+ }
1135
+ // The run's work is all committed by now; a merge only ever starts from a
1136
+ // clean worktree, so undoing it below can't lose anything.
1137
+ if (await this.isDirty(ws.dir)) {
1138
+ return {
1139
+ outcome: "skipped",
1140
+ reason: "The run folder has uncommitted changes, so the base branch was not merged in.",
1141
+ };
1142
+ }
1143
+ const baseRef = `${ws.remote}/${ws.baseBranch}`;
1144
+ const behind = await this.git(["rev-list", "--count", `HEAD..${baseRef}`], ws.dir);
1145
+ if (behind.status === 0 && behind.stdout.trim() === "0")
1146
+ return { outcome: "up_to_date" };
1147
+ const message = `Merge ${baseRef} into ${ws.branch} (CompBox wrap-up)`;
1148
+ const merge = await this.git(["merge", "--no-ff", "--no-edit", "-m", message, baseRef], ws.dir);
1149
+ if (merge.status === 0)
1150
+ return { outcome: "merged", resolvedFiles: [] };
1151
+ const files = await this.conflictedFiles(ws.dir);
1152
+ if (files.length === 0) {
1153
+ // Not a content conflict (e.g. untracked files in the way): undo and report.
1154
+ await this.git(["merge", "--abort"], ws.dir);
1155
+ return {
1156
+ outcome: "conflict",
1157
+ files: [],
1158
+ reason: `The merge failed: ${gitReason(merge.stderr) || gitReason(merge.stdout) || "unknown error"}.`,
1159
+ };
1160
+ }
1161
+ const abort = async (reason) => {
1162
+ await this.git(["merge", "--abort"], ws.dir);
1163
+ // The worktree was clean when the merge started, so anything left now is
1164
+ // the conflict turn's own stray edits: drop them (never ignored files).
1165
+ await this.git(["reset", "--hard", "HEAD"], ws.dir);
1166
+ await this.git(["clean", "-fd"], ws.dir);
1167
+ return { outcome: "conflict", files, reason };
1168
+ };
1169
+ if (!resolveConflicts)
1170
+ return abort("No agent was available to resolve them, so the merge was undone.");
1171
+ if (signal?.aborted)
1172
+ return abort("The run was cancelled, so the merge was undone.");
1173
+ // Everything outside the conflicted files, as merged by git: the agent may
1174
+ // not change any of it.
1175
+ const before = await this.untouchableState(ws.dir, files);
1176
+ let resolved;
1177
+ try {
1178
+ resolved = await resolveConflicts({
1179
+ dir: ws.dir,
1180
+ files,
1181
+ baseBranch: ws.baseBranch,
1182
+ ...(signal ? { signal } : {}),
1183
+ });
1184
+ }
1185
+ catch (error) {
1186
+ resolved = { ok: false, reason: error instanceof Error ? error.message : String(error) };
1187
+ }
1188
+ if (signal?.aborted)
1189
+ return abort("The run was cancelled, so the merge was undone.");
1190
+ if (!resolved.ok) {
1191
+ return abort(`The agent couldn't resolve them${resolved.reason ? ` (${resolved.reason})` : ""}, so the merge was undone.`);
1192
+ }
1193
+ if ((await this.untouchableState(ws.dir, files)) !== before) {
1194
+ return abort("The agent changed files outside the conflicts, so the merge was undone.");
1195
+ }
1196
+ const add = await this.git(["add", "--", ...files], ws.dir);
1197
+ if (add.status !== 0)
1198
+ return abort(`Couldn't stage the resolved files: ${gitReason(add.stderr) || "unknown error"}.`);
1199
+ if ((await this.conflictedFiles(ws.dir)).length > 0) {
1200
+ return abort("Some conflicts were left unresolved, so the merge was undone.");
1201
+ }
1202
+ // `git grep` exits 0 when it finds a match: leftover conflict markers.
1203
+ const markers = await this.git(["grep", "--cached", "-l", "-E", "^(<<<<<<<|>>>>>>>)( |$)", "--", ...files], ws.dir);
1204
+ if (markers.status === 0) {
1205
+ return abort(`Conflict markers were left in ${markers.stdout.trim().split("\n").join(", ")}, so the merge was undone.`);
1206
+ }
1207
+ const commit = await this.git(["commit", "--no-verify", "--no-edit", "-m", message], ws.dir);
1208
+ if (commit.status !== 0) {
1209
+ return abort(`Couldn't commit the merge: ${gitReason(commit.stderr) || gitReason(commit.stdout) || "unknown error"}.`);
1210
+ }
1211
+ return { outcome: "merged", resolvedFiles: files };
1212
+ }
1213
+ /** Paths git still marks as conflicted (unmerged). */
1214
+ async conflictedFiles(dir) {
1215
+ const result = await this.git(["diff", "--name-only", "--diff-filter=U", "-z"], dir);
1216
+ return [...new Set(result.stdout.split("\0").filter((f) => f.length > 0))];
1217
+ }
1218
+ /**
1219
+ * A fingerprint of everything outside `files`: the index entries, unstaged
1220
+ * changes and untracked files. Any change means the conflict turn strayed.
1221
+ */
1222
+ async untouchableState(dir, files) {
1223
+ const allowed = new Set(files);
1224
+ const keep = (out) => out
1225
+ .split("\0")
1226
+ .filter((entry) => entry.length > 0)
1227
+ .filter((entry) => !allowed.has(entry.includes("\t") ? entry.slice(entry.indexOf("\t") + 1) : entry))
1228
+ .join("\n");
1229
+ const index = await this.git(["ls-files", "--stage", "-z"], dir);
1230
+ const unstaged = await this.git(["diff", "--name-only", "-z"], dir);
1231
+ const untracked = await this.git(["ls-files", "--others", "--exclude-standard", "-z"], dir);
1232
+ // Unstaged changes are fingerprinted by content too, so a second edit to an
1233
+ // already-dirty file still counts.
1234
+ const unstagedFiles = keep(unstaged.stdout)
1235
+ .split("\n")
1236
+ .filter((f) => f.length > 0);
1237
+ const hashes = unstagedFiles.length > 0
1238
+ ? (await this.git(["hash-object", "--", ...unstagedFiles], dir)).stdout
1239
+ : "";
1240
+ return [
1241
+ String(index.status),
1242
+ keep(index.stdout),
1243
+ String(unstaged.status),
1244
+ unstagedFiles.join("\n"),
1245
+ hashes,
1246
+ String(untracked.status),
1247
+ keep(untracked.stdout),
1248
+ ].join("\u0001");
1249
+ }
488
1250
  /** True when the worktree has uncommitted (or unreadable) state. */
489
1251
  async isDirty(dir) {
490
- const status = await this.git(['status', '--porcelain'], dir);
1252
+ const status = await this.git(["status", "--porcelain"], dir);
491
1253
  // A failed `git status` counts as dirty: never assume a worktree is clean.
492
1254
  return status.status !== 0 || status.stdout.trim().length > 0;
493
1255
  }
@@ -503,7 +1265,7 @@ export class RunWorkspaceManager {
503
1265
  }
504
1266
  // --force only skips git's own check for ignored/submodule state; this
505
1267
  // method already verified there is nothing uncommitted.
506
- await this.git(['worktree', 'remove', '--force', ws.dir], ws.projectDir);
1268
+ await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
507
1269
  return true;
508
1270
  }
509
1271
  }