codex-supervisor-mcp 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -161,7 +161,7 @@ Thirty-nine.
161
161
  | `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | The worker's own report, clipped past 6000 bytes with `truncated` and the size to ask for. `acceptance` is whether the supervisor's own checks passed, `verification` the commands the worker ran with exit codes, `base_behind` how far main has moved (`behind` is `null` with a note when `contains_base` is false, meaning the directory switched lines) |
162
162
  | `get_worker_diff` | `task_id`, `maxChars`, `paths` | What the worker actually changed: patches from the worktree's start to its working tree, committed or not. `maxChars` bounds the answer; files past it are listed without a patch |
163
163
  | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | Ask the worker on the side. Its thread is forked into a read-only session with no network and no MCP tools; the worker itself is untouched. A resumed worker gets a new fork by itself, `fresh` forces one, `end` deletes it |
164
- | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | Cherry-pick the worker's `codex/<id>` commits onto the current branch of the dispatch directory: clean target only, a conflict rolls back, a failed acceptance is refused. `commitMessage` first commits its uncommitted edits as one commit; `ignoreAcceptance` lands anyway |
164
+ | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | Cherry-pick the worker's `codex/<id>` commits onto the current branch of the dispatch directory: clean target only, a conflict rolls back, a failed acceptance is refused. A malformed report summary no longer blocks an explicit landing when acceptance and the reviewed diff are sound. `commitMessage` first commits its uncommitted edits as one commit; `ignoreAcceptance` lands anyway |
165
165
  | `verify_delivery_push` | `task_id`, `remote`, `branch` | Fetch a remote branch and prove landed_head is reachable; records push_verified and creates a cleanup plan without pushing or deploying |
166
166
  | `cleanup_plan` | `task_ids`, `project_root` | Create a 15-minute SAFE / REVIEW / BLOCKED plan with reasons and fingerprints; SAFE requires explicit acceptance, delivery proof, clean state and no active process/dependency |
167
167
  | `apply_cleanup` | `plan_id`, `item_ids` | Revalidate selected SAFE items, fetch the remote and prove landed SHA reachability, then run only git worktree remove/prune |
@@ -190,7 +190,9 @@ Thirty-nine.
190
190
 
191
191
  Two are required: `ownedPaths` (checked against every running worker before dispatch, overlap refuses the call, dispatch-time only) and `goal.objective` (the worker turns it into a native Codex goal). Without `session_id` nothing groups the batch; use one value for the whole batch.
192
192
 
193
- `acceptance` runs in Bash with `errexit` and `pipefail`: an unhandled failure stops the check, including a failing test in `npm test | tail`. Handle expected failures explicitly with `if` or `||`; a timeout always fails, even when the command exits 0 after termination. Windows requires Git for Windows Bash and reports an error when it is missing. Displayed output is clipped without changing the exit code.
193
+ `acceptance` runs in Bash with `errexit` and `pipefail`: an unhandled failure stops the check, including a failing test in `npm test | tail`. Workers run `node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"` for the exact supervisor contract instead of retyping checks in an interactive zsh. Handle expected failures explicitly with `if` or `||`; a timeout always fails, even when the command exits 0 after termination. Windows requires Git for Windows Bash and reports an error when it is missing. Displayed output is clipped without changing the exit code.
194
+
195
+ In a repository with `package.json`, acceptance that uses local JavaScript tooling such as `npm`, `pnpm`, `vitest`, `vue-tsc`, `eslint` or `nuxi` is rejected with `workspace_setup_required` unless `workspaceSetup` was provided. Dependency preparation is now a runtime gate, not a reminder for the model.
194
196
 
195
197
  Acceptance commands receive `CODEX_SUPERVISOR_TASK_ID`, `CODEX_SUPERVISOR_BASE_COMMIT` and `CODEX_SUPERVISOR_RUN`: the current task, run base and run number, refreshed after rebase/resume.
196
198
 
@@ -210,7 +212,7 @@ An `allowedCommands` entry ending in `*` is a prefix match (so `go test ./intern
210
212
 
211
213
  The guard relaxes by workspace shape: a `git_worktree` editor with non-empty `ownedPaths` gets only declared commands and simple reads; `read_only_in_place` cannot write or use network; networked research uses `scratch` under `SUPERVISOR_HOME`, never the source directory; `in_place_write` requires explicit authorization, owned paths and acceptance with before/after manifests. A non-Git `workspace-write` request without `workspaceKind` is refused. A worker capsule names its branch and acceptance source without embedding acceptance commands. Repository facts cross checkouts only when canonical `origin`, repository-relative watched paths and base SHA all match; an unrecognized origin leaves them work-scoped. A fact is append-only expired and excluded from a future worker capsule when its base SHA no longer covers the task, a watched path changed, its declared context content hash changed, or its in-place manifest drifted; explicit dependencies provide only delivery summaries.
212
214
 
213
- After reconciliation, check_workers atomically resumes a dead first lost/no_work/invalid_report run once and returns recovery receipts (an invalid report only re-asks for the bare JSON; it does not redo the work). Two consecutive no-output/no-command runs with the same fingerprint become `two_stall` and `needs_attention`, never another blind retry; approval, authentication, permission and quota waits are not retried. Final reports use JSON result/verification/not_done; structured_report exposes validation independently of command history and acceptance. Invalid JSON is failed/invalid_report and cannot land. Existing history is labelled legacy_text.
215
+ After reconciliation, check_workers atomically resumes a dead first lost/no_work/invalid_report run once and returns recovery receipts (an invalid report only re-asks for the bare JSON; it does not redo the work). Two consecutive no-output/no-command runs with the same fingerprint become `two_stall` and `needs_attention`, never another blind retry; approval, authentication, permission and quota waits are not retried. Final reports use JSON result/verification/not_done. Parsing safely normalizes a single string field into string[] and one missing closing `]`/`}`; fabricated shapes still fail. The report is a summary: invalid_report preserves the completed lifecycle and attention, does not override the same run's acceptance or reviewed diff, and an explicit landing remains possible. Existing history is labelled legacy_text.
214
216
 
215
217
  context declares up to 20 absolute file paths with optional sha256, within a combined 6000-character budget with contracts; each file is at most 5 MB. Dispatch pins actual hashes and resume refuses drift unless new context is explicitly supplied. Handoffs are limited to 1800 characters/16 lines with a truncation marker; complete contracts and refs remain separate, and inputs grant no write permission.
216
218
 
@@ -326,7 +328,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
326
328
  | Worker `failed` at once with `spawn codex ENOENT` | No codex on the process `PATH` | Set `CODEX_BIN` in the config |
327
329
  | `Cannot find module 'node:sqlite'` | Node older than 22.13.0 | Upgrade Node |
328
330
  | Worker `lost` | The worker or independent run process was interrupted | Inspect events, then `resume_codex_worker` |
329
- | Worker reports `git add` failing with `index.lock: Operation not permitted` | The default sandbox keeps `.git` read-only | `land_codex_worker` with `commitMessage`, or dispatch with `danger-full-access` |
331
+ | Worker reports `git add` failing with `index.lock: Operation not permitted` | The default sandbox keeps `.git` read-only; this is the intended boundary | Keep the worker to edits and acceptance, then use `land_codex_worker` with `commitMessage` |
330
332
  | `ownedPaths overlap with active worker(s)` | Two workers claimed the same paths | Split differently, or cancel the one holding them |
331
333
  | The board is empty | The board and the MCP use different `SUPERVISOR_HOME`s | Start it inside the project with the `.mcp.json`, or pass the same `SUPERVISOR_HOME` |
332
334
  | `port 7877 ... is already in use` | A board is already running | Open it, or start another with `SUPERVISOR_WEB_PORT=8080` |
@@ -334,7 +336,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
334
336
  ## Known limitations
335
337
 
336
338
  - Each run has an independent process that drains worker output, records its exit, and runs acceptance before exiting. These continue after the dispatching MCP is killed; a new window uses `get_session_works` to collect results. If the run process is also killed, inspect lost/interrupted evidence before resuming the preserved worktree and thread_id.
337
- - In the default `workspace-write` sandbox a worker cannot commit (Codex keeps `.git` read-only). Either `land_codex_worker` with `commitMessage` commits for it, or dispatch with `danger-full-access`.
339
+ - In the default `workspace-write` sandbox a worker cannot commit (Codex keeps `.git` read-only). Use `land_codex_worker` with `commitMessage`; do not switch to `danger-full-access` just to commit.
338
340
  - The worktree is cut from a commit; uncommitted work in your checkout is not in it.
339
341
  - Only the working directory is isolated. Temp directories, databases and ports are shared.
340
342
  - `ownedPaths` is checked at dispatch only; it does not stop a worker from creating files outside its list. Read the diff.
package/README.md CHANGED
@@ -172,7 +172,7 @@ land_codex_worker 核过了,落进集成分支
172
172
  | `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | worker 自己的汇报,默认截 6000 字节、`truncated` 提示读全。`acceptance` 是 supervisor 替你跑的验收过没过,`verification` 是它自己跑过的命令和退出码,`base_behind` 是主线走了多远(`contains_base: false` 时 `behind` 为 `null`,那是换了线) |
173
173
  | `get_worker_diff` | `task_id`, `file`, `hunk`, `pageSize`, `cursor`, `maxChars`, `paths` | worker 实际改了什么。默认完整文件索引与 hunk 数;按 `file` + `hunk`/`cursor` 分页读 patch。显式 `maxChars` 且不传 `file` 保留旧整份限流模式 |
174
174
  | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | 旁路问 worker 一句。线程 fork 成只读侧会话,没网络、没 MCP 工具,worker 本身不动。worker 被 resume 过会自动换新 fork,`fresh` 强制换,`end` 删 |
175
- | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝。`commitMessage` 先替它把未提交的改动提交成一笔,`ignoreAcceptance` 放行 |
175
+ | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝;报告格式错不再单独阻止显式 land。`commitMessage` 先替它把未提交的改动提交成一笔,`ignoreAcceptance` 放行 |
176
176
  | `verify_delivery_push` | `task_id`, `remote`, `branch` | fetch 指定 remote branch 并证明 `landed_head` 已可达;只读验证,不会 push 或部署。通过后记录 `push_verified` 并生成 cleanup plan |
177
177
  | `cleanup_plan` | `task_ids`, `project_root` | 生成 15 分钟有效的 SAFE / REVIEW / BLOCKED 计划,含原因、fingerprint 与回收空间估算;SAFE 必须 acceptance passed、push verified、干净且无活跃依赖/进程 |
178
178
  | `apply_cleanup` | `plan_id`, `item_ids` | 只在未过期计划上二次校验 SAFE item、重新 fetch remote 并确认 landed SHA 仍可达后执行 `git worktree remove/prune`;保留 branch、task、events、JSONL、artifacts |
@@ -201,7 +201,9 @@ land_codex_worker 核过了,落进集成分支
201
201
 
202
202
  必填的两个:`ownedPaths`(派单前和在跑的 worker 求交集,重叠就拒,只在派单时查)和 `goal.objective`(worker 会建成 Codex 原生 goal)。`session_id` 不传就归不了组,一批活传同一个值。
203
203
 
204
- `acceptance` 在 Bash 中启用 `errexit` 和 `pipefail`:未处理的失败会停止检查,`npm test | tail` 中的测试失败也会保留。写 worker 不能只用 `test -s`、`test -f` 或 `[ -e ]` 这类文件存在性命令交付;要加真实 test、endpoint probe 或结构化执行证据。识别到的 test runner 输出 `no tests to run` / `[no test files]` 时,即使退出码是 0 也判失败。预期失败用 `if` 或 `||` 显式处理;超时始终判失败,即使命令收到终止信号后退出 0。Windows 需要 Git for Windows 的 Bash;找不到会报错。显示的输出会裁剪,退出码不会因此改变。
204
+ `acceptance` 在 Bash 中启用 `errexit` 和 `pipefail`:未处理的失败会停止检查,`npm test | tail` 中的测试失败也会保留。worker 自查必须运行 `node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"`,它执行同一份 supervisor 验收契约;不要手抄到 zsh,变量拆词等交互壳差异不会污染证据。写 worker 不能只用 `test -s`、`test -f` 或 `[ -e ]` 这类文件存在性命令交付;要加真实 test、endpoint probe 或结构化执行证据。识别到的 test runner 输出 `no tests to run` / `[no test files]` 时,即使退出码是 0 也判失败。预期失败用 `if` 或 `||` 显式处理;超时始终判失败,即使命令收到终止信号后退出 0。Windows 需要 Git for Windows 的 Bash;找不到会报错。显示的输出会裁剪,退出码不会因此改变。
205
+
206
+ `package.json` 仓库里,如果 `acceptance` 使用 `npm`、`pnpm`、`vitest`、`vue-tsc`、`eslint`、`nuxi` 等本地 JavaScript 工具,而派单没有 `workspaceSetup`,会直接拒绝为 `workspace_setup_required`。这条是 runtime 硬门禁,不再靠模型记得手工链接依赖。
205
207
 
206
208
  普通 worker 启动时会关闭它继承到的 `codex-supervisor` MCP,不能再派 worker、resume、cancel 或改编排状态;主线程是唯一编排者。其他业务 MCP 不受影响;旁问 fork 仍关闭全部 MCP,因为它只允许只读回答。
207
209
 
@@ -231,7 +233,7 @@ wait 默认预算60秒、默认compact;includeEvents会选择详细结果(
231
233
 
232
234
  守卫按 worker 形状放权:`git_worktree` 编辑 worker 只放声明过的命令和简单读取;`read_only_in_place` 无写入无网络;`scratch` 的联网草稿只能写在 `SUPERVISOR_HOME/scratch/<taskId>`;`in_place_write` 必须有显式授权、ownedPaths 与 acceptance,并保存前后 manifest。非 Git `workspace-write` 没写 `workspaceKind` 会拒绝,绝不默认写用户目录。
233
235
 
234
- check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON,不重做活)。两轮同 fingerprint 的无输出/无命令会升级为 `two_stall` 和 `needs_attention`,不再自动重试;审批、认证、权限和quota等待也不重试,返回recoveries记录。worker最终输出强制JSON result/verification/not_done;get_worker_result的structured_report给格式校验,独立命令与acceptance仍为实际证据。非法JSON标failed/invalid_report并拒绝land;旧历史标legacy_text。
236
+ check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON,不重做活)。两轮同 fingerprint 的无输出/无命令会升级为 `two_stall` 和 `needs_attention`,不再自动重试;审批、认证、权限和quota等待也不重试,返回recoveries记录。worker最终输出要求JSON result/verification/not_done;解析只做安全修复:字符串字段归一成 string[],以及唯一缺少的 `]`/`}`,伪造字段仍拒绝。报告只是摘要;invalid_report 保持 `completed` 生命周期和 attention,不否定同 run acceptance 和真实 diff,显式 land 仍可用;旧历史标legacy_text。
235
237
 
236
238
  context用绝对文件路径与可选sha256声明材料,最多20份、与contracts合计6000字;文件不超过5 MB。首次派单记录实际哈希,resume校验原材料未变,需要新材料时显式传context。handoff最多1800字/16行,截断明确标记;完整约束和引用单独保留,材料不授予写权限。
237
239
 
@@ -348,7 +350,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
348
350
  | worker 一起来就 `failed`,`spawn codex ENOENT` | 进程 `PATH` 里没有 codex | 配置里设 `CODEX_BIN` |
349
351
  | `Cannot find module 'node:sqlite'` | Node 低于 22.13.0 | 升 Node |
350
352
  | worker `lost` | worker 或独立运行进程中断 | 查事件后用 `resume_codex_worker` 接回 |
351
- | worker 说 `git add` 报 `index.lock: Operation not permitted` | 默认沙箱把 `.git` 设成只读 | 收活时 `land_codex_worker` 带 `commitMessage`,或派单用 `danger-full-access` |
353
+ | worker 说 `git add` 报 `index.lock: Operation not permitted` | 默认沙箱把 `.git` 设成只读,这是正常边界 | 保持 worker 只改和验收,收活时 `land_codex_worker` 带 `commitMessage` |
352
354
  | `ownedPaths overlap with active worker(s)` | 两路认领了同一片路径 | 改拆法,或先取消占着的那路 |
353
355
  | 看板打开是空的 | 看板和 MCP 的 `SUPERVISOR_HOME` 不是同一个 | 在配了 `.mcp.json` 的项目目录里起,或显式传同一个 `SUPERVISOR_HOME` |
354
356
  | `port 7877 ... is already in use` | 已经有一个看板在跑 | 直接开它,或 `SUPERVISOR_WEB_PORT=8080` 再起一个 |
@@ -356,7 +358,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
356
358
  ## 已知限制
357
359
 
358
360
  - 每次运行由独立进程读取 worker 输出、落状态和执行验收,直到结算后退出。派单 MCP 被 kill 后这些工作继续;新窗口用 `get_session_works` 收结果。若运行进程也被杀,保留 worktree 和 thread_id,核对 lost/interrupted 后恢复。
359
- - 默认 `workspace-write` 沙箱里 worker 提交不了(Codex 把 `.git` 设成只读)。要么收活时 `land_codex_worker` 带 `commitMessage` 替它提交,要么派单用 `danger-full-access`。
361
+ - 默认 `workspace-write` 沙箱里 worker 提交不了(Codex 把 `.git` 设成只读)。收活时 `land_codex_worker` 带 `commitMessage` 替它提交;不要为了提交改用 `danger-full-access`。
360
362
  - worktree 从一个提交切,你工作区里没 commit 的东西不在里面。
361
363
  - 只隔离工作目录。临时目录、数据库、端口是共用的。
362
364
  - `ownedPaths` 只在派单时查,拦不住 worker 新建清单外的文件。收活看 diff。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.12.2",
3
+ "version": "0.13.0",
4
4
  "mcpName": "io.github.zriyox/codex-supervisor-mcp",
5
5
  "type": "module",
6
6
  "description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
@@ -25,6 +25,7 @@
25
25
  ],
26
26
  "bin": {
27
27
  "codex-supervisor-mcp": "src/mcp-server.js",
28
+ "codex-supervisor-accept": "src/acceptance-cli.js",
28
29
  "codex-supervisor-setup": "src/setup.js",
29
30
  "codex-supervisor-web": "src/web-server.js",
30
31
  "codex-supervisor-stage": "src/stage.js"
@@ -41,6 +42,7 @@
41
42
  "src/worktree.js",
42
43
  "src/landing.js",
43
44
  "src/acceptance.js",
45
+ "src/acceptance-cli.js",
44
46
  "src/acceptance-baseline.js",
45
47
  "src/worker-changes.js",
46
48
  "src/owned-changes.js",
@@ -11,10 +11,19 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
11
11
 
12
12
  一批能拆开的活、活偏大不想占自己的上下文、跑到一半可能断要能接回来。一个文件的小改、纯问答、要来回确认的活,自己干更快。
13
13
 
14
+ ## 派单硬门禁
15
+
16
+ - `ownedPaths` 是完整交付面,不是主文件:实现、测试、路由、注册表、DI、配置、迁移、i18n 和模板接线都要预估;路径多就给唯一模块目录,漏列就是 guard 正常拒绝。
17
+ - 依赖不在 worktree 里就传 `workspaceSetup`,同一份 setup 同时给 preflight 和目标 worker。前端 `node_modules`、`.nuxt` 和 Vitest 缓存,后端 submodule/proto,都不准靠 sleep 或主线程手工补。
18
+ - 写 worker 先跑同 contract 的 `preflight_codex_worker`,`get_worker_preflight` 必须 passed;不能拿宿主 `check_acceptance` 冒充 worker 环境。
19
+ - `workspace-write` worker 不提交。不要让它 `git add` / `git commit` / `amend`;验后用 `land_codex_worker({commitMessage})` 由 supervisor 代提交并 cherry-pick。
20
+ - worker 自查验收统一运行 `node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"`。不要手抄到 zsh;supervisor 和 worker 都走同一个 Bash `errexit + pipefail` 入口。
21
+ - 最终 JSON 只是摘要。格式错会让 `attention_reason=invalid_report`,不再否定已经通过的同 run acceptance 和真实 diff;先 `check_workers` 做一次 report-only 修复,仍失败可审过 diff 后显式 land。
22
+
14
23
  ## 派单
15
24
 
16
25
  1. 先 `search_works` 搜一下,别重复派。
17
- 2. 拆功能包。每路写清楚:干什么、能写哪些文件、依赖谁、怎么算做完和谁负责集成。改同一批文件就串行;文件不重叠只是并行前提,不等于依赖已满足。
26
+ 2. 拆功能包。每路写清楚:干什么、完整写集和 `ownedPaths`、依赖谁、怎么算做完和谁负责集成。改同一批文件就串行;文件不重叠只是并行前提,不等于依赖已满足。
18
27
  3. 写 worker 先 `preflight_codex_worker`:用目标同一份 `workspaceKind` / `baseRef` / `ownedPaths` / `sandbox` / `allowedCommands` / `context` / `networkAccess` / `writableRoots` 跑必要命令。等它终态后 `get_worker_preflight` 必须 `passed`,再把它的 `task_id` 填进 `create_codex_worker.preflight_id`。contract 变了重跑,不能拿宿主 `check_acceptance` 冒充 worker 环境成功。
19
28
  4. `create_codex_worker` 派出去。回执只有 `id`、`worktree_path`、`branch`、`owned_paths`、`status`,不回传任务原文。
20
29
  5. 长任务配宿主 `/loop 5m check_workers` 定时收活,没变化 quiet,有新结果按 next_step 收。工具会按规则恢复一次,但不会唤醒关闭的主窗口;每个主线程设独立 `CODEX_SUPERVISOR_OBSERVER_ID` 可重启接回。短等用 `wait_codex_workers` 的 `timeoutMs: 60000`、`compact: true`,到点继续同批 task_ids。
@@ -27,8 +36,8 @@ worker 默认不是调度员:启动时会禁用它继承到的 `codex-supervis
27
36
  | `cwd` | Git 项目根,或非 Git 输入目录;实际执行目录由 `workspaceKind` 决定,不能默认写原目录 |
28
37
  | `workspaceKind` | Git 代码默认 `git_worktree`;非 Git 只读用 `read_only_in_place`,联网研究用 `scratch`,要改用户非 Git 目录只能显式 `in_place_write` |
29
38
  | `inPlaceAuthorization` | 仅 `in_place_write`:写明用户授权原因;同时必须有非空 `ownedPaths` 和 `acceptance`,系统记录前后 manifest |
30
- | `workspaceSetup` | 仅 Git worktree,在 worker 启动前完成环境准备:`links` 把主仓依赖链接进 worktree;`submodules: true` 初始化子模块;`commands` 跑 `nuxi prepare` 等准备工作。setup 失败会在派单阶段回收 worktree。链接名为 `node_modules` 时自动把 `.vite`、`.vite-temp`、`.cache` 放进该 worker 可写缓存根 |
31
- | `acceptance` | 这一步"做完了"的判据,worker 退出后 supervisor 在它的 worktree 里逐条跑。写 worker 不能只用 `test -s/-f`、`[ -e ]` 这类文件存在性检查;要有真实 test、endpoint probe 或结构化执行证据。识别到的 test runner 输出 `no tests to run` / `[no test files]` 即使 exit 0 也失败。必跑用例、skip、旧报告和失败身份用 `{command,reportPath,baseline}` 结构化验收证明;远端机器的检查包进 `ssh` |
39
+ | `workspaceSetup` | 仅 Git worktree,在 worker 启动前完成环境准备:`links` 把主仓依赖链接进 worktree;`submodules: true` 初始化子模块;`commands` 跑 `nuxi prepare` 等准备工作。**只要测试或构建依赖生成物,就必须在派单前准备;禁止 sleep 抢时间或主线程事后补。** setup 失败会在派单阶段回收 worktree。链接名为 `node_modules` 时自动把 `.vite`、`.vite-temp`、`.cache` 放进该 worker 可写缓存根 |
40
+ | `acceptance` | 这一步"做完了"的判据,worker 退出后 supervisor 在它的 worktree 里逐条跑。worker 自查统一用 `node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"`,不要手抄到 zsh。写 worker 不能只用 `test -s/-f`、`[ -e ]` 这类文件存在性检查;要有真实 test、endpoint probe 或结构化执行证据。识别到的 test runner 输出 `no tests to run` / `[no test files]` 即使 exit 0 也失败。必跑用例、skip、旧报告和失败身份用 `{command,reportPath,baseline}` 结构化验收证明;远端机器的检查包进 `ssh` |
32
41
  | `forbid` / `allowedCommands` | 原样声明红线与验证命令;守卫拒绝未声明Shell程序,编辑用apply_patch |
33
42
  | `writableRoots` | 只有需要凭据目录时才传(绝对路径、已存在、自动解析软链、只对 workspace-write 生效):ssh/远程测试 → `["~/.ssh"]`;kubectl → `["~/.kube"]`;推私有镜像 → `["~/.docker"]`;aws cli → `["~/.aws"]`;签名提交 → `["~/.gnupg"]`。缓存目录不用写,已经自动加 |
34
43
  | `ownedPaths` | 必填。这路允许写的路径,和在跑的 worker 重叠会被拒(**读不排他**,多路读同一份共享文件合法)。冲突是好事,说明该改拆法。传 `[]` 表示这路不落地:只读验证或研究 |
@@ -41,7 +50,7 @@ worker 默认不是调度员:启动时会禁用它继承到的 `codex-supervis
41
50
  `probeCommands` 会自动加入这次 probe worker 的 guard-only allowlist,不会进入目标 worker 的 runtime contract;目标 worker 仍只声明自己真正需要的 `allowedCommands`。ssh 等联网探针仍要显式 `networkAccess: true`,需要写 `known_hosts` 时同时声明 `writableRoots: ["~/.ssh"]`。
42
51
 
43
52
  预检结论以 probe command evidence 为准,不把模型最终 JSON 或进程 close handler 当环境事实:所有探针都实际执行且通过、没有失败命令时,最终报告格式错误不会让预检失败;probe-only worker 即使最终变 `lost` 且退出码未记录,也只记诊断,不重跑。命令未执行、非零或取消仍失败。
44
- | `sandbox` | 默认 `workspace-write`,worker 提交不了(Codex 把 `.git` 设成只读)。要它自己提交就 `danger-full-access`,否则收活时让 supervisor 替它提交 |
53
+ | `sandbox` | 默认 `workspace-write`,worker 提交不了(Codex 把 `.git` 设成只读)。这是正常形状:worker 只改和验收,收活时 `land_codex_worker(commitMessage)` 由 supervisor 代提交;不要为提交改用 `danger-full-access` |
45
54
 
46
55
  验收用 Bash 的 `errexit` + `pipefail`:`npm test | tail` 不能吞失败;文件存在只可做附加门禁,不能单独证明业务完成。预期失败用 `if` / `||` 显式判。超时、`no tests to run`、`[no test files]` 都失败,别只看退出码 0。Windows 要有 Git for Windows Bash;缺失先修工具,别换回 cmd。
47
56
 
@@ -70,7 +79,7 @@ worker不止改代码,按这路要什么选形状:
70
79
 
71
80
  read-only 下 `networkAccess: true` 会被拒(实测该沙箱连 DNS 都不通,配了也没用);要联网就按 `scratch` 研究 worker 派。非 Git `workspace-write` 不写 `workspaceKind` 会拒绝,绝不偷偷落到用户目录。研究 worker 的 shell 不受 allowedCommands 限制,forbid 红线照旧。读共享文件永远不排他,只有写按 ownedPaths 排他。
72
81
 
73
- check_workers可对已死的第1轮lost/no_work/invalid_report自动resume一次,recoveries记动作;invalid_report只让它重发裸JSON、不重做活,审批/认证/权限/quota不盲重试。连续两轮同 fingerprint 的无输出/无命令会变 `two_stall` + `needs_attention`,禁止再自动 resume;看 evidence 决定主线程接管、修工具或重派。最终报告强制JSON,structured_report仅验证格式;invalid_report拒land,resume让模型提交合法JSON,命令和acceptance另外核对。
82
+ check_workers可对已死的第1轮lost/no_work/invalid_report自动resume一次,recoveries记动作;invalid_report只让它重发裸JSON、不重做活,审批/认证/权限/quota不盲重试。连续两轮同 fingerprint 的无输出/无命令会变 `two_stall` + `needs_attention`,禁止再自动 resume;看 evidence 决定主线程接管、修工具或重派。最终报告强制JSON,但报告只是摘要:常见安全修复包括把单个字符串归一成 string[]、补上唯一缺失的 `]`/`}`;invalid_report 保留 `completed` 生命周期和 attention,不否定同 run 的 acceptance/diff。先自动重发一次,仍失败可审过 diff 后显式 land。
74
83
 
75
84
  未提交材料用context:[{path:绝对路径,sha256:可选}];首次记哈希,resume材料变了要显式换context。context/contracts总6000字、最多20份文件,每份≤5 MB;handoff1800字/16行可裁,完整约束和refs另传。输入路径不等于写授权。
76
85
 
@@ -98,7 +107,7 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
98
107
  1. `get_worker_result`:它说自己做了什么。默认截到 6000 字节,`truncated: true` 就按 `next_step` 带 `maxChars` 读全。`verification` 是它真跑过的命令和退出码:说"测过了"但 `commands_run: 0`、说"没建成"但那条命令退出码是 0、`last_command_failed: true` 却说完成、说"环境问题"但 `failed[].output_tail` 里是代码报错,都打回(走第 4 步),别替它圆。`base_behind.behind > 0` 说明派单后主线往前走了,改之前先 rebase(第 4 步);`contains_base: false` 时 `behind` 是 `null` 并带 `note`,那是派单目录换了线,不是落后。
99
108
  2. `get_worker_diff`:它实际做了什么。默认只回完整文件/hunk 索引;再传 `file` + `hunk` 或 `cursor` 分页读 patch,避免 500 行测试文件一次灌满上下文。显式传 `maxChars` 且不传 `file` 才走旧的整份 bounded diff。它说过了不算,diff 对得上才算。
100
109
  3. 对不上、看不懂为什么:`ask_codex_worker` 带 `question` 问它。fork 出一个只读旁路,worker 自己的线程不动;fork 没网络没 MCP 工具,问"改了什么、为什么、在哪",别问要联网才能答的事。超时回 `running`,只带 `task_id` 再调拿答案。worker 被 resume 过后下一问自动换新 fork,`fresh: true` 强制换,问完 `end: true` 删。
101
- 4. 要它改:`resume_codex_worker`,写清问题在哪,让它改完 `git commit --amend --no-edit` 并进原来那个提交。旁路只读,改东西永远走 resume。主线往前走过(`base_behind.behind > 0`)就带 `rebaseOnto: "HEAD"`(在派单目录里解析):未提交的改动先 stash,跳过已合入的补丁,只把新增提交重放到新头,stash 放回,`base_commit` 跟着动。冲突(`rebase_conflict` / `stash_conflict`)会原样退回、不起 worker、`files` 列冲突文件;这时让它先 `land_codex_worker` 带 `commitMessage` 提交成一笔再 rebase,或者重派一路 `baseRef` 填新头。
110
+ 4. 要它改:`resume_codex_worker`,写清问题在哪;不要要求 `workspace-write` worker 自己 commit 或 amend。旁路只读,改东西永远走 resume。主线往前走过(`base_behind.behind > 0`)就带 `rebaseOnto: "HEAD"`(在派单目录里解析):未提交的改动先 stash,跳过已合入的补丁,只把新增提交重放到新头,stash 放回,`base_commit` 跟着动。冲突(`rebase_conflict` / `stash_conflict`)会原样退回、不起 worker、`files` 列冲突文件;这时先 `land_codex_worker` 带 `commitMessage` 让 supervisor 提交成一笔再 rebase,或者重派一路 `baseRef` 填新头。
102
111
  5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录当前分支。目标脏了、分支不对、冲突都拒绝并原样退回。worker 没提交(默认沙箱提交不了)就带 `commitMessage`,supervisor 在它分支上替它提交一笔再落。验收 `failed` 它会拒,修完再落;`ignoreAcceptance` 只在用户说了"就这样落"时用。
103
112
 
104
113
  一批活全部到终态后:`get_orchestration_overview` 确认没有 `needs_attention`、`acceptance_failed` 为空,再逐路走上面几步。合不合、怎么合由主线程定。
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
3
+ import { getTask } from "./task-store.js";
4
+
5
+ const taskId = process.env.CODEX_SUPERVISOR_TASK_ID;
6
+ if (!taskId) {
7
+ console.error("CODEX_SUPERVISOR_TASK_ID is required");
8
+ process.exit(2);
9
+ }
10
+
11
+ const task = await getTask(taskId);
12
+ if (!task) {
13
+ console.error(`unknown supervisor task: ${taskId}`);
14
+ process.exit(2);
15
+ }
16
+ if (!Array.isArray(task.acceptance) || task.acceptance.length === 0) {
17
+ console.error(`task ${taskId} has no acceptance commands`);
18
+ process.exit(2);
19
+ }
20
+
21
+ const run = Number(process.env.CODEX_SUPERVISOR_RUN);
22
+ const result = await runAcceptance(task.acceptance, {
23
+ cwd: task.worktree_path || task.cwd,
24
+ env: process.env,
25
+ timeoutMs: task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
26
+ run: Number.isInteger(run) && run > 0 ? run : task.run_count,
27
+ taskId,
28
+ baseCommit: process.env.CODEX_SUPERVISOR_BASE_COMMIT || task.base_commit || null
29
+ });
30
+ process.stdout.write(`${JSON.stringify(result)}\n`);
31
+ process.exit(result.passed === true ? 0 : 1);
@@ -190,6 +190,17 @@ function normalizeWorkspaceSetup(value, projectRoot) {
190
190
  return links.length || submodules || commands.length ? { links, submodules, commands } : null;
191
191
  }
192
192
 
193
+ const JS_DEPENDENCY_COMMAND = /(?:^|[\s"'/])(?:npm|pnpm|yarn|npx|vitest|jest|vue-tsc|tsc|eslint|oxlint|nuxi)(?:\s|$)/;
194
+
195
+ function requireDependencySetup({ kind, projectRoot, setup, commands }) {
196
+ if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
197
+ const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
198
+ if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
199
+ 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)");
200
+ error.code = "workspace_setup_required";
201
+ throw error;
202
+ }
203
+
193
204
  async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
194
205
  if (!setup) return;
195
206
  for (const link of setup.links) {
@@ -377,10 +388,12 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
377
388
  // This CLI writes only data/stages/<this task>.json. It is part of the
378
389
  // runtime contract, not an ad-hoc command the model must declare. The
379
390
  // task id comes from the injected environment; stage.js has no override.
380
- 'node "$CODEX_SUPERVISOR_STAGE_CLI"*'
391
+ 'node "$CODEX_SUPERVISOR_STAGE_CLI"*',
392
+ 'node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"*'
381
393
  ] };
382
394
  const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
383
395
  const stageCli = fileURLToPath(new URL("./stage.js", import.meta.url));
396
+ const acceptanceCli = fileURLToPath(new URL("./acceptance-cli.js", import.meta.url));
384
397
  const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
385
398
  const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
386
399
  const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
@@ -407,6 +420,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
407
420
  env: withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
408
421
  CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
409
422
  CODEX_SUPERVISOR_STAGE_CLI: stageCli,
423
+ CODEX_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
410
424
  CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) }),
411
425
  windowsHide: true,
412
426
  ...spawnOptions
@@ -648,9 +662,12 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
648
662
  if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
649
663
  }
650
664
  if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
651
- next.status = "failed";
665
+ // The report is a summary, not the business result. Keep the completed
666
+ // lifecycle and let acceptance plus the reviewed diff decide whether it
667
+ // can land; a report-only recovery can still repair the summary.
652
668
  next.attention_reason = "invalid_report";
653
669
  next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
670
+ next.current_action = "Work completed, but the final report is invalid; acceptance and diff remain authoritative";
654
671
  }
655
672
 
656
673
  // Acceptance runs after the worker is gone, in two writes. The first
@@ -977,6 +994,8 @@ export async function createCodexWorker({
977
994
  throw error;
978
995
  }
979
996
  const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
997
+ requireDependencySetup({ kind: workspace.kind, projectRoot, setup: normalizedWorkspaceSetup,
998
+ commands: [...(combinedAcceptance ?? []), ...(preflight?.probeCommands ?? [])] });
980
999
 
981
1000
  const worktree = workspace.kind === "git_worktree"
982
1001
  ? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
package/src/mcp-server.js CHANGED
@@ -773,7 +773,7 @@ server.registerTool(
773
773
  {
774
774
  title: "Create Codex worker",
775
775
  description:
776
- "Launch a Codex CLI worker with codex exec --json and track its events. workspaceKind controls where it runs: Git work writes only in an isolated git_worktree; read_only_in_place cannot write or use network; scratch writes only under SUPERVISOR_HOME and never lands; in_place_write is only for an explicitly authorized non-Git directory with ownedPaths and acceptance. A non-Git worker may never write the user directory by default. ownedPaths reserves files a landable worker may write; reading is never exclusive. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them after Codex exits. The worker's sandbox may write its execution directory, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
776
+ "Launch a Codex CLI worker with codex exec --json and track its events. workspaceKind controls where it runs: Git work writes only in an isolated git_worktree; read_only_in_place cannot write or use network; scratch writes only under SUPERVISOR_HOME and never lands; in_place_write is only for an explicitly authorized non-Git directory with ownedPaths and acceptance. A non-Git worker may never write the user directory by default. ownedPaths reserves files a landable worker may write; reading is never exclusive. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them after Codex exits, and workers run the same contract with codex-supervisor-accept. In a Git package project, acceptance using local JavaScript tooling requires workspaceSetup so node_modules and generated prepare files exist before dispatch. The worker's sandbox may write its execution directory, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
777
777
  inputSchema: {
778
778
  title: z.string().optional(),
779
779
  task: z.string().min(1),
@@ -1842,7 +1842,7 @@ server.registerTool(
1842
1842
  {
1843
1843
  title: "Land a worker's commits",
1844
1844
  description:
1845
- "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
1845
+ "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes. A malformed report summary is attention, not a separate landing veto when the same run's acceptance passed and the reviewed diff is sound. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
1846
1846
  inputSchema: {
1847
1847
  task_id: z.string().min(1),
1848
1848
  onto: z.string().min(1).optional(),
@@ -1858,7 +1858,6 @@ server.registerTool(
1858
1858
  return textResult({ error: "workspace_kind_not_landable", task_id, workspace_kind: task.workspace_kind, reason: `${task.workspace_kind} does not create a Git worktree and cannot be landed` });
1859
1859
  }
1860
1860
  const session = task.session_id ? await getSession(task.session_id) : null;
1861
- if (task.attention_reason === "invalid_report") return textResult({ error: "invalid_report", task_id, reason: task.error });
1862
1861
  if (!isSettled(task)) return textResult({ error: "worker_active", task_id, reason: "wait for this run and acceptance to settle before landing" });
1863
1862
  if (session?.approval_state === "waiting_user") return textResult({ error: "session_waiting_user", task_id, reason: "session requires user approval before landing" });
1864
1863
  if (session && task.session_policy_revision !== session.policy_revision) return textResult({ error: "session_policy_stale", task_id, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" });
package/src/prompt.js CHANGED
@@ -93,13 +93,15 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
93
93
  export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
94
94
  const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
95
95
  if (commands.length === 0) return "";
96
+ const runner = 'Run node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI" to execute this exact contract through the supervisor\'s non-interactive Bash with errexit and pipefail. Do not retype the commands in zsh; the interactive shell is not the acceptance shell.';
96
97
  if (resume) {
97
- return `Acceptance is unchanged; run it before you report: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`;
98
+ return ["Acceptance is unchanged.", runner, `Commands: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`].join("\n");
98
99
  }
99
100
  return [
100
101
  "Acceptance: when you exit, the supervisor runs these commands in this directory and each must exit 0:",
101
102
  ...commands.map((command) => `- ${typeof command === "string" ? command : JSON.stringify(command)}`),
102
- "Run them yourself before you report and put their exit codes under Verification. Do not edit what they test to make them pass; if a check is wrong, say why under Not done / risks."
103
+ runner,
104
+ "Run that contract before you report and put its exit code and key evidence under Verification. Do not edit what it tests to make it pass; if a check is wrong, say why under Not done / risks."
103
105
  ].join("\n");
104
106
  }
105
107
 
package/src/task-store.js CHANGED
@@ -654,6 +654,21 @@ async function reconcileInterruptedAcceptance() {
654
654
  && !isPidAlive(task.acceptance_results.supervisor_pid));
655
655
  for (const task of interrupted) {
656
656
  const now = new Date().toISOString();
657
+ const durable = (await readTaskEvents(task.id, 1, ["supervisor.acceptance"]))[0] ?? null;
658
+ if (durable && durable.run === task.run_count) {
659
+ const reportInvalid = task.attention_reason === "invalid_report";
660
+ await writeTask({
661
+ ...task,
662
+ status: reportInvalid ? "completed" : task.status,
663
+ exit_code: task.exit_code ?? (reportInvalid ? 0 : null),
664
+ acceptance_results: durable,
665
+ current_action: durable.passed === true
666
+ ? "Acceptance passed (recovered from the durable event)"
667
+ : `Acceptance ${durable.status} (recovered from the durable event)`,
668
+ updated_at: now
669
+ });
670
+ continue;
671
+ }
657
672
  await writeTask({
658
673
  ...task,
659
674
  acceptance_results: { ...task.acceptance_results, status: "interrupted", passed: null, finished_at: now },
@@ -19,19 +19,54 @@ function reportCandidates(text) {
19
19
  return candidates;
20
20
  }
21
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
+
22
60
  export function parseWorkerReport(text) {
23
61
  if (typeof text !== "string" || !text.trim()) return { format: "json_schema", valid: false, error: "worker wrote no final report" };
24
62
  let parseError = null;
25
63
  for (const { source, text: candidate } of reportCandidates(text)) {
26
- let value;
27
- try { value = JSON.parse(candidate); }
28
- catch (error) { parseError = parseError ?? error; continue; }
29
- const valid = value && typeof value === "object" && !Array.isArray(value)
30
- && Object.keys(value).sort().join(",") === "not_done,result,verification"
31
- && typeof value.result === "string" && Array.isArray(value.verification) && Array.isArray(value.not_done)
32
- && [...value.verification, ...value.not_done].every((entry) => typeof entry === "string");
33
- if (!valid) return { format: "json_schema", valid: false, error: "report must contain result:string, verification:string[], not_done:string[] only" };
34
- return { format: "json_schema", valid: true, report: value, ...(source === "bare" ? {} : { repaired: source }) };
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("+") } : {}) };
35
70
  }
36
71
  return { format: "json_schema", valid: false, error: parseError?.message ?? "report is not JSON" };
37
72
  }