codex-supervisor-mcp 0.11.1 → 0.12.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.md CHANGED
@@ -29,6 +29,7 @@
29
29
  | 进程重启后不知道谁还在跑 | `supervisor.sqlite` 一行一个 work,带 `thread_id` |
30
30
  | 换个会话接不上之前的 worker | `resume_codex_worker` 走 `codex exec resume <thread_id>`,接的是同一个 Codex 会话 |
31
31
  | 分不清「跑失败」和「进程没了」 | 状态机把 `failed` 和 `lost` 分开 |
32
+ | 分不清是谁报错 | status / overview / overview_delta 带 `failure.source` 和 `failure.code`,区分 provider、supervisor_process、workspace_setup、model_output、acceptance、worker_process |
32
33
  | worker 说做完了其实没有 | 派单给 `acceptance` 验收命令,worker 退出后 supervisor 在它的 worktree 里跑,失败 `land` 拒绝 |
33
34
  | 看不见一批活现在到哪了 | `codex-supervisor-web` 开一个看板,按 session 看每路 worker 在干什么 |
34
35
  | 改动留在本地没上线 | 收活默认 `land_codex_worker` 合回主分支;主线程自己的改动必须 commit + push;部署前用远端 SHA 核对文件真的在线上 |
@@ -81,6 +82,14 @@ npx -p codex-supervisor-mcp codex-supervisor-web
81
82
 
82
83
  打开 `http://127.0.0.1:7877`。状态目录按 `SUPERVISOR_HOME`、最近的 `.mcp.json`、`~/.codex-supervisor` 的顺序找;端口用 `SUPERVISOR_WEB_PORT` 改。看板只看,不派单不取消。
83
84
 
85
+ 长门禁脚本可主动上报阶段:
86
+
87
+ ```bash
88
+ node "$CODEX_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "integration queue"
89
+ ```
90
+
91
+ `current_stage` 会出现在 status / overview / wait,终态保留为 `last_stage`;不要放 token、密码或 DSN。
92
+
84
93
  ## 我自己怎么用
85
94
 
86
95
  能连 MCP 的都能当主线程,这里只是我的用法。我开两个 Claude Code 会话,一个只管文档,一个只管派活:一个会话又写详设又盯 worker,上下文两小时就满。
@@ -153,15 +162,15 @@ land_codex_worker 核过了,落进集成分支
153
162
  | `check_workers` | 无参 | 交付新终态、验收失败和需处理goal;新格式第1轮lost/no_work自动恢复一次,未变返回quiet;用宿主定时唤醒调用,每个主线程设独立CODEX_SUPERVISOR_OBSERVER_ID可在重启后接回 |
154
163
  | `overview_delta` | `cursor` | 主线程默认轮询入口:只返回 active / needs_attention / ready_to_land / ready_to_clean、cursor 后变化、短版 attention_reason / next_action 和 next_cursor;不返回全量历史、prompt、diff、event 或 worker capsule |
155
164
  | `check_acceptance` | `cwd`, `acceptance`, `baseRef`, `timeoutMs` | 派单前实际运行给定验收命令,不建 worker,不证明 worker 完成;数量 grep 会提示不能证明失败名单和必跑执行 |
156
- | `preflight_codex_worker` | `cwd`, `workspaceKind`, `inPlaceAuthorization`, `ownedPaths`, `probeCommands`, `baseRef`, `sandbox`, `allowedCommands`, `context`, `contracts`, `networkAccess`, `writableRoots` | 用与目标 worker 相同的 workspace/base/sandbox/guard 起短 probe worker;它必须实际跑完每条 probe command。等终态后读 `get_worker_preflight` |
157
- | `get_worker_preflight` | `task_id` | 返回 probe 的实际 command evidence、运行环境 contract hash 和 `running/passed/failed`;只有 `passed` 才能复用 |
158
- | `create_codex_worker` | `task`, `cwd`, `workspaceKind`, `inPlaceAuthorization`, **`ownedPaths`**, **`goal`**, `preflight_id`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Git 默认隔离 worktree;非 Git 写入必须选 `scratch` 或有授权、paths、acceptance 的 `in_place_write`。`preflight_id` 给了就必须是通过的同环境 probe |
165
+ | `preflight_codex_worker` | `cwd`, `workspaceKind`, `inPlaceAuthorization`, `workspaceSetup`, `ownedPaths`, `probeCommands`, `baseRef`, `sandbox`, `allowedCommands`, `context`, `contracts`, `networkAccess`, `writableRoots` | 用与目标 worker 相同的 workspace/base/sandbox/guard 起短 probe worker;它必须实际跑完每条 probe command。probe 自动获得本次 guard-only 允许,但不进入目标 worker contract;联网和凭据目录仍须显式授权 |
166
+ | `get_worker_preflight` | `task_id` | 返回 probe 的实际 command evidence、运行环境 contract hash、worker outcome 和 `running/passed/failed`;probe 全部执行通过时,报告 JSON 错误或已 exit 0 的 close-handler 缺失只留诊断,不误判环境失败 |
167
+ | `create_codex_worker` | `task`, `cwd`, `workspaceKind`, `inPlaceAuthorization`, `workspaceSetup`, **`ownedPaths`**, **`goal`**, `preflight_id`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Git 默认隔离 worktree;非 Git 写入必须选 `scratch` 或有授权、paths、acceptance 的 `in_place_write`。`workspaceSetup` 在起 worker 前链接依赖、初始化子模块、跑 prepare;`preflight_id` 给了就必须是通过的同环境 probe |
159
168
  | `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, 其余同上 | 开一个新会话,把老 worker 的 prompt、状态、近期事件拼进去 |
160
169
  | `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | 接同一个 Codex 会话继续跑,`thread_id` 不变。`rebaseOnto` 先把 worktree 挪到主线新头(stash、跳过已合入补丁、重放新增提交、放回),冲突原样退回不起 worker |
161
- | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态。默认 60 秒,到点带快照返回,worker 照跑;`compact` 每路只回一行,带 `idle_seconds` / `command_running`,分得清长命令和卡住 |
170
+ | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态。默认 60 秒且不推周期 heartbeat;显式 `emitProgress: true` 才每 30 秒通知。`termination_reason` 区分 settled / budget_exhausted / client_cancelled;`compact` 每路一行 |
162
171
  | `get_orchestration_overview` | `status`, `limit` | 全部 worker 的状态表,封顶 7000 字节。带 `version` 和 `update` |
163
172
  | `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | worker 自己的汇报,默认截 6000 字节、`truncated` 提示读全。`acceptance` 是 supervisor 替你跑的验收过没过,`verification` 是它自己跑过的命令和退出码,`base_behind` 是主线走了多远(`contains_base: false` 时 `behind` 为 `null`,那是换了线) |
164
- | `get_worker_diff` | `task_id`, `maxChars`, `paths` | worker 实际改了什么:从 worktree 起点到工作区的 patch,提交没提交都算。`maxChars` 管总量,超了的文件只列名 |
173
+ | `get_worker_diff` | `task_id`, `file`, `hunk`, `pageSize`, `cursor`, `maxChars`, `paths` | worker 实际改了什么。默认完整文件索引与 hunk 数;按 `file` + `hunk`/`cursor` 分页读 patch。显式 `maxChars` 且不传 `file` 保留旧整份限流模式 |
165
174
  | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | 旁路问 worker 一句。线程 fork 成只读侧会话,没网络、没 MCP 工具,worker 本身不动。worker 被 resume 过会自动换新 fork,`fresh` 强制换,`end` 删 |
166
175
  | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝。`commitMessage` 先替它把未提交的改动提交成一笔,`ignoreAcceptance` 放行 |
167
176
  | `verify_delivery_push` | `task_id`, `remote`, `branch` | fetch 指定 remote branch 并证明 `landed_head` 已可达;只读验证,不会 push 或部署。通过后记录 `push_verified` 并生成 cleanup plan |
@@ -202,7 +211,7 @@ worker 的最终 JSON 报告会先记录为该 run 的 `candidate` fact,不能
202
211
 
203
212
  交付状态分开:acceptance 通过只是 `verified`,`land_codex_worker` 只是 `landed`,仍不代表远端有这笔提交。需要显式 `verify_delivery_push` fetch 并校验 `landed_head` 已在目标 remote branch 上,才是 `push_verified`;它会自动生成 cleanup plan,SAFE 项进入 `cleanup_eligible`,但永远不会自己删除。该工具绝不代替用户执行 push 或部署。
204
213
 
205
- 验收命令的环境包含 `CODEX_SUPERVISOR_TASK_ID`、`CODEX_SUPERVISOR_BASE_COMMIT` 和 `CODEX_SUPERVISOR_RUN`;分别是当前任务、当前运行基线和运行次数,rebase/resume 后会更新。
214
+ worker 进程和 supervisor 验收子进程都包含当前 `CODEX_SUPERVISOR_TASK_ID`、`CODEX_SUPERVISOR_BASE_COMMIT` 和 `CODEX_SUPERVISOR_RUN`;分别是当前任务、运行基线和次数,rebase/resume 后两边一起更新。
206
215
 
207
216
  结构化验收项用 `{command, reportPath, baseline}`。baseline 包含 `identity.base_commit`、`failures`(test_id/kind/signature)和 `required`;报告包含 complete、identity、failures、executed、skipped,以及本次 `CODEX_SUPERVISOR_CHECK_ID`。必跑用例缺失/跳过、旧报告、失败名单变化都拒绝通过,原始退出码保留。reportPath 必须在工作目录内;测试报告可能写文件,要用忽略的临时目录,避免把报告合入。
208
217
 
@@ -285,6 +294,7 @@ ownedPaths预留和任务入库在同一事务内,跨MCP并发派单/恢复不
285
294
  | `GIT_BIN` | `git` | Git 路径 |
286
295
  | `SUPERVISOR_WEB_PORT` / `SUPERVISOR_WEB_HOST` | `7877` / `127.0.0.1` | 看板监听地址 |
287
296
  | `CODEX_SUPERVISOR_NO_UPDATE_CHECK` | 未设 | `1` 关闭更新检查 |
297
+ | `CODEX_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD` | `300000` | native goal 累计 token 达到该值时 status/overview 标记 `handoff_recommended`;设 `0` 关闭 |
288
298
  | `CODEX_SUPERVISOR_REGISTRY` | `https://registry.npmjs.org` | 更新检查和自动更新用的 registry |
289
299
  | `CODEX_SUPERVISOR_UPDATE_TIMEOUT_MS` | `4000` | 等 registry 的上限 |
290
300
  | `CODEX_SUPERVISOR_NO_AUTO_UPDATE` | 未设 | `1` 关闭后台自动更新(只提醒) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.11.1",
3
+ "version": "0.12.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.",
@@ -26,7 +26,8 @@
26
26
  "bin": {
27
27
  "codex-supervisor-mcp": "src/mcp-server.js",
28
28
  "codex-supervisor-setup": "src/setup.js",
29
- "codex-supervisor-web": "src/web-server.js"
29
+ "codex-supervisor-web": "src/web-server.js",
30
+ "codex-supervisor-stage": "src/stage.js"
30
31
  },
31
32
  "files": [
32
33
  "src/mcp-server.js",
@@ -52,6 +53,11 @@
52
53
  "src/external-output.js",
53
54
  "src/truncate.js",
54
55
  "src/status.js",
56
+ "src/failure-class.js",
57
+ "src/worker-env.js",
58
+ "src/thread-health.js",
59
+ "src/stage-store.js",
60
+ "src/stage.js",
55
61
  "src/paths.js",
56
62
  "src/prompt.js",
57
63
  "src/cleanup.js",
@@ -82,6 +88,7 @@
82
88
  "cleanup": "node ./src/cleanup.js",
83
89
  "test": "node ./src/bin-resolver-test.js && node ./src/truncate-test.js && node ./src/status-test.js && node ./src/migration-test.js && node ./src/setup-test.js && node ./src/setup-windows-test.js && node ./src/regression-test.js && node --test test/edge/*.test.js",
84
90
  "test:real": "node ./src/real-codex-test.js",
91
+ "test:real:multi": "node ./src/multi-project-real-test.js",
85
92
  "smoke": "node ./src/smoke-test.js",
86
93
  "smoke:followup": "node ./src/followup-smoke-test.js",
87
94
  "smoke:mcp": "node ./src/mcp-smoke-test.js",
@@ -27,6 +27,7 @@ worker 默认不是调度员:启动时会禁用它继承到的 `codex-supervis
27
27
  | `cwd` | Git 项目根,或非 Git 输入目录;实际执行目录由 `workspaceKind` 决定,不能默认写原目录 |
28
28
  | `workspaceKind` | Git 代码默认 `git_worktree`;非 Git 只读用 `read_only_in_place`,联网研究用 `scratch`,要改用户非 Git 目录只能显式 `in_place_write` |
29
29
  | `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 可写缓存根 |
30
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` |
31
32
  | `forbid` / `allowedCommands` | 原样声明红线与验证命令;守卫拒绝未声明Shell程序,编辑用apply_patch |
32
33
  | `writableRoots` | 只有需要凭据目录时才传(绝对路径、已存在、自动解析软链、只对 workspace-write 生效):ssh/远程测试 → `["~/.ssh"]`;kubectl → `["~/.kube"]`;推私有镜像 → `["~/.docker"]`;aws cli → `["~/.aws"]`;签名提交 → `["~/.gnupg"]`。缓存目录不用写,已经自动加 |
@@ -36,17 +37,21 @@ worker 默认不是调度员:启动时会禁用它继承到的 `codex-supervis
36
37
  | `dependsOn` | 有先后依赖填上游的 `task_id`,它是硬门禁:上游必须同 `project_root`、成功结算、配置了 acceptance 就已通过、已 `land_codex_worker`,并且本路实际 `baseRef` 包含上游 `landed_head`。没满足先集成/修验收,不会启动下游 |
37
38
  | `baseRef` | worktree 从哪个提交切,默认 `HEAD`。第 N+1 步要建立在第 N 步上,填 `codex/<第 N 步 task_id>` |
38
39
  | `preflight_id` | 写 worker 必填。先跑 `preflight_codex_worker`,它实际在目标 sandbox/guard 里执行 `probeCommands`;`get_worker_preflight.status` 必须是 `passed`。base、ownedPaths、命令、context、contracts、network、可写根有变化就重跑 |
40
+
41
+ `probeCommands` 会自动加入这次 probe worker 的 guard-only allowlist,不会进入目标 worker 的 runtime contract;目标 worker 仍只声明自己真正需要的 `allowedCommands`。ssh 等联网探针仍要显式 `networkAccess: true`,需要写 `known_hosts` 时同时声明 `writableRoots: ["~/.ssh"]`。
42
+
43
+ 预检结论以 probe command evidence 为准,不把模型最终 JSON 当环境事实:所有探针都实际执行且通过、没有失败命令时,最终报告格式错误不会让预检失败;进程 close handler 缺失但退出码已为 0 的 probe-only worker 也只记诊断,不重跑。命令未执行、非零、取消或无法解释的 lost 仍失败。
39
44
  | `sandbox` | 默认 `workspace-write`,worker 提交不了(Codex 把 `.git` 设成只读)。要它自己提交就 `danger-full-access`,否则收活时让 supervisor 替它提交 |
40
45
 
41
46
  验收用 Bash 的 `errexit` + `pipefail`:`npm test | tail` 不能吞失败;文件存在只可做附加门禁,不能单独证明业务完成。预期失败用 `if` / `||` 显式判。超时、`no tests to run`、`[no test files]` 都失败,别只看退出码 0。Windows 要有 Git for Windows Bash;缺失先修工具,别换回 cmd。
42
47
 
43
- 验收取当前身份用 `CODEX_SUPERVISOR_TASK_ID` / `CODEX_SUPERVISOR_BASE_COMMIT` / `CODEX_SUPERVISOR_RUN`;不要在命令里写死旧 base,rebase/resume 后这些值会更新。
48
+ 验收取当前身份用 `CODEX_SUPERVISOR_TASK_ID` / `CODEX_SUPERVISOR_BASE_COMMIT` / `CODEX_SUPERVISOR_RUN`;worker 进程和 supervisor 验收子进程都会注入同一组当前值,rebase/resume 后一起更新。不要在命令里写死旧 base。
44
49
 
45
50
  `check_acceptance` 只是在宿主权限跑验收命令,预检通过不代表 worker sandbox/guard/PATH/cache/network 可用;写 worker 的实际环境预检必须走上面的 `preflight_codex_worker`。已知失败必须按结构化 baseline 的用例名/类型/签名比,必跑项写 required;报告必须标本次 `CODEX_SUPERVISOR_CHECK_ID`,给 complete/identity/failures/executed/skipped,缺失、跳过和旧报告都不算过。reportPath 用工作区内忽略的临时目录,验收报告别混进业务提交。
46
51
 
47
52
  同批公共门禁用 `describe_session.default_acceptance`,自动追加本路验收;更新目标/门禁传 `expected_revision`,避免旧窗口覆盖。需要用户拍板时设 `approval_state: waiting_user`,不得自动resume;获批改approved并同步宿主goal。回执host_goal_sync给当前策略的/goal命令;宿主已有原生goal时,用/goal替换条件,支持ProposeGoal时提议同一condition并走宿主批准。这个条件要求读取最新session revision,批准旧失败或waiting_user后不再追旧目标;工具不偷偷改/禁用Stop hook。
48
53
 
49
- wait默认60秒和compact,带includeEvents则详细返回;客户端带progress token时每30秒收到通知。已实测Claude2.1.299在35秒idle下收到三次progress,65秒wait正常返回;通知不能唤醒关闭的宿主。/loop实测可定时调用,主窗口须保持运行。
54
+ wait默认60秒和compact,带includeEvents则详细返回;默认不推周期 heartbeat,只有显式 `emitProgress: true` 才在客户端带 progress token 时每30秒通知。需要一条长 wait 被宿主转后台后只收终态,就保持默认;需要桌面进度才 opt-in。返回的 `termination_reason` 区分 `settled` / `budget_exhausted` / `client_cancelled`,通知不能唤醒关闭的宿主。/loop实测可定时调用,主窗口须保持运行。
50
55
 
51
56
  派单写forbid红线、allowedCommands验证命令;runtime守卫按次注入并随resume/followup继承。apply_patch核对ownedPaths;安全只读检查(rg/cat/sed无-i/git只读/jq无-i/find无-exec或-delete)默认允许且不占其他 worker 的写路径,写入/执行/有副作用的 Shell 命令必须显式声明;声明脚本可以有副作用,须先核对,不能当万能文件沙箱。no_work表示本轮write无输出变化且没跑命令;先看run_evidence,不拿上轮提交/命令当本轮完成。
52
57
 
@@ -75,6 +80,8 @@ check_workers可对已死的第1轮lost/no_work/invalid_report自动resume一次
75
80
 
76
81
  沙箱只放工作区、临时目录、OS cache目录(macOS ~/Library/Caches、Linux ~/.cache、Windows %LOCALAPPDATA%)以及home下已存在的工具链缓存目录(.cargo/.npm/.yarn/.pnpm-store/.bun/.m2/.gradle/.nuget/.ivy2/.bundle/.composer/.pub-cache/.mix/.hex/.stack/.cpanm/.deno/.conda、go/pkg)。Go build cache(平台默认 `go-build` 或显式 `GOCACHE`)会单独解析 realpath 并放行真实目录,所以它指向外置盘 symlink 时 worker 也能用;其他语言也不需要逐个加环境变量。**凭据目录一律不自动放开**(.ssh/.gnupg/.config/.aws/.docker/.kube/.netrc/.git-credentials/~/Library/Keychains):ssh 连服务器要写 known_hosts、kubectl、推私有镜像、签名提交这类需求,派单时按参数表显式传 writableRoots,只在这一路生效、随 resume/followup 继承。SUPERVISOR_NO_AUTO_CACHE_ROOTS=1 关掉全部自动缓存根,显式声明的照常生效。Codex 拒绝含软链的可写根,所以自动 cache 与 `writableRoots` 都先按 realpath 解析;解析不到无软链路径的根直接不传。其他 cache 在别处(如 ~/.m2、~/.gradle、vendor 镜像)就传 `writableRoots:[绝对路径]`(已存在目录、最多20个、只对workspace-write生效、随resume/followup继承);能只读复用就不用传。
77
82
 
83
+ 前端多 worktree 的标准派单不要让人手补目录:`workspaceSetup: { links: [{ path: "node_modules", source: "node_modules" }], commands: ["npx nuxi prepare"] }`;后端有 proto 等子模块时用 `workspaceSetup: { submodules: true }`。同一个 setup 必须同时传给 preflight 和目标 worker,contract 才会匹配。
84
+
78
85
  Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CLI。goal查询看native_goal_read,missing与locked/read_error分开;budget/usage限制也要处理。cleanup保留ignored成果、共享证据及未解决attention。
79
86
 
80
87
  等待的几条规矩:
@@ -89,7 +96,7 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
89
96
 
90
97
  0. 先看 `acceptance`(compact wait、overview 的 `acceptance_failed`、`get_worker_result.acceptance` 都有)。`failed`:不用读它的汇报,直接走第 4 步,把 `checks[].output_tail` 原样贴进 resume 的 prompt。`passed` 但它说没做成、goal 是 `blocked`:信命令不信它,去看 diff。命令本身写错了,resume 带新的 `acceptance` 换掉,别 `ignoreAcceptance`。`null` 是没配,退出码只说明没崩,对不对自己看。
91
98
  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`,那是派单目录换了线,不是落后。
92
- 2. `get_worker_diff`:它实际做了什么。起点到工作区的全部改动,提交没提交都算;`maxChars` 管总量,`paths` 缩范围。它说过了不算,diff 对得上才算。
99
+ 2. `get_worker_diff`:它实际做了什么。默认只回完整文件/hunk 索引;再传 `file` + `hunk` 或 `cursor` 分页读 patch,避免 500 行测试文件一次灌满上下文。显式传 `maxChars` 且不传 `file` 才走旧的整份 bounded diff。它说过了不算,diff 对得上才算。
93
100
  3. 对不上、看不懂为什么:`ask_codex_worker` 带 `question` 问它。fork 出一个只读旁路,worker 自己的线程不动;fork 没网络没 MCP 工具,问"改了什么、为什么、在哪",别问要联网才能答的事。超时回 `running`,只带 `task_id` 再调拿答案。worker 被 resume 过后下一问自动换新 fork,`fresh: true` 强制换,问完 `end: true` 删。
94
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` 填新头。
95
102
  5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录当前分支。目标脏了、分支不对、冲突都拒绝并原样退回。worker 没提交(默认沙箱提交不了)就带 `commitMessage`,supervisor 在它分支上替它提交一笔再落。验收 `failed` 它会拒,修完再落;`ignoreAcceptance` 只在用户说了"就这样落"时用。
@@ -123,12 +130,14 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
123
130
  | 主线程日常增量 | `overview_delta`,保存 `next_cursor`;只看计数、变化 task 摘要、短版阻塞原因和下一步 |
124
131
  | 全部 worker 的状态 | `get_orchestration_overview`,只在需要全量状态时用 |
125
132
  | 一路的完整结论 | `get_worker_result` |
126
- | 一路改了什么 | `get_worker_diff`;只要文件名用 `get_worker_result` 带 `includeFiles: true` |
133
+ | 一路改了什么 | `get_worker_diff` 默认拿文件/hunk 索引;选一个 `file` 后用 `hunk` 或 `cursor` 分页。只要文件名用 `get_worker_result` 带 `includeFiles: true` |
127
134
  | 活着还是完了 | `get_worker_summary` |
128
135
  | 过程 | `get_codex_worker_events`,`kinds` 先滤、`limit` 限条数、`maxChars` 截长串,先看 `available_kinds` |
136
+ | 门禁内部阶段 | worker 脚本调用 `node "$CODEX_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "..."`;status/overview/wait 显示 `current_stage`,终态保留 `last_stage`。不要写 secret |
129
137
  | 一路的状态细节 | `get_codex_worker_status`,`current_action` 是它正在跑的命令 |
130
138
  | 验收过没过 | 每个读都带 `acceptance`;命令和每条的输出在 `get_worker_result.acceptance.checks` |
131
139
  | worker 吃了哪些上下文 | `get_context_snapshot_meta`,只看 fact IDs/token/排除项,不会回 capsule 正文 |
140
+ | 线程是否太长 | `thread_health`:`ok` / `getting_long` / `handoff_recommended`;达到阈值时用 `create_codex_followup_worker` 起新线程,原线程留作证据 |
132
141
  | 一条共享事实的来源 | `get_fact`,按 ID 精确读;不要把一批 facts 全拉进主线程 |
133
142
  | 找当前任务的已验证事实 | `search_worker_facts`,传 task_id/query/cursor;只回 scope 内 verified summary + coverage,绝不拉 raw history |
134
143
  | 找某路的证据索引 | `get_worker_evidence`,再按需 `get_artifact` 或 `get_codex_worker_events` |
@@ -139,6 +148,8 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
139
148
 
140
149
  worker 的 capsule 只在内部 create/resume 时生成:L0 身份会标 branch 与 acceptance 来源但不放 acceptance 命令正文、当前 work 的 verified facts、显式 `dependsOn` 的最小交付摘要、路径命中且 SHA 有效的 repo facts。repo fact 跨 checkout 必须 canonical `origin`、repo-relative watched path 与 SHA 同时命中;没有可识别 origin 就不共享。`session_id` peers、raw event、完整 diff/报告、candidate facts 一律不自动注入。base SHA 不再覆盖、watched path 有 Git diff、context 输入 content hash 或 in_place_write manifest 漂移时,旧 fact 自动 append-only `expired` 并排除,保留原始版本。主线程只能看 snapshot 元数据;要查事实用 `search_worker_facts` / `get_fact`,查证据用 `get_worker_evidence` / `get_artifact`,不能把自己变成 worker。
141
150
 
151
+ `thread_health` 依据 native goal 的累计 tokens;默认 30 万建议 handoff,可用 `CODEX_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD` 调整,设 0 关闭。它只提醒,不自动结束线程。
152
+
142
153
  worker 最终 JSON 只是 `candidate`:先留在本 run 做审计,绝不因为它自己说“完成”就变共享事实。supervisor acceptance 通过才会派生当前 work 的 `verified` outcome;验收失败/未配置、脏 diff、未 land/push 都不是 verified 交付证据。
143
154
 
144
155
  ## 断了怎么接
@@ -151,7 +162,9 @@ worker 最终 JSON 只是 `candidate`:先留在本 run 做审计,绝不因
151
162
  | worker `failed` | 看 `error` 和日志,查完再 resume 或重派 |
152
163
  | 没记到 `thread_id` 的老行 | `create_codex_followup_worker`,新线程靠文本重述 |
153
164
 
154
- `status` 是生命周期:`queued` / `running` / `completed` / `failed` / `cancelled` / `lost`。`phase` 只在跑着时有值:`starting` → `thinking` → `command` → `editing` → `reporting`。`completed` 配 `exit_code: null` 是中间态,`wait` 会等到退出码落了再返回。goal 的 `paused` / `blocked` 不是结束,是等人管,overview 会列进 `needs_attention`。
165
+ `status` 是生命周期:`queued` / `running` / `completed` / `failed` / `cancelled` / `lost`。`phase` 只在跑着时有值:`starting` → `thinking` → `command` → `editing` → `reporting`。`completed` 配 `exit_code: null` 是中间态,`wait` 会等到退出码落了再返回;验收已被中断且 worker/run-host 都已退出时,宽限 5 秒后自动转成可 `resume` 的 `lost`,不会永远卡在 completed。goal 的 `paused` / `blocked` 不是结束,是等人管,overview 会列进 `needs_attention`。
166
+
167
+ 终态优先看 `failure.source` / `failure.code`:`provider` 是模型代理或上游,`supervisor_process` 是 exit 未收口/启动/超时,`workspace_setup` 是依赖链接、子模块或 prepare,`model_output` 是最终报告格式,`acceptance` 是验收命令,`worker_process` 是 worker 进程非零退出,`worker_progress` 是 no_work/two_stall。不要把所有 failed/lost 都当业务代码失败。
155
168
 
156
169
  ## 看到 `update` 字段就转告用户
157
170
 
@@ -1,8 +1,8 @@
1
1
  import { createWriteStream, existsSync } from "node:fs";
2
- import { mkdir, rm, stat } from "node:fs/promises";
2
+ import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { execFileSync, spawn } from "node:child_process";
5
- import { join, resolve, sep, dirname, isAbsolute } from "node:path";
5
+ import { basename, join, resolve, relative, sep, dirname, isAbsolute } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import {
8
8
  appendTaskEvent,
@@ -26,6 +26,7 @@ import {
26
26
  } from "./task-store.js";
27
27
  import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
28
28
  import { worktreesDir } from "./paths.js";
29
+ import { clearStage } from "./stage-store.js";
29
30
  import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
30
31
  import { cacheRoots, resolveWritableRoot } from "./sandbox-roots.js";
31
32
  import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
@@ -41,6 +42,7 @@ import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, run
41
42
  import { supervisorMcpDisableArgs } from "./mcp-config.js";
42
43
  import { captureWorkspaceManifest, isGitCheckout, prepareWorkspace } from "./workspace-kind.js";
43
44
  import { codexRunner } from "./runner-adapter.js";
45
+ import { withWorkerToolPath } from "./worker-env.js";
44
46
 
45
47
  const processes = new Map();
46
48
  // taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
@@ -167,6 +169,73 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
167
169
  }
168
170
  }
169
171
 
172
+ function insidePath(parent, child) {
173
+ const rel = relative(parent, child);
174
+ return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
175
+ }
176
+
177
+ function normalizeWorkspaceSetup(value, projectRoot) {
178
+ if (value == null) return null;
179
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspaceSetup must be an object");
180
+ const links = (value.links ?? []).map((entry) => {
181
+ if (!entry || typeof entry.path !== "string" || !entry.path.trim()
182
+ || typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspaceSetup.links requires path and source");
183
+ const path = entry.path.trim();
184
+ if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspaceSetup link path must stay inside the worktree: ${path}`);
185
+ return { path, source: resolve(projectRoot, entry.source.trim()) };
186
+ });
187
+ const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
188
+ if (links.length > 20 || commands.length > 20) throw new Error("workspaceSetup accepts at most 20 links and 20 commands");
189
+ const submodules = value.submodules === true;
190
+ return links.length || submodules || commands.length ? { links, submodules, commands } : null;
191
+ }
192
+
193
+ async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
194
+ if (!setup) return;
195
+ for (const link of setup.links) {
196
+ if (!existsSync(link.source)) throw new Error(`workspaceSetup link source does not exist: ${link.source}`);
197
+ const destination = resolve(worktreePath, link.path);
198
+ if (!insidePath(worktreePath, destination)) throw new Error(`workspaceSetup link escapes the worktree: ${link.path}`);
199
+ await mkdir(dirname(destination), { recursive: true });
200
+ if (existsSync(destination)) {
201
+ const existing = await lstat(destination);
202
+ if (!existing.isSymbolicLink()) throw new Error(`workspaceSetup link destination already exists: ${link.path}`);
203
+ const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
204
+ if (actual !== expected) throw new Error(`workspaceSetup link destination points elsewhere: ${link.path}`);
205
+ continue;
206
+ }
207
+ const sourceInfo = await stat(link.source);
208
+ await symlink(link.source, destination, process.platform === "win32" ? "junction" : sourceInfo.isDirectory() ? "dir" : "file");
209
+ if (basename(link.path) === "node_modules" && sourceInfo.isDirectory()) {
210
+ for (const name of [".vite", ".vite-temp", ".cache"]) await mkdir(join(link.source, name), { recursive: true });
211
+ }
212
+ }
213
+ if (setup.submodules) {
214
+ await runCommand(defaultGitBin, ["-c", "protocol.file.allow=always", "-C", worktreePath, "submodule", "update", "--init", "--recursive"]);
215
+ }
216
+ if (setup.commands.length) {
217
+ const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
218
+ if (!result.passed) {
219
+ const failing = result.checks.find((check) => !check.passed);
220
+ throw new Error(`workspaceSetup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
221
+ }
222
+ }
223
+ }
224
+
225
+ function workspaceSetupWriteRoots(record) {
226
+ const roots = [];
227
+ for (const link of record.workspace_metadata?.setup?.links ?? []) {
228
+ const source = resolveWritableRoot(link.source);
229
+ if (!source.error) roots.push(source.path);
230
+ if (basename(link.path) !== "node_modules") continue;
231
+ for (const name of [".vite", ".vite-temp", ".cache"]) {
232
+ const candidate = resolveWritableRoot(join(link.source, name));
233
+ if (!candidate.error) roots.push(candidate.path);
234
+ }
235
+ }
236
+ return roots;
237
+ }
238
+
170
239
  function sleep(ms) {
171
240
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
172
241
  }
@@ -301,8 +370,16 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
301
370
  const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
302
371
  const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
303
372
  const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
304
- allowedCommands: [...(record.guard_policy?.allowedCommands ?? []), ...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command)] };
373
+ allowedCommands: [
374
+ ...(record.guard_policy?.allowedCommands ?? []),
375
+ ...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command),
376
+ // This CLI writes only data/stages/<this task>.json. It is part of the
377
+ // runtime contract, not an ad-hoc command the model must declare. The
378
+ // task id comes from the injected environment; stage.js has no override.
379
+ 'node "$CODEX_SUPERVISOR_STAGE_CLI"*'
380
+ ] };
305
381
  const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
382
+ const stageCli = fileURLToPath(new URL("./stage.js", import.meta.url));
306
383
  const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
307
384
  const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
308
385
  const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
@@ -311,16 +388,25 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
311
388
  // must not inherit this supervisor and create a second orchestration tree.
312
389
  configArgs.push(...supervisorMcpDisableArgs());
313
390
  configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
314
- const sandboxWritableRoots = [...new Set([...externalBefore.map((file) => dirname(file.path)), ...cacheRoots(), ...(record.guard_policy?.writableRoots ?? [])])];
391
+ const sandboxWritableRoots = [...new Set([
392
+ ...externalBefore.map((file) => dirname(file.path)),
393
+ ...cacheRoots(),
394
+ ...workspaceSetupWriteRoots(record),
395
+ ...(record.guard_policy?.writableRoots ?? [])
396
+ ])];
315
397
  if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
316
398
  // Insert before the prompt/session positional arguments for exec/resume.
317
399
  const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
318
400
  prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
319
401
 
402
+ clearStage(record.id);
403
+
320
404
  const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, guardedArgs, {
321
405
  stdio: ["pipe", "pipe", "pipe"],
322
- env: { ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
323
- CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) },
406
+ env: withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
407
+ CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
408
+ CODEX_SUPERVISOR_STAGE_CLI: stageCli,
409
+ CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) }),
324
410
  windowsHide: true,
325
411
  ...spawnOptions
326
412
  });
@@ -560,7 +646,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
560
646
  next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
561
647
  if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
562
648
  }
563
- if (status === "completed" && !next.run_evidence.structured_report.valid) {
649
+ if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
564
650
  next.status = "failed";
565
651
  next.attention_reason = "invalid_report";
566
652
  next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
@@ -805,6 +891,7 @@ export async function createCodexWorker({
805
891
  followupOf = null,
806
892
  workspaceKind = null,
807
893
  inPlaceAuthorization = null,
894
+ workspaceSetup = null,
808
895
  baseRef = null,
809
896
  preflightId = null,
810
897
  preflight = null,
@@ -873,6 +960,8 @@ export async function createCodexWorker({
873
960
  });
874
961
  const projectRoot = workspace.sourceRoot;
875
962
  const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
963
+ const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
964
+ if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspaceSetup is only supported for git_worktree workers");
876
965
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
877
966
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
878
967
 
@@ -897,6 +986,15 @@ export async function createCodexWorker({
897
986
  error.code = "git_worktree_unavailable";
898
987
  throw error;
899
988
  }
989
+ if (normalizedWorkspaceSetup) {
990
+ try {
991
+ await prepareWorktreeWorkspace(normalizedWorkspaceSetup, projectRoot, worktreePath, id);
992
+ } catch (error) {
993
+ await runCommand(defaultGitBin, ["-C", projectRoot, "worktree", "remove", worktreePath]).catch(() => {});
994
+ await runCommand(defaultGitBin, ["-C", projectRoot, "branch", "-D", `codex/${id}`]).catch(() => {});
995
+ throw error;
996
+ }
997
+ }
900
998
  const effectiveCwd = worktreePath ?? workspace.executionCwd;
901
999
  if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
902
1000
  || preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
@@ -904,7 +1002,14 @@ export async function createCodexWorker({
904
1002
  }
905
1003
  const guardPolicy = {
906
1004
  forbid,
907
- allowedCommands,
1005
+ // Probe commands need enough permission to prove the worker environment,
1006
+ // but they are not part of the target worker's executable contract. Keep
1007
+ // them in this preflight run's guard only so the final worker can reuse the
1008
+ // exact contract its dispatcher declared.
1009
+ allowedCommands: [...new Set([
1010
+ ...allowedCommands,
1011
+ ...(preflight?.probeCommands ?? [])
1012
+ ])],
908
1013
  externalOutputs,
909
1014
  networkAccess,
910
1015
  writableRoots: [...new Set(resolvedWritableRoots)],
@@ -922,6 +1027,7 @@ export async function createCodexWorker({
922
1027
  writableRoots: guardPolicy.writableRoots,
923
1028
  context,
924
1029
  contracts,
1030
+ workspaceSetup: normalizedWorkspaceSetup,
925
1031
  workspaceKind: workspace.kind,
926
1032
  workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
927
1033
  });
@@ -945,7 +1051,8 @@ export async function createCodexWorker({
945
1051
  before_manifest: workspace.beforeManifest,
946
1052
  in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
947
1053
  landable: workspace.landable,
948
- cleanable: workspace.cleanable
1054
+ cleanable: workspace.cleanable,
1055
+ setup: normalizedWorkspaceSetup
949
1056
  },
950
1057
  sandbox,
951
1058
  model,
@@ -1037,7 +1144,11 @@ export async function createCodexWorker({
1037
1144
  objective: validatedGoal.objective,
1038
1145
  tokenBudget: validatedGoal.tokenBudget
1039
1146
  }, { acceptance: combinedAcceptance }),
1040
- logPath: record.run_log
1147
+ logPath: record.run_log,
1148
+ // --cd tells Codex where the agent works. The shell/tool process must also
1149
+ // inherit the worktree as its OS cwd: otherwise a login shell may restore
1150
+ // the project directory and relative probes read the wrong checkout.
1151
+ spawnOptions: { cwd: effectiveCwd }
1041
1152
  });
1042
1153
  return started.record;
1043
1154
  }
@@ -1149,6 +1260,7 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
1149
1260
  export async function recoverEligibleRuns() {
1150
1261
  const recovered = [];
1151
1262
  for (const task of await readTasks()) {
1263
+ if (task.guard_policy?.preflight) continue;
1152
1264
  if ((task.run_count ?? 0) !== 1 || !task.thread_id
1153
1265
  || !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
1154
1266
  || !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
@@ -1326,7 +1438,8 @@ export async function createFollowupWorker({
1326
1438
  maxRunMs,
1327
1439
  maxTotalMs,
1328
1440
  workspaceKind,
1329
- inPlaceAuthorization
1441
+ inPlaceAuthorization,
1442
+ workspaceSetup
1330
1443
  }) {
1331
1444
  const parent = await getTask(taskId);
1332
1445
  if (!parent) throw new Error(`task not found: ${taskId}`);
@@ -1380,6 +1493,7 @@ export async function createFollowupWorker({
1380
1493
  followupOf: parent.id,
1381
1494
  workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
1382
1495
  inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
1496
+ workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
1383
1497
  baseRef: baseRef ?? null,
1384
1498
  // Inherited unless given; the follow-up runs in a fresh worktree cut
1385
1499
  // from the project HEAD, so the parent's checks only pass there once
@@ -0,0 +1,31 @@
1
+ import { isGoalNeedingAttention } from "./status.js";
2
+
3
+ function providerFailure(text) {
4
+ if (!/provider|upstream_status|upstream status|cc switch|responses endpoint/i.test(text)) return null;
5
+ const status = Number(text.match(/(?:upstream_status|upstream status|unexpected status|HTTP)\D{0,8}(\d{3})/i)?.[1] ?? 0);
6
+ const retryable = status === 429 || status >= 500 || /timeout|temporar|rate.?limit/i.test(text);
7
+ return { source: "provider", code: status ? `provider_http_${status}` : "provider_error", retryable };
8
+ }
9
+
10
+ export function classifyFailure(task) {
11
+ if (!task) return null;
12
+ const error = String(task.error ?? "");
13
+ const attention = String(task.attention_reason ?? "");
14
+
15
+ const provider = providerFailure(error);
16
+ if (provider) return provider;
17
+ if (/did not record the process exit/i.test(error)) return { source: "supervisor_process", code: "exit_unrecorded", retryable: true };
18
+ if (attention === "start_failed") return { source: "supervisor_process", code: "start_failed", retryable: true };
19
+ if (/^workspaceSetup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
20
+ if (/^workspaceSetup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
21
+ if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
22
+ if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
23
+ if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
24
+ if (attention === "time_limit" || attention === "total_time_limit") return { source: "supervisor_process", code: attention, retryable: false };
25
+ if (task.status === "lost") return { source: "supervisor_process", code: "worker_lost", retryable: true };
26
+ if (task.status === "cancelled") return { source: "caller", code: "cancelled", retryable: true };
27
+ if (/codex exited with code/i.test(error)) return { source: "worker_process", code: "process_exit_nonzero", retryable: true };
28
+ if (isGoalNeedingAttention(task.goal_status)) return { source: "goal", code: `goal_${task.goal_status}`, retryable: false };
29
+ if (task.status === "failed") return { source: "unknown", code: "failed", retryable: null };
30
+ return null;
31
+ }
package/src/landing.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { execFileSync } from "node:child_process";
10
10
  import { existsSync, rmSync } from "node:fs";
11
11
  import { join, relative } from "node:path";
12
- import { parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff } from "./worktree.js";
12
+ import { filterWorkspaceSetupChanges, parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff, workspaceSetupIgnorePaths } from "./worktree.js";
13
13
  import { findOutsideOwnedChanges } from "./owned-changes.js";
14
14
 
15
15
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
@@ -137,9 +137,9 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
137
137
  const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
138
138
  if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
139
139
  if (!allowOutsideOwned) {
140
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0 });
140
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0, ignorePaths: workspaceSetupIgnorePaths(task) });
141
141
  if (diff.error) return { error: "ownership_unverified", reason: "cannot prove the complete diff before landing", diff_error: diff.error };
142
- const paths = [...readWorktreeChanges(task.worktree_path, worktreeRef(task)),
142
+ const paths = [...filterWorkspaceSetupChanges(task, readWorktreeChanges(task.worktree_path, worktreeRef(task))),
143
143
  ...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
144
144
  const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
145
145
  if (outside.length) return { error: "outside_owned_paths", reason: "worker changes exceed declared ownedPaths; review them and obtain explicit authorization before allowing an exception", outside_paths: outside.map((entry) => relative(task.worktree_path, entry)) };
@@ -154,7 +154,12 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
154
154
  let committedForWorker = null;
155
155
  if (uncommitted.length > 0 && commitMessage) {
156
156
  try {
157
- git(task.worktree_path, ["add", "-A"]);
157
+ if (allowOutsideOwned) git(task.worktree_path, ["add", "-A"]);
158
+ else {
159
+ const owned = findOutsideOwnedChanges(task, []).mapping.map((entry) => relative(task.worktree_path, entry.worker));
160
+ if (owned.length === 0) return { error: "outside_owned_paths", reason: "the worker left uncommitted changes but owns no landable path" };
161
+ git(task.worktree_path, ["add", "-A", "--", ...owned]);
162
+ }
158
163
  if (hasStagedChanges(task.worktree_path)) {
159
164
  git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
160
165
  committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();