codex-supervisor-mcp 0.13.4 → 0.13.6

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 (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,77 @@
1
+ import "./compose.js";
2
+ import { spawnProcess } from "../infra/process.js";
3
+ import { upsertTask } from "../infra/store/tasks.js";
4
+ import { compileWorkerContext } from "./context-compiler.js";
5
+ import { failedStart, MAX_RUN_HOST_PROMPT_BYTES, RUN_HOST_STARTUP_TIMEOUT_MS } from "./run-state.js";
6
+ import { closeSync, openSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // The MCP client may disappear at any point. A detached process owns the
10
+ // streams, exit write and acceptance until all three settle; IPC is only a
11
+ // startup handshake and never the channel carrying worker results.
12
+ export async function startTrackedRun(job) {
13
+ if (Buffer.byteLength(String(job.prompt ?? ""), "utf8") > MAX_RUN_HOST_PROMPT_BYTES) {
14
+ const result = failedStart(job.record, `worker prompt is too large for the detached run host IPC channel (maximum ${MAX_RUN_HOST_PROMPT_BYTES} bytes); reduce task text and move materials to context files`);
15
+ await upsertTask(result.record);
16
+ return result;
17
+ }
18
+ const compiled = await compileWorkerContext(job.record, { attempt: (job.record.run_count ?? 0) + 1 });
19
+ job.record = {
20
+ ...job.record,
21
+ input_context: {
22
+ ...job.record.input_context,
23
+ context: compiled.sourceRefs,
24
+ source_refs: compiled.sourceRefs,
25
+ content_hash: compiled.contentHash,
26
+ context_snapshot_id: compiled.snapshot.id,
27
+ context_snapshot_tokens: compiled.snapshot.estimated_tokens,
28
+ context_fact_count: compiled.factCount
29
+ }
30
+ };
31
+ job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
32
+ const hostLogPath = job.logPath.endsWith(".jsonl")
33
+ ? job.logPath.replace(/\.jsonl$/, ".host.log")
34
+ : `${job.logPath}.host.log`;
35
+ let hostLogFd;
36
+ try {
37
+ hostLogFd = openSync(hostLogPath, "a");
38
+ } catch (error) {
39
+ const result = failedStart(job.record, `cannot open run host log ${hostLogPath}: ${error.message}`);
40
+ await upsertTask(result.record);
41
+ return result;
42
+ }
43
+ let host;
44
+ try {
45
+ host = spawnProcess(process.execPath, [fileURLToPath(new URL("../run-host/entry.js", import.meta.url)), "--run-host"], {
46
+ detached: true, stdio: ["ignore", hostLogFd, hostLogFd, "ipc"],
47
+ env: process.env, windowsHide: true
48
+ });
49
+ } finally {
50
+ closeSync(hostLogFd);
51
+ }
52
+ const started = await new Promise((resolveStart) => {
53
+ let settled = false;
54
+ const finish = (result) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ host.removeAllListeners("message");
59
+ host.removeAllListeners("exit");
60
+ if (host.connected) host.disconnect();
61
+ host.unref();
62
+ resolveStart(result);
63
+ };
64
+ const timer = setTimeout(() => {
65
+ host.kill();
66
+ finish(failedStart(job.record, "run host startup timed out"));
67
+ }, RUN_HOST_STARTUP_TIMEOUT_MS);
68
+ host.once("message", finish);
69
+ host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
70
+ host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
71
+ host.send(job, (error) => {
72
+ if (error) finish(failedStart(job.record, `run host IPC failed: ${error.message}`));
73
+ });
74
+ });
75
+ if (!started.ok) await upsertTask(started.record);
76
+ return started;
77
+ }
@@ -0,0 +1,119 @@
1
+ // Proves a landed commit is on a remote branch. Read-only towards the remote:
2
+ // it fetches and compares, and never pushes or deploys.
3
+ import "./compose.js";
4
+ import { runGit } from "../infra/git.js";
5
+ import { appendTaskEvent } from "../infra/store/events.js";
6
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
7
+ import { recordJsonArtifact, saveCleanupPlan, updateWorkItemDelivery } from "../infra/store/records.js";
8
+ import { getTask, upsertTask } from "../infra/store/tasks.js";
9
+ import { runIdFor } from "../infra/store/db.js";
10
+ import { createCleanupPlan } from "./cleanup-plan.js";
11
+
12
+ const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
13
+ const CLEANUP_NEXT_STEP = "Review SAFE items, then call apply_cleanup with their item IDs; cleanup is never automatic.";
14
+
15
+ async function recordPushFacts(task, proof, { eventId, artifactId }) {
16
+ const workItem = await getWorkItemForTask(task.id);
17
+ if (!workItem) return;
18
+ const { remote, branch, remoteHead } = proof;
19
+ const shared = {
20
+ workItemId: workItem.id,
21
+ scopeId: workItem.id,
22
+ state: "verified",
23
+ sourceEventId: eventId,
24
+ sourceArtifactId: artifactId,
25
+ validForSha: task.landed_head,
26
+ watchedPaths: task.owned_paths ?? [],
27
+ verifiedBy: "supervisor.remote_readback"
28
+ };
29
+ await recordFact({
30
+ ...shared,
31
+ scopeType: "work_item",
32
+ key: "push_verified",
33
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead }
34
+ });
35
+ await recordFact({
36
+ ...shared,
37
+ scopeType: "dependency",
38
+ key: "push_delivery_summary",
39
+ value: { task_id: task.id, landed_head: task.landed_head, remote, branch, remote_head: remoteHead }
40
+ });
41
+ }
42
+
43
+ // Writes the task row, the delivery state, the event, the proof artifact and the facts.
44
+ async function recordPushVerified(task, proof) {
45
+ const { remote, branch, remoteHead } = proof;
46
+ const now = new Date().toISOString();
47
+ await upsertTask({ ...task, push_verified_at: now, push_remote: remote, push_branch: branch, push_remote_head: remoteHead, updated_at: now });
48
+ await updateWorkItemDelivery(task.id, "push_verified");
49
+ const runId = runIdFor(task.id, task.run_count ?? 1);
50
+ const event = await appendTaskEvent(task.id, {
51
+ type: "supervisor.push_verified",
52
+ remote,
53
+ branch,
54
+ landed_head: task.landed_head,
55
+ remote_head: remoteHead,
56
+ verified_at: now
57
+ }, { runId, actor: "supervisor" });
58
+ const artifact = await recordJsonArtifact({
59
+ runId,
60
+ type: "push_proof",
61
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead, verified_at: now, event_id: event.id },
62
+ securityClass: "internal"
63
+ });
64
+ await recordPushFacts(task, proof, { eventId: event.id, artifactId: artifact.id });
65
+ return { now, artifact };
66
+ }
67
+
68
+ function remoteHeadOf(task, remote, branch) {
69
+ git(task.project_root, ["remote", "get-url", remote]);
70
+ git(task.project_root, ["fetch", "--no-tags", remote, `refs/heads/${branch}`]);
71
+ return git(task.project_root, ["rev-parse", "FETCH_HEAD"]);
72
+ }
73
+
74
+ function reaches(task, remoteHead) {
75
+ try {
76
+ git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, remoteHead]);
77
+ return true;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ export async function verifyDeliveryPush({ taskId, remote, branch }) {
84
+ const task = await getTask(taskId);
85
+ if (!task) return { error: "task_not_found", task_id: taskId };
86
+ const targetBranch = branch ?? task.landed_branch;
87
+ if (!task.landed_at || !task.landed_head || !targetBranch) {
88
+ return { error: "not_landed", task_id: taskId, reason: "land the worker first; this task has no landed head and branch to verify" };
89
+ }
90
+ try {
91
+ const remoteHead = remoteHeadOf(task, remote, targetBranch);
92
+ if (!reaches(task, remoteHead)) {
93
+ return {
94
+ error: "not_pushed",
95
+ task_id: taskId,
96
+ remote,
97
+ branch: targetBranch,
98
+ landed_head: task.landed_head,
99
+ remote_head: remoteHead,
100
+ reason: "landed_head is not reachable from the fetched remote branch"
101
+ };
102
+ }
103
+ const { now, artifact } = await recordPushVerified(task, { remote, branch: targetBranch, remoteHead });
104
+ const cleanupPlan = await createCleanupPlan({ taskIds: [taskId] });
105
+ await saveCleanupPlan(cleanupPlan);
106
+ return {
107
+ task_id: taskId,
108
+ remote,
109
+ branch: targetBranch,
110
+ landed_head: task.landed_head,
111
+ remote_head: remoteHead,
112
+ artifact_id: artifact.id,
113
+ push_verified_at: now,
114
+ cleanup_plan: { id: cleanupPlan.id, summary: cleanupPlan.summary, expires_at: cleanupPlan.expires_at, next_step: CLEANUP_NEXT_STEP }
115
+ };
116
+ } catch (error) {
117
+ return { error: "push_verification_failed", task_id: taskId, remote, branch: targetBranch, reason: error.message.split("\n")[0] };
118
+ }
119
+ }
@@ -0,0 +1,176 @@
1
+ import { gitBin, runGit } from "../infra/git.js";
2
+ import { worktreesDir } from "../infra/paths.js";
3
+ import { runToExit } from "../infra/process.js";
4
+ import { resolveWritableRoot } from "../infra/sandbox-roots.js";
5
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
6
+ import { WORKTREE_LOCK_TIMEOUT_MS } from "./run-state.js";
7
+ import { createHash } from "node:crypto";
8
+ import { existsSync } from "node:fs";
9
+ import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
+
12
+ export function splitLines(buffer, chunk) {
13
+ const next = buffer + chunk;
14
+ const lines = next.split(/\r?\n/);
15
+ return { lines: lines.slice(0, -1), rest: lines.at(-1) ?? "" };
16
+ }
17
+
18
+ export async function exists(path) {
19
+ if (!path) return false;
20
+ try {
21
+ await stat(path);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ export function resolveCommit(cwd, ref) {
29
+ return runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { timeout: 15000, stderr: "ignore" });
30
+ }
31
+
32
+ export function invalidBaseRefError(cwd, baseRef) {
33
+ const error = new Error(`baseRef "${baseRef}" does not resolve to a commit in ${cwd}`);
34
+ error.code = "invalid_base_ref";
35
+ return error;
36
+ }
37
+
38
+ // The worktree is cut from baseRef when given, else from the repository's
39
+ // HEAD. The resolved commit is recorded on the task: it is what
40
+ // readWorktreeChanges diffs against, so committed work stays visible. An
41
+ // explicit baseRef that does not resolve is an error, not a silent fallback
42
+ // to HEAD - the caller asked for a specific baseline for a reason.
43
+ export async function ensureWorktree(cwd, taskId, baseRef = null) {
44
+ const taskWorktreeDir = join(worktreesDir, taskId);
45
+ await mkdir(worktreesDir, { recursive: true });
46
+ const gitDir = join(cwd, ".git");
47
+ if (!(await exists(cwd)) || !(await exists(gitDir))) {
48
+ if (baseRef) throw invalidBaseRefError(cwd, baseRef);
49
+ return { path: null, baseCommit: null };
50
+ }
51
+ let baseCommit;
52
+ try {
53
+ baseCommit = resolveCommit(cwd, baseRef ?? "HEAD");
54
+ } catch {
55
+ if (baseRef) throw invalidBaseRefError(cwd, baseRef);
56
+ return { path: null, baseCommit: null };
57
+ }
58
+ if (!baseCommit) {
59
+ if (baseRef) throw invalidBaseRefError(cwd, baseRef);
60
+ return { path: null, baseCommit: null };
61
+ }
62
+ try {
63
+ await rm(taskWorktreeDir, { recursive: true, force: true });
64
+ const branch = `codex/${taskId}`;
65
+ await runToExit(gitBin(), ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
66
+ await runToExit(gitBin(), ["-C", taskWorktreeDir, "switch", "-c", branch]);
67
+ return { path: taskWorktreeDir, baseCommit };
68
+ } catch (error) {
69
+ const failure = new Error(`could not create isolated worker checkout: ${error.message}`);
70
+ failure.code = "worktree_creation_failed";
71
+ throw failure;
72
+ }
73
+ }
74
+
75
+ function insidePath(parent, child) {
76
+ const rel = relative(parent, child);
77
+ return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
78
+ }
79
+
80
+ export function normalizeWorkspaceSetup(value, projectRoot) {
81
+ if (value == null) return null;
82
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspaceSetup must be an object");
83
+ const links = (value.links ?? []).map((entry) => {
84
+ if (!entry || typeof entry.path !== "string" || !entry.path.trim()
85
+ || typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspaceSetup.links requires path and source");
86
+ const path = entry.path.trim();
87
+ if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspaceSetup link path must stay inside the worktree: ${path}`);
88
+ return { path, source: resolve(projectRoot, entry.source.trim()) };
89
+ });
90
+ const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
91
+ if (links.length > 20 || commands.length > 20) throw new Error("workspaceSetup accepts at most 20 links and 20 commands");
92
+ const submodules = value.submodules === true;
93
+ return links.length || submodules || commands.length ? { links, submodules, commands } : null;
94
+ }
95
+
96
+ const JS_DEPENDENCY_COMMAND = /(?:^|[\s"'/])(?:npm|pnpm|yarn|npx|vitest|jest|vue-tsc|tsc|eslint|oxlint|nuxi)(?:\s|$)/;
97
+
98
+ export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
99
+ if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
100
+ const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
101
+ if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
102
+ const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspaceSetup with dependency links and prepare commands (the same setup must be used by preflight)");
103
+ error.code = "workspace_setup_required";
104
+ throw error;
105
+ }
106
+
107
+ export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
108
+ if (!setup) return;
109
+ for (const link of setup.links) {
110
+ if (!existsSync(link.source)) throw new Error(`workspaceSetup link source does not exist: ${link.source}`);
111
+ const destination = resolve(worktreePath, link.path);
112
+ if (!insidePath(worktreePath, destination)) throw new Error(`workspaceSetup link escapes the worktree: ${link.path}`);
113
+ await mkdir(dirname(destination), { recursive: true });
114
+ if (existsSync(destination)) {
115
+ const existing = await lstat(destination);
116
+ if (!existing.isSymbolicLink()) throw new Error(`workspaceSetup link destination already exists: ${link.path}`);
117
+ const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
118
+ if (actual !== expected) throw new Error(`workspaceSetup link destination points elsewhere: ${link.path}`);
119
+ continue;
120
+ }
121
+ const sourceInfo = await stat(link.source);
122
+ await symlink(link.source, destination, process.platform === "win32" ? "junction" : sourceInfo.isDirectory() ? "dir" : "file");
123
+ if (basename(link.path) === "node_modules" && sourceInfo.isDirectory()) {
124
+ for (const name of [".vite", ".vite-temp", ".cache"]) await mkdir(join(link.source, name), { recursive: true });
125
+ }
126
+ }
127
+ if (setup.submodules) {
128
+ await runToExit(gitBin(), ["-c", "protocol.file.allow=always", "-C", worktreePath, "submodule", "update", "--init", "--recursive"]);
129
+ }
130
+ if (setup.commands.length) {
131
+ const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
132
+ if (!result.passed) {
133
+ const failing = result.checks.find((check) => !check.passed);
134
+ throw new Error(`workspaceSetup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
135
+ }
136
+ }
137
+ }
138
+
139
+ export function workspaceSetupWriteRoots(record) {
140
+ const roots = [];
141
+ for (const link of record.workspace_metadata?.setup?.links ?? []) {
142
+ const source = resolveWritableRoot(link.source);
143
+ if (!source.error) roots.push(source.path);
144
+ if (basename(link.path) !== "node_modules") continue;
145
+ for (const name of [".vite", ".vite-temp", ".cache"]) {
146
+ const candidate = resolveWritableRoot(join(link.source, name));
147
+ if (!candidate.error) roots.push(candidate.path);
148
+ }
149
+ }
150
+ return roots;
151
+ }
152
+
153
+ function sleep(ms) {
154
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
155
+ }
156
+
157
+ export async function withWorktreeCreationLock(cwd, work) {
158
+ const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
159
+ const lockPath = join(worktreesDir, lockName);
160
+ await mkdir(worktreesDir, { recursive: true });
161
+ const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
162
+ while (true) {
163
+ try {
164
+ await mkdir(lockPath);
165
+ break;
166
+ } catch (error) {
167
+ if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`, { cause: error });
168
+ await sleep(100);
169
+ }
170
+ }
171
+ try {
172
+ return await work();
173
+ } finally {
174
+ await rm(lockPath, { recursive: true, force: true }).catch(() => {});
175
+ }
176
+ }
@@ -59,6 +59,7 @@ export function compareFailureBaseline(expected, actual) {
59
59
  }
60
60
  for (const [id, item] of baseline) if (!observed.has(id)) result.removed.push(item);
61
61
  for (const key of ["added", "removed", "changed"]) result[key].sort((a, b) => a.test_id.localeCompare(b.test_id));
62
- result.passed = errors.length === 0 && result.added.length === 0 && result.removed.length === 0 && result.changed.length === 0 && result.missing_required.length === 0;
62
+ const unchanged = result.added.length === 0 && result.removed.length === 0 && result.changed.length === 0;
63
+ result.passed = errors.length === 0 && unchanged && result.missing_required.length === 0;
63
64
  return result;
64
65
  }
@@ -0,0 +1,30 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { compareFailureBaseline } from "./acceptance-baseline.js";
3
+
4
+ export const MAX_ACCEPTANCE_COMMANDS = 10;
5
+
6
+ // One string or a list; blanks dropped; an empty list is "not configured".
7
+ export function normalizeAcceptance(value) {
8
+ const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
9
+ const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
10
+ if (typeof entry === "string") return entry.trim();
11
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
12
+ if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("reportPath must stay inside the worktree");
13
+ const validation = compareFailureBaseline(entry.baseline, {
14
+ complete: true, identity: entry.baseline?.identity,
15
+ executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
16
+ skipped: [], failures: entry.baseline?.failures
17
+ });
18
+ // Validation errors concern the contract; diff results concern actual
19
+ // failures, which do not exist at normalization time.
20
+ if (validation.errors.length) throw new Error(`invalid acceptance baseline: ${validation.errors.join("; ")}`);
21
+ return { command: entry.command.trim(), reportPath: entry.reportPath, baseline: structuredClone(entry.baseline) };
22
+ }).filter(Boolean);
23
+ if (commands.length === 0) return null;
24
+ if (commands.length > MAX_ACCEPTANCE_COMMANDS) {
25
+ const error = new Error(`acceptance lists ${commands.length} commands; at most ${MAX_ACCEPTANCE_COMMANDS} are run`);
26
+ error.code = "too_many_acceptance_commands";
27
+ throw error;
28
+ }
29
+ return commands;
30
+ }
@@ -0,0 +1,6 @@
1
+ // A command counts as failed when the CLI said so or it exited non-zero.
2
+ export function commandFailed(entry) {
3
+ if (!entry) return false;
4
+ if (entry.status === "failed") return true;
5
+ return entry.exit_code !== null && entry.exit_code !== undefined && entry.exit_code !== 0;
6
+ }
@@ -41,7 +41,11 @@ export function buildOverviewDelta(tasks, cursor = {}, { readyToCleanTaskIds = n
41
41
  const reason = attentionReason(task);
42
42
  const failure = classifyFailure(task);
43
43
  const health = threadHealth(task);
44
- const fingerprint = JSON.stringify([task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null, task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.goal_tokens_used ?? null, health.state, task.updated_at]);
44
+ const fingerprint = JSON.stringify([
45
+ task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null,
46
+ task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.goal_tokens_used ?? null,
47
+ health.state, task.updated_at
48
+ ]);
45
49
  nextCursor[task.id] = fingerprint;
46
50
  if (cursor[task.id] !== fingerprint) {
47
51
  changes.push({
@@ -0,0 +1,73 @@
1
+ // Stored stream chunks -> the message parts and the answer text a reader sees.
2
+ // Chunks of a turn, assembled into the UIMessage parts the page shows for a
3
+ // finished (or interrupted) turn. The page rebuilds history from this.
4
+ export function partsFromChunks(chunks) {
5
+ const parts = [];
6
+ const open = new Map(); // id -> part for text / reasoning
7
+ const tools = new Map(); // toolCallId -> part
8
+ for (const c of chunks) {
9
+ switch (c.type) {
10
+ case "text-start":
11
+ open.set(c.id, { type: "text", text: "", state: "streaming" });
12
+ parts.push(open.get(c.id));
13
+ break;
14
+ case "text-delta":
15
+ if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
16
+ break;
17
+ case "text-end":
18
+ if (open.has(c.id)) open.get(c.id).state = "done";
19
+ break;
20
+ case "reasoning-start":
21
+ open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
22
+ parts.push(open.get(c.id));
23
+ break;
24
+ case "reasoning-delta":
25
+ if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
26
+ break;
27
+ case "reasoning-end":
28
+ if (open.has(c.id)) open.get(c.id).state = "done";
29
+ break;
30
+ case "tool-input-available": {
31
+ const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
32
+ tools.set(c.toolCallId, part);
33
+ parts.push(part);
34
+ break;
35
+ }
36
+ case "tool-output-available":
37
+ if (tools.has(c.toolCallId)) {
38
+ tools.get(c.toolCallId).state = "output-available";
39
+ tools.get(c.toolCallId).output = c.output;
40
+ }
41
+ break;
42
+ case "data-notice":
43
+ case "data-usage":
44
+ case "data-session":
45
+ parts.push({ type: c.type, data: c.data });
46
+ break;
47
+ default:
48
+ break;
49
+ }
50
+ }
51
+ return parts;
52
+ }
53
+
54
+ // The answer of a turn, as the text parts joined; null while nothing has
55
+ // been said yet.
56
+ export function answerOf(turn) {
57
+ const parts = partsFromChunks(turn.chunks ?? []);
58
+ const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
59
+ return text || null;
60
+ }
61
+
62
+ export function turnView(turn) {
63
+ return {
64
+ turn_id: turn.id,
65
+ question: turn.question,
66
+ status: turn.status,
67
+ answer: answerOf(turn),
68
+ usage: turn.usage ?? null,
69
+ error: turn.error ?? null,
70
+ started_at: turn.started_at ?? null,
71
+ ended_at: turn.ended_at ?? null
72
+ };
73
+ }
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { resolve } from "node:path";
3
- import { commandFailed } from "./event-parser.js";
3
+ import { commandFailed } from "./command-outcome.js";
4
4
 
5
5
  export const PREFLIGHT_VERSION = 1;
6
6
 
@@ -0,0 +1,30 @@
1
+ // The only place that runs git. Callers differ in real ways (optional locks,
2
+ // path quoting, what happens to stderr, whether output is trimmed), so those
3
+ // are options here instead of one private copy per caller.
4
+ import { execFileSync } from "node:child_process";
5
+
6
+ export const gitBin = () => process.env.GIT_BIN?.trim() || "git";
7
+
8
+ export function runGit(cwd, args, options = {}) {
9
+ const { timeout = 60000, noOptionalLocks = false, rawPaths = false, stderr = "pipe", input = null, maxBuffer, encoding = "utf8", env, trim = true } = options;
10
+ const argv = [...(noOptionalLocks ? ["--no-optional-locks"] : []), "-C", cwd, ...(rawPaths ? ["-c", "core.quotePath=false"] : []), ...args];
11
+ const output = execFileSync(gitBin(), argv, {
12
+ encoding,
13
+ timeout,
14
+ stdio: [input == null ? "ignore" : "pipe", "pipe", stderr],
15
+ ...(input == null ? {} : { input }),
16
+ ...(maxBuffer ? { maxBuffer } : {}),
17
+ ...(env ? { env } : {})
18
+ });
19
+ return trim && typeof output === "string" ? output.trim() : output;
20
+ }
21
+
22
+ // For questions git answers with its exit code, such as merge-base --is-ancestor.
23
+ export function gitSucceeds(cwd, args, { timeout = 15000 } = {}) {
24
+ try {
25
+ execFileSync(gitBin(), ["-C", cwd, ...args], { stdio: "ignore", timeout });
26
+ return true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
@@ -0,0 +1,59 @@
1
+ // The only place, besides git.js, that touches node:child_process. Everything
2
+ // else asks for a process through these names, which keeps blocking calls and
3
+ // platform-specific process handling in one file.
4
+ import { execFile, execFileSync, spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ export const runSync = execFileSync;
9
+ export const runFile = execFile;
10
+ export const spawnProcess = spawn;
11
+
12
+ // Resolves when the command exits 0, rejects otherwise. Output is discarded.
13
+ export function runToExit(command, args, options = {}) {
14
+ return new Promise((resolvePromise, reject) => {
15
+ const child = spawn(command, args, { stdio: "ignore", windowsHide: true, ...options });
16
+ child.on("exit", (code) => {
17
+ if (code === 0) resolvePromise();
18
+ else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
19
+ });
20
+ child.on("error", reject);
21
+ });
22
+ }
23
+
24
+ function powershellBin() {
25
+ const root = process.env.SystemRoot?.trim() || "C:\\Windows";
26
+ const full = join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
27
+ return existsSync(full) ? full : "powershell";
28
+ }
29
+
30
+ // The command line of a pid, or "" when it cannot be read. A pid recorded on
31
+ // disk is only signalled once this confirms it still belongs to a worker, so a
32
+ // recycled pid is never killed. Windows has no `ps`: CIM is the only reliable
33
+ // source for a full command line, and the full line matters because the npm
34
+ // shim is bypassed by running `node <entry>`, which puts the CLI's name in the
35
+ // arguments, not the image name. `tasklist` is the fallback when PowerShell is
36
+ // unavailable; it only reports the image name.
37
+ //
38
+ // The timeout is generous on purpose: this runs once per cross-process cancel,
39
+ // and a cold Windows PowerShell on a fresh machine routinely takes several
40
+ // seconds to print anything. A tight timeout silently degrades to the useless
41
+ // tasklist probe, and the cancel comes back "process_not_found".
42
+ export function describeProcess(pid) {
43
+ const options = { encoding: "utf8", timeout: 15000, windowsHide: true };
44
+ try {
45
+ if (process.platform === "win32") {
46
+ try {
47
+ const command = `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`;
48
+ const viaCim = execFileSync(powershellBin(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], options).trim();
49
+ if (viaCim) return viaCim;
50
+ } catch {
51
+ // fall through to the image-name probe below
52
+ }
53
+ return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
54
+ }
55
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
56
+ } catch {
57
+ return "";
58
+ }
59
+ }
@@ -87,7 +87,8 @@ function goBuildCacheCandidate({ env, platform, home }) {
87
87
  return pathJoin(platform, env.XDG_CACHE_HOME?.trim() || pathJoin(platform, home, ".cache"), "go-build");
88
88
  }
89
89
 
90
- export function cacheRoots({ env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = {}) {
90
+ export function cacheRoots(options = {}) {
91
+ const { env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = options;
91
92
  if (/^(1|true|yes)$/i.test((env.SUPERVISOR_NO_AUTO_CACHE_ROOTS ?? "").trim())) return [];
92
93
  const candidates = [
93
94
  ...osCacheCandidates({ env, platform, home }),
@@ -9,7 +9,7 @@ import { homedir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
 
12
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
12
+ const packageRoot = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
13
13
 
14
14
  export const SKILL_NAME = "codex-supervisor";
15
15
  export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");