codex-supervisor-mcp 0.9.0 → 0.9.2

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
@@ -23,6 +23,7 @@ Point several agents at one repository and they overwrite each other, nobody can
23
23
  | Problem | What it does |
24
24
  |---|---|
25
25
  | Workers trample each other's files | One Git worktree per worker, `ownedPaths` checked for overlap before dispatch |
26
+ | A worker is not only an editor | Three shapes: edit (`ownedPaths` non-empty), read-only verify (`read-only` + `ownedPaths: []`: no writes, no network), research/retrieval (`workspace-write` + `networkAccess: true` + `ownedPaths: []`: fetches, keeps scratch notes, never lands). Reading shared files is never exclusive; writing is |
26
27
  | A worker says it is done and it is not | Dispatch with `acceptance` commands; the supervisor runs them in the worktree after the worker exits, and `land` refuses while they fail |
27
28
  | Worker output floods the main thread | Events go to `data/runs/<taskId>.jsonl`; reads are gated by `limit` / `maxChars` / `kinds` |
28
29
  | One status read fills the context | `get_orchestration_overview` fits every worker into 7000 bytes |
@@ -43,7 +44,7 @@ Prerequisites: Node.js 22.13.0 or newer, `codex` on `PATH`. macOS, Linux and Win
43
44
  npm install -g codex-supervisor-mcp
44
45
  ```
45
46
 
46
- `postinstall` installs the skill and registers the MCP. If `claude mcp list` does not show it (`npx`, pnpm and `--ignore-scripts` skip `postinstall`), add it by hand:
47
+ A global npm install runs `postinstall` when lifecycle scripts are enabled, installing the skill and registering MCP with detected Claude Code/Codex clients. `--ignore-scripts`, disabled lifecycle scripts, and running through npx do not guarantee registration; run `codex-supervisor-setup` and inspect both clients with `mcp get`. Manual registration also works:
47
48
 
48
49
  ```bash
49
50
  claude mcp add -s user codex-supervisor -- npx -y codex-supervisor-mcp
@@ -62,7 +63,7 @@ What the main thread does underneath (you can call the tools yourself):
62
63
 
63
64
  ```
64
65
  create_codex_worker ×3 each with session_id, session_title, ownedPaths, goal
65
- wait_codex_workers two minutes by default, then a snapshot, call again until done
66
+ wait_codex_workers 60 seconds by default, then a snapshot, call again until done
66
67
  get_worker_result ×3 each worker's report, with the commands it really ran
67
68
  ```
68
69
 
@@ -115,7 +116,7 @@ What the main brain calls in one round:
115
116
  ```
116
117
  search_works has this batch been dispatched before
117
118
  create_codex_worker one worker per step, same session_id, ownedPaths disjoint
118
- wait_codex_workers two minutes a round, compact: true, call again until done
119
+ wait_codex_workers 60 seconds a round, compact: true, call again until done
119
120
  get_worker_result what it says it did; verification is what it really ran
120
121
  get_worker_diff what it actually did
121
122
  ask_codex_worker when the two differ, ask why; read-only, its thread untouched
@@ -147,12 +148,12 @@ Twenty-one.
147
148
  |---|---|---|
148
149
  | `check_workers` | none | Report newly settled runs and actionable changes; recover a new-format first lost/no_work run once. Unchanged state is quiet. Call from a host-scheduled loop and use a distinct CODEX_SUPERVISOR_OBSERVER_ID for each reconnecting main thread |
149
150
  | `check_acceptance` | `cwd`, `acceptance`, `baseRef`, `timeoutMs` | Execute supplied checks before dispatch, without creating a worker or proving completion; warns that failure-count greps do not establish an approved failure list or required execution |
150
- | `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Start a worker. `acceptance` lists the commands the supervisor runs in the worktree once the worker exits; exit 0 on every one passes. `baseRef` picks the commit the worktree is cut from (default `HEAD`); pass another worker's `codex/<id>` to build on it |
151
+ | `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Start a worker. `acceptance` lists the commands the supervisor runs in the worktree once the worker exits; exit 0 on every one passes. `baseRef` picks the commit the worktree is cut from (default `HEAD`); pass another worker's `codex/<id>` to build on it |
151
152
  | `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, plus the above | A new session seeded with the old worker's prompt, status and recent events |
152
153
  | `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | Continue the same Codex conversation; `thread_id` stays. `rebaseOnto` first moves the worktree onto the project's newer commit (stash, skip integrated patches, replay new commits, unstash); a conflict puts it back and does not start the worker |
153
- | `wait_codex_workers` | `task_ids`, `mode` (any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for terminal states. Two minutes by default, then a snapshot while the workers keep running; `compact` returns one line per worker with `idle_seconds` / `command_running`, so a long command and a stuck worker look different |
154
+ | `wait_codex_workers` | `task_ids`, `mode` (any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for terminal states. 60 seconds by default, then a snapshot while the workers keep running; `compact` returns one line per worker with `idle_seconds` / `command_running`, so a long command and a stuck worker look different |
154
155
  | `get_orchestration_overview` | `status`, `limit` | Every worker in one table, capped at 7000 bytes. Carries `version` and `update` |
155
- | `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 |
156
+ | `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) |
156
157
  | `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 |
157
158
  | `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 |
158
159
  | `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 |
@@ -183,7 +184,13 @@ Wait defaults to 60 seconds and compact rows; includeEvents selects details unle
183
184
 
184
185
  Each run injects the shipped PreToolUse guard: apply_patch checks every target including renames and symlinks; forbid rejects red lines. Shell allows simple reads and explicitly declared allowedCommands/acceptance. Declared validation scripts run with dispatcher privileges and may have side effects; this is not a filesystem sandbox for arbitrary programs. Resume/follow-up inherit the policy without changing global hooks. Empty write runs use current output and command evidence and surface no_work; read-only tasks are not empty merely for having no diff.
185
186
 
186
- After reconciliation, check_workers atomically resumes a dead first lost/no_work run once and returns recovery receipts. A second failure remains actionable; 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.
187
+ A model with no separate `apply_patch` tool (measured with Codex 0.162 + DeepSeek/cc-switch) sends the patch as a shell call: `apply_patch <<'EOF' ... EOF`. The guard accepts that shape and judges every target path with the same ownedPaths rule, so such a model can still edit; an unquoted heredoc, or one followed by `&&`/`;`, is refused.
188
+
189
+ An `allowedCommands` entry ending in `*` is a prefix match (so `go test ./internal/*` covers `go test ./internal/service -run TestX`), valid only for a single command without shell metacharacters. An editor worker may also read with grep/sed (without `-i`)/find (without `-exec`/`-delete`)/jq (without `-i`)/awk, the git read subcommands and pure read pipes such as `cmd | head|tail|wc|sort|uniq`; `tee`, redirects and `env` stay refused. The guard is not a filesystem sandbox: a miss only writes inside the worker's own worktree, and land refuses it.
190
+
191
+ The guard relaxes by worker shape: an editor with non-empty `ownedPaths` gets only declared commands and simple reads; a `read-only` worker, or one with `ownedPaths: []`, has no landable write boundary left, so the shell is no longer restricted command by command (forbid red lines still apply) and retrieval, review, `curl`, `gh` and `python` work. Measured with Codex 0.162: the read-only sandbox cannot write even `/tmp` and has no DNS, so a fetching worker runs `workspace-write` + `networkAccess: true` + `ownedPaths: []` and its output never merges.
192
+
193
+ 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). A second failure remains actionable; 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.
187
194
 
188
195
  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.
189
196
 
@@ -191,6 +198,8 @@ Declare externalOutputs:[{path,sha256?}] and acceptance for shared writes. Targe
191
198
 
192
199
  workspace-write defaults to networkAccess:false; explicitly enable it for ssh/network checks. Resume/follow-up inherit the setting. maxRunMs bounds one run and maxTotalMs bounds wall time since dispatch; exceeding either stops the worker and preserves actionable partial results without automatic retry. A wait budget does not change these quotas.
193
200
 
201
+ Besides the worktree and the temp directory the sandbox writes the OS cache directory only (macOS `~/Library/Caches`, Linux `~/.cache`, Windows `%LOCALAPPDATA%`). Toolchains that cache there, Go's build cache among them, need no per-language variable and no patch when a new language shows up. A toolchain that caches elsewhere (`~/.m2`, `~/.gradle`, a vendored mirror) passes `writableRoots:[absolute paths]`: existing directories, at most 20, workspace-write only, inherited by resume/follow-up. Read-only reuse needs nothing.
202
+
194
203
  Dispatch checks required hooks/output-schema support (Codex 0.162+); unsupported capability returns settled start_failed. get_worker_goal.native_goal_read distinguishes missing_goal, missing_database, locked and read_error; a read failure is not evidence that no goal exists. Native budget/usage limits need attention. Cleanup preserves ignored artifacts, shared evidence and unresolved attention.
195
204
 
196
205
  Ownership reservation and task insertion are atomic across MCP dispatch/resume processes; ownership remains reserved during acceptance or exit settlement. Failure to create an isolated Git checkout is explicit and never falls back to executing in the project directory.
@@ -253,7 +262,7 @@ A terminal state lands in two steps: `turn.completed` sets `completed`, the proc
253
262
  | `CODEX_SUPERVISOR_SKIP_SETUP` | unset | `1` skips the `postinstall` setup |
254
263
  | `CODEX_SUPERVISOR_NPM` | unset | npm for the auto-update; default is the one shipped with the running node |
255
264
 
256
- GUI clients (Claude Desktop, Cursor, Windsurf) do not run `postinstall`: add this to their MCP config file, and since their `PATH` often lacks `codex`, give `CODEX_BIN` explicitly:
265
+ GUI clients (Claude Desktop, Cursor, Windsurf) are not automatic registration targets of this installer: add this to their MCP config file, and since their `PATH` often lacks `codex`, give `CODEX_BIN` explicitly:
257
266
 
258
267
  ```json
259
268
  {
@@ -271,7 +280,7 @@ GUI clients (Claude Desktop, Cursor, Windsurf) do not run `postinstall`: add thi
271
280
 
272
281
  Nothing to do by hand. At start the server asks the registry in the background; a newer version is installed by a detached `npm i -g` into the same global path, the running session is untouched and the next session starts on it. Only a copy that `npm i -g` installed is touched; a git checkout or an `npx` copy is left alone. The skill does the same: every start copies it into the existing skill directories, backing up an edited file as `SKILL.md.bak-<timestamp>`.
273
282
 
274
- When the install fails (a global directory that needs sudo) the `update` field says why and `npm install -g codex-supervisor-mcp@latest` by hand still works. Versions up to 0.6.1 only notify; upgrade by hand once and it is automatic from then on. A Node version switch breaks the registered path: `claude mcp remove -s user codex-supervisor`, `codex mcp remove codex-supervisor`, reinstall. To run the setup again: `codex-supervisor-setup` (`--skill-only` / `--mcp-only` / `--dry-run`).
283
+ When the install fails (a global directory that needs sudo) the `update` field says why and `npm install -g codex-supervisor-mcp@latest` by hand still works. Versions up to 0.6.1 only notify; upgrade by hand once and it is automatic from then on. After changing Node versions/install prefixes, setup repairs old package-generated paths and verifies command/args through client read-back. Custom, disabled and project registrations are preserved with a repair warning. To run the setup again: `codex-supervisor-setup` (`--skill-only` / `--mcp-only` / `--dry-run`). Manual registration failures exit nonzero; automatic installs warn without failing npm. A skill write failure does not prevent MCP registration. Set `CLAUDE_BIN` / `CODEX_BIN` for off-PATH CLIs. Skill locations follow `CLAUDE_CONFIG_DIR` / `CODEX_HOME`.
275
284
 
276
285
  Uninstall:
277
286
 
package/README.md CHANGED
@@ -23,6 +23,7 @@
23
23
  | 问题 | 做法 |
24
24
  |---|---|
25
25
  | 几个 worker 互相踩文件 | 一个 worker 一个 Git worktree,`ownedPaths` 在派单前查冲突 |
26
+ | worker 不是只会改代码 | 三种形状:编辑(`ownedPaths` 非空)、只读验证(`read-only` + `ownedPaths: []`,无写入无网络)、研究检索(`workspace-write` + `networkAccess: true` + `ownedPaths: []`,能联网、能写草稿、永不 land);读共享文件不排他,只有写排他 |
26
27
  | worker 的过程塞爆主线程上下文 | 事件写 `data/runs/<taskId>.jsonl`,读的时候有 `limit` / `maxChars` / `kinds` 三道闸 |
27
28
  | 主线程读一次状态就顶满 | `get_orchestration_overview` 把全部 worker 压进 7000 字节 |
28
29
  | 进程重启后不知道谁还在跑 | `supervisor.sqlite` 一行一个 work,带 `thread_id` |
@@ -43,7 +44,7 @@ worker 跑的是 `codex exec`,`model` 透传:主线程留在 Claude,worker
43
44
  npm install -g codex-supervisor-mcp
44
45
  ```
45
46
 
46
- `postinstall` 装 skill、注册 MCP。`claude mcp list` 里没看到(`npx`、pnpm、`--ignore-scripts` 不跑 `postinstall`)就手动补:
47
+ npm 全局安装在允许执行安装脚本时,会运行 `postinstall`,给检测到的 Claude Code/Codex 装 skill 并注册 MCP。`--ignore-scripts`、禁用安装脚本或只运行 npx 不保证自动注册;没看到时先运行 `codex-supervisor-setup`,再查两端 `mcp get`。手动注册也可以:
47
48
 
48
49
  ```bash
49
50
  claude mcp add -s user codex-supervisor -- npx -y codex-supervisor-mcp
@@ -62,7 +63,7 @@ codex mcp add codex-supervisor -- npx -y codex-supervisor-mcp
62
63
 
63
64
  ```
64
65
  create_codex_worker ×3 每路带 session_id、session_title、ownedPaths、goal
65
- wait_codex_workers 默认等 2 分钟,到点返回快照,没完就接着等
66
+ wait_codex_workers 默认等 60 秒,到点返回快照,没完就接着等
66
67
  get_worker_result ×3 收每路的汇报,带它真跑过的命令和退出码
67
68
  ```
68
69
 
@@ -115,7 +116,7 @@ npx -p codex-supervisor-mcp codex-supervisor-web
115
116
  ```
116
117
  search_works 查这批活派过没有
117
118
  create_codex_worker 一步一个 worker,同一个 session_id,ownedPaths 不重叠
118
- wait_codex_workers 2 分钟一轮,compact: true,没完接着调
119
+ wait_codex_workers 60 秒一轮,compact: true,没完接着调
119
120
  get_worker_result 它说自己做了什么,verification 里是它真跑过的命令
120
121
  get_worker_diff 它实际做了什么
121
122
  ask_codex_worker 对不上就问它为什么,只读,不动它的线程
@@ -147,12 +148,12 @@ land_codex_worker 核过了,落进集成分支
147
148
  |---|---|---|
148
149
  | `check_workers` | 无参 | 交付新终态、验收失败和需处理goal;新格式第1轮lost/no_work自动恢复一次,未变返回quiet;用宿主定时唤醒调用,每个主线程设独立CODEX_SUPERVISOR_OBSERVER_ID可在重启后接回 |
149
150
  | `check_acceptance` | `cwd`, `acceptance`, `baseRef`, `timeoutMs` | 派单前实际运行给定验收命令,不建 worker,不证明 worker 完成;数量 grep 会提示不能证明失败名单和必跑执行 |
150
- | `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | 起一个 worker。`acceptance` 是验收命令,worker 退出后 supervisor 在它的 worktree 里跑,退出码 0 算过。`baseRef` 指定 worktree 从哪个提交切,默认 `HEAD`,接另一路填它的 `codex/<id>` |
151
+ | `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `maxRunMs`, `maxTotalMs`, `acceptance`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | 起一个 worker。`acceptance` 是验收命令,worker 退出后 supervisor 在它的 worktree 里跑,退出码 0 算过。`baseRef` 指定 worktree 从哪个提交切,默认 `HEAD`,接另一路填它的 `codex/<id>` |
151
152
  | `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, 其余同上 | 开一个新会话,把老 worker 的 prompt、状态、近期事件拼进去 |
152
153
  | `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | 接同一个 Codex 会话继续跑,`thread_id` 不变。`rebaseOnto` 先把 worktree 挪到主线新头(stash、跳过已合入补丁、重放新增提交、放回),冲突原样退回不起 worker |
153
- | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态。默认 2 分钟,到点带快照返回,worker 照跑;`compact` 每路只回一行,带 `idle_seconds` / `command_running`,分得清长命令和卡住 |
154
+ | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态。默认 60 秒,到点带快照返回,worker 照跑;`compact` 每路只回一行,带 `idle_seconds` / `command_running`,分得清长命令和卡住 |
154
155
  | `get_orchestration_overview` | `status`, `limit` | 全部 worker 的状态表,封顶 7000 字节。带 `version` 和 `update` |
155
- | `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | worker 自己的汇报,默认截 6000 字节、`truncated` 提示读全。`acceptance` 是 supervisor 替你跑的验收过没过,`verification` 是它自己跑过的命令和退出码,`base_behind` 是主线走了多远 |
156
+ | `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | worker 自己的汇报,默认截 6000 字节、`truncated` 提示读全。`acceptance` 是 supervisor 替你跑的验收过没过,`verification` 是它自己跑过的命令和退出码,`base_behind` 是主线走了多远(`contains_base: false` 时 `behind` 为 `null`,那是换了线) |
156
157
  | `get_worker_diff` | `task_id`, `maxChars`, `paths` | worker 实际改了什么:从 worktree 起点到工作区的 patch,提交没提交都算。`maxChars` 管总量,超了的文件只列名 |
157
158
  | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | 旁路问 worker 一句。线程 fork 成只读侧会话,没网络、没 MCP 工具,worker 本身不动。worker 被 resume 过会自动换新 fork,`fresh` 强制换,`end` 删 |
158
159
  | `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝。`commitMessage` 先替它把未提交的改动提交成一笔,`ignoreAcceptance` 放行 |
@@ -183,7 +184,13 @@ wait 默认预算60秒、默认compact;includeEvents会选择详细结果(
183
184
 
184
185
  每路临时注入随包PreToolUse守卫:apply_patch核对全部目标路径(含rename和symlink),forbid拒绝红线;Shell仅允许简单读取和派单显式allowedCommands/acceptance。声明的验证脚本以派单者权限执行,可有副作用,不能当作任意程序的文件沙箱。guard策略随resume/followup继承,不写全局hooks。空跑write run按本轮输出前后内容和命令判断,no_work进入needs_attention;只读任务不因没改文件判空跑。
185
186
 
186
- check_workers在状态协调后,对已结束的第1轮lost/no_work原子resume一次;第2轮仍有问题则保留证据等处理。审批、认证、权限和quota等待不重试,返回recoveries记录。worker最终输出强制JSON result/verification/not_done;get_worker_result的structured_report给格式校验,独立命令与acceptance仍为实际证据。非法JSON标failed/invalid_report并拒绝land;旧历史标legacy_text。
187
+ 没有独立 `apply_patch` 工具的模型(实测 Codex 0.162 + DeepSeek/cc-switch)把补丁当 shell 命令发过来:`apply_patch <<'EOF' ... EOF`。守卫认这个形状,用同一套 ownedPaths 规则判每个目标路径,所以这种模型也能改文件;未加引号的 heredoc、后面还接 `&&`/`;` 的都拒绝。
188
+
189
+ `allowedCommands` 里以 `*` 结尾的条目是前缀匹配(如 `go test ./internal/*` 覆盖 `go test ./internal/service -run TestX`),只对没有 shell 元字符的单条命令生效。编辑器 worker 的只读白名单覆盖 grep/sed(无 `-i`)/find(无 `-exec`/`-delete`)/jq(无 `-i`)/awk、git 只读子命令和 `cmd | head|tail|wc|sort|uniq` 纯读管道;`tee`、重定向、`env` 仍拒。守卫不是文件沙箱,漏网的写入只会落在 worker 自己的 worktree,land 会拒。
190
+
191
+ 守卫按 worker 形状放权:`ownedPaths` 非空的编辑 worker 只放声明过的命令和简单读取;`read-only` 或 `ownedPaths: []` 的 worker 没有可 land 的写边界,Shell 不再逐条限制(forbid 红线照旧),所以检索、审查、跑 `curl`/`gh`/`python` 都能干活。实测 read-only 沙箱连 `/tmp` 都写不了、也不通 DNS,所以联网检索要用 `workspace-write` + `networkAccess: true` + `ownedPaths: []`,产物永不进主分支。
192
+
193
+ check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON,不重做活);第2轮仍有问题则保留证据等处理。审批、认证、权限和quota等待不重试,返回recoveries记录。worker最终输出强制JSON result/verification/not_done;get_worker_result的structured_report给格式校验,独立命令与acceptance仍为实际证据。非法JSON标failed/invalid_report并拒绝land;旧历史标legacy_text。
187
194
 
188
195
  context用绝对文件路径与可选sha256声明材料,最多20份、与contracts合计6000字;文件不超过5 MB。首次派单记录实际哈希,resume校验原材料未变,需要新材料时显式传context。handoff最多1800字/16行,截断明确标记;完整约束和引用单独保留,材料不授予写权限。
189
196
 
@@ -191,6 +198,8 @@ context用绝对文件路径与可选sha256声明材料,最多20份、与contr
191
198
 
192
199
  workspace-write默认networkAccess:false;需要ssh/联网验证显式true,随resume/followup继承,不以danger-full-access代替。maxRunMs限制单轮、maxTotalMs限制从派单开始的总时长;超限中止worker并保留needs_attention/partial work,不自动重试。wait预算不改变这些quota。
193
200
 
201
+ 沙箱除工作区和临时目录外,只再放开 OS cache 目录(macOS `~/Library/Caches`、Linux `~/.cache`、Windows `%LOCALAPPDATA%`):Go 的 build cache 这类默认落在 cache 目录的工具链直接可用,换语言也不用改 supervisor。cache 放在别处(`~/.m2`、`~/.gradle`、vendor 镜像)就传 `writableRoots:[绝对路径]`,要求是已存在目录、最多 20 个、只对 workspace-write 生效、随 resume/followup 继承;只读复用就不用传。
202
+
194
203
  运行前核验Codex CLI是否具备hooks/output-schema(要求0.162+);能力不足返回start_failed,wait可正常结算。get_worker_goal.native_goal_read区分missing_goal、missing_database、locked和read_error,不能把读取失败当没建goal。原生budget/usage限制也进入needs_attention。cleanup保留ignored artifacts、共享证据和未解决attention。
195
204
 
196
205
  ownedPaths预留和任务入库在同一事务内,跨MCP并发派单/恢复不能抢同一输出;验收或退出尚未结算时仍保留归属。Git工作区隔离创建失败明确报错,不退回主目录执行。
@@ -253,7 +262,7 @@ ownedPaths预留和任务入库在同一事务内,跨MCP并发派单/恢复不
253
262
  | `CODEX_SUPERVISOR_SKIP_SETUP` | 未设 | `1` 跳过 `postinstall` 的自动安装 |
254
263
  | `CODEX_SUPERVISOR_NPM` | 未设 | 自动更新用的 npm,默认用当前 node 自带的 |
255
264
 
256
- GUI 客户端(Claude Desktop、Cursor、Windsurf)不跑 `postinstall`,自己把这段加进它的 MCP 配置文件,`PATH` 里常常没有 `codex`,显式给 `CODEX_BIN`:
265
+ GUI 客户端(Claude Desktop、Cursor、Windsurf)不在本安装器的自动注册目标中,自己把这段加进它的 MCP 配置文件,`PATH` 里常常没有 `codex`,显式给 `CODEX_BIN`:
257
266
 
258
267
  ```json
259
268
  {
@@ -271,7 +280,7 @@ GUI 客户端(Claude Desktop、Cursor、Windsurf)不跑 `postinstall`,自
271
280
 
272
281
  不用手动更。server 启动时后台查一次 registry,有新版就起独立进程 `npm i -g` 到同一个全局路径;正在跑的会话不受影响,下一个新会话就是新版。只对 `npm i -g` 装的那份生效,git 源码和 `npx` 起的不碰。skill 也一样,每次启动刷到已有的 skill 目录,改过的先备份成 `SKILL.md.bak-<时间戳>`。
273
282
 
274
- 装失败(全局目录要 sudo)时 `update` 字段带原因,手动 `npm install -g codex-supervisor-mcp@latest`。0.6.1 及以前只提醒不自动装,手动升一次就进自动了。换了 Node 版本注册的路径会失效,`claude mcp remove -s user codex-supervisor`、`codex mcp remove codex-supervisor` 后重装。重跑安装:`codex-supervisor-setup`(`--skill-only` / `--mcp-only` / `--dry-run`)。
283
+ 装失败(全局目录要 sudo)时 `update` 字段带原因,手动 `npm install -g codex-supervisor-mcp@latest`。0.6.1 及以前只提醒不自动装,手动升一次就进自动了。换 Node/安装前缀后,setup 会修复本包生成的旧入口,并读回核对 command/args;已有自定义、disabled、project配置保留并提示处理,不擅自覆盖。重跑安装:`codex-supervisor-setup`(`--skill-only` / `--mcp-only` / `--dry-run`)。手动注册失败返回非0,自动安装保持成功但打印warning;skill写入失败仍继续尝试MCP注册;没找到CLI时可设 `CLAUDE_BIN` / `CODEX_BIN`。skill路径跟随 `CLAUDE_CONFIG_DIR` / `CODEX_HOME`。
275
284
 
276
285
  卸载:
277
286
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
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.",
@@ -46,6 +46,7 @@
46
46
  "src/tool-guard.js",
47
47
  "src/worker-report.js",
48
48
  "src/worker-report.schema.json",
49
+ "src/sandbox-roots.js",
49
50
  "src/handoff.js",
50
51
  "src/external-output.js",
51
52
  "src/truncate.js",
@@ -24,7 +24,7 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
24
24
  | `cwd` | 项目根目录。worker 在自己的 worktree 里干活,不动你的工作区 |
25
25
  | `acceptance` | 这一步"做完了"的判据,shell 命令列表,worker 退出后 supervisor 在它的 worktree 里逐条跑,退出码 0 算过,worker 在 prompt 里看得到。任务书里的验证命令原样抄:查那个文件在不在、那个接口通不通、那个测试文件过不过。写能判这一步的,不写全仓回归;远端机器的检查包进 `ssh`。命令用 supervisor 自己的权限跑,等于你自己跑 |
26
26
  | `forbid` / `allowedCommands` | 原样声明红线与验证命令;守卫拒绝未声明Shell程序,编辑用apply_patch |
27
- | `ownedPaths` | 必填。这路允许写的路径,和在跑的 worker 重叠会被拒。冲突是好事,说明该改拆法 |
27
+ | `ownedPaths` | 必填。这路允许写的路径,和在跑的 worker 重叠会被拒(**读不排他**,多路读同一份共享文件合法)。冲突是好事,说明该改拆法。传 `[]` 表示这路不落地:只读验证或研究 |
28
28
  | `goal.objective` | 必填。一句话说目标,worker 会建成 Codex 原生 goal |
29
29
  | `session_id` | 同一批传同一个值。第一路顺手带 `session_title`(30 字内,看板和 `get_session_works` 显示它),漏了用 `describe_session` 补 |
30
30
  | `dependsOn` | 有先后依赖填上游的 `task_id` |
@@ -43,7 +43,21 @@ wait默认60秒和compact,带includeEvents则详细返回;客户端带progre
43
43
 
44
44
  派单写forbid红线、allowedCommands验证命令;runtime守卫按次注入并随resume/followup继承。apply_patch核对ownedPaths,Shell仅放简单读取和显式声明的验证命令;声明脚本可以有副作用,须先核对,不能当万能文件沙箱。no_work表示本轮write无输出变化且没跑命令;先看run_evidence,不拿上轮提交/命令当本轮完成。
45
45
 
46
- check_workers可对已死的第1轮lost/no_work自动resume一次,recoveries记动作;第2轮仍失败看证据处理,审批/认证/权限/quota不盲重试。最终报告强制JSON,structured_report仅验证格式;invalid_report拒land,resume让模型提交合法JSON,命令和acceptance另外核对。
46
+ 没有独立 `apply_patch` 工具的模型会把补丁当 shell 命令发过来(`apply_patch <<'EOF' ... EOF`):守卫认这个形状,按同一套 ownedPaths 判路径、同样拒越界,所以模型不需要有那个工具也能改文件。Quoted heredoc 才认;后面跟 `&&`/`;` 的、未加引号的都不算。
47
+
48
+ `allowedCommands` 里以 `*` 结尾的条目是**前缀**:声明 `go test ./internal/*` 就覆盖 `go test ./internal/service -run TestX`,但只对没有 shell 元字符的单条命令生效(`; rm -rf /` 不会通过)。守卫的只读白名单包含 grep/sed/find/jq/awk/go env、git 的只读子命令和 `cmd | head|tail|wc|sort|uniq` 这类纯读管道;`sed -i`、`find -delete/-exec`、`jq -i`、`tee`、重定向仍被拒。
49
+
50
+ worker不止改代码,按这路要什么选形状:
51
+
52
+ | 形状 | 参数 | 能干什么 |
53
+ |---|---|---|
54
+ | 编辑 worker | `ownedPaths` 非空(默认) | apply_patch 只能落在 ownedPaths,shell 只放声明过的命令和简单读取 |
55
+ | 只读验证 worker | `sandbox: "read-only"` + `ownedPaths: []` | 随便跑读命令(rg/cat/git/jq),**沙箱没有任何写入(连 /tmp 都不行)、也没有网络**;结论写在最终报告 |
56
+ | 研究/检索 worker | `sandbox: "workspace-write"` + `networkAccess: true` + `ownedPaths: []` | 能联网 curl/gh、能往自己的 worktree 写草稿;没有任何东西会 land,只出报告 |
57
+
58
+ read-only 下 `networkAccess: true` 会被拒(实测该沙箱连 DNS 都不通,配了也没用);要联网就按研究 worker 派。研究 worker 的 shell 不受 allowedCommands 限制,forbid 红线照旧。读共享文件永远不排他,只有写按 ownedPaths 排他。
59
+
60
+ check_workers可对已死的第1轮lost/no_work/invalid_report自动resume一次,recoveries记动作;invalid_report只让它重发裸JSON、不重做活,第2轮仍失败看证据处理,审批/认证/权限/quota不盲重试。最终报告强制JSON,structured_report仅验证格式;invalid_report拒land,resume让模型提交合法JSON,命令和acceptance另外核对。
47
61
 
48
62
  未提交材料用context:[{path:绝对路径,sha256:可选}];首次记哈希,resume材料变了要显式换context。context/contracts总6000字、最多20份文件,每份≤5 MB;handoff1800字/16行可裁,完整约束和refs另传。输入路径不等于写授权。
49
63
 
@@ -51,6 +65,8 @@ check_workers可对已死的第1轮lost/no_work自动resume一次,recoveries
51
65
 
52
66
  远端编译/ssh在workspace-write显式networkAccess:true,默认false,resume/followup继承;不要用danger-full-access代替联网配置。需要时声明maxRunMs/maxTotalMs,超限保留partial work并提示处理,不自动恢复;wait预算与quota分开。
53
67
 
68
+ 沙箱只放工作区、临时目录和OS cache目录(macOS ~/Library/Caches、Linux ~/.cache、Windows %LOCALAPPDATA%):Go 这类默认把build cache写那儿的工具链不用再单独设 GOCACHE,加语言也不用改supervisor。cache在别处(如 ~/.m2、~/.gradle、vendor镜像)就传 `writableRoots:[绝对路径]`(已存在目录、最多20个、只对workspace-write生效、随resume/followup继承);能只读复用就不用传。
69
+
54
70
  Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CLI。goal查询看native_goal_read,missing与locked/read_error分开;budget/usage限制也要处理。cleanup保留ignored成果、共享证据及未解决attention。
55
71
 
56
72
  等待的几条规矩:
@@ -64,7 +80,7 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
64
80
  ## 收活:先看证据,再问,再改,再落
65
81
 
66
82
  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` 是没配,退出码只说明没崩,对不对自己看。
67
- 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 步)。
83
+ 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`,那是派单目录换了线,不是落后。
68
84
  2. `get_worker_diff`:它实际做了什么。起点到工作区的全部改动,提交没提交都算;`maxChars` 管总量,`paths` 缩范围。它说过了不算,diff 对得上才算。
69
85
  3. 对不上、看不懂为什么:`ask_codex_worker` 带 `question` 问它。fork 出一个只读旁路,worker 自己的线程不动;fork 没网络没 MCP 工具,问"改了什么、为什么、在哪",别问要联网才能答的事。超时回 `running`,只带 `task_id` 再调拿答案。worker 被 resume 过后下一问自动换新 fork,`fresh: true` 强制换,问完 `end: true` 删。
70
86
  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` 填新头。
@@ -117,3 +133,5 @@ overview、派单回执、`wait` 返回里出现 `update` 且 `update_available:
117
133
  ## 看板
118
134
 
119
135
  用户想用眼睛看就让他起 `codex-supervisor-web`(或 `npx -p codex-supervisor-mcp codex-supervisor-web`),开 `http://127.0.0.1:7877`。按 session 分组,每路有「旁问」tab,用户可以自己问 worker。
136
+
137
+ 安装后没工具:先查Claude/Codex的mcp get codex-supervisor;运行codex-supervisor-setup修复本包旧入口,手动失败非0,skill写入失败仍尝试注册。CLI不在PATH设CLAUDE_BIN/CODEX_BIN;skill跟随CLAUDE_CONFIG_DIR/CODEX_HOME。禁用安装脚本时不会自动注册,自定义/disabled/project配置保留并提示处理;重开会话加载新工具和skill。
@@ -1,8 +1,8 @@
1
- import { createWriteStream, existsSync } from "node:fs";
1
+ import { createWriteStream, existsSync, statSync } from "node:fs";
2
2
  import { mkdir, rm, stat } from "node:fs/promises";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { execFileSync, spawn } from "node:child_process";
5
- import { join, resolve, sep, dirname } from "node:path";
5
+ import { join, resolve, sep, dirname, isAbsolute } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import {
8
8
  appendTaskEvent,
@@ -22,7 +22,8 @@ import {
22
22
  import { applyCodexEvent } from "./event-parser.js";
23
23
  import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
24
24
  import { worktreesDir } from "./paths.js";
25
- import { frameWorkerPrompt } from "./prompt.js";
25
+ import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
26
+ import { cacheRoots } from "./sandbox-roots.js";
26
27
  import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
27
28
  import { rebaseWorktree } from "./landing.js";
28
29
  import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance, runAcceptance } from "./acceptance.js";
@@ -240,7 +241,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
240
241
  const outputBefore = snapshotTaskOutput(record);
241
242
  const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
242
243
  const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
243
- const guardPolicy = { cwd: record.cwd, ownedPaths: owned, ...(record.guard_policy ?? {}),
244
+ const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
244
245
  allowedCommands: [...(record.guard_policy?.allowedCommands ?? []), ...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command)] };
245
246
  const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
246
247
  const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
@@ -248,10 +249,11 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
248
249
  const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
249
250
  `hooks.PreToolUse=[{matcher="Bash|apply_patch",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
250
251
  configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
251
- if (externalBefore.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify([...new Set(externalBefore.map((file) => dirname(file.path)))])}`);
252
+ const sandboxWritableRoots = [...new Set([...externalBefore.map((file) => dirname(file.path)), ...cacheRoots(), ...(record.guard_policy?.writableRoots ?? [])])];
253
+ if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
252
254
  // Insert before the prompt/session positional arguments for exec/resume.
253
255
  const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
254
- prompt = `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(owned)}. Shell verification must exactly match declared commands ${JSON.stringify(guardPolicy.allowedCommands)}. Forbidden: ${JSON.stringify(guardPolicy.forbid ?? [])}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard.\n\n${prompt}`;
256
+ prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
255
257
 
256
258
  const { child, spawnError } = await spawnAndAwaitStart(target, guardedArgs, {
257
259
  stdio: ["pipe", "pipe", "pipe"],
@@ -598,6 +600,7 @@ export async function createCodexWorker({
598
600
  contracts = [],
599
601
  externalOutputs = [],
600
602
  networkAccess = false,
603
+ writableRoots = [],
601
604
  maxRunMs = null,
602
605
  maxTotalMs = null
603
606
  }) {
@@ -607,15 +610,23 @@ export async function createCodexWorker({
607
610
  if (!allowedReasoningEfforts.has(reasoningEffort)) {
608
611
  throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
609
612
  }
610
- if (!Array.isArray(ownedPaths) || (ownedPaths.length === 0 && sandbox !== "read-only")) {
611
- throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write (an empty list is allowed only for a read-only worker)");
613
+ if (!Array.isArray(ownedPaths)) {
614
+ throw new Error("ownedPaths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
612
615
  }
613
616
  const validatedGoal = validateGoal(goal);
614
617
  await buildHandoff({ context, contracts });
615
618
  await captureExternalOutputs(externalOutputs, { checkBaseline: true });
616
619
  if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
617
620
  if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
618
- if (networkAccess && sandbox !== "workspace-write") throw new Error("networkAccess is only configurable for workspace-write workers");
621
+ if (networkAccess && sandbox === "danger-full-access") throw new Error("networkAccess is only for the sandboxed workers");
622
+ if (networkAccess && sandbox === "read-only") throw new Error("the read-only sandbox has no network (a fetch there fails on DNS even with network_access); for a worker that must fetch, use sandbox \"workspace-write\" with networkAccess: true and ownedPaths: []");
623
+ if (!Array.isArray(writableRoots) || writableRoots.length > 20 || writableRoots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
624
+ throw new Error("writableRoots must be a list of at most 20 absolute paths");
625
+ }
626
+ if (writableRoots.length && sandbox !== "workspace-write") throw new Error("writableRoots is only configurable for workspace-write workers");
627
+ for (const root of writableRoots) {
628
+ if (!existsSync(root) || !statSync(root).isDirectory()) throw new Error(`writableRoots entry must be an existing directory: ${root}`);
629
+ }
619
630
  for (const value of [maxRunMs, maxTotalMs]) if (value !== null && (!Number.isInteger(value) || value < 1000)) throw new Error("time limits must be integer milliseconds of at least 1000");
620
631
  for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
621
632
  if (!Array.isArray(values) || values.length > 100 || values.some((value) => typeof value !== "string" || !value.trim())) throw new Error(`${name} must be a list of at most 100 nonempty strings`);
@@ -662,7 +673,7 @@ export async function createCodexWorker({
662
673
  session_id: sessionId ?? null,
663
674
  thread_id: null,
664
675
  owned_paths: normalizedOwnedPaths,
665
- guard_policy: { forbid, allowedCommands, externalOutputs, networkAccess, maxRunMs, maxTotalMs },
676
+ guard_policy: { forbid, allowedCommands, externalOutputs, networkAccess, writableRoots, maxRunMs, maxTotalMs },
666
677
  input_context: { context, contracts },
667
678
  depends_on: Array.isArray(dependsOn) ? dependsOn : [],
668
679
  goal_objective: validatedGoal.objective,
@@ -826,7 +837,7 @@ export async function recoverEligibleRuns() {
826
837
  for (const task of await readTasks()) {
827
838
  if ((task.run_count ?? 0) !== 1 || !task.thread_id
828
839
  || !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
829
- || !(task.status === "lost" || task.attention_reason === "no_work")
840
+ || !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
830
841
  || ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
831
842
  || /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
832
843
  || /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
@@ -835,7 +846,9 @@ export async function recoverEligibleRuns() {
835
846
  if (session?.approval_state === "waiting_user") continue;
836
847
  try {
837
848
  const result = await resumeCodexWorker({ taskId: task.id,
838
- prompt: `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
849
+ prompt: task.attention_reason === "invalid_report"
850
+ ? "Your run finished, but the final message was not the required bare JSON report. Do not redo the work and do not edit files: reply with ONLY the JSON object with result (string), verification (string[]) and not_done (string[]), describing what you already did. No code fences, nothing before or after it."
851
+ : `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
839
852
  const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
840
853
  reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
841
854
  await appendTaskEvent(task.id, event);
@@ -1014,6 +1027,7 @@ export async function createFollowupWorker({
1014
1027
  contracts,
1015
1028
  externalOutputs,
1016
1029
  networkAccess,
1030
+ writableRoots,
1017
1031
  maxRunMs,
1018
1032
  maxTotalMs
1019
1033
  }) {
@@ -1061,6 +1075,7 @@ export async function createFollowupWorker({
1061
1075
  contracts: contracts ?? parent.input_context?.contracts ?? [],
1062
1076
  externalOutputs: externalOutputs ?? parent.guard_policy?.externalOutputs ?? [],
1063
1077
  networkAccess: networkAccess ?? parent.guard_policy?.networkAccess ?? false,
1078
+ writableRoots: writableRoots ?? parent.guard_policy?.writableRoots ?? [],
1064
1079
  maxRunMs: maxRunMs ?? parent.guard_policy?.maxRunMs ?? null,
1065
1080
  maxTotalMs: maxTotalMs ?? parent.guard_policy?.maxTotalMs ?? null,
1066
1081
  goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
package/src/mcp-server.js CHANGED
@@ -577,7 +577,7 @@ server.registerTool(
577
577
  {
578
578
  title: "Create Codex worker",
579
579
  description:
580
- "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write (empty only for a read-only verifier), goal records what the worker is for. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them in the worker's worktree after codex exits, each must exit 0, and the worker sees them in its prompt so it can run them first. Write the check for this step (a test file, a file that must exist, an endpoint that must answer), not the whole suite; a check on another machine goes through ssh. They run with the supervisor's own privileges, as if you ran them yourself. The verdict shows as acceptance on wait, the overview and get_worker_result, and land_codex_worker refuses while it is failed.",
580
+ "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write, and an empty list is the deliberate promise that nothing lands, which is how a read-only verifier or a research worker is dispatched. The worker is not only an editor: a read-only worker gets no network and may run any read command, and a research worker runs with sandbox \"workspace-write\", networkAccess: true and ownedPaths: [] so it can fetch, keep notes in its own throwaway worktree and never merge anything. Reading is never exclusive; only writes conflict. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them in the worker's worktree after codex exits, each must exit 0, and the worker sees them in its prompt so it can run them first. Write the check for this step (a test file, a file that must exist, an endpoint that must answer), not the whole suite; a check on another machine goes through ssh. They run with the supervisor's own privileges, as if you ran them yourself. The verdict shows as acceptance on wait, the overview and get_worker_result, and land_codex_worker refuses while it is failed. The worker's sandbox may write the worktree, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
581
581
  inputSchema: {
582
582
  title: z.string().optional(),
583
583
  task: z.string().min(1),
@@ -592,8 +592,8 @@ server.registerTool(
592
592
  model: z.string().optional(),
593
593
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
594
594
  skipGitRepoCheck: z.boolean().default(true),
595
- // Empty only for a read-only worker (a verifier): it writes nothing,
596
- // so it owns nothing.
595
+ // Empty is the promise that nothing lands: a read-only verifier, or a
596
+ // research worker that reads, fetches and reports but merges nothing.
597
597
  ownedPaths: z.array(z.string().min(1)),
598
598
  forbid: z.array(z.string().min(1)).max(100).optional(),
599
599
  allowedCommands: z.array(z.string().min(1)).max(100).optional(),
@@ -601,6 +601,10 @@ server.registerTool(
601
601
  contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
602
602
  externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
603
603
  networkAccess: z.boolean().default(false),
604
+ // Extra absolute directories the sandbox may write. The OS cache
605
+ // directory is already writable; this is for toolchains that keep a
606
+ // cache somewhere else (~/.m2, ~/.gradle, a vendored mirror).
607
+ writableRoots: z.array(z.string().min(1)).max(20).optional(),
604
608
  maxRunMs: z.number().int().min(1000).max(86400000).optional(),
605
609
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
606
610
  goal: z.object({
@@ -657,6 +661,7 @@ server.registerTool(
657
661
  contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
658
662
  externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
659
663
  networkAccess: z.boolean().optional(),
664
+ writableRoots: z.array(z.string().min(1)).max(20).optional(),
660
665
  maxRunMs: z.number().int().min(1000).max(86400000).optional(),
661
666
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
662
667
  goal: z
package/src/prompt.js CHANGED
@@ -46,6 +46,36 @@ export function buildGoalPreamble({ objective, tokenBudget = null, resume = fals
46
46
 
47
47
  export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
48
48
 
49
+ // The first thing a worker reads, and the only place the run's write boundary
50
+ // is stated. A worker is not always an editor: a read-only one can only read,
51
+ // and one with no ownedPaths lands nothing, so both are told what their shell
52
+ // may do instead of being told to use apply_patch they cannot use.
53
+ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false } = {}) {
54
+ const forbidden = JSON.stringify(forbid);
55
+ if (sandbox === "read-only") {
56
+ return [
57
+ "Runtime supervisor guard: this is a read-only task.",
58
+ "The sandbox denies every file write, the temp directory included, and it has no network, so do not try to write files, fetch URLs or install anything: they fail and waste the turn.",
59
+ "Run the read commands you need (rg, cat, git, jq, the project's own read-only tools) and put the findings in the final report.",
60
+ `Forbidden: ${forbidden}.`
61
+ ].join(" ");
62
+ }
63
+ if (Array.isArray(ownedPaths) && ownedPaths.length === 0) {
64
+ return [
65
+ "Runtime supervisor guard: this worker lands nothing: no ownedPaths means nothing it writes is ever merged into the project.",
66
+ "Its worktree is a scratch copy, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.",
67
+ networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
68
+ `Forbidden: ${forbidden}.`,
69
+ "Report what you found and name the files a writer would have to change."
70
+ ].join(" ");
71
+ }
72
+ // A model whose toolset has no apply_patch tool sends the patch through the
73
+ // shell as a heredoc; the guard accepts that shape too, so the worker is told
74
+ // about it instead of stalling on a tool it does not have.
75
+ const shellEdit = "If your toolset has no apply_patch tool, run it through the shell as apply_patch <<'EOF' ... EOF; the guard checks the file paths the same way. A declared command ending in * is a prefix, so go test ./internal/* covers go test ./internal/service -run TestX.";
76
+ return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} Shell verification must exactly match declared commands ${JSON.stringify(allowedCommands)}. Forbidden: ${forbidden}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard.`;
77
+ }
78
+
49
79
  // The acceptance commands are shown to the worker. Hiding them would not
50
80
  // stop a worker from gaming a check (it can see the tests in the tree
51
81
  // anyway) and would stop it from running them before it reports, which is
@@ -73,6 +103,7 @@ export function buildReportPreamble({ resume = false, acceptance = null } = {})
73
103
  return withAcceptance([
74
104
  "Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
75
105
  "Return JSON with exactly result:string, verification:string[], not_done:string[]; --output-schema enforces these fields. Cover the following content in those fields.",
106
+ "Write that JSON value on its own: no markdown code fences and nothing before or after it.",
76
107
  "Keep each verification entry concise: command name, exit code and key evidence; avoid embedding long quoted shell source. Ensure arrays and the object are fully closed and all strings use valid JSON escaping.",
77
108
  "1. Result: what is done, in two or three sentences. Say plainly what is not done.",
78
109
  "2. Verification: every command you ran to check the work, its exit code, and the output lines that prove the result. Write \"not verified\" if you ran none.",
@@ -0,0 +1,18 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ // A worker runs in Codex's workspace-write sandbox, which may write the
6
+ // worktree and the temp directory and nothing else. Every toolchain that keeps
7
+ // a build cache in the OS cache directory then dies on permissions before it
8
+ // runs any project code (Go's ~/Library/Caches/go-build on macOS is the one
9
+ // seen in practice). Naming one environment variable per language does not
10
+ // hold: the next language adds another name and another patch. The sandbox
11
+ // instead gets the OS cache directory itself as a writable root, which is
12
+ // where those default caches live on every platform.
13
+ export function cacheRoots({ env = process.env, platform = process.platform, home = homedir(), exists = existsSync } = {}) {
14
+ const candidates = platform === "win32"
15
+ ? [env.LOCALAPPDATA]
16
+ : [env.XDG_CACHE_HOME, platform === "darwin" ? join(home, "Library", "Caches") : null, join(home, ".cache")];
17
+ return [...new Set(candidates.map((dir) => dir?.trim()).filter(Boolean))].filter((dir) => exists(dir));
18
+ }
package/src/setup.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import { execFile } from "node:child_process";
13
13
  import { existsSync, readdirSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
- import { dirname, join } from "node:path";
15
+ import { basename, dirname, isAbsolute, join } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { promisify } from "node:util";
18
18
  import {
@@ -42,7 +42,7 @@ const CLIENTS = [
42
42
  {
43
43
  ...SKILL_ROOTS.claude,
44
44
  binary: "claude",
45
- binEnv: null,
45
+ binEnv: "CLAUDE_BIN",
46
46
  npmEntry: { pkg: "@anthropic-ai/claude-code", bin: "bin/claude.exe" }
47
47
  },
48
48
  { ...SKILL_ROOTS.agents, binary: null },
@@ -151,7 +151,9 @@ function versionManagerBinDirs() {
151
151
  // instead (see bin-resolver.js).
152
152
  function locateClient(binary) {
153
153
  if (!binary) return null;
154
- const path = findBinaryPath(binary, {
154
+ const client = CLIENTS.find((entry) => entry.binary === binary);
155
+ const configured = client?.binEnv && process.env[client.binEnv]?.trim();
156
+ const path = findBinaryPath(configured || binary, {
155
157
  extraDirs: [...EXTRA_BIN_DIRS, ...versionManagerBinDirs()]
156
158
  });
157
159
  if (!path) return null;
@@ -167,25 +169,34 @@ function selectClients(options) {
167
169
  return CLIENTS.filter((client) => {
168
170
  if (options.targets && !options.targets.includes(client.id)) return false;
169
171
  if (client.binary && locateClient(client.binary)) return true;
170
- return existsSync(client.skillRoot);
172
+ return existsSync(client.skillRoot) || (client.binary && existsSync(dirname(client.skillRoot)));
171
173
  });
172
174
  }
173
175
 
174
- async function mcpAlreadyRegistered(target, options) {
175
- if (options.dryRun) return false;
176
+ async function registeredMcp(target, client) {
176
177
  try {
177
- await runClient(target, ["mcp", "get", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
178
- return true;
179
- } catch {
180
- return false;
178
+ const { stdout } = await runClient(target, ["mcp", "get", MCP_NAME, ...(client.id === "codex" ? ["--json"] : [])], { timeout: CLIENT_TIMEOUT_MS });
179
+ if (client.id === "codex") {
180
+ const value = JSON.parse(stdout);
181
+ const transport = value.transport ?? value;
182
+ return { command: transport.command, args: transport.args ?? [], env: transport.env ?? {}, cwd: transport.cwd, enabled: value.enabled !== false, userScope: true };
183
+ }
184
+ const command = stdout.match(/^\s*Command: (.+)$/m)?.[1]?.trim();
185
+ const args = stdout.match(/^\s*Args: (.*)$/m)?.[1]?.trim();
186
+ const environment = stdout.split(/\n[ \t]*Environment:[ \t]*\r?\n/)[1]?.split(/(?:^|\n)[ \t]*To remove/)[0]?.trim();
187
+ return { command, args: args ? [args] : [], env: environment ? { custom: true } : {}, enabled: !/Status:.*Disabled/i.test(stdout), userScope: /Scope: User config/.test(stdout) };
188
+ } catch (error) {
189
+ const message = `${error.stdout ?? ""}${error.stderr ?? ""}${error.message}`;
190
+ if (/not found|no mcp server|could not find|does not exist/i.test(message)) return null;
191
+ throw new Error(`cannot read ${client.label} MCP registration: ${error.message.split("\n")[0]}`);
181
192
  }
182
193
  }
183
194
 
184
195
  async function registerMcp(client, options, log, warn) {
185
196
  const target = locateClient(client.binary);
186
197
  if (!target) {
187
- log(`mcp ${client.label}: skipped (no ${client.binary} found)`);
188
- return "skipped";
198
+ warn(`mcp ${client.label}: no ${client.binary} CLI found; install it or set ${client.binEnv} to its executable, then run "codex-supervisor-setup"`);
199
+ return "failed";
189
200
  }
190
201
  if (target.shim) {
191
202
  warn(
@@ -193,9 +204,21 @@ async function registerMcp(client, options, log, warn) {
193
204
  );
194
205
  return "failed";
195
206
  }
196
- if (await mcpAlreadyRegistered(target, options)) {
197
- log(`mcp ${client.label}: already registered`);
198
- return "unchanged";
207
+ let previous;
208
+ try { previous = options.dryRun ? null : await registeredMcp(target, client); }
209
+ catch (error) { warn(`mcp ${client.label}: ${error.message}`); return "failed"; }
210
+ if (previous) {
211
+ const same = previous.userScope && previous.command === process.execPath && previous.args.length === 1 && previous.args[0] === serverEntry;
212
+ if (same && previous.enabled) { log(`mcp ${client.label}: already registered at this installation`); return "unchanged"; }
213
+ const managed = previous.userScope && previous.enabled && !previous.cwd && Object.keys(previous.env).length === 0
214
+ && ["node", "node.exe"].includes(basename(previous.command ?? "").toLowerCase())
215
+ && previous.args.length === 1 && isAbsolute(previous.args[0])
216
+ && /(?:^|[\\/])codex-supervisor-mcp[\\/]src[\\/]mcp-server\.js$/.test(previous.args[0])
217
+ && (/[\\/]node_modules[\\/]/.test(previous.args[0]) || !existsSync(previous.args[0]));
218
+ if (!managed) {
219
+ warn(`mcp ${client.label}: existing custom, disabled or project registration preserved; inspect "${client.binary} mcp get ${MCP_NAME}" before replacing it`);
220
+ return "failed";
221
+ }
199
222
  }
200
223
 
201
224
  const args =
@@ -204,14 +227,25 @@ async function registerMcp(client, options, log, warn) {
204
227
  : ["mcp", "add", MCP_NAME, "--", process.execPath, serverEntry];
205
228
 
206
229
  if (options.dryRun) {
230
+ if (previous) log(`mcp ${client.label}: would repair stale package registration`);
207
231
  log(`mcp ${client.label}: would run ${client.binary} ${args.join(" ")}`);
208
232
  return "would-register";
209
233
  }
210
234
  try {
235
+ if (previous) await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
211
236
  await runClient(target, args, { timeout: CLIENT_TIMEOUT_MS });
212
- log(`mcp ${client.label}: registered`);
237
+ const actual = await registeredMcp(target, client);
238
+ if (!actual || actual.command !== process.execPath || actual.args.length !== 1 || actual.args[0] !== serverEntry || !actual.enabled) throw new Error("registration command succeeded but read-back does not match this package");
239
+ log(`mcp ${client.label}: ${previous ? "repaired" : "registered"}`);
213
240
  return "registered";
214
241
  } catch (error) {
242
+ if (previous) {
243
+ try {
244
+ await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS }).catch(() => {});
245
+ const restore = client.id === "claude" ? ["mcp", "add", "-s", "user", MCP_NAME, "--", previous.command, ...previous.args] : ["mcp", "add", MCP_NAME, "--", previous.command, ...previous.args];
246
+ await runClient(target, restore, { timeout: CLIENT_TIMEOUT_MS });
247
+ } catch (restoreError) { warn(`mcp ${client.label}: restoring the original registration failed (${restoreError.message.split("\n")[0]})`); }
248
+ }
215
249
  warn(
216
250
  `mcp ${client.label}: registration failed (${error.message.split("\n")[0]}) ` +
217
251
  `- run "codex-supervisor-setup" once ${client.label} is working`
@@ -240,27 +274,31 @@ async function main() {
240
274
  const log = options.quiet ? () => {} : (line) => console.log(line);
241
275
  const warn = (line) => console.error(line);
242
276
  const clients = selectClients(options);
277
+ const missingTargets = options.targets?.filter((id) => !clients.some((client) => client.id === id)) ?? [];
278
+ if (missingTargets.length) warn(`setup: requested client(s) not detected: ${missingTargets.join(", ")}; install the CLI or set CLAUDE_BIN / CODEX_BIN`);
243
279
 
244
280
  if (clients.length === 0) {
245
- log("setup: no Claude Code / Codex client detected; nothing to do");
246
- return 0;
281
+ warn("setup: no Claude Code / Codex client detected; MCP was not registered. Install a client, then run codex-supervisor-setup.");
282
+ return options.targets?.length && !options.auto ? 1 : 0;
247
283
  }
248
284
 
249
285
  log(`setup: ${options.dryRun ? "dry run against" : "configuring"} ${clients.map((client) => client.label).join(", ")}`);
250
286
 
287
+ let failures = missingTargets.length;
251
288
  if (options.skills) {
252
289
  for (const client of clients) {
253
- await installSkill(client, options, log);
290
+ try { await installSkill(client, options, log); }
291
+ catch (error) { failures += 1; warn(`skill ${client.label}: install failed (${error.message.split("\n")[0]}); MCP registration will still be attempted`); }
254
292
  }
255
293
  }
256
294
  if (options.mcp) {
257
295
  for (const client of clients.filter((client) => client.binary)) {
258
- await registerMcp(client, options, log, warn);
296
+ if (await registerMcp(client, options, log, warn) === "failed") failures += 1;
259
297
  }
260
298
  }
261
299
 
262
- log("setup: done");
263
- return 0;
300
+ log(failures ? `setup: ${failures} setup step(s) require repair` : "setup: done");
301
+ return failures && !options.auto ? 1 : 0;
264
302
  }
265
303
 
266
304
  try {
package/src/skill-sync.js CHANGED
@@ -18,9 +18,9 @@ export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");
18
18
  export function skillRoots() {
19
19
  const home = homedir();
20
20
  return {
21
- claude: { id: "claude", label: "Claude Code", skillRoot: join(home, ".claude", "skills") },
21
+ claude: { id: "claude", label: "Claude Code", skillRoot: join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude"), "skills") },
22
22
  agents: { id: "agents", label: "~/.agents", skillRoot: join(home, ".agents", "skills") },
23
- codex: { id: "codex", label: "Codex", skillRoot: join(home, ".codex", "skills") }
23
+ codex: { id: "codex", label: "Codex", skillRoot: join(process.env.CODEX_HOME?.trim() || join(home, ".codex"), "skills") }
24
24
  };
25
25
  }
26
26
 
package/src/tool-guard.js CHANGED
@@ -19,9 +19,102 @@ function inside(path, owner) {
19
19
  return !isAbsolute(part) && part !== ".." && !part.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
20
20
  }
21
21
 
22
+ const PATCH_PATH = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm;
23
+
24
+ function patchPaths(patchText) {
25
+ return [...patchText.matchAll(PATCH_PATH)].map((match) => match[1]);
26
+ }
27
+
28
+ // Codex 0.162 runs a patch through the shell tool when the model has no
29
+ // separate apply_patch tool: the call arrives as
30
+ //
31
+ // apply_patch <<'EOF'
32
+ // *** Begin Patch
33
+ // ...
34
+ // *** End Patch
35
+ // EOF
36
+ //
37
+ // Without this branch the guard denies it as an undeclared shell command and a
38
+ // worker on such a model can never edit a file. Only a quoted heredoc counts:
39
+ // an unquoted one would expand $() and backticks inside the body before the
40
+ // patch runs. Nothing may follow the closing delimiter, so an "EOF && rm -rf x"
41
+ // tail never qualifies.
42
+ const PATCH_HEREDOC = /^\s*(?:\S*\/)?apply_patch\s+<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1\s*\r?\n([\s\S]*?)\r?\n\2\s*$/;
43
+
44
+ function patchFromHeredoc(command) {
45
+ const match = command.match(PATCH_HEREDOC);
46
+ if (!match) return null;
47
+ const body = match[3];
48
+ return body.includes("*** Begin Patch") && body.includes("*** End Patch") ? body : null;
49
+ }
50
+
51
+ // The one place a patch's targets are judged, shared by the native tool and the
52
+ // shell form so both enforce the same ownership.
53
+ function judgePatch(paths, { event, policy, readOnly, deny }) {
54
+ if (readOnly) return deny("read-only worker: the sandbox denies every write, including the temp directory; report the change instead of editing");
55
+ if (!paths.length) return deny("patch has no recognized file paths");
56
+ try {
57
+ // With no ownedPaths the worker may still keep scratch notes, but only
58
+ // inside its own worktree, which is never landed.
59
+ const owners = policy.ownedPaths.length ? policy.ownedPaths.map(canonical) : [canonical(policy.worktree ?? policy.cwd)];
60
+ for (const path of paths) {
61
+ const target = canonical(resolve(event.cwd ?? policy.cwd, path));
62
+ if (!owners.some((owner) => inside(target, owner))) return deny(policy.ownedPaths.length
63
+ ? "outside ownedPaths: " + path
64
+ : "outside this worker's own worktree: " + path);
65
+ }
66
+ } catch (error) { return deny("cannot prove patch ownership: " + error.message); }
67
+ return { allow: true, reason: policy.ownedPaths.length ? "owned patch" : "scratch patch in the worker's own worktree" };
68
+ }
69
+
70
+ // A writing worker may still look around between edits. These are the safe
71
+ // reads; anything that can write (sed -i, find -delete/-exec, jq -i, tee,
72
+ // redirects) stays out. The guard is not a filesystem sandbox, so a miss only
73
+ // costs an unowned file inside the worker's own worktree, which land refuses.
74
+ const SIMPLE_READ = /^(?:pwd|ls|cat|head|tail|rg|grep|wc|sort|uniq|cut|tr|file|stat|du|df|date|which|basename|dirname|realpath|jq|sed|find|tree|nl|od|strings|shasum|sha256sum|cksum|awk)(?:\s|$)/;
75
+ const VERSION_PROBE = /^(?:go|node|npm|npx|java|javac|mvn|gradle|python3?|pip3?|rustc|cargo|dotnet|php|ruby|deno|bun|tsc|cmake|make|git)\s+(?:-v|--version|version|-h|--help)(?:\s|$)/;
76
+ const GIT_READ = /^git\s+(?:status|diff|show|log|rev-parse|rev-list|grep|branch|remote|tag|describe|ls-files|blame|shortlog|cat-file|name-rev|for-each-ref|version|config\s+--get|worktree\s+list)(?:\s|$)/;
77
+
78
+ // Shell syntax that can chain, redirect or execute. A bare $VAR is allowed:
79
+ // an expansion is not re-parsed as syntax, which is what lets awk programs
80
+ // such as {print $1} through, while $(...) and ${...} stay out.
81
+ const SHELL_SYNTAX = /[;&<>()`\n\r]|\$\(|\$\{/;
82
+
83
+ function readOnlySegment(segment) {
84
+ const text = segment.trim();
85
+ if (!text) return false;
86
+ if (/(?:^|\s)--(?:pre|ext-diff|output|exec)(?:=|\s|$)/.test(text)) return false;
87
+ if (/^git(?:\s|$)/.test(text)) return GIT_READ.test(text);
88
+ if (/^sed(?:\s|$)/.test(text)) return !/(?:^|\s)-i(?:\s|$)/.test(text);
89
+ if (/^find(?:\s|$)/.test(text)) return !/(?:^|\s)-(?:exec|execdir|ok|okdir|delete|fprint|fprintf|fls)(?:\s|$)/.test(text);
90
+ if (/^jq(?:\s|$)/.test(text)) return !/(?:^|\s)(?:-i|--in-place)(?:\s|$)/.test(text);
91
+ if (/^go(?:\s|$)/.test(text)) return /^go\s+(?:env|version)(?:\s|$)/.test(text);
92
+ return SIMPLE_READ.test(text) || VERSION_PROBE.test(text);
93
+ }
94
+
95
+ // A pipe only reads if every segment reads: "rg x | head" is fine, while
96
+ // "cat f | tee out" or "rg x | sh" is not. Any other metacharacter refuses too.
97
+ function isReadCommand(command) {
98
+ const text = command.trim();
99
+ if (SHELL_SYNTAX.test(text)) return false;
100
+ return text.split("|").every((segment) => readOnlySegment(segment));
101
+ }
102
+
103
+
22
104
  export function evaluateToolUse(event, policy) {
23
105
  const deny = (reason) => ({ allow: false, reason });
24
106
  if (!policy || !Array.isArray(policy.ownedPaths) || !policy.cwd) return deny("missing supervisor guard policy");
107
+ // Who needs the shell allowlist? It exists to stop a writing worker from
108
+ // going around ownedPaths. Two shapes have no landable write boundary left:
109
+ // the read-only sandbox denies every file write, temp directory included, and
110
+ // a workspace-write worker with no ownedPaths can only write its own throwaway
111
+ // worktree, its temp dir and the OS cache dir while land refuses everything it
112
+ // produced. Both are what a research worker looks like, and the allowlist would
113
+ // only stop it from running curl, gh or python.
114
+ // danger-full-access keeps the allowlist: there the sandbox is gone.
115
+ const landsNothing = policy.sandbox === "read-only"
116
+ || (policy.sandbox === "workspace-write" && policy.ownedPaths.length === 0);
117
+ const readOnly = policy.sandbox === "read-only";
25
118
  const tool = event.tool_name;
26
119
  const input = event.tool_input;
27
120
  const command = typeof input === "string" ? input : input?.command;
@@ -29,28 +122,36 @@ export function evaluateToolUse(event, policy) {
29
122
  if (typeof command !== "string") return deny("invalid shell input");
30
123
  const normalized = command.replace(/\\\r?\n/g, "").replace(/\s+/g, " ").trim();
31
124
  for (const forbidden of policy.forbid ?? []) {
32
- if (normalized.toLowerCase().includes(forbidden.toLowerCase())) return deny(`forbidden command: ${forbidden}`);
125
+ if (normalized.toLowerCase().includes(forbidden.toLowerCase())) return deny("forbidden command: " + forbidden);
33
126
  }
127
+ // The patch is judged before the shapes below: a read-only worker gets a
128
+ // clearer refusal than the OS one, and a no-land worker still cannot patch
129
+ // outside its own worktree.
130
+ const shellPatch = patchFromHeredoc(command);
131
+ if (shellPatch) return judgePatch(patchPaths(shellPatch), { event, policy, readOnly, deny });
132
+ // Reading is never exclusive: no branch below looks at another worker's
133
+ // ownedPaths, so two workers may read the same file at the same time.
134
+ if (landsNothing) return { allow: true, reason: readOnly
135
+ ? "read-only sandbox: every write is denied by the OS, so shell commands need no allowlist"
136
+ : "no landable path: writes stay in this worker's own worktree" };
34
137
  // Validation lines are a dispatcher's explicit executable contract, just
35
- // like acceptance. They can have side effects and are never inferred from
36
- // the model's own report. Arbitrary shell programs are not path sandboxes.
138
+ // like acceptance. They can have side effects and are never inferred from the
139
+ // model's own report. Arbitrary shell programs are not path sandboxes.
37
140
  if ((policy.allowedCommands ?? []).some((entry) => entry.trim() === command.trim())) return { allow: true, reason: "declared validation command" };
38
- if (!/[;&|<>`$()\n\r]/.test(command) && !/--(?:pre|ext-diff|output|exec)(?:=|\s|$)/.test(command)
39
- && /^(?:pwd|ls|cat|head|tail|rg|wc|git (?:status|diff|show|log|rev-parse))(?:\s|$)/.test(command.trim())) return { allow: true, reason: "read command" };
40
- return deny("undeclared shell command; use apply_patch for edits or a declared validation command");
141
+ // A declaration ending in * is a prefix pattern, so a declared
142
+ // "go test ./internal/*" covers "go test ./internal/service -run TestX".
143
+ // Only a single command with no metacharacters: a prefix must not smuggle
144
+ // in a second command behind a semicolon.
145
+ if (!SHELL_SYNTAX.test(command)) {
146
+ const prefixes = (policy.allowedCommands ?? []).map((entry) => entry.trim()).filter((entry) => entry.endsWith("*")).map((entry) => entry.slice(0, -1));
147
+ if (prefixes.some((prefix) => prefix && command.trim().startsWith(prefix))) return { allow: true, reason: "declared command prefix" };
148
+ }
149
+ if (isReadCommand(command)) return { allow: true, reason: "read command" };
150
+ return deny("undeclared shell command; edit with apply_patch (the tool, or apply_patch <<'EOF' ... EOF in the shell) or declare the command");
41
151
  }
42
152
  if (tool === "apply_patch") {
43
153
  if (typeof command !== "string" || !command.startsWith("*** Begin Patch")) return deny("invalid patch input");
44
- const paths = [...command.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)].map((match) => match[1]);
45
- if (!paths.length) return deny("patch has no recognized file paths");
46
- try {
47
- const owners = policy.ownedPaths.map(canonical);
48
- for (const path of paths) {
49
- const target = canonical(resolve(event.cwd ?? policy.cwd, path));
50
- if (!owners.some((owner) => inside(target, owner))) return deny(`outside ownedPaths: ${path}`);
51
- }
52
- } catch (error) { return deny(`cannot prove patch ownership: ${error.message}`); }
53
- return { allow: true, reason: "owned patch" };
154
+ return judgePatch(patchPaths(command), { event, policy, readOnly, deny });
54
155
  }
55
156
  return { allow: true, reason: "tool is outside the Bash/apply_patch policy" };
56
157
  }
@@ -60,7 +161,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
60
161
  for await (const chunk of process.stdin) input += chunk;
61
162
  let decision;
62
163
  try { decision = evaluateToolUse(JSON.parse(input), JSON.parse(process.env.CODEX_SUPERVISOR_GUARD_POLICY ?? "null")); }
63
- catch (error) { decision = { allow: false, reason: `invalid supervisor guard input: ${error.message}` }; }
164
+ catch (error) { decision = { allow: false, reason: "invalid supervisor guard input: " + error.message }; }
64
165
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
65
166
  permissionDecision: decision.allow ? "allow" : "deny", permissionDecisionReason: decision.reason } }) + "\n");
66
167
  }
168
+
@@ -1,15 +1,37 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  export const workerReportSchemaPath = fileURLToPath(new URL("./worker-report.schema.json", import.meta.url));
3
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
+
4
22
  export function parseWorkerReport(text) {
5
- try {
6
- const value = JSON.parse(text);
7
- if (!value || typeof value !== "object" || Array.isArray(value)
8
- || Object.keys(value).sort().join(",") !== "not_done,result,verification"
9
- || typeof value.result !== "string" || !Array.isArray(value.verification) || !Array.isArray(value.not_done)
10
- || [...value.verification, ...value.not_done].some((entry) => typeof entry !== "string")) {
11
- throw new Error("report must contain result:string, verification:string[], not_done:string[] only");
12
- }
13
- return { format: "json_schema", valid: true, report: value };
14
- } catch (error) { return { format: "json_schema", valid: false, error: error.message }; }
23
+ if (typeof text !== "string" || !text.trim()) return { format: "json_schema", valid: false, error: "worker wrote no final report" };
24
+ let parseError = null;
25
+ 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 }) };
35
+ }
36
+ return { format: "json_schema", valid: false, error: parseError?.message ?? "report is not JSON" };
15
37
  }
package/src/worktree.js CHANGED
@@ -258,7 +258,15 @@ export function baseBehind(projectRoot, baseCommit) {
258
258
  if (error.status === 1) containsBase = false;
259
259
  else return { behind: null, contains_base: null, ref };
260
260
  }
261
- return { behind: Number.isFinite(behind) ? behind : null, contains_base: containsBase, ref };
261
+ // When the recorded base is not an ancestor of the directory's current
262
+ // HEAD, the parent thread switched branches or the worktree was cut from
263
+ // another line: the count then describes unrelated history, so it is
264
+ // reported as unknown instead of as "the worker is behind".
265
+ if (!containsBase) {
266
+ return { behind: null, contains_base: false, ref,
267
+ note: `${baseCommit.slice(0, 12)} is not an ancestor of ${ref}; the directory is on a different line, so behind is unknown` };
268
+ }
269
+ return { behind: Number.isFinite(behind) ? behind : null, contains_base: true, ref };
262
270
  } catch {
263
271
  return { behind: null, contains_base: null, ref };
264
272
  }