codex-supervisor-mcp 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +73 -7
- package/README.md +73 -7
- package/package.json +5 -1
- package/skills/codex-supervisor/SKILL.md +14 -2
- package/src/auto-update-worker.js +186 -0
- package/src/auto-update.js +144 -0
- package/src/event-parser.js +21 -2
- package/src/landing.js +117 -0
- package/src/mcp-server.js +146 -7
- package/src/setup.js +6 -47
- package/src/side-chat.js +82 -4
- package/src/skill-sync.js +93 -0
- package/src/update-check.js +53 -13
- package/src/worktree.js +110 -2
- package/web/dist/assets/{index-Dne-82WY.js → index-CqG_XY9n.js} +1 -1
- package/web/dist/index.html +1 -1
package/src/side-chat.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
// turn failed / timed out / stopped error on the turn, session still usable
|
|
23
23
|
// board restarted mid-turn ........ turn marked interrupted
|
|
24
24
|
// session ended ................... fork deleted, history cleared
|
|
25
|
-
import { spawn } from "node:child_process";
|
|
25
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
26
26
|
import { randomUUID } from "node:crypto";
|
|
27
27
|
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
28
28
|
import {
|
|
@@ -58,6 +58,21 @@ function codexTarget() {
|
|
|
58
58
|
return { cmd: target.cmd, prefixArgs: target.prefixArgs };
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
// Stop a side turn and everything under it. On Windows the direct child is
|
|
62
|
+
// the JS wrapper around the native Codex binary; killing the wrapper alone
|
|
63
|
+
// leaves the real CLI running, so the whole tree goes through taskkill.
|
|
64
|
+
function killTree(child) {
|
|
65
|
+
if (process.platform === "win32" && child.pid) {
|
|
66
|
+
try {
|
|
67
|
+
execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
68
|
+
return;
|
|
69
|
+
} catch {
|
|
70
|
+
// fall back to the handle below
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
child.kill("SIGTERM");
|
|
74
|
+
}
|
|
75
|
+
|
|
61
76
|
function clip(text, max = OUTPUT_CLIP) {
|
|
62
77
|
if (typeof text !== "string") return text ?? null;
|
|
63
78
|
return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
|
|
@@ -321,11 +336,11 @@ export async function runSideTurn({ task, text, res = null }) {
|
|
|
321
336
|
let stoppedBy = null;
|
|
322
337
|
const timer = setTimeout(() => {
|
|
323
338
|
stoppedBy = "timeout";
|
|
324
|
-
child
|
|
339
|
+
killTree(child);
|
|
325
340
|
}, TURN_TIMEOUT_MS);
|
|
326
341
|
live.stop = (reason) => {
|
|
327
342
|
stoppedBy = reason;
|
|
328
|
-
child
|
|
343
|
+
killTree(child);
|
|
329
344
|
};
|
|
330
345
|
|
|
331
346
|
child.stdout.setEncoding("utf8");
|
|
@@ -395,6 +410,69 @@ export async function runSideTurn({ task, text, res = null }) {
|
|
|
395
410
|
});
|
|
396
411
|
}
|
|
397
412
|
|
|
413
|
+
// The answer of a turn, as the text parts joined; null while nothing has
|
|
414
|
+
// been said yet.
|
|
415
|
+
function answerOf(turn) {
|
|
416
|
+
const parts = partsFromChunks(turn.chunks ?? []);
|
|
417
|
+
const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
|
|
418
|
+
return text || null;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function turnView(turn) {
|
|
422
|
+
return {
|
|
423
|
+
turn_id: turn.id,
|
|
424
|
+
question: turn.question,
|
|
425
|
+
status: turn.status,
|
|
426
|
+
answer: answerOf(turn),
|
|
427
|
+
usage: turn.usage ?? null,
|
|
428
|
+
error: turn.error ?? null,
|
|
429
|
+
started_at: turn.started_at ?? null,
|
|
430
|
+
ended_at: turn.ended_at ?? null
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// The newest side turn of a worker, for a caller that asked earlier and
|
|
435
|
+
// comes back for the answer. Null when nothing was ever asked.
|
|
436
|
+
export async function latestSideTurn(taskId) {
|
|
437
|
+
await sweepOnce();
|
|
438
|
+
const turns = await readSideTurns(taskId);
|
|
439
|
+
const live = running.get(taskId) ?? null;
|
|
440
|
+
const latest = turns.at(-1) ?? null;
|
|
441
|
+
const session = await getSideSession(taskId);
|
|
442
|
+
if (!latest) return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: null };
|
|
443
|
+
const view = turnView(latest);
|
|
444
|
+
if (live && live.turnId === latest.id) {
|
|
445
|
+
view.status = "running";
|
|
446
|
+
view.answer = answerOf({ chunks: live.chunks });
|
|
447
|
+
}
|
|
448
|
+
return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: view };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Ask the worker a question on the side, without touching its own thread,
|
|
452
|
+
// and wait up to `timeoutMs` for the answer. A turn that outlives the budget
|
|
453
|
+
// keeps running in this process; the caller reads it back with latestSideTurn.
|
|
454
|
+
export async function askWorker({ task, question, timeoutMs = 110000 }) {
|
|
455
|
+
const turn = runSideTurn({ task, text: question });
|
|
456
|
+
// runSideTurn throws synchronously-ish (rejected promise) for no_thread,
|
|
457
|
+
// busy and codex_missing before anything starts; surface those as-is.
|
|
458
|
+
let timer;
|
|
459
|
+
const budget = new Promise((resolve) => {
|
|
460
|
+
timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
|
|
461
|
+
});
|
|
462
|
+
try {
|
|
463
|
+
const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
|
|
464
|
+
if (!outcome.timedOut) {
|
|
465
|
+
const state = await latestSideTurn(task.id);
|
|
466
|
+
return { ...state, timed_out: false };
|
|
467
|
+
}
|
|
468
|
+
turn.catch(() => {});
|
|
469
|
+
const state = await latestSideTurn(task.id);
|
|
470
|
+
return { ...state, timed_out: true };
|
|
471
|
+
} finally {
|
|
472
|
+
clearTimeout(timer);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
398
476
|
export function stopSideTurn(taskId) {
|
|
399
477
|
const live = running.get(taskId);
|
|
400
478
|
if (!live) return { stopped: false };
|
|
@@ -415,7 +493,7 @@ export async function endSideSession(taskId) {
|
|
|
415
493
|
if (!target.error) {
|
|
416
494
|
deleted = await new Promise((resolve) => {
|
|
417
495
|
const child = spawn(target.cmd, [...target.prefixArgs, "delete", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
|
|
418
|
-
const t = setTimeout(() => { child
|
|
496
|
+
const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
|
|
419
497
|
child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
|
|
420
498
|
child.on("error", () => { clearTimeout(t); resolve(false); });
|
|
421
499
|
});
|
|
@@ -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/update-check.js
CHANGED
|
@@ -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:
|
|
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:
|
|
95
|
+
// unreadable lock: integrity stays unknown
|
|
75
96
|
}
|
|
76
97
|
}
|
|
77
|
-
if (
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|