codex-supervisor-mcp 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/side-chat.js CHANGED
@@ -24,6 +24,9 @@
24
24
  // session ended ................... fork deleted, history cleared
25
25
  import { execFileSync, spawn } from "node:child_process";
26
26
  import { randomUUID } from "node:crypto";
27
+ import { readFileSync } from "node:fs";
28
+ import { join } from "node:path";
29
+ import { codexHome } from "./paths.js";
27
30
  import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
28
31
  import {
29
32
  closeSideSession,
@@ -38,6 +41,77 @@ import {
38
41
 
39
42
  const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
40
43
  const TURN_TIMEOUT_MS = 10 * 60 * 1000;
44
+
45
+ // What a side question is, said to the fork every time. Without it the fork
46
+ // treats the question as a new task: one real fork spent its whole turn
47
+ // trying to ssh to a build host from inside the read-only sandbox, probing
48
+ // the network, and finally reaching for an MCP tool.
49
+ const SIDE_PREAMBLE = `This is a side question about the work you did in this thread, asked from a read-only fork. Rules for this turn:
50
+ - Answer from what you already know from this thread. You may read files in the working directory to check.
51
+ - The sandbox is read-only and has no network: do not try ssh, curl, builds, tests, package installs or writes; they will fail and waste the turn. MCP tools are disabled here.
52
+ - If answering properly needs something you cannot check from here (a remote machine, a running service, a command), say exactly what and stop; do not retry.
53
+ - Nothing you do here changes the work. If the work needs changing, say what should change; the main thread will ask the worker itself.
54
+ - Be direct and short. Lead with the answer.`;
55
+
56
+ export function sideQuestionText(question) {
57
+ return `${SIDE_PREAMBLE}\n\nQuestion:\n${question}`;
58
+ }
59
+
60
+ // The fork inherits the worker's MCP servers. A side question must not be
61
+ // able to dispatch, resume or cancel anything through them, and a fork that
62
+ // waits on a tool it cannot use burns its turn; every server named in the
63
+ // Codex config is switched off for the turn. Sub-tables
64
+ // ([mcp_servers.x.env]) are not servers and are skipped.
65
+ //
66
+ // The key path is written bare: `-c mcp_servers.name.enabled=false`. A
67
+ // quoted name (`mcp_servers."name".enabled`) is taken by codex as a new
68
+ // server literally called "name", quotes included, with no transport, and
69
+ // the whole config then fails to load.
70
+ export function sideTurnConfigArgs(configText) {
71
+ const names = new Set();
72
+ for (const line of String(configText ?? "").split("\n")) {
73
+ const match = line.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^\].]+))\]\s*(?:#.*)?$/);
74
+ if (match) names.add(match[1] ?? match[2]);
75
+ }
76
+ const args = [];
77
+ for (const name of names) {
78
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) continue; // a name codex cannot take bare on the command line
79
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
80
+ }
81
+ return args;
82
+ }
83
+
84
+ function codexConfigText() {
85
+ try {
86
+ return readFileSync(join(codexHome, "config.toml"), "utf8");
87
+ } catch {
88
+ return "";
89
+ }
90
+ }
91
+
92
+ // The session to ask on. A fork taken before the worker was resumed no
93
+ // longer reflects the worker's thread; it is dropped and a new one taken
94
+ // from the current thread. `fresh` forces that. Returns the session and why
95
+ // it was (re)opened: "requested", "worker_resumed", "first" or null.
96
+ export async function prepareSideSession(task, { fresh = false } = {}) {
97
+ let session = await getSideSession(task.id);
98
+ let refreshed = null;
99
+ const stale =
100
+ session?.fork_thread_id &&
101
+ session.worker_run_count !== null &&
102
+ session.worker_run_count !== undefined &&
103
+ (task.run_count ?? 0) > session.worker_run_count;
104
+ if (session && (fresh || stale)) {
105
+ await endSideSession(task.id);
106
+ session = null;
107
+ refreshed = fresh ? "requested" : "worker_resumed";
108
+ }
109
+ if (!session) {
110
+ session = await openSideSession(task.id, task.run_count ?? 0);
111
+ refreshed = refreshed ?? "first";
112
+ }
113
+ return { session, refreshed };
114
+ }
41
115
  const OUTPUT_CLIP = 4000;
42
116
 
43
117
  // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
@@ -280,19 +354,19 @@ export function attachToTurn(taskId, res) {
280
354
 
281
355
  // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
282
356
  // turn has ended, however it ended.
283
- export async function runSideTurn({ task, text, res = null }) {
357
+ export async function runSideTurn({ task, text, res = null, fresh = false }) {
284
358
  await sweepOnce();
285
359
  if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
286
360
  if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
287
361
  const target = codexTarget();
288
362
  if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
289
363
 
290
- let session = await getSideSession(task.id);
291
- if (!session) session = await openSideSession(task.id);
364
+ const { session, refreshed } = await prepareSideSession(task, { fresh });
292
365
 
293
366
  const args = session.fork_thread_id
294
367
  ? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
295
368
  : ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
369
+ args.push(...sideTurnConfigArgs(codexConfigText()));
296
370
  if (task.model) args.push("-m", task.model);
297
371
  args.push(session.fork_thread_id ?? task.thread_id, "-");
298
372
 
@@ -369,7 +443,7 @@ export async function runSideTurn({ task, text, res = null }) {
369
443
  stderr = (stderr + chunk).slice(-4000);
370
444
  });
371
445
  child.stdin.on("error", () => {});
372
- child.stdin.end(text);
446
+ child.stdin.end(sideQuestionText(text));
373
447
 
374
448
  return new Promise((resolve) => {
375
449
  const finish = async (code, signal) => {
@@ -400,7 +474,7 @@ export async function runSideTurn({ task, text, res = null }) {
400
474
  live.watchers.clear();
401
475
  running.delete(task.id);
402
476
  await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
403
- resolve({ status, turnId, forkThreadId: session.fork_thread_id });
477
+ resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
404
478
  };
405
479
  child.on("error", (error) => {
406
480
  stderr += `\nfailed to start codex: ${error.message}`;
@@ -410,6 +484,72 @@ export async function runSideTurn({ task, text, res = null }) {
410
484
  });
411
485
  }
412
486
 
487
+ // The answer of a turn, as the text parts joined; null while nothing has
488
+ // been said yet.
489
+ function answerOf(turn) {
490
+ const parts = partsFromChunks(turn.chunks ?? []);
491
+ const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
492
+ return text || null;
493
+ }
494
+
495
+ function turnView(turn) {
496
+ return {
497
+ turn_id: turn.id,
498
+ question: turn.question,
499
+ status: turn.status,
500
+ answer: answerOf(turn),
501
+ usage: turn.usage ?? null,
502
+ error: turn.error ?? null,
503
+ started_at: turn.started_at ?? null,
504
+ ended_at: turn.ended_at ?? null
505
+ };
506
+ }
507
+
508
+ // The newest side turn of a worker, for a caller that asked earlier and
509
+ // comes back for the answer. Null when nothing was ever asked.
510
+ export async function latestSideTurn(taskId) {
511
+ await sweepOnce();
512
+ const turns = await readSideTurns(taskId);
513
+ const live = running.get(taskId) ?? null;
514
+ const latest = turns.at(-1) ?? null;
515
+ const session = await getSideSession(taskId);
516
+ if (!latest) return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: null };
517
+ const view = turnView(latest);
518
+ if (live && live.turnId === latest.id) {
519
+ view.status = "running";
520
+ view.answer = answerOf({ chunks: live.chunks });
521
+ }
522
+ return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: view };
523
+ }
524
+
525
+ // Ask the worker a question on the side, without touching its own thread,
526
+ // and wait up to `timeoutMs` for the answer. A turn that outlives the budget
527
+ // keeps running in this process; the caller reads it back with latestSideTurn.
528
+ export async function askWorker({ task, question, timeoutMs = 110000, fresh = false }) {
529
+ // Decided here, before the race, so a turn that outruns the budget still
530
+ // reports whether the fork was taken anew.
531
+ const { refreshed } = await prepareSideSession(task, { fresh });
532
+ const turn = runSideTurn({ task, text: question });
533
+ // runSideTurn throws synchronously-ish (rejected promise) for no_thread,
534
+ // busy and codex_missing before anything starts; surface those as-is.
535
+ let timer;
536
+ const budget = new Promise((resolve) => {
537
+ timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
538
+ });
539
+ try {
540
+ const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
541
+ if (!outcome.timedOut) {
542
+ const state = await latestSideTurn(task.id);
543
+ return { ...state, timed_out: false, refreshed };
544
+ }
545
+ turn.catch(() => {});
546
+ const state = await latestSideTurn(task.id);
547
+ return { ...state, timed_out: true, refreshed };
548
+ } finally {
549
+ clearTimeout(timer);
550
+ }
551
+ }
552
+
413
553
  export function stopSideTurn(taskId) {
414
554
  const live = running.get(taskId);
415
555
  if (!live) return { stopped: false };
@@ -429,7 +569,8 @@ export async function endSideSession(taskId) {
429
569
  const target = codexTarget();
430
570
  if (!target.error) {
431
571
  deleted = await new Promise((resolve) => {
432
- const child = spawn(target.cmd, [...target.prefixArgs, "delete", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
572
+ // --force: without a terminal codex asks for confirmation and exits.
573
+ const child = spawn(target.cmd, [...target.prefixArgs, "delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
433
574
  const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
434
575
  child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
435
576
  child.on("error", () => { clearTimeout(t); resolve(false); });
@@ -0,0 +1,93 @@
1
+ // Copies the bundled skill into the skill directories of the agent clients on
2
+ // this machine. setup.js runs it after a global install; mcp-server.js runs it
3
+ // every time the server starts, because a server launched through
4
+ // `npx -y codex-supervisor-mcp@latest` never runs postinstall, and the skill
5
+ // text has to move together with the tool surface it describes.
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
13
+
14
+ export const SKILL_NAME = "codex-supervisor";
15
+ export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");
16
+
17
+ // Resolved on each call so a test can point HOME somewhere else first.
18
+ export function skillRoots() {
19
+ const home = homedir();
20
+ return {
21
+ claude: { id: "claude", label: "Claude Code", skillRoot: join(home, ".claude", "skills") },
22
+ agents: { id: "agents", label: "~/.agents", skillRoot: join(home, ".agents", "skills") },
23
+ codex: { id: "codex", label: "Codex", skillRoot: join(home, ".codex", "skills") }
24
+ };
25
+ }
26
+
27
+ // The skill is read by other processes at any moment, and the server that
28
+ // writes it may be killed at any moment: write beside it, then rename, so
29
+ // the file is always either the old text or the new one, never a torso.
30
+ async function writeAtomically(destination, text) {
31
+ const staging = `${destination}.tmp-${process.pid}-${Date.now()}`;
32
+ await writeFile(staging, text);
33
+ await rename(staging, destination);
34
+ }
35
+
36
+ // Writes the bundled skill under client.skillRoot. A file that differs is
37
+ // backed up as SKILL.md.bak-<timestamp> first unless options.force is set.
38
+ // Returns one of: unchanged, updated, installed, would-update, would-install.
39
+ export async function installSkill(client, options = {}, log = () => {}) {
40
+ const destination = join(client.skillRoot, SKILL_NAME, "SKILL.md");
41
+ const source = await readFile(skillSource, "utf8");
42
+
43
+ if (existsSync(destination)) {
44
+ const current = await readFile(destination, "utf8");
45
+ if (current === source) {
46
+ log(`skill ${client.label}: up to date`);
47
+ return "unchanged";
48
+ }
49
+ if (!options.force) {
50
+ const backup = `${destination}.bak-${Date.now()}`;
51
+ if (options.dryRun) {
52
+ log(`skill ${client.label}: would back up to ${backup} and overwrite`);
53
+ return "would-update";
54
+ }
55
+ await writeAtomically(backup, current);
56
+ }
57
+ if (options.dryRun) {
58
+ log(`skill ${client.label}: would overwrite`);
59
+ return "would-update";
60
+ }
61
+ await writeAtomically(destination, source);
62
+ log(`skill ${client.label}: updated`);
63
+ return "updated";
64
+ }
65
+
66
+ if (options.dryRun) {
67
+ log(`skill ${client.label}: would install to ${destination}`);
68
+ return "would-install";
69
+ }
70
+ await mkdir(dirname(destination), { recursive: true });
71
+ await writeAtomically(destination, source);
72
+ log(`skill ${client.label}: installed`);
73
+ return "installed";
74
+ }
75
+
76
+ // Brings every client whose skill directory already exists up to date. It
77
+ // never creates a client's skill directory: a missing ~/.codex/skills means
78
+ // Codex is not used here. One client failing does not stop the others.
79
+ // Returns { installed, updated, unchanged, failed } as lists of client labels
80
+ // (failed entries carry the error message).
81
+ export async function syncSkills({ force = false } = {}) {
82
+ const result = { installed: [], updated: [], unchanged: [], failed: [] };
83
+ for (const client of Object.values(skillRoots())) {
84
+ if (!existsSync(client.skillRoot)) continue;
85
+ try {
86
+ const outcome = await installSkill(client, { force });
87
+ result[outcome].push(client.label);
88
+ } catch (error) {
89
+ result.failed.push(`${client.label}: ${error.message}`);
90
+ }
91
+ }
92
+ return result;
93
+ }
package/src/task-store.js CHANGED
@@ -180,7 +180,8 @@ const SIDE_DDL = `
180
180
  task_id TEXT PRIMARY KEY,
181
181
  fork_thread_id TEXT,
182
182
  created_at TEXT NOT NULL,
183
- ended_at TEXT
183
+ ended_at TEXT,
184
+ worker_run_count INTEGER
184
185
  );
185
186
  CREATE TABLE IF NOT EXISTS side_turns (
186
187
  id TEXT PRIMARY KEY,
@@ -231,6 +232,15 @@ function initializeSchema(dbInstance) {
231
232
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
232
233
  dbInstance.exec(SESSIONS_DDL);
233
234
  dbInstance.exec(SIDE_DDL);
235
+ // Rows written before 0.7.1 have no worker_run_count: the fork is then
236
+
237
+ // never judged stale, which is what those rows did before.
238
+
239
+ if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
240
+
241
+ dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
242
+
243
+ }
234
244
  dbInstance.exec("COMMIT;");
235
245
  } catch (error) {
236
246
  try {
@@ -470,13 +480,15 @@ export async function getSideSession(taskId) {
470
480
  return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
471
481
  }
472
482
 
473
- export async function openSideSession(taskId) {
483
+ // `workerRunCount` is the worker's run_count when the fork is taken; a
484
+ // worker resumed after that has a thread the fork no longer reflects.
485
+ export async function openSideSession(taskId, workerRunCount = null) {
474
486
  await ensureFilesystem();
475
487
  const now = new Date().toISOString();
476
488
  openDb()
477
- .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at) VALUES (?, NULL, ?, NULL)
478
- ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL`)
479
- .run(taskId, now);
489
+ .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at, worker_run_count) VALUES (?, NULL, ?, NULL, ?)
490
+ ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL, worker_run_count = excluded.worker_run_count`)
491
+ .run(taskId, now, workerRunCount);
480
492
  return getSideSession(taskId);
481
493
  }
482
494
 
@@ -10,7 +10,7 @@
10
10
  import { existsSync, readFileSync } from "node:fs";
11
11
  import { mkdir, readFile, writeFile } from "node:fs/promises";
12
12
  import { execFileSync } from "node:child_process";
13
- import { dirname, join, resolve } from "node:path";
13
+ import { basename, dirname, join, resolve } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { dataDir } from "./paths.js";
16
16
 
@@ -59,27 +59,47 @@ export function compareVersions(a, b) {
59
59
  // What is actually on disk: the version from package.json, plus whichever
60
60
  // provenance is available - npm's recorded integrity for a global install,
61
61
  // the HEAD commit for a git checkout.
62
+ // A copy that npx fetched lives under npm's cache (.../_npx/<hash>/...).
63
+ // npx resolves `latest` on every start, so such a copy must never be
64
+ // auto-installed over a global one.
65
+ export function isNpxPath(path) {
66
+ return String(path).split(/[\\/]/).includes("_npx");
67
+ }
68
+
69
+ // Who put this copy here. Pure, so it can be tested on made-up paths.
70
+ // git - a checkout (also what `npm link` resolves to, since node follows
71
+ // the symlink before import.meta.url is set)
72
+ // npx - npm's exec cache; npx refreshes it by itself
73
+ // npm - a directory npm installed, global or project-local (the
74
+ // auto-updater tells those apart with `npm root -g` before writing)
75
+ export function installSource(root, { exists = existsSync } = {}) {
76
+ if (exists(join(root, ".git"))) return "git";
77
+ if (isNpxPath(root)) return "npx";
78
+ if (basename(dirname(root)) === "node_modules") return "npm";
79
+ return "unknown";
80
+ }
81
+
62
82
  export function installedPackage() {
63
- const info = { name: PACKAGE_NAME, version: packageJson.version, path: packageRoot, integrity: null, commit: null, source: "unknown" };
83
+ const info = { name: PACKAGE_NAME, version: packageJson.version, path: packageRoot, integrity: null, commit: null, source: installSource(packageRoot) };
84
+ // A project-local install records the package's integrity in the hidden
85
+ // lockfile one level up. A global install has no such record (each global
86
+ // package is its own root), so integrity stays null and only the version
87
+ // is compared.
64
88
  const lockPath = join(packageRoot, "..", ".package-lock.json");
65
- if (existsSync(lockPath)) {
89
+ if (info.source === "npm" && existsSync(lockPath)) {
66
90
  try {
67
91
  const lock = JSON.parse(readFileSync(lockPath, "utf8"));
68
92
  const entry = lock.packages?.[`node_modules/${PACKAGE_NAME}`];
69
- if (entry?.integrity) {
70
- info.integrity = entry.integrity;
71
- info.source = "npm";
72
- }
93
+ if (entry?.integrity) info.integrity = entry.integrity;
73
94
  } catch {
74
- // unreadable lock: fall through, provenance stays unknown
95
+ // unreadable lock: integrity stays unknown
75
96
  }
76
97
  }
77
- if (!info.integrity && existsSync(join(packageRoot, ".git"))) {
98
+ if (info.source === "git") {
78
99
  try {
79
100
  info.commit = execFileSync("git", ["-C", packageRoot, "rev-parse", "HEAD"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
80
- info.source = "git";
81
101
  } catch {
82
- // not a usable checkout
102
+ // a checkout without a usable git: still a checkout
83
103
  }
84
104
  }
85
105
  return info;
@@ -193,9 +213,12 @@ export async function checkForUpdate({ force = false } = {}) {
193
213
 
194
214
  // The small object that rides along in tool results. Null when there is
195
215
  // nothing to say, so the common case costs no bytes.
196
- export function updateNotice(result) {
216
+ // `autoUpdate` is the auto-update record (see auto-update.js); when it says
217
+ // the install is already under way or done, the notice stops asking the user
218
+ // to run npm and says what to do instead: start a new session.
219
+ export function updateNotice(result, autoUpdate = null) {
197
220
  if (!result || !result.notice) return null;
198
- return {
221
+ const field = {
199
222
  update_available: result.update_available,
200
223
  installed_version: result.installed.version,
201
224
  latest_version: result.latest?.version ?? null,
@@ -203,4 +226,21 @@ export function updateNotice(result) {
203
226
  install_command: result.install_command,
204
227
  notice: result.notice
205
228
  };
229
+ if (result.update_available && autoUpdate && autoUpdate.version === field.latest_version) {
230
+ const name = `${PACKAGE_NAME} ${field.latest_version}`;
231
+ if (autoUpdate.state === "done") {
232
+ field.install_command = null;
233
+ field.notice = `${name} has been installed in the background; this session still runs ${field.installed_version}. Start a new session (restart the MCP client) to use it.`;
234
+ } else if (autoUpdate.state === "started" || autoUpdate.state === "running") {
235
+ field.install_command = null;
236
+ field.notice = `${name} is being installed in the background; this session still runs ${field.installed_version}. The next session starts on it once the install finishes.`;
237
+ } else if (autoUpdate.state === "failed") {
238
+ field.notice = `${field.notice} (automatic install failed: ${autoUpdate.reason ?? "unknown"})`;
239
+ }
240
+ field.auto_update = { state: autoUpdate.state, version: autoUpdate.version, ...(autoUpdate.reason ? { reason: autoUpdate.reason } : {}) };
241
+ } else if (result.update_available && result.installed.source === "npx") {
242
+ field.install_command = null;
243
+ field.notice = `${PACKAGE_NAME} ${field.latest_version} is published; this npx-started session runs ${field.installed_version}. The next session fetches the new one by itself.`;
244
+ }
245
+ return field;
206
246
  }
package/src/worktree.js CHANGED
@@ -11,8 +11,9 @@
11
11
  // so the committed part is read as `git diff --name-only <base> HEAD`, where
12
12
  // base is the commit the worktree was created from.
13
13
  import { execFileSync } from "node:child_process";
14
- import { existsSync } from "node:fs";
14
+ import { existsSync, readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
+ import { truncateMiddleChars } from "./truncate.js";
16
17
 
17
18
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
18
19
 
@@ -36,7 +37,7 @@ function git(worktreePath, args) {
36
37
  });
37
38
  }
38
39
 
39
- function parsePorcelainLine(line) {
40
+ export function parsePorcelainLine(line) {
40
41
  // " M path", "?? path", "R old -> new"
41
42
  const trimmed = line.replace(/\s+$/, "");
42
43
  if (trimmed.length < 4) return null;
@@ -86,6 +87,113 @@ export function readWorktreeChanges(worktreePath, { baseCommit = null, branch =
86
87
  return Array.from(found, (entry) => join(worktreePath, entry));
87
88
  }
88
89
 
90
+ // What the worker changed, as patches: everything between the commit the
91
+ // worktree started from and the working tree, committed or not, plus files
92
+ // git does not track yet. This is the main thread's ground truth for "what
93
+ // did it do", as opposed to what the worker says it did.
94
+ //
95
+ // `maxChars` bounds the whole answer. Files are served in git's order; a
96
+ // file that does not fit is cut in the middle (truncated: true), and files
97
+ // after the budget is spent come back without a patch so the list of what
98
+ // changed is still complete.
99
+ export function readWorktreeDiff(worktreePath, { baseCommit = null, branch = null } = {}, { maxChars = 60000, paths = [] } = {}) {
100
+ if (!worktreePath || !existsSync(worktreePath)) return { error: "no_worktree", files: [] };
101
+ const base = resolveWorktreeBase(worktreePath, { baseCommit, branch });
102
+ if (!base) return { error: "no_base_commit", files: [] };
103
+ let head = null;
104
+ try {
105
+ head = git(worktreePath, ["rev-parse", "HEAD"]).trim();
106
+ } catch {
107
+ // a worktree without a resolvable HEAD still has a working tree to diff
108
+ }
109
+ const scope = Array.isArray(paths) && paths.length > 0 ? ["--", ...paths] : [];
110
+
111
+ const files = [];
112
+ const known = new Set();
113
+ try {
114
+ for (const line of nonEmptyLines(git(worktreePath, ["diff", "--name-status", "-M", base, ...scope]))) {
115
+ const [code, ...rest] = line.split("\t");
116
+ const path = rest.at(-1);
117
+ if (!path) continue;
118
+ known.add(path);
119
+ files.push({ path, status: statusWord(code), from: code.startsWith("R") && rest.length > 1 ? rest[0] : null });
120
+ }
121
+ } catch {
122
+ return { error: "diff_failed", base_commit: base, head, files: [] };
123
+ }
124
+ const counts = new Map();
125
+ try {
126
+ for (const line of nonEmptyLines(git(worktreePath, ["diff", "--numstat", "-M", base, ...scope]))) {
127
+ const [added, deleted, ...rest] = line.split("\t");
128
+ counts.set(rest.at(-1), { additions: added === "-" ? null : Number(added), deletions: deleted === "-" ? null : Number(deleted) });
129
+ }
130
+ } catch {
131
+ // counts are decoration
132
+ }
133
+ // Untracked files never show in `git diff`; the worker may have created
134
+ // them with a shell command and not added them.
135
+ try {
136
+ for (const line of git(worktreePath, ["status", "--porcelain", "--untracked-files=all", ...scope]).split("\n")) {
137
+ if (!line.startsWith("??")) continue;
138
+ const path = parsePorcelainLine(line);
139
+ if (!path || known.has(path)) continue;
140
+ known.add(path);
141
+ files.push({ path, status: "untracked", from: null });
142
+ }
143
+ } catch {
144
+ // status failing leaves the tracked part
145
+ }
146
+
147
+ let remaining = maxChars;
148
+ let truncatedFiles = 0;
149
+ for (const file of files) {
150
+ const stat = counts.get(file.path);
151
+ file.additions = stat?.additions ?? null;
152
+ file.deletions = stat?.deletions ?? null;
153
+ file.patch = null;
154
+ file.truncated = false;
155
+ if (remaining <= 0) {
156
+ file.truncated = true;
157
+ truncatedFiles += 1;
158
+ continue;
159
+ }
160
+ let patch = "";
161
+ try {
162
+ if (file.status === "untracked") {
163
+ const text = readFileSync(join(worktreePath, file.path), "utf8");
164
+ patch = text.split("\n").map((l, i, all) => (i === all.length - 1 && l === "" ? null : `+${l}`)).filter((l) => l !== null).join("\n");
165
+ if (file.additions === null) file.additions = patch === "" ? 0 : patch.split("\n").length;
166
+ } else {
167
+ patch = git(worktreePath, ["diff", "-M", base, "--", file.path]);
168
+ }
169
+ } catch {
170
+ patch = "";
171
+ }
172
+ if (patch.length > remaining) {
173
+ file.patch = truncateMiddleChars(patch, remaining);
174
+ file.truncated = true;
175
+ truncatedFiles += 1;
176
+ remaining = 0;
177
+ } else {
178
+ file.patch = patch;
179
+ remaining -= patch.length;
180
+ }
181
+ }
182
+ return { base_commit: base, head, files, total_files: files.length, truncated_files: truncatedFiles };
183
+ }
184
+
185
+ function statusWord(code) {
186
+ switch (code[0]) {
187
+ case "A": return "added";
188
+ case "M": return "modified";
189
+ case "D": return "deleted";
190
+ case "R": return "renamed";
191
+ case "C": return "copied";
192
+ case "T": return "type-changed";
193
+ default: return code;
194
+ }
195
+ }
196
+
89
197
  export function mergeChangedFiles(existing, discovered) {
90
198
  return Array.from(new Set([...(existing ?? []), ...(discovered ?? [])]));
91
199
  }