codex-supervisor-mcp 0.13.5 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/package.json +19 -63
  4. package/skills/codex-supervisor/SKILL.md +5 -4
  5. package/src/{acceptance.js → app/acceptance.js} +54 -68
  6. package/src/app/auto-cleanup.js +90 -0
  7. package/src/app/cancel.js +60 -0
  8. package/src/app/cleanup-facts.js +96 -0
  9. package/src/app/cleanup-plan.js +164 -0
  10. package/src/app/compose.js +7 -0
  11. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  12. package/src/app/dispatch.js +396 -0
  13. package/src/app/followup.js +98 -0
  14. package/src/app/land-chain.js +133 -0
  15. package/src/app/landing.js +357 -0
  16. package/src/app/ownership.js +57 -0
  17. package/src/app/rebase.js +216 -0
  18. package/src/app/restore-worktree.js +50 -0
  19. package/src/app/resume.js +181 -0
  20. package/src/app/run-state.js +26 -0
  21. package/src/app/settled.js +28 -0
  22. package/src/{side-chat.js → app/side-chat.js} +82 -265
  23. package/src/app/sse.js +20 -0
  24. package/src/app/start-run.js +77 -0
  25. package/src/app/verify-push.js +114 -0
  26. package/src/app/worktree-setup.js +176 -0
  27. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  28. package/src/domain/acceptance-spec.js +30 -0
  29. package/src/domain/cleanup-policy.js +44 -0
  30. package/src/domain/command-outcome.js +6 -0
  31. package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
  32. package/src/domain/side-turn-view.js +73 -0
  33. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  34. package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
  35. package/src/infra/git.js +30 -0
  36. package/src/infra/process.js +59 -0
  37. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  38. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  39. package/src/infra/store/db.js +265 -0
  40. package/src/infra/store/events.js +146 -0
  41. package/src/infra/store/facts.js +338 -0
  42. package/src/infra/store/reconcile.js +172 -0
  43. package/src/infra/store/records.js +171 -0
  44. package/src/infra/store/runner-readers.js +16 -0
  45. package/src/infra/store/schema.js +306 -0
  46. package/src/infra/store/sessions.js +138 -0
  47. package/src/infra/store/tasks.js +337 -0
  48. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  49. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  50. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  51. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  52. package/src/{worktree.js → infra/worktree.js} +56 -41
  53. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  54. package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
  55. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  56. package/src/{setup.js → interface/bin/setup.js} +7 -6
  57. package/src/{stage.js → interface/bin/stage.js} +1 -1
  58. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  59. package/src/interface/mcp/meta.js +7 -0
  60. package/src/interface/mcp/result.js +34 -0
  61. package/src/interface/mcp/schemas.js +24 -0
  62. package/src/interface/mcp/server.js +94 -0
  63. package/src/interface/mcp/tools/delivery.js +197 -0
  64. package/src/interface/mcp/tools/dispatch.js +267 -0
  65. package/src/interface/mcp/tools/facts.js +239 -0
  66. package/src/interface/mcp/tools/overview.js +202 -0
  67. package/src/interface/mcp/tools/poll.js +58 -0
  68. package/src/interface/mcp/tools/results.js +284 -0
  69. package/src/interface/mcp/tools/review.js +135 -0
  70. package/src/interface/mcp/tools/wait.js +145 -0
  71. package/src/interface/mcp/update-state.js +34 -0
  72. package/src/interface/mcp/views/overview.js +183 -0
  73. package/src/interface/mcp/views/task.js +223 -0
  74. package/src/interface/web/app.js +226 -0
  75. package/src/interface/web/views.js +224 -0
  76. package/src/mcp-server.js +3 -2223
  77. package/src/run-host/entry.js +23 -0
  78. package/src/run-host/finalize.js +236 -0
  79. package/src/run-host/launch.js +63 -0
  80. package/src/run-host/live-run.js +73 -0
  81. package/src/run-host/outcome-facts.js +61 -0
  82. package/src/run-host/streams.js +76 -0
  83. package/src/run-host/track.js +128 -0
  84. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  85. package/src/runners/codex/chat-chunks.js +97 -0
  86. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  87. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  88. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  89. package/src/cleanup-plan.js +0 -158
  90. package/src/codex-runner.js +0 -1586
  91. package/src/landing.js +0 -507
  92. package/src/task-store.js +0 -1800
  93. package/src/web-app.js +0 -425
  94. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  95. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  96. /package/src/{prompt.js → domain/prompt.js} +0 -0
  97. /package/src/{status.js → domain/status.js} +0 -0
  98. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  99. /package/src/{truncate.js → domain/truncate.js} +0 -0
  100. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  101. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  102. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  103. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  104. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  105. /package/src/{external-output.js → infra/external-output.js} +0 -0
  106. /package/src/{handoff.js → infra/handoff.js} +0 -0
  107. /package/src/{paths.js → infra/paths.js} +0 -0
  108. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  109. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -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,44 @@
1
+ // When a worker's worktree may be removed.
2
+ //
3
+ // The worker's branch is never deleted, so commits are never at risk. The only
4
+ // thing a removal can lose is uncommitted edits, and those are saved as a
5
+ // checkpoint commit on the branch first. What the policy protects is therefore
6
+ // convenience, not data: work that has not landed keeps its worktree for a
7
+ // while so it can still be inspected, resumed and landed in place.
8
+
9
+ export const DEFAULT_HOLD_DAYS = 7;
10
+
11
+ export function holdMsFrom(raw) {
12
+ if (raw === undefined || raw === null || raw === "") return DEFAULT_HOLD_DAYS * 86400000;
13
+ const days = Number(raw);
14
+ return Number.isFinite(days) && days >= 0 ? days * 86400000 : DEFAULT_HOLD_DAYS * 86400000;
15
+ }
16
+
17
+ const verdict = (value, reasons, extra = {}) => ({ verdict: value, reasons, checkpoint: false, eligible_after: null, ...extra });
18
+
19
+ // facts: { active, dependent, terminal, identity, landed, uncommitted, unlandedCommits, finishedAt }
20
+ // active / identity are a reason string or null; finishedAt is epoch ms or null.
21
+ export function cleanupVerdict(facts, { now, holdMs }) {
22
+ if (facts.active) return verdict("blocked", [facts.active]);
23
+ if (facts.dependent) return verdict("blocked", ["an active dependent still needs this work"]);
24
+ if (!facts.terminal) return verdict("blocked", ["worker has not finished"]);
25
+ if (facts.identity) return verdict("review", [facts.identity]);
26
+
27
+ const unlanded = !facts.landed && facts.unlandedCommits > 0;
28
+ if (facts.uncommitted === 0 && !unlanded) {
29
+ return verdict("safe", facts.landed ? ["landed on the target branch", "worktree clean"] : ["no changes to keep"]);
30
+ }
31
+ const what = [
32
+ unlanded ? `${facts.unlandedCommits} commit(s) not landed` : null,
33
+ facts.uncommitted > 0 ? `${facts.uncommitted} uncommitted path(s)` : null
34
+ ].filter(Boolean).join(", ");
35
+ const eligibleAt = (facts.finishedAt ?? now) + holdMs;
36
+ const eligibleAfter = new Date(eligibleAt).toISOString();
37
+ if (now < eligibleAt) {
38
+ return verdict("review", [`${what}; kept until ${eligibleAfter}, then saved on the worker branch and removed`], { eligible_after: eligibleAfter });
39
+ }
40
+ return verdict("safe", [`${what}; the hold period is over`, "everything is kept on the worker branch"], {
41
+ checkpoint: facts.uncommitted > 0,
42
+ eligible_after: eligibleAfter
43
+ });
44
+ }
@@ -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
+ }
@@ -8,7 +8,7 @@ function readyToLand(task) {
8
8
 
9
9
  function readyToClean(task, readyToCleanTaskIds = null) {
10
10
  if (readyToCleanTaskIds) return readyToCleanTaskIds.has(task.id);
11
- return task.push_verified_at && ["cleanup_eligible"].includes(task.delivery_state);
11
+ return task.delivery_state === "cleanup_eligible";
12
12
  }
13
13
 
14
14
  function attentionReason(task) {
@@ -22,7 +22,7 @@ function nextAction(task, { attention, readyToLand, readyToClean }) {
22
22
  if (attention) return "inspect the worker evidence and resolve the recorded blocker";
23
23
  if (task.delivery_state === "cleanup_eligible" && !readyToClean) return "rerun cleanup_plan; the previous cleanup proof is no longer current";
24
24
  if (readyToLand) return "review the diff and acceptance, then land the worker";
25
- if (readyToClean) return "review the cleanup plan item, then explicitly apply it";
25
+ if (readyToClean) return "nothing to do: the worktree is removed on a later poll, and its branch is kept";
26
26
  if (task.status === "completed" && !task.landed_at) return "review the worker result and decide whether to land it";
27
27
  return null;
28
28
  }
@@ -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
 
@@ -9,10 +9,10 @@ export function cleanupThreshold(raw = process.env.SUPERVISOR_CLEANUP_HINT) {
9
9
  return Number.isFinite(value) && value >= 0 ? value : DEFAULT_THRESHOLD;
10
10
  }
11
11
 
12
- // A batch that never cleans up should say so instead of quietly growing to
13
- // hundreds of worktrees. The hint only reports a count and the two commands;
14
- // deletion stays a deliberate step, because cleanup only removes worktrees that
15
- // are merged and clean and keeps dirty, unmerged, lost and failed work.
12
+ // Safe worktrees are removed automatically, so a store that still holds this
13
+ // many has work that is being kept on purpose (unlanded and inside the hold
14
+ // period, or needing review) or has automatic cleanup switched off. The hint
15
+ // reports the count and where to look.
16
16
  export async function cleanupHint({ list = readdir, root = supervisorRoot, dir = worktreesDir, threshold = cleanupThreshold() } = {}) {
17
17
  if (!threshold) return null;
18
18
  let entries;
@@ -21,10 +21,9 @@ export async function cleanupHint({ list = readdir, root = supervisorRoot, dir =
21
21
  return {
22
22
  worktrees: entries,
23
23
  threshold,
24
- command: `SUPERVISOR_HOME=${root} npm run cleanup -- --dry-run`,
24
+ command: `SUPERVISOR_HOME=${root} codex-supervisor-cleanup --dry-run`,
25
25
  apply: null,
26
- next_step: "Review the dry-run plan_id and a SAFE item id, then call apply_cleanup; CLI apply also requires --plan and --item.",
27
- note: "only acceptance-passed, push-verified, clean worktrees without active processes or dependents become SAFE; apply retains branches and evidence"
26
+ next_step: "Read the plan: REVIEW items say when they become removable. Land or resume the work you still want; apply_cleanup removes a SAFE item right away.",
27
+ note: "a worktree is SAFE once its work has landed, or has nothing to keep, or its hold period is over; uncommitted edits are saved on the worker branch first, and branches and evidence are never removed"
28
28
  };
29
29
  }
30
-
@@ -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");