agent-supervisor-mcp 0.0.0-stage → 2.0.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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -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
+ }
@@ -0,0 +1,50 @@
1
+ // Single source of truth for the work state machine.
2
+ //
3
+ // status = lifecycle. One value per work, never overwritten by progress.
4
+ // phase = what the worker is doing right now. Only meaningful while
5
+ // status === "running"; NULL once the work reaches a terminal status.
6
+
7
+ // timed_out is a worker the supervisor stopped because its time budget ran
8
+ // out. It is not lost: nothing vanished, and re-running it unchanged would
9
+ // only run out of time again.
10
+ export const TASK_STATUSES = ["queued", "running", "completed", "failed", "cancelled", "lost", "timed_out"];
11
+
12
+ export const PHASES = ["starting", "thinking", "command", "editing", "reporting"];
13
+
14
+ export const ACTIVE_STATUSES = new Set(["queued", "running"]);
15
+
16
+ export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost", "timed_out"]);
17
+
18
+ // Codex native thread goal status -> work status.
19
+ // Storage uses snake_case ("usage_limited"); the RPC layer uses camelCase
20
+ // ("usageLimited"). mapGoalStatus accepts either.
21
+ const GOAL_STATUS_MAP = new Map([
22
+ ["active", "running"],
23
+ ["paused", "running"],
24
+ ["blocked", "running"],
25
+ ["usagelimited", "failed"],
26
+ ["budgetlimited", "failed"],
27
+ ["complete", "completed"]
28
+ ]);
29
+
30
+ export function mapGoalStatus(nativeStatus) {
31
+ if (!nativeStatus) return null;
32
+ const key = String(nativeStatus).replace(/_/g, "").toLowerCase();
33
+ return GOAL_STATUS_MAP.get(key) ?? null;
34
+ }
35
+
36
+ // A goal that is not finished but is not progressing on its own.
37
+ export function isGoalNeedingAttention(nativeStatus) {
38
+ const key = String(nativeStatus ?? "").replace(/_/g, "").toLowerCase();
39
+ return ["blocked", "paused", "usagelimited", "budgetlimited"].includes(key);
40
+ }
41
+
42
+ // True once nothing of a worker's last run can still be running: its exit
43
+ // code or the signal that ended it is recorded (the last thing a run host
44
+ // writes), or the row was marked
45
+ // lost (done only after both processes were seen gone). From then on the pids
46
+ // on the row are history. The system hands them to other processes, on
47
+ // Windows within seconds, and a live stranger must not read as a live worker.
48
+ export function runIsOver(task) {
49
+ return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && (task.exit_code != null || task.signal != null));
50
+ }
@@ -0,0 +1,33 @@
1
+ const DEFAULT_HANDOFF_TOKEN_THRESHOLD = 300000;
2
+ const LONG_THREAD_RATIO = 0.75;
3
+
4
+ export function handoffTokenThreshold(env = process.env) {
5
+ const raw = env.AGENT_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
6
+ if (raw == null || raw === "") return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
7
+ const value = Number(raw);
8
+ if (!Number.isFinite(value) || value < 0) return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
9
+ return value;
10
+ }
11
+
12
+ export function threadHealth(task, { threshold = handoffTokenThreshold() } = {}) {
13
+ if (threshold === 0) return { state: "disabled", threshold: 0, tokens_used: task?.goal_tokens_used ?? 0, next_step: null };
14
+ const tokens = Number(task?.goal_tokens_used ?? 0);
15
+ if (!Number.isFinite(tokens) || tokens <= 0) return { state: "ok", threshold, tokens_used: 0, next_step: null };
16
+ if (tokens >= threshold) {
17
+ return {
18
+ state: "handoff_recommended",
19
+ threshold,
20
+ tokens_used: tokens,
21
+ next_step: "Start a fresh 1000-1500-token handoff with create_worker with followup_of; keep this thread as evidence"
22
+ };
23
+ }
24
+ if (tokens >= Math.floor(threshold * LONG_THREAD_RATIO)) {
25
+ return {
26
+ state: "getting_long",
27
+ threshold,
28
+ tokens_used: tokens,
29
+ next_step: "Finish this bounded step, then create a follow-up worker instead of extending the thread"
30
+ };
31
+ }
32
+ return { state: "ok", threshold, tokens_used: tokens, next_step: null };
33
+ }
@@ -0,0 +1,148 @@
1
+ // Port of Codex's output truncation so supervisor output reads the same way
2
+ // Codex's own tool output does.
3
+ //
4
+ // Rust source: codex-rs/utils/string/src/truncate.rs
5
+ // codex-rs/utils/output-truncation/src/lib.rs
6
+ //
7
+ // Truncation keeps the head and the tail and drops the middle, then reports
8
+ // how much was dropped. The budget is measured in UTF-8 bytes, exactly like
9
+ // TruncationPolicy::Bytes.
10
+
11
+ const APPROX_BYTES_PER_TOKEN = 4;
12
+
13
+ export function approxTokenCount(text) {
14
+ const len = Buffer.byteLength(text, "utf8");
15
+ return Math.floor((len + APPROX_BYTES_PER_TOKEN - 1) / APPROX_BYTES_PER_TOKEN);
16
+ }
17
+
18
+ export function approxBytesForTokens(tokens) {
19
+ return tokens * APPROX_BYTES_PER_TOKEN;
20
+ }
21
+
22
+ function splitBudget(budget) {
23
+ const left = Math.floor(budget / 2);
24
+ return [left, budget - left];
25
+ }
26
+
27
+ function formatTruncationMarker(useTokens, removedCount) {
28
+ return useTokens ? `…${removedCount} tokens truncated…` : `…${removedCount} chars truncated…`;
29
+ }
30
+
31
+ function removedUnits(useTokens, removedBytes, removedChars) {
32
+ if (!useTokens) return removedChars;
33
+ return Math.floor((removedBytes + APPROX_BYTES_PER_TOKEN - 1) / APPROX_BYTES_PER_TOKEN);
34
+ }
35
+
36
+ export function splitString(s, beginningBytes, endBytes) {
37
+ const buf = Buffer.from(s, "utf8");
38
+ const len = buf.length;
39
+ const tailStartTarget = Math.max(0, len - endBytes);
40
+ let prefixEnd = 0;
41
+ let suffixStart = len;
42
+ let removedChars = 0;
43
+ let suffixStarted = false;
44
+ let byteOffset = 0;
45
+
46
+ for (const ch of s) {
47
+ const size = Buffer.byteLength(ch, "utf8");
48
+ const startByte = byteOffset;
49
+ const endByte = byteOffset + size;
50
+ byteOffset = endByte;
51
+
52
+ if (endByte <= beginningBytes) {
53
+ prefixEnd = endByte;
54
+ continue;
55
+ }
56
+ if (startByte >= tailStartTarget) {
57
+ if (!suffixStarted) {
58
+ suffixStart = startByte;
59
+ suffixStarted = true;
60
+ }
61
+ continue;
62
+ }
63
+ removedChars += 1;
64
+ }
65
+
66
+ if (suffixStart < prefixEnd) suffixStart = prefixEnd;
67
+ return {
68
+ removedChars,
69
+ before: buf.subarray(0, prefixEnd).toString("utf8"),
70
+ after: buf.subarray(suffixStart).toString("utf8")
71
+ };
72
+ }
73
+
74
+ function truncateWithByteEstimate(s, maxBytes, useTokens) {
75
+ if (s === "") return "";
76
+ const totalBytes = Buffer.byteLength(s, "utf8");
77
+
78
+ if (maxBytes === 0) {
79
+ return formatTruncationMarker(useTokens, removedUnits(useTokens, totalBytes, [...s].length));
80
+ }
81
+ if (totalBytes <= maxBytes) return s;
82
+
83
+ const [leftBudget, rightBudget] = splitBudget(maxBytes);
84
+ const { removedChars, before, after } = splitString(s, leftBudget, rightBudget);
85
+ const marker = formatTruncationMarker(
86
+ useTokens,
87
+ removedUnits(useTokens, totalBytes - maxBytes, removedChars)
88
+ );
89
+ return before + marker + after;
90
+ }
91
+
92
+ export function truncateMiddleChars(s, maxBytes) {
93
+ return truncateWithByteEstimate(s, maxBytes, false);
94
+ }
95
+
96
+ // A worker's report leads with its conclusion and ends with what it left
97
+ // out, so a clipped report keeps most of the head and some of the tail
98
+ // instead of an even split, which cut exactly the verification section out
99
+ // of a three-part report.
100
+ export function truncateReport(s, maxBytes, headShare = 0.7) {
101
+ if (s === "") return s;
102
+ const totalBytes = Buffer.byteLength(s, "utf8");
103
+ if (maxBytes <= 0 || totalBytes <= maxBytes) return s;
104
+ const head = Math.floor(maxBytes * headShare);
105
+ const { removedChars, before, after } = splitString(s, head, maxBytes - head);
106
+ return `${before}\n${formatTruncationMarker(false, removedChars)}\n${after}`;
107
+ }
108
+
109
+ export function truncateMiddleWithTokenBudget(s, maxTokens) {
110
+ if (s === "") return { text: "", originalTokenCount: null };
111
+ if (maxTokens > 0 && Buffer.byteLength(s, "utf8") <= approxBytesForTokens(maxTokens)) {
112
+ return { text: s, originalTokenCount: null };
113
+ }
114
+ const truncated = truncateWithByteEstimate(s, approxBytesForTokens(maxTokens), true);
115
+ if (truncated === s) return { text: truncated, originalTokenCount: null };
116
+ return { text: truncated, originalTokenCount: approxTokenCount(s) };
117
+ }
118
+
119
+ function lineCount(s) {
120
+ if (s === "") return 0;
121
+ const parts = s.split("\n");
122
+ return s.endsWith("\n") ? parts.length - 1 : parts.length;
123
+ }
124
+
125
+ export function formattedTruncateText(content, byteBudget) {
126
+ if (Buffer.byteLength(content, "utf8") <= byteBudget) return content;
127
+ const originalTokenCount = approxTokenCount(content);
128
+ const totalLines = lineCount(content);
129
+ const result = truncateMiddleChars(content, byteBudget);
130
+ return `Warning: truncated output (original token count: ${originalTokenCount})\nTotal output lines: ${totalLines}\n\n${result}`;
131
+ }
132
+
133
+ // Truncate every oversized string inside an event, keeping the event a valid
134
+ // object so the caller still gets structured JSON back.
135
+ export function truncateEventStrings(value, byteBudget) {
136
+ if (typeof value === "string") {
137
+ return Buffer.byteLength(value, "utf8") > byteBudget ? formattedTruncateText(value, byteBudget) : value;
138
+ }
139
+ if (Array.isArray(value)) return value.map((item) => truncateEventStrings(item, byteBudget));
140
+ if (value && typeof value === "object") {
141
+ const out = {};
142
+ for (const [key, entry] of Object.entries(value)) {
143
+ out[key] = truncateEventStrings(entry, byteBudget);
144
+ }
145
+ return out;
146
+ }
147
+ return value;
148
+ }
@@ -0,0 +1,6 @@
1
+ // The branch a worker's commits live on. Workers dispatched before 1.0 used
2
+ // codex/<id>; their rows carry no branch name, so that is the fallback, and
3
+ // they can still be resumed, landed and restored.
4
+ export const newWorkerBranch = (taskId) => `worker/${taskId}`;
5
+
6
+ export const branchOf = (task) => task.workspace_metadata?.branch ?? `codex/${task.id}`;
@@ -0,0 +1,58 @@
1
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES, isGoalNeedingAttention } from "./status.js";
2
+ import { threadHealth } from "./thread-health.js";
3
+
4
+ // Cursors belong to observers, not workers. A resumed run gets a new receipt;
5
+ // old acceptance cannot produce a current-run completion or failure notice.
6
+ export function collectWorkerChanges(tasks, cursor = {}) {
7
+ const next = {};
8
+ const transitions = [];
9
+ const attention = [];
10
+ for (const task of tasks) {
11
+ const acceptance = task.acceptance_results?.run === task.run_count ? task.acceptance_results : null;
12
+ const health = threadHealth(task);
13
+ const healthKey = `${task.id}:thread_health`;
14
+ if (cursor[healthKey]) next[healthKey] = cursor[healthKey];
15
+ if (ACTIVE_STATUSES.has(task.status) && health.state === "handoff_recommended") {
16
+ const healthFingerprint = JSON.stringify([task.run_count, health.state]);
17
+ next[healthKey] = healthFingerprint;
18
+ if (cursor[healthKey] !== healthFingerprint) {
19
+ const receipt = {
20
+ id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
21
+ reason: "handoff_recommended", tokens_used: health.tokens_used, threshold: health.threshold,
22
+ next_step: {
23
+ tool: "get_worker", arguments: { task_id: task.id, include: ["status"] },
24
+ instruction: "Inspect the live command and stage. Let this bounded step settle or explicitly cancel it before preparing a reviewed checkpoint and a fresh follow-up; do not launch a duplicate while it is active."
25
+ }
26
+ };
27
+ transitions.push(receipt);
28
+ attention.push(receipt);
29
+ }
30
+ }
31
+ let reason = null;
32
+ if (isGoalNeedingAttention(task.goal_status)) reason = `goal_${task.goal_status}`;
33
+ else if (task.attention_reason) reason = task.attention_reason;
34
+ else if (acceptance?.passed === false) reason = "acceptance_failed";
35
+ else if (["interrupted", "cancelled"].includes(acceptance?.status)) reason = `acceptance_${acceptance.status}`;
36
+ else if (TERMINAL_STATUSES.has(task.status) && acceptance?.status !== "running" &&
37
+ (!["completed", "failed"].includes(task.status) || task.exit_code != null)) reason = task.status;
38
+ if (!reason) {
39
+ if (cursor[task.id]) next[task.id] = cursor[task.id];
40
+ continue;
41
+ }
42
+ const fingerprint = JSON.stringify([task.run_count, reason, task.goal_status, acceptance?.status, task.landed_head]);
43
+ next[task.id] = fingerprint;
44
+ if (cursor[task.id] === fingerprint) continue;
45
+ const needsAttention = !["completed", "cancelled"].includes(reason);
46
+ const receipt = {
47
+ id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
48
+ reason, next_step: {
49
+ tool: needsAttention ? "get_worker" : "get_worker_diff",
50
+ arguments: needsAttention ? { task_id: task.id, include: ["result"] } : { task_id: task.id },
51
+ instruction: needsAttention ? "Read the failure or goal evidence before deciding whether to resume; user approval waits must not auto-resume." : "Read the result and diff, then decide whether to land. Completion is not proof of correctness."
52
+ }
53
+ };
54
+ transitions.push(receipt);
55
+ if (needsAttention) attention.push(receipt);
56
+ }
57
+ return { quiet: transitions.length === 0, transitions, attention, cursor: next };
58
+ }
@@ -0,0 +1,14 @@
1
+ import { delimiter, dirname } from "node:path";
2
+
3
+ // Codex may wrap a shell command as either `zsh -lc` or `zsh -c`. The latter
4
+ // does not load the user's login profile, so a Homebrew or version-manager
5
+ // Node directory can disappear even though the supervisor itself is running
6
+ // under that exact executable. Put the current Node directory first and keep
7
+ // the inherited PATH for every other toolchain.
8
+ export function withWorkerToolPath(env, execPath = process.execPath, pathDelimiter = delimiter) {
9
+ const nodeDir = dirname(execPath);
10
+ const inherited = env.PATH ?? env.Path ?? "";
11
+ const parts = inherited.split(pathDelimiter).filter((part) => part && part !== nodeDir);
12
+ const value = [nodeDir, ...parts].join(pathDelimiter);
13
+ return { ...env, PATH: value, ...(process.platform === "win32" ? { Path: value } : {}) };
14
+ }
@@ -0,0 +1,167 @@
1
+ import { TERMINAL_STATUSES } from "./status.js";
2
+ import { createHash } from "node:crypto";
3
+ import { resolve } from "node:path";
4
+ import { commandFailed } from "./command-outcome.js";
5
+
6
+ export const PREFLIGHT_VERSION = 1;
7
+
8
+ function stableValue(value) {
9
+ if (Array.isArray(value)) return value.map(stableValue);
10
+ if (value && typeof value === "object") {
11
+ return Object.fromEntries(
12
+ Object.keys(value)
13
+ .sort()
14
+ .map((key) => [key, stableValue(value[key])])
15
+ );
16
+ }
17
+ return value;
18
+ }
19
+
20
+ function uniqueSorted(values) {
21
+ return [...new Set((values ?? []).map((value) => String(value)))].sort();
22
+ }
23
+
24
+ export function normalizeObservedCommand(command) {
25
+ const text = String(command ?? "").trim();
26
+ const wrapped = text.match(/^(?:[^\s]+\/)?(?:zsh|bash|sh)\s+-l?c\s+([\s\S]+)$/);
27
+ if (!wrapped) return text;
28
+ let body = wrapped[1].trim();
29
+ const quote = body[0];
30
+ if ((quote === "'" || quote === '"') && body.at(-1) === quote) body = body.slice(1, -1);
31
+ // Codex may display the wrapped command with JSON-style escaped quotes.
32
+ // Decode those before reversing zsh's display-only quote insertions.
33
+ body = body.replace(/\\"/g, '"');
34
+ // An interactive zsh protects history expansion and quoted literals by
35
+ // inserting "' around them, for example if("'!ready) and ('"'setup').
36
+ // Both are display artifacts, not part of the command that ran.
37
+ body = body.replace(/"'/g, "");
38
+ // Codex displays a shell command that already contains single quotes by
39
+ // closing and reopening the outer quote around them: -run '"^Test$'"'.
40
+ // Decode that display-only wrapping before comparing it with the contract.
41
+ body = body.replace(/'"'/g, "'");
42
+ // Codex may quote path arguments while displaying a command even when the
43
+ // dispatcher wrote the path bare. Absolute, home-relative and Windows paths
44
+ // are quote-safe here because a path containing whitespace remains quoted in
45
+ // both forms and is not touched by this rule.
46
+ body = body.replace(/(^|\s)['"]((?:[A-Za-z]:[\\/]|\/|\.\/|\.\.\/|~\/)[^'"\s]*)['"](?=\s|$)/g, "$1$2");
47
+ return body.trim();
48
+ }
49
+
50
+ export function commandsEquivalent(observed, expected) {
51
+ const normalizedExpected = normalizeObservedCommand(expected);
52
+ return normalizeObservedCommand(observed) === normalizedExpected;
53
+ }
54
+
55
+ export function buildRuntimeContract({
56
+ projectRoot,
57
+ baseCommit,
58
+ sandbox,
59
+ ownedPaths,
60
+ allowedCommands,
61
+ networkAccess,
62
+ writableRoots,
63
+ context,
64
+ contracts,
65
+ workspaceSetup = null,
66
+ workspaceKind = "git_worktree",
67
+ workspaceManifestSha256 = null,
68
+ runner = "codex"
69
+ }) {
70
+ return stableValue({
71
+ // Named only when it is not the default, so contracts made before runners existed still match.
72
+ ...(runner && runner !== "codex" ? { runner } : {}),
73
+ version: PREFLIGHT_VERSION,
74
+ project_root: resolve(projectRoot),
75
+ base_commit: baseCommit ?? null,
76
+ sandbox,
77
+ owned_paths: uniqueSorted(ownedPaths),
78
+ allowed_commands: uniqueSorted(allowedCommands),
79
+ network_access: networkAccess === true,
80
+ writable_roots: uniqueSorted(writableRoots),
81
+ workspace_kind: workspaceKind,
82
+ workspace_manifest_sha256: workspaceManifestSha256,
83
+ context: (context ?? [])
84
+ .map((entry) => ({ path: resolve(entry.path), sha256: entry.sha256 ?? null }))
85
+ .sort((left, right) => left.path.localeCompare(right.path)),
86
+ contracts: uniqueSorted(contracts),
87
+ workspace_setup: stableValue(workspaceSetup)
88
+ });
89
+ }
90
+
91
+ export function runtimeContractHash(contract) {
92
+ return createHash("sha256").update(JSON.stringify(stableValue(contract))).digest("hex");
93
+ }
94
+
95
+ export function createPreflightMetadata(contract, probeCommands) {
96
+ const commands = uniqueSorted(probeCommands);
97
+ if (commands.length === 0) throw new Error("preflight requires at least one probe command");
98
+ return {
99
+ version: PREFLIGHT_VERSION,
100
+ contract,
101
+ contract_hash: runtimeContractHash(contract),
102
+ probe_commands: commands
103
+ };
104
+ }
105
+
106
+ export function readPreflightResult(task) {
107
+ const metadata = task?.guard_policy?.preflight;
108
+ if (!metadata?.contract_hash || !Array.isArray(metadata.probe_commands)) {
109
+ return { error: "not_a_preflight", status: "unknown" };
110
+ }
111
+
112
+ const commands = Array.isArray(task.commands) ? task.commands : [];
113
+ const probes = metadata.probe_commands.map((command) => {
114
+ const matches = commands.filter((entry) => commandsEquivalent(entry.command, command));
115
+ const result = matches.at(-1) ?? null;
116
+ return {
117
+ command,
118
+ executed: Boolean(result),
119
+ exit_code: result?.exit_code ?? null,
120
+ status: result?.status ?? null,
121
+ passed: Boolean(result) && !commandFailed(result)
122
+ };
123
+ });
124
+ const terminal = TERMINAL_STATUSES.has(task.status);
125
+ const failedCommands = commands.filter(commandFailed);
126
+ const probesPassed = probes.every((probe) => probe.passed);
127
+ const exitConfirmed = task.status === "completed" && task.exit_code === 0;
128
+ const reportWasInvalid = task.attention_reason === "invalid_report";
129
+ const probesProveEnvironment = probesPassed && failedCommands.length === 0;
130
+ const exitWasLost = task.status === "lost" && probesProveEnvironment;
131
+ // A preflight proves the worker environment through its command evidence.
132
+ // Its own final report and close-handler completion are useful diagnostics,
133
+ // but neither changes what those commands already proved. A completed turn
134
+ // without a recorded exit is accepted for this probe-only task; real failed,
135
+ // cancelled or unexplained-lost commands still fail below.
136
+ const workerOutcomeAcceptable = exitConfirmed
137
+ || (task.status === "completed" && task.exit_code == null)
138
+ || reportWasInvalid
139
+ || exitWasLost;
140
+ let status = "running";
141
+ if (terminal) {
142
+ status = workerOutcomeAcceptable && probesPassed && failedCommands.length === 0
143
+ ? "passed"
144
+ : "failed";
145
+ }
146
+ return {
147
+ task_id: task.id,
148
+ status,
149
+ terminal,
150
+ contract_hash: metadata.contract_hash,
151
+ contract: metadata.contract,
152
+ worker_outcome: {
153
+ status: task.status,
154
+ exit_code: task.exit_code ?? null,
155
+ exit_confirmed: exitConfirmed,
156
+ report_ignored: reportWasInvalid,
157
+ missing_exit_tolerated: task.status === "completed" && task.exit_code == null || exitWasLost
158
+ },
159
+ probes,
160
+ failed_commands: failedCommands.map((entry) => ({
161
+ command: entry.command,
162
+ exit_code: entry.exit_code ?? null,
163
+ status: entry.status ?? null,
164
+ output_tail: entry.output_tail ?? null
165
+ }))
166
+ };
167
+ }
@@ -0,0 +1,85 @@
1
+ import { fileURLToPath } from "node:url";
2
+ export const workerReportSchemaPath = fileURLToPath(new URL("./worker-report.schema.json", import.meta.url));
3
+
4
+ // The last message should be the bare JSON value, but a provider or a weaker
5
+ // model sometimes wraps it in a markdown fence or pads it with a sentence.
6
+ // Unwrapping that is not a schema relaxation: the object still has to carry
7
+ // exactly result/verification/not_done with the right types. The first
8
+ // candidate that parses as JSON decides the verdict, so a wrong object is
9
+ // never rescued by a second one.
10
+ function reportCandidates(text) {
11
+ const trimmed = text.trim();
12
+ const candidates = [{ source: "bare", text: trimmed }];
13
+ for (const match of trimmed.matchAll(/```[a-zA-Z]*\s*\n?([\s\S]*?)```/g)) {
14
+ candidates.push({ source: "fence", text: match[1].trim() });
15
+ }
16
+ const first = trimmed.indexOf("{");
17
+ const last = trimmed.lastIndexOf("}");
18
+ if (first !== -1 && last > first) candidates.push({ source: "embedded", text: trimmed.slice(first, last + 1) });
19
+ return candidates;
20
+ }
21
+
22
+ function validateReport(value) {
23
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { valid: false, error: "report must be a JSON object" };
24
+ if (Object.keys(value).sort().join(",") !== "not_done,result,verification") {
25
+ return { valid: false, error: "report must contain result:string, verification:string[], not_done:string[] only" };
26
+ }
27
+ if (typeof value.result !== "string") return { valid: false, error: "report.result must be a string" };
28
+ const repaired = [];
29
+ const normalized = { ...value };
30
+ for (const field of ["verification", "not_done"]) {
31
+ if (typeof value[field] === "string") {
32
+ normalized[field] = [value[field]];
33
+ repaired.push(`${field}_string`);
34
+ }
35
+ if (!Array.isArray(normalized[field]) || !normalized[field].every((entry) => typeof entry === "string")) {
36
+ return { valid: false, error: `report.${field} must be a string or string[]` };
37
+ }
38
+ }
39
+ return { valid: true, report: normalized, repaired };
40
+ }
41
+
42
+ function parseWithClosure(candidate) {
43
+ try { return { value: JSON.parse(candidate), repair: null }; } catch (error) {
44
+ const parsedError = error;
45
+ const attempts = [
46
+ [candidate, "}", "closed_object"],
47
+ [candidate, "]", "closed_array"]
48
+ ];
49
+ if (candidate.endsWith("}")) {
50
+ const body = candidate.slice(0, -1);
51
+ attempts.push([body, "]}", "closed_array"]);
52
+ }
53
+ for (const [body, suffix, repair] of attempts) {
54
+ try { return { value: JSON.parse(body + suffix), repair }; } catch { /* try the next bounded repair */ }
55
+ }
56
+ return { value: null, repair: null, error: parsedError };
57
+ }
58
+ }
59
+
60
+ export function parseWorkerReport(text) {
61
+ if (typeof text !== "string" || !text.trim()) return { format: "json_schema", valid: false, error: "worker wrote no final report" };
62
+ let parseError = null;
63
+ for (const { source, text: candidate } of reportCandidates(text)) {
64
+ const parsed = parseWithClosure(candidate);
65
+ if (parsed.error) { parseError = parseError ?? parsed.error; continue; }
66
+ const checked = validateReport(parsed.value);
67
+ if (!checked.valid) return { format: "json_schema", valid: false, error: checked.error };
68
+ const repairs = [source === "bare" ? null : source, parsed.repair, ...checked.repaired].filter(Boolean);
69
+ return { format: "json_schema", valid: true, report: checked.report, ...(repairs.length ? { repaired: repairs.join("+") } : {}) };
70
+ }
71
+ return { format: "json_schema", valid: false, error: parseError?.message ?? "report is not JSON" };
72
+ }
73
+
74
+ export function parseWorkerReportForRun(text, { outputSchema = true } = {}) {
75
+ const parsed = parseWorkerReport(text);
76
+ if (!outputSchema && !parsed.valid && typeof text === "string" && text.trim()) {
77
+ return {
78
+ format: "text",
79
+ valid: true,
80
+ repaired: "output_schema_disabled_text_fallback",
81
+ report: { result: text, verification: [], not_done: [] }
82
+ };
83
+ }
84
+ return parsed;
85
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "type": "object",
3
+ "additionalProperties": false,
4
+ "required": ["result", "verification", "not_done"],
5
+ "properties": {
6
+ "result": {"type": "string"},
7
+ "verification": {"type": "array", "items": {"type": "string"}},
8
+ "not_done": {"type": "array", "items": {"type": "string"}}
9
+ }
10
+ }