codex-supervisor-mcp 0.13.2 → 0.13.4
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 +17 -7
- package/README.md +16 -8
- package/package.json +1 -1
- package/skills/codex-supervisor/SKILL.md +10 -3
- package/src/codex-runner.js +97 -35
- package/src/landing.js +77 -5
- package/src/mcp-server.js +180 -59
- package/src/prompt.js +9 -6
- package/src/task-store.js +76 -0
- package/src/worker-changes.js +21 -1
- package/src/worker-report.js +13 -0
package/README.en.md
CHANGED
|
@@ -151,20 +151,20 @@ Thirty-nine.
|
|
|
151
151
|
|
|
152
152
|
| Tool | Arguments | What it does |
|
|
153
153
|
|---|---|---|
|
|
154
|
-
| `check_workers` | none | Report newly settled runs and
|
|
154
|
+
| `check_workers` | none | Report newly settled runs, actionable failures and active-thread handoff reminders once per run; never cancel or replace a live worker for its token count. Recover a new-format first `lost`, `no_work` or `invalid_report` run once; unchanged state is quiet and a host-scheduled loop with a distinct observer ID supports reconnecting |
|
|
155
155
|
| `overview_delta` | `cursor` | Main-thread incremental view: counters, changed summaries, short attention reason / next action and next_cursor; no prompt, diff, event or capsule history |
|
|
156
156
|
| `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 |
|
|
157
157
|
| `preflight_codex_worker` | `cwd`, `workspaceKind`, `inPlaceAuthorization`, `workspaceSetup`, `ownedPaths`, `probeCommands`, `baseRef`, `sandbox`, `allowedCommands`, `context`, `contracts`, `networkAccess`, `writableRoots` | Run a short probe worker under the exact workspace/base/sandbox/guard contract intended for the later worker; wait for `get_worker_preflight` to report passed before dispatch |
|
|
158
158
|
| `get_worker_preflight` | `task_id` | Read probe command evidence and the immutable runtime contract hash |
|
|
159
159
|
| `create_codex_worker` | `task`, `cwd`, `workspaceKind`, `inPlaceAuthorization`, `workspaceSetup`, **`ownedPaths`**, **`goal`**, `preflight_id`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `maxRunMs`, `maxTotalMs`, `acceptance`, `acceptanceTimeoutMs`, `session_id`, `session_title`, `session_note`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Git defaults to an isolated worktree. A non-Git write must choose `scratch`, or an authorized `in_place_write` with paths and acceptance. `workspaceSetup` prepares dependencies before the worker starts; when `preflight_id` is present its complete runtime contract must match. |
|
|
160
|
-
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, `session_title`, `title`, `cwd`, `sandbox`, `model`, `ownedPaths`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `workspaceKind`, `workspaceSetup`, `goal`, `baseRef`, `acceptance` | A
|
|
161
|
-
| `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 |
|
|
162
|
-
| `wait_codex_workers` | `task_ids`, `mode` (any/all), `timeoutMinutes`, `timeoutMs`, `pollMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for terminal states
|
|
160
|
+
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, `session_title`, `title`, `cwd`, `sandbox`, `model`, `ownedPaths`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `workspaceKind`, `workspaceSetup`, `goal`, `baseRef`, `acceptance` | A fresh session inherits the parent's current branch commit before landing, or the current target HEAD after landing; explicit `baseRef` takes precedence. Parent drafts are not copied; `preflight_id`, `dependsOn` and `skipGitRepoCheck` are unsupported. |
|
|
161
|
+
| `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | Continue the same Codex conversation; `thread_id` stays. When the native goal is still active or its state database cannot prove completion, the resume omits the output schema for that turn to avoid `ActiveTurnOutputSchemaMismatch`. `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 |
|
|
162
|
+
| `wait_codex_workers` | `task_ids`, `mode` (any/all), `timeoutMinutes`, `timeoutMs`, `allowLongWait`, `pollMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for terminal states with a call budget capped at 60 seconds unless the caller explicitly sets `allowLongWait: true` after verifying its client timeout. Returns requested/effective budgets, `timeout_capped` and a termination reason; `compact` gives one row per worker and `emitProgress` optionally sends progress notifications |
|
|
163
163
|
| `get_orchestration_overview` | `status`, `limit` | Every worker in one table, capped at 7000 bytes. Carries `version` and `update` |
|
|
164
164
|
| `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) |
|
|
165
165
|
| `get_worker_diff` | `task_id`, `file`, `hunk`, `pageSize`, `cursor`, `maxChars`, `paths` | What the worker actually changed. The default response is a complete file/hunk index. Select one file and page hunks with `hunk` or `cursor`; `maxChars` without `file` keeps the legacy bounded full-diff mode |
|
|
166
166
|
| `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 |
|
|
167
|
-
| `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | Cherry-pick the worker's `codex/<id>` commits onto the current branch of the dispatch directory: clean target only, a conflict rolls back, a failed acceptance is refused. A malformed report summary no longer blocks an explicit landing when acceptance and the reviewed diff are sound. `commitMessage` first commits
|
|
167
|
+
| `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `includeFollowupParents`, `commitMessages`, `ignoreAcceptance`, `allowOutsideOwned` | Cherry-pick the worker's `codex/<id>` commits onto the current branch of the dispatch directory: clean target only, a conflict rolls back, a failed acceptance is refused. A malformed report summary no longer blocks an explicit landing when acceptance and the reviewed diff are sound. `commitMessage` first commits the current worker's uncommitted edits as one commit. `includeFollowupParents` lands the follow-up chain root first and `commitMessages` supplies a distinct checkpoint message for any task in that chain; `ignoreAcceptance` lands anyway |
|
|
168
168
|
| `verify_delivery_push` | `task_id`, `remote`, `branch` | Fetch a remote branch and prove landed_head is reachable; records push_verified and creates a cleanup plan without pushing or deploying |
|
|
169
169
|
| `cleanup_plan` | `task_ids`, `project_root` | Create a 15-minute SAFE / REVIEW / BLOCKED plan with reasons and fingerprints; SAFE requires explicit acceptance, delivery proof, clean state and no active process/dependency |
|
|
170
170
|
| `apply_cleanup` | `plan_id`, `item_ids` | Revalidate selected SAFE items, fetch the remote and prove landed SHA reachability, then run only git worktree remove/prune |
|
|
@@ -213,6 +213,14 @@ Pass the same setup to `preflight_codex_worker` and the target `create_codex_wor
|
|
|
213
213
|
|
|
214
214
|
`workspaceSetup.links.source` resolves against the dispatch `cwd` and may also be absolute; `path` is always a relative destination inside the worktree. The source must already exist.
|
|
215
215
|
|
|
216
|
+
`create_codex_followup_worker` starts from the current parent `codex/<parent>` checkpoint while the parent is unlanded, or the current target HEAD after it has landed; an explicit `baseRef` takes precedence. Uncommitted parent edits stay with that task, and a missing checkpoint returns `followup_checkpoint_missing`. Review each task's acceptance and diff before calling `land_codex_worker({includeFollowupParents: true})` to cherry-pick the chain root first; a failure preserves earlier landings, and the operation can be repeated after fixing the failing task.
|
|
217
|
+
|
|
218
|
+
When both the worker and run host have exited, the current run's durable `turn.completed` can recover completed status and exit settlement independently of the acceptance verdict. Missing acceptance is marked interrupted and must be rerun before landing; recovery neither removes worktrees nor reruns the worker automatically.
|
|
219
|
+
|
|
220
|
+
Plain-text reports from schema-free resumes remain candidate facts even after acceptance passes; synthesized empty arrays are not promoted as verified claims.
|
|
221
|
+
|
|
222
|
+
Chain landing skips commits proven present on the target and ancestors with no changes; `ignoreAcceptance` and `allowOutsideOwned` apply only to the named leaf, not to its ancestors.
|
|
223
|
+
|
|
216
224
|
When dispatch omits `goal.tokenBudget`, the worker must omit `token_budget` entirely. The runtime guard rejects `0`, `1`, `null` and any invented value. If a budget is supplied explicitly, the worker must use that exact positive integer.
|
|
217
225
|
|
|
218
226
|
Acceptance commands receive `CODEX_SUPERVISOR_TASK_ID`, `CODEX_SUPERVISOR_BASE_COMMIT` and `CODEX_SUPERVISOR_RUN`: the current task, run base and run number, refreshed after rebase/resume.
|
|
@@ -221,9 +229,11 @@ Structured acceptance entries use `{command, reportPath, baseline}`. The baselin
|
|
|
221
229
|
|
|
222
230
|
Landing checks the real diff against ownedPaths before committing drafts; only use allowOutsideOwned for an explicitly approved exception.
|
|
223
231
|
|
|
232
|
+
Worker acceptance runs before the dispatcher commits draft edits, so it should validate functionality and tests. Check clean Git status, commit counts and messages after landing. Inspect the failing check and its run before claiming a verdict is stale; a newer report, external test run or manual commit does not replace supervisor acceptance. Route conflicting requirements to the integration owner for revision and fresh acceptance instead of bypassing the gate with a manual cherry-pick.
|
|
233
|
+
|
|
224
234
|
Session default_acceptance is prepended to local checks; resume uses the latest policy. describe_session returns policy_revision and expected_revision prevents stale edits. waiting_user blocks dispatch/resume until approved. host_goal_sync returns a current-policy /goal command. Replace an active native goal through /goal, or propose the same condition through ProposeGoal for host approval when available. The condition reads the latest session revision and approved scope; MCP does not silently modify or disable the host Stop hook.
|
|
225
235
|
|
|
226
|
-
Wait defaults to 60 seconds and compact rows;
|
|
236
|
+
Wait defaults to 60 seconds and compact rows; longer requests are capped unless `allowLongWait: true` explicitly opts in. `requested_timeout_ms`, `timeout_ms` and `timeout_capped` expose the applied budget. Progress requires both `emitProgress` and a client progress token; it does not extend a host's hard timeout. Reattach an existing background wait instead of creating duplicates, and schedule `check_workers` for long monitoring.
|
|
227
237
|
|
|
228
238
|
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.
|
|
229
239
|
|
|
@@ -235,7 +245,7 @@ An `allowedCommands` entry ending in `*` is a prefix match (so `go test ./intern
|
|
|
235
245
|
|
|
236
246
|
The guard relaxes by workspace shape: a `git_worktree` editor with non-empty `ownedPaths` gets only declared commands and simple reads; `read_only_in_place` cannot write or use network; networked research uses `scratch` under `SUPERVISOR_HOME`, never the source directory; `in_place_write` requires explicit authorization, owned paths and acceptance with before/after manifests. A non-Git `workspace-write` request without `workspaceKind` is refused. A worker capsule names its branch and acceptance source without embedding acceptance commands. Repository facts cross checkouts only when canonical `origin`, repository-relative watched paths and base SHA all match; an unrecognized origin leaves them work-scoped. A fact is append-only expired and excluded from a future worker capsule when its base SHA no longer covers the task, a watched path changed, its declared context content hash changed, or its in-place manifest drifted; explicit dependencies provide only delivery summaries.
|
|
237
247
|
|
|
238
|
-
After reconciliation, check_workers atomically resumes a dead first lost/no_work/invalid_report run once and returns recovery receipts (an invalid report only re-asks for the bare JSON; it does not redo the work). Two consecutive no-output/no-command runs with the same fingerprint become `two_stall` and `needs_attention`, never another blind retry; approval, authentication, permission and quota waits are not retried. Final reports use JSON result/verification/not_done. Parsing safely normalizes a single string field into string[] and one missing closing `]`/`}`; fabricated shapes still fail. The report is a summary: invalid_report preserves the completed lifecycle and attention, does not override the same run's acceptance or reviewed diff, and an explicit landing remains possible. Existing history is labelled legacy_text.
|
|
248
|
+
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). If the current run has a durable `turn.completed` and only its run host failed to record the exit code, the task is recovered as completed with report and attention evidence preserved instead of being marked lost. Two consecutive no-output/no-command runs with the same fingerprint become `two_stall` and `needs_attention`, never another blind retry; approval, authentication, permission and quota waits are not retried. Final reports use JSON result/verification/not_done. Parsing safely normalizes a single string field into string[] and one missing closing `]`/`}`; fabricated shapes still fail. The report is a summary: invalid_report preserves the completed lifecycle and attention, does not override the same run's acceptance or reviewed diff, and an explicit landing remains possible. Existing history is labelled legacy_text.
|
|
239
249
|
|
|
240
250
|
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.
|
|
241
251
|
|
package/README.md
CHANGED
|
@@ -161,20 +161,20 @@ land_codex_worker 核过了,带 commitMessage 代提交并落进集成
|
|
|
161
161
|
|
|
162
162
|
| 工具 | 入参 | 作用 |
|
|
163
163
|
|---|---|---|
|
|
164
|
-
| `check_workers` | 无参 |
|
|
164
|
+
| `check_workers` | 无参 | 返回新终态、故障及长线程交接提醒;同一 run 的 handoff 只提醒一次,不中止或复制活跃 worker。已死的第1轮 `lost` / `no_work` / `invalid_report` 最多恢复一次;用宿主定时调用及独立 CODEX_SUPERVISOR_OBSERVER_ID 接回 |
|
|
165
165
|
| `overview_delta` | `cursor` | 主线程默认轮询入口:只返回 active / needs_attention / ready_to_land / ready_to_clean、cursor 后变化、短版 attention_reason / next_action 和 next_cursor;不返回全量历史、prompt、diff、event 或 worker capsule |
|
|
166
166
|
| `check_acceptance` | `cwd`, `acceptance`, `baseRef`, `timeoutMs` | 派单前实际运行给定验收命令,不建 worker,不证明 worker 完成;数量 grep 会提示不能证明失败名单和必跑执行 |
|
|
167
167
|
| `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;联网和凭据目录仍须显式授权 |
|
|
168
168
|
| `get_worker_preflight` | `task_id` | 返回 probe 的实际 command evidence、运行环境 contract hash、worker outcome 和 `running/passed/failed`;probe 全部执行通过时,报告 JSON 错误或已 exit 0 的 close-handler 缺失只留诊断,不误判环境失败 |
|
|
169
169
|
| `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 |
|
|
170
|
-
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, `session_title`, `title`, `cwd`, `sandbox`, `model`, `ownedPaths`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `workspaceKind`, `workspaceSetup`, `goal`, `baseRef`, `acceptance` |
|
|
171
|
-
| `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | 接同一个 Codex 会话继续跑,`thread_id`
|
|
172
|
-
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` |
|
|
170
|
+
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, `session_title`, `title`, `cwd`, `sandbox`, `model`, `ownedPaths`, `forbid`, `allowedCommands`, `context`, `contracts`, `externalOutputs`, `networkAccess`, `writableRoots`, `workspaceKind`, `workspaceSetup`, `goal`, `baseRef`, `acceptance` | 新会话继承父任务上下文:未 land 用父分支当前提交,已 land 用当前集成 HEAD,显式 `baseRef` 优先。未提交父改动不复制;不支持 `preflight_id`、`dependsOn`、`skipGitRepoCheck` |
|
|
171
|
+
| `resume_codex_worker` | `task_id`, `prompt`, `rebaseOnto`, `acceptance`, `context` | 接同一个 Codex 会话继续跑,`thread_id` 不变。原生 goal 仍 active 或 goal 状态库不可判定时,本轮自动省略 output schema,避免 `ActiveTurnOutputSchemaMismatch`。`rebaseOnto` 先把 worktree 挪到主线新头(stash、跳过已合入补丁、重放新增提交、放回),冲突原样退回不起 worker |
|
|
172
|
+
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `allowLongWait`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态,单次预算默认最多 60 秒,只有确认宿主超时允许后才传 `allowLongWait: true`。返回实际/请求预算与 `timeout_capped`,`termination_reason` 区分 settled / budget_exhausted / client_cancelled;`emitProgress` 可选,每路摘要用 `compact` |
|
|
173
173
|
| `get_orchestration_overview` | `status`, `limit` | 全部 worker 的状态表,封顶 7000 字节。带 `version` 和 `update` |
|
|
174
174
|
| `get_worker_result` | `task_id`, `limit`, `maxChars`, `includeFiles` | worker 自己的汇报,默认截 6000 字节、`truncated` 提示读全。`acceptance` 是 supervisor 替你跑的验收过没过,`verification` 是它自己跑过的命令和退出码,`base_behind` 是主线走了多远(`contains_base: false` 时 `behind` 为 `null`,那是换了线) |
|
|
175
175
|
| `get_worker_diff` | `task_id`, `file`, `hunk`, `pageSize`, `cursor`, `maxChars`, `paths` | worker 实际改了什么。默认完整文件索引与 hunk 数;按 `file` + `hunk`/`cursor` 分页读 patch。显式 `maxChars` 且不传 `file` 保留旧整份限流模式 |
|
|
176
176
|
| `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | 旁路问 worker 一句。线程 fork 成只读侧会话,没网络、没 MCP 工具,worker 本身不动。worker 被 resume 过会自动换新 fork,`fresh` 强制换,`end` 删 |
|
|
177
|
-
| `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝;报告格式错不再单独阻止显式 land。`commitMessage`
|
|
177
|
+
| `land_codex_worker` | `task_id`, `onto`, `commitMessage`, `includeFollowupParents`, `commitMessages`, `ignoreAcceptance`, `allowOutsideOwned` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标要干净,冲突回滚,验收 `failed` 拒绝;报告格式错不再单独阻止显式 land。`commitMessage` 先替当前 worker 把未提交改动提交成一笔;`includeFollowupParents` 按 root-first 落地整条 followup 链,`commitMessages` 给链中各路提供各自的 checkpoint 提交说明 |
|
|
178
178
|
| `verify_delivery_push` | `task_id`, `remote`, `branch` | fetch 指定 remote branch 并证明 `landed_head` 已可达;只读验证,不会 push 或部署。通过后记录 `push_verified` 并生成 cleanup plan |
|
|
179
179
|
| `cleanup_plan` | `task_ids`, `project_root` | 生成 15 分钟有效的 SAFE / REVIEW / BLOCKED 计划,含原因、fingerprint 与回收空间估算;SAFE 必须 acceptance passed、push verified、干净且无活跃依赖/进程 |
|
|
180
180
|
| `apply_cleanup` | `plan_id`, `item_ids` | 只在未过期计划上二次校验 SAFE item、重新 fetch remote 并确认 landed SHA 仍可达后执行 `git worktree remove/prune`;保留 branch、task、events、JSONL、artifacts |
|
|
@@ -223,11 +223,17 @@ MCP schema 必填两个:`ownedPaths` 和 `goal.objective`。写 worker 还必
|
|
|
223
223
|
|
|
224
224
|
`workspaceSetup.links.source` 按派单的 `cwd` 解析,也可以直接写绝对路径;`path` 始终是 worktree 内的相对目标。源目录必须先存在。
|
|
225
225
|
|
|
226
|
+
`create_codex_followup_worker` 在父任务未 land 时继承其 `codex/<parent>` 分支的当前提交,父任务已 land 则从当前集成分支 HEAD 开始;显式 `baseRef` 优先。父 worktree 里没提交的改动仍只属于父任务,父 checkpoint 丢失时返回 `followup_checkpoint_missing`。需要整条接续链落地时调用 `land_codex_worker({includeFollowupParents: true})`,主线程先审各路 acceptance 和 diff,工具再按 root-first 落地;途中失败保留此前已落地的结果,修复后可重复调用。
|
|
227
|
+
|
|
228
|
+
worker 和 run host 都已退出时,当前 run 的 durable `turn.completed` 可以恢复 `completed` 和退出结算,独立保留 acceptance 的通过、失败或中断状态。缺失验收结果标记为 interrupted,仍需重新验收后才能 land;恢复不会删除 worktree 或自动重跑 worker。
|
|
229
|
+
|
|
230
|
+
链式 landing 会跳过已证明在目标分支上的提交和零改动祖先;`ignoreAcceptance` / `allowOutsideOwned` 只作用于指定的 leaf,不自动扩大到祖先。
|
|
231
|
+
|
|
226
232
|
普通 worker 启动时会关闭它继承到的 `codex-supervisor` MCP,不能再派 worker、resume、cancel 或改编排状态;主线程是唯一编排者。其他业务 MCP 不受影响;旁问 fork 仍关闭全部 MCP,因为它只允许只读回答。
|
|
227
233
|
|
|
228
234
|
`session_id` 只负责批次、默认门禁和审批,不再把同批 worker 的标题、汇报或 session objective 自动塞进新 worker。worker 只收到内部编译的 context capsule:L0 只标明 branch 与 acceptance 来源(不塞命令正文)、自身身份/任务、显式依赖的最小交付摘要和路径/SHA 命中的 verified facts;raw event、完整 diff、历史报告、candidate facts 都只可按需读取。repo fact 只有两个 checkout 的 canonical `origin`、repo-relative watched path 和 base SHA 同时匹配时才跨 checkout 可见;无可识别 origin 就保持 work-scoped。事实的 base SHA 不再覆盖、watched path 发生 Git diff、context 输入内容 hash 或非 Git in-place manifest 漂移时会自动追加 `expired` 版本并从 capsule 排除。主线程只看 `get_context_snapshot_meta`,需要证据时再显式 `get_fact` / `get_worker_result` / `get_worker_diff`。
|
|
229
235
|
|
|
230
|
-
worker 的最终 JSON 报告会先记录为该 run 的 `candidate` fact,不能跨 work 自动注入;supervisor acceptance 通过后才生成当前 work 的 `verified` outcome,并带 report/acceptance event 来源、base SHA 与 watched paths。push proof 另存为 retained artifact,verified fact 可回指该 artifact。验收失败、未配置验收或 worker 自报完成都不会升级成共享真相。
|
|
236
|
+
worker 的最终 JSON 报告会先记录为该 run 的 `candidate` fact,不能跨 work 自动注入;supervisor acceptance 通过后才生成当前 work 的 `verified` outcome,并带 report/acceptance event 来源、base SHA 与 watched paths。schema-free resume 的纯文本报告只保留为 candidate,不把合成的空数组当作已验证事实。push proof 另存为 retained artifact,verified fact 可回指该 artifact。验收失败、未配置验收或 worker 自报完成都不会升级成共享真相。
|
|
231
237
|
|
|
232
238
|
交付状态分开:acceptance 通过只是 `verified`,`land_codex_worker` 只是 `landed`,仍不代表远端有这笔提交。需要显式 `verify_delivery_push` fetch 并校验 `landed_head` 已在目标 remote branch 上,才是 `push_verified`;它会自动生成 cleanup plan,SAFE 项进入 `cleanup_eligible`,但永远不会自己删除。该工具绝不代替用户执行 push 或部署。
|
|
233
239
|
|
|
@@ -237,9 +243,11 @@ worker 进程和 supervisor 验收子进程都包含当前 `CODEX_SUPERVISOR_TAS
|
|
|
237
243
|
|
|
238
244
|
落地前按真实 diff 核对 ownedPaths,越界拒绝且不提交草稿;只有用户明确授权时才用 allowOutsideOwned。
|
|
239
245
|
|
|
246
|
+
worker 的 acceptance 在代提交之前执行,应检查功能和测试;`test -z "$(git status --porcelain)"`、提交数量和提交信息检查由主线程放到 land 后执行。验收失败先核对当前 run 的具体失败项,不能仅因报告更新、外部测试通过或主线程补过提交就视旧失败为已解决;契约冲突交规划/集成负责人修订并重新验收,不手工 cherry-pick 绕过。
|
|
247
|
+
|
|
240
248
|
同 session 的 `default_acceptance` 自动加到每路本地检查前;resume 会取最新策略。`describe_session` 返回 policy_revision,改目标/门禁可传 expected_revision 防旧窗口覆盖;waiting_user 拒绝派单与恢复,approved 后再继续。回执host_goal_sync包含按当前策略生成的/goal命令;宿主已有原生goal时用/goal替换条件,支持ProposeGoal时可提议同一条件并走宿主批准。条件要求读取最新session revision及批准范围;MCP不会偷偷修改或禁用宿主Stop hook。
|
|
241
249
|
|
|
242
|
-
wait 默认预算60秒、默认compact
|
|
250
|
+
wait 默认预算60秒、默认compact,过长请求也限制为60秒,返回 `requested_timeout_ms` / `timeout_ms` / `timeout_capped`。确认客户端允许长调用后可显式 `allowLongWait: true`;`emitProgress` 只在请求且客户端传 progress token 时通知,不能延长宿主的硬超时。已有后台 wait 就接回它,不重复开长 wait;长期监控用宿主定时调用 `check_workers`。
|
|
243
251
|
|
|
244
252
|
每路临时注入随包PreToolUse守卫:apply_patch核对全部目标路径(含rename和symlink),forbid拒绝红线;安全只读检查(rg/cat/sed无-i/git只读/jq无-i/find无-exec或-delete)默认允许且不占其他 worker 的写路径,写入/执行/有副作用的 Shell 命令必须显式声明。声明的验证脚本以派单者权限执行,可有副作用,不能当作任意程序的文件沙箱。guard策略随resume/followup继承,不写全局hooks。空跑write run按本轮输出前后内容和命令判断,no_work进入needs_attention;只读任务不因没改文件判空跑。
|
|
245
253
|
|
|
@@ -251,7 +259,7 @@ wait 默认预算60秒、默认compact;includeEvents会选择详细结果(
|
|
|
251
259
|
|
|
252
260
|
守卫按 worker 形状放权:`git_worktree` 编辑 worker 只放声明过的命令和简单读取;`read_only_in_place` 无写入无网络;`scratch` 的联网草稿只能写在 `SUPERVISOR_HOME/scratch/<taskId>`;`in_place_write` 必须有显式授权、ownedPaths 与 acceptance,并保存前后 manifest。非 Git `workspace-write` 没写 `workspaceKind` 会拒绝,绝不默认写用户目录。
|
|
253
261
|
|
|
254
|
-
check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON
|
|
262
|
+
check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON,不重做活)。如果当前 run 已经持久化 `turn.completed`,只是 run host 没落 exit code,supervisor 会从 durable event 恢复为 completed 并保留 report/attention 证据,不再误标 lost。两轮同 fingerprint 的无输出/无命令会升级为 `two_stall` 和 `needs_attention`,不再自动重试;审批、认证、权限和quota等待也不重试,返回recoveries记录。worker最终输出要求JSON result/verification/not_done;解析只做安全修复:字符串字段归一成 string[],以及唯一缺少的 `]`/`}`,伪造字段仍拒绝。报告只是摘要;invalid_report 保持 `completed` 生命周期和 attention,不否定同 run acceptance 和真实 diff,显式 land 仍可用;旧历史标legacy_text。
|
|
255
263
|
|
|
256
264
|
context用绝对文件路径与可选sha256声明材料,最多20份、与contracts合计6000字;文件不超过5 MB。首次派单记录实际哈希,resume校验原材料未变,需要新材料时显式传context。handoff最多1800字/16行,截断明确标记;完整约束和引用单独保留,材料不授予写权限。
|
|
257
265
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.4",
|
|
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.",
|
|
@@ -20,6 +20,7 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
20
20
|
5. 写 worker 先跑同 contract 的 `preflight_codex_worker`。`get_worker_preflight` 必须是 `passed`,再把 preflight task id 填进 `preflight_id`。`check_acceptance` 不能代替 worker 环境预检。
|
|
21
21
|
6. 只要 worker 会 land,就必须有能证明结果的 acceptance。文件存在检查只能当附加条件,不能单独当完成证据。
|
|
22
22
|
7. `workspace-write` worker 不执行 `git add`、`git commit` 或 `amend`。验收通过后由主线程 `land_codex_worker(commitMessage)` 代提交并落地。
|
|
23
|
+
worker acceptance 验功能与实际测试;Git 干净、提交数量和提交信息由主线程在 land 后检查,不能让未提交编辑的 worker 同时满足“必须无 diff”。契约冲突先报告规划/集成负责人修订,不手工 cherry-pick 或忽略门禁绕过。
|
|
23
24
|
8. worker 不 push、不合并、不再派生 worker。临时 `codex/<id>` 分支不是交付物。
|
|
24
25
|
|
|
25
26
|
`preflight_id` 是 AI 派单硬规则。MCP schema 为了兼容旧客户端仍允许省略,但不能把“没被 schema 拒绝”当成可以跳过预检。
|
|
@@ -75,8 +76,9 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
75
76
|
## 等待与状态
|
|
76
77
|
|
|
77
78
|
- 日常增量看 `overview_delta`,保存 `next_cursor`。需要全量状态时才用 `get_orchestration_overview`。
|
|
78
|
-
- 短等用 `wait_codex_workers
|
|
79
|
+
- 短等用 `wait_codex_workers`,默认最多60秒、`compact: true`;`timeout_capped` 表示长请求被限为短等,`still_running` 只表示预算用完。仅确认宿主允许长调用时才传 `allowLongWait: true`;已有后台 wait 就接回,不重复创建。
|
|
79
80
|
- 长任务用宿主 `/loop 5m check_workers`。不同主线程设置不同的 `CODEX_SUPERVISOR_OBSERVER_ID`。
|
|
81
|
+
- `check_workers` 在活跃线程超过交接阈值时每个 run 提醒一次;先看状态与 stage,等当前步骤结算或明确取消后再整理 checkpoint 接续,不能因 token 多重复起同一任务。
|
|
80
82
|
- `idle_seconds` 是距上一条 Codex 事件的时间。`command_running: true` 时长命令可能仍在跑;没有命令且长时间无事件,再查 `get_codex_worker_events`。
|
|
81
83
|
- 不要用 shell 循环 grep `data/runs/*.jsonl` 判断状态。`failed`、`lost`、退出码和恢复状态以 supervisor 状态机为准。
|
|
82
84
|
|
|
@@ -86,9 +88,13 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
86
88
|
2. 读 `get_worker_result`。注意 `commands_run`、命令退出码和 `last_command_failed`,不要只听结论。
|
|
87
89
|
3. 读 `get_worker_diff`。默认先看文件和 hunk 索引,再按 `file` + `hunk`/`cursor` 分页读 patch。
|
|
88
90
|
4. 对不上就问 `ask_codex_worker`。旁路只读,不改 worker 线程。
|
|
89
|
-
5. 要改就 `resume_codex_worker`。不要要求 worker commit 或 amend;主线前进时按需带 `rebaseOnto: "HEAD"`。
|
|
91
|
+
5. 要改就 `resume_codex_worker`。不要要求 worker commit 或 amend;主线前进时按需带 `rebaseOnto: "HEAD"`。原生 goal 未明确 complete 或状态不可读时,supervisor 续跑省略 output schema,避免 `ActiveTurnOutputSchemaMismatch`。
|
|
90
92
|
6. 验收和 diff 都过了,用 `land_codex_worker({commitMessage})` 把未提交改动提交到 worker 分支并 cherry-pick 到当前集成分支。
|
|
91
93
|
|
|
94
|
+
`create_codex_followup_worker` 在父任务未 land 时从其 `codex/<parent>` 当前提交起新 worktree;父任务已 land 则用当前集成 HEAD,显式 `baseRef` 优先。父 worktree 未提交改动留在原任务,checkpoint 丢失时先恢复或明确选新 base。整条接续链先审各路 acceptance 和 diff,再用 `land_codex_worker({includeFollowupParents: true, commitMessages: { [task_id]: "..." }})` 按 root-first 落地;途中失败保留已落地部分,修复后重调,不手工压 WIP。
|
|
95
|
+
|
|
96
|
+
零改动祖先可跳过;`ignoreAcceptance` / `allowOutsideOwned` 只对指定 leaf 生效,不豁免祖先的验收或写入范围。
|
|
97
|
+
|
|
92
98
|
`invalid_report` 不是业务失败。常见情况是单个字符串字段、缺一个 `]`/`}`,或内容完整但 schema 不合规。先让 `check_workers` 做一次 report-only 修复;仍失败时,acceptance 通过且 diff 审过,可以显式 land。报告只是摘要,不是交付证据。
|
|
93
99
|
|
|
94
100
|
## 上下文与事实
|
|
@@ -97,6 +103,7 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
97
103
|
- `session_id` peers、完整事件、完整 diff、历史报告和 candidate facts 不会自动注入。
|
|
98
104
|
- 主线程看事实摘要用 `search_worker_facts`;追溯来源用 `get_fact`;看证据索引用 `get_worker_evidence` / `get_artifact`。
|
|
99
105
|
- worker 的报告先记为 candidate。只有 supervisor acceptance 通过后,才有资格成为当前 work 的 verified outcome。
|
|
106
|
+
- schema-free resume 的纯文本报告只留 candidate;合成的 verification/not_done 空数组不是已验证结论。
|
|
100
107
|
- base SHA、watched path、context hash 或 in-place manifest 变化后,旧 fact 会过期并从后续 capsule 排除。
|
|
101
108
|
|
|
102
109
|
## 中断与恢复
|
|
@@ -104,7 +111,7 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
104
111
|
| 情况 | 处理 |
|
|
105
112
|
|---|---|
|
|
106
113
|
| 主线程挂了 | worker 的独立 run host 会继续记录日志、状态和验收。新窗口用 `get_session_works` 接回 |
|
|
107
|
-
| worker 变 `lost` | `
|
|
114
|
+
| worker 变 `lost` | 当前 run 有 durable `turn.completed` 且 worker/run host 均退出时,reconcile 恢复 completed;验收中断仍需重跑。确实中断才 resume,worktree、改动和 thread id 都保留 |
|
|
108
115
|
| worktree 落后主线 | `resume_codex_worker` 带 `rebaseOnto: "HEAD"` |
|
|
109
116
|
| worker 失败 | 先看 `failure.source` 和 `error`,区分 provider、supervisor、workspace setup、model output、acceptance、worker process |
|
|
110
117
|
| 没有 thread id 的旧行 | 用 `create_codex_followup_worker`,通过文本重述上下文 |
|
package/src/codex-runner.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createWriteStream, existsSync } from "node:fs";
|
|
1
|
+
import { closeSync, createWriteStream, existsSync, openSync } from "node:fs";
|
|
2
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";
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
completeRunRecord,
|
|
20
20
|
getWorkItemForTask,
|
|
21
21
|
recordFact,
|
|
22
|
+
runIdFor,
|
|
22
23
|
updateWorkItemDelivery,
|
|
23
24
|
claimTaskRun,
|
|
24
25
|
releaseTaskRun,
|
|
@@ -34,8 +35,9 @@ import { rebaseWorktree } from "./landing.js";
|
|
|
34
35
|
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
35
36
|
import { appendFile } from "node:fs/promises";
|
|
36
37
|
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
37
|
-
import {
|
|
38
|
+
import { parseWorkerReportForRun, workerReportSchemaPath } from "./worker-report.js";
|
|
38
39
|
import { buildHandoff } from "./handoff.js";
|
|
40
|
+
import { readNativeGoalState } from "./goal-store.js";
|
|
39
41
|
import { compileWorkerContext } from "./context-compiler.js";
|
|
40
42
|
import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
|
|
41
43
|
import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "./worker-preflight.js";
|
|
@@ -72,7 +74,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
72
74
|
validForManifestHash,
|
|
73
75
|
watchedPaths: task.owned_paths ?? []
|
|
74
76
|
});
|
|
75
|
-
if (!acceptancePassed) return;
|
|
77
|
+
if (!acceptancePassed || report.format === "text") return;
|
|
76
78
|
await recordFact({
|
|
77
79
|
workItemId: workItem.id,
|
|
78
80
|
scopeType: "work_item",
|
|
@@ -372,7 +374,7 @@ async function spawnAndAwaitStart(target, args, options) {
|
|
|
372
374
|
// Attaches stream handlers and keeps `record` in the supervisor database.
|
|
373
375
|
// Every write goes through one serialized chain so concurrent stdout/stderr
|
|
374
376
|
// callbacks cannot interleave and persist out of order.
|
|
375
|
-
async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {} }) {
|
|
377
|
+
async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}, outputSchema = true }) {
|
|
376
378
|
const capability = codexRunner.capabilityPreflight();
|
|
377
379
|
if (!capability.ok) return failedStart(record, capability.error);
|
|
378
380
|
const target = capability.target;
|
|
@@ -381,6 +383,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
381
383
|
const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
|
|
382
384
|
const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
|
|
383
385
|
const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
|
|
386
|
+
output_schema: outputSchema,
|
|
384
387
|
goalTokenBudget: record.goal_token_budget ?? null,
|
|
385
388
|
allowedCommands: [
|
|
386
389
|
...(record.guard_policy?.allowedCommands ?? []),
|
|
@@ -396,7 +399,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
396
399
|
const acceptanceCli = fileURLToPath(new URL("./acceptance-cli.js", import.meta.url));
|
|
397
400
|
const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
|
|
398
401
|
const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
|
|
399
|
-
const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
|
|
402
|
+
const configArgs = [...(outputSchema ? ["--output-schema", workerReportSchemaPath] : []), "--dangerously-bypass-hook-trust", "-c",
|
|
400
403
|
`hooks.PreToolUse=[{matcher="Bash|apply_patch|create_goal",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
|
|
401
404
|
// A worker may use its explicitly configured business MCP servers, but it
|
|
402
405
|
// must not inherit this supervisor and create a second orchestration tree.
|
|
@@ -451,6 +454,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
451
454
|
acceptance_results: null,
|
|
452
455
|
attention_reason: null,
|
|
453
456
|
run_evidence: null,
|
|
457
|
+
guard_policy: { ...record.guard_policy, output_schema: outputSchema },
|
|
454
458
|
commands: [],
|
|
455
459
|
last_message: null,
|
|
456
460
|
current_action: null,
|
|
@@ -474,15 +478,22 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
474
478
|
}, 250) : null;
|
|
475
479
|
|
|
476
480
|
let writeChain = Promise.resolve();
|
|
477
|
-
const
|
|
481
|
+
const writeSnapshot = (next) => {
|
|
478
482
|
live = next;
|
|
479
483
|
const snapshot = live;
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
484
|
+
const pending = writeChain.then(() => upsertTask(snapshot));
|
|
485
|
+
// Keep later writes usable after one failed snapshot. Callers that need
|
|
486
|
+
// failure visibility use the returned promise explicitly.
|
|
487
|
+
writeChain = pending.catch(() => {});
|
|
488
|
+
return pending;
|
|
489
|
+
};
|
|
490
|
+
const persist = async (next, label = "persist") => {
|
|
491
|
+
try { await writeSnapshot(next); }
|
|
492
|
+
catch (error) {
|
|
493
|
+
await appendTaskEvent(next.id, { type: "supervisor.persist_failed", label, error: error.message, run: next.run_count },
|
|
494
|
+
{ runId: runIdFor(next.id, next.run_count), actor: "supervisor" }).catch(() => null);
|
|
495
|
+
process.stderr.write(`[codex-supervisor] ${label} failed for ${next.id}: ${error.message}\n`);
|
|
496
|
+
}
|
|
486
497
|
};
|
|
487
498
|
await persist(live);
|
|
488
499
|
const runId = await ensureRunRecord(live, live.run_count);
|
|
@@ -504,6 +515,22 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
504
515
|
let terminalEvent = false;
|
|
505
516
|
let rawReport = null;
|
|
506
517
|
let rawReportEventId = null;
|
|
518
|
+
const projectOutcomeFacts = async (finalRecord, { acceptanceEventId = null, acceptancePassed = false } = {}) => {
|
|
519
|
+
try {
|
|
520
|
+
await recordOutcomeFacts({
|
|
521
|
+
task: finalRecord,
|
|
522
|
+
runId,
|
|
523
|
+
report: finalRecord.run_evidence?.structured_report,
|
|
524
|
+
reportEventId: rawReportEventId,
|
|
525
|
+
acceptanceEventId,
|
|
526
|
+
acceptancePassed
|
|
527
|
+
});
|
|
528
|
+
} catch (error) {
|
|
529
|
+
await appendTaskEvent(finalRecord.id, { type: "supervisor.fact_record_failed", error: error.message, run: live.run_count },
|
|
530
|
+
{ runId, actor: "supervisor" }).catch(() => null);
|
|
531
|
+
process.stderr.write(`[codex-supervisor] fact projection failed for ${finalRecord.id}: ${error.message}\n`);
|
|
532
|
+
}
|
|
533
|
+
};
|
|
507
534
|
const handleLines = async (lines) => {
|
|
508
535
|
const events = [];
|
|
509
536
|
for (const line of lines) {
|
|
@@ -633,9 +660,10 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
633
660
|
next.error = error.message;
|
|
634
661
|
}
|
|
635
662
|
}
|
|
663
|
+
const structuredReport = parseWorkerReportForRun(rawReport, { outputSchema });
|
|
636
664
|
next.run_evidence = {
|
|
637
665
|
run: live.run_count, commands_run: live.commands.length,
|
|
638
|
-
structured_report:
|
|
666
|
+
structured_report: structuredReport,
|
|
639
667
|
output_before: outputBefore, output_after: outputAfter,
|
|
640
668
|
output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
|
|
641
669
|
workspace: workspaceBefore ? {
|
|
@@ -721,27 +749,21 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
721
749
|
: next.current_action,
|
|
722
750
|
updated_at: new Date().toISOString()
|
|
723
751
|
};
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
752
|
+
// The terminal lifecycle and exit code are primary evidence. Persist
|
|
753
|
+
// them before fact projection, which is secondary and may fail on a
|
|
754
|
+
// stale control record without turning completed work into lost work.
|
|
755
|
+
await persist(finalRecord, "final persist");
|
|
756
|
+
await projectOutcomeFacts(finalRecord, {
|
|
729
757
|
acceptanceEventId: acceptanceEvent?.id ?? null,
|
|
730
758
|
acceptancePassed: results.passed === true
|
|
731
759
|
});
|
|
732
760
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
733
|
-
await persist(finalRecord);
|
|
734
761
|
await completeRunRecord(finalRecord, live.run_count);
|
|
735
762
|
} else {
|
|
736
763
|
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
737
|
-
await
|
|
738
|
-
|
|
739
|
-
runId,
|
|
740
|
-
report: finalRecord.run_evidence?.structured_report,
|
|
741
|
-
reportEventId: rawReportEventId
|
|
742
|
-
});
|
|
764
|
+
await persist(finalRecord, "final persist");
|
|
765
|
+
await projectOutcomeFacts(finalRecord);
|
|
743
766
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
744
|
-
await persist(finalRecord);
|
|
745
767
|
await completeRunRecord(finalRecord, live.run_count);
|
|
746
768
|
}
|
|
747
769
|
cancelledTasks.delete(record.id);
|
|
@@ -787,10 +809,26 @@ async function startTrackedRun(job) {
|
|
|
787
809
|
}
|
|
788
810
|
};
|
|
789
811
|
job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
|
|
790
|
-
const
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
812
|
+
const hostLogPath = job.logPath.endsWith(".jsonl")
|
|
813
|
+
? job.logPath.replace(/\.jsonl$/, ".host.log")
|
|
814
|
+
: `${job.logPath}.host.log`;
|
|
815
|
+
let hostLogFd;
|
|
816
|
+
try {
|
|
817
|
+
hostLogFd = openSync(hostLogPath, "a");
|
|
818
|
+
} catch (error) {
|
|
819
|
+
const result = failedStart(job.record, `cannot open run host log ${hostLogPath}: ${error.message}`);
|
|
820
|
+
await upsertTask(result.record);
|
|
821
|
+
return result;
|
|
822
|
+
}
|
|
823
|
+
let host;
|
|
824
|
+
try {
|
|
825
|
+
host = spawn(process.execPath, [fileURLToPath(import.meta.url), "--run-host"], {
|
|
826
|
+
detached: true, stdio: ["ignore", hostLogFd, hostLogFd, "ipc"],
|
|
827
|
+
env: process.env, windowsHide: true
|
|
828
|
+
});
|
|
829
|
+
} finally {
|
|
830
|
+
closeSync(hostLogFd);
|
|
831
|
+
}
|
|
794
832
|
const started = await new Promise((resolveStart) => {
|
|
795
833
|
let settled = false;
|
|
796
834
|
const finish = (result) => {
|
|
@@ -1163,8 +1201,9 @@ export async function createCodexWorker({
|
|
|
1163
1201
|
prompt: frameWorkerPrompt(task, {
|
|
1164
1202
|
objective: validatedGoal.objective,
|
|
1165
1203
|
tokenBudget: validatedGoal.tokenBudget
|
|
1166
|
-
}, { acceptance: combinedAcceptance }),
|
|
1204
|
+
}, { acceptance: combinedAcceptance, outputSchema: true }),
|
|
1167
1205
|
logPath: record.run_log,
|
|
1206
|
+
outputSchema: true,
|
|
1168
1207
|
// --cd tells Codex where the agent works. The shell/tool process must also
|
|
1169
1208
|
// inherit the worktree as its OS cwd: otherwise a login shell may restore
|
|
1170
1209
|
// the project directory and relative probes read the wrong checkout.
|
|
@@ -1262,6 +1301,13 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
|
|
|
1262
1301
|
|
|
1263
1302
|
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
1264
1303
|
const args = codexRunner.resumeArgs(task);
|
|
1304
|
+
const goalRead = readNativeGoalState(task.thread_id);
|
|
1305
|
+
// Only a thread with no native goal, or one explicitly stored as complete,
|
|
1306
|
+
// can safely resume with a structured output schema. Paused, blocked,
|
|
1307
|
+
// usage-limited and budget-limited goals are not complete; Codex can still
|
|
1308
|
+
// activate their goal turn and reject the incompatible schema.
|
|
1309
|
+
const outputSchema = ["missing_goal", "missing_database"].includes(goalRead.state)
|
|
1310
|
+
|| (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
|
|
1265
1311
|
|
|
1266
1312
|
const started = await startTrackedRun({
|
|
1267
1313
|
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
@@ -1269,8 +1315,9 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
|
|
|
1269
1315
|
prompt: frameWorkerPrompt(prompt, {
|
|
1270
1316
|
objective: task.goal_objective ?? task.title ?? task.id,
|
|
1271
1317
|
resume: true
|
|
1272
|
-
}, { acceptance: task.acceptance }),
|
|
1318
|
+
}, { acceptance: task.acceptance, outputSchema }),
|
|
1273
1319
|
logPath: task.run_log,
|
|
1320
|
+
outputSchema,
|
|
1274
1321
|
spawnOptions: { cwd }
|
|
1275
1322
|
});
|
|
1276
1323
|
return rebase ? { ...started.record, rebase } : started.record;
|
|
@@ -1463,6 +1510,17 @@ export async function createFollowupWorker({
|
|
|
1463
1510
|
}) {
|
|
1464
1511
|
const parent = await getTask(taskId);
|
|
1465
1512
|
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
1513
|
+
let inheritedBaseRef = baseRef ?? null;
|
|
1514
|
+
if (!baseRef && !parent.landed_at && parent.project_root && parent.worktree_path) {
|
|
1515
|
+
try {
|
|
1516
|
+
resolveCommit(parent.project_root, `codex/${parent.id}`);
|
|
1517
|
+
inheritedBaseRef = `codex/${parent.id}`;
|
|
1518
|
+
} catch {
|
|
1519
|
+
const error = new Error(`parent checkpoint codex/${parent.id} is unavailable; restore it or choose an explicit baseRef`);
|
|
1520
|
+
error.code = "followup_checkpoint_missing";
|
|
1521
|
+
throw error;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1466
1524
|
const recentEvents = await readTaskEvents(taskId, 20);
|
|
1467
1525
|
const prompt = [
|
|
1468
1526
|
"You are continuing a previous Codex worker run.",
|
|
@@ -1514,10 +1572,14 @@ export async function createFollowupWorker({
|
|
|
1514
1572
|
workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
|
|
1515
1573
|
inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
|
|
1516
1574
|
workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
|
|
1517
|
-
|
|
1575
|
+
// A follow-up continues the same logical line of work. Start from the
|
|
1576
|
+
// parent branch so commits already made there are present; uncommitted
|
|
1577
|
+
// parent edits remain in the parent worktree and are deliberately not
|
|
1578
|
+
// smuggled across task boundaries.
|
|
1579
|
+
baseRef: inheritedBaseRef,
|
|
1518
1580
|
// Inherited unless given; the follow-up runs in a fresh worktree cut
|
|
1519
|
-
// from the
|
|
1520
|
-
// the parent
|
|
1581
|
+
// from the parent's codex/<parent> branch, so checks that depend on the
|
|
1582
|
+
// parent checkpoint are valid before the parent has landed on the target.
|
|
1521
1583
|
acceptance: acceptance === undefined ? (parent.session_policy_revision == null ? parent.acceptance : parent.acceptance_local) : acceptance,
|
|
1522
1584
|
acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
|
|
1523
1585
|
});
|
package/src/landing.js
CHANGED
|
@@ -13,6 +13,7 @@ import { filterWorkspaceSetupChanges, parsePorcelainLine, resolveWorktreeBase, w
|
|
|
13
13
|
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
14
14
|
|
|
15
15
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
16
|
+
const PATCH_ID_MAX_BUFFER = 256 * 1024 * 1024;
|
|
16
17
|
|
|
17
18
|
// A commit needs a committer. On a machine where git has no user.name or
|
|
18
19
|
// user.email (CI runners, a fresh box, a GUI-launched MCP with no HOME
|
|
@@ -46,11 +47,13 @@ export function identityEnv(cwd) {
|
|
|
46
47
|
return env;
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
function git(cwd, args, { timeout = 60000 } = {}) {
|
|
50
|
+
function git(cwd, args, { timeout = 60000, input = null, maxBuffer = 1024 * 1024, encoding = "utf8" } = {}) {
|
|
50
51
|
return execFileSync(defaultGitBin, ["-C", cwd, "-c", "core.quotePath=false", ...args], {
|
|
51
|
-
encoding
|
|
52
|
+
encoding,
|
|
53
|
+
input,
|
|
52
54
|
timeout,
|
|
53
|
-
|
|
55
|
+
maxBuffer,
|
|
56
|
+
stdio: [input == null ? "ignore" : "pipe", "pipe", "pipe"],
|
|
54
57
|
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(cwd) }
|
|
55
58
|
});
|
|
56
59
|
}
|
|
@@ -65,6 +68,54 @@ function porcelainPaths(output) {
|
|
|
65
68
|
return output.split("\n").filter((line) => line.length > 3).map(parsePorcelainLine).filter(Boolean);
|
|
66
69
|
}
|
|
67
70
|
|
|
71
|
+
function patchIdsInRange(cwd, range) {
|
|
72
|
+
const patches = git(cwd, ["log", "--no-merges", "--format=commit %H", "--patch", "--binary", range], {
|
|
73
|
+
timeout: 2 * 60 * 1000,
|
|
74
|
+
encoding: "buffer",
|
|
75
|
+
maxBuffer: PATCH_ID_MAX_BUFFER
|
|
76
|
+
});
|
|
77
|
+
const output = git(cwd, ["patch-id", "--stable"], {
|
|
78
|
+
input: patches,
|
|
79
|
+
timeout: 2 * 60 * 1000,
|
|
80
|
+
maxBuffer: PATCH_ID_MAX_BUFFER
|
|
81
|
+
});
|
|
82
|
+
const ids = new Map();
|
|
83
|
+
for (const line of lines(output)) {
|
|
84
|
+
const [id, sha] = line.split(/\s+/);
|
|
85
|
+
if (id && sha && !/^0+$/.test(id)) ids.set(sha, id);
|
|
86
|
+
}
|
|
87
|
+
return ids;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// `git rev-list --cherry-pick` proves an original worker commit is not
|
|
91
|
+
// pending, but it does not name the target-side commit that carried the same
|
|
92
|
+
// patch. Lifecycle fields need that target-side SHA: using the target's
|
|
93
|
+
// current HEAD would point at unrelated later work and make cleanup/push
|
|
94
|
+
// verification lie.
|
|
95
|
+
function matchAlreadyLanded(cwd, target, targetHead, base, originals, workerHead) {
|
|
96
|
+
if (originals.length === 0) return { matches: [], complete: true, head: null };
|
|
97
|
+
const targetOrder = lines(git(target, ["rev-list", `${base}..${targetHead}`]));
|
|
98
|
+
const targetCommits = new Set(targetOrder);
|
|
99
|
+
const needsPatchIds = originals.some((original) => !targetCommits.has(original));
|
|
100
|
+
const targetByPatch = new Map([...(needsPatchIds ? patchIdsInRange(target, `${base}..${targetHead}`) : [])]
|
|
101
|
+
.map(([sha, id]) => [id, sha]));
|
|
102
|
+
const originalPatches = needsPatchIds ? patchIdsInRange(cwd, `${base}..${workerHead}`) : new Map();
|
|
103
|
+
const matches = originals.flatMap((original) => {
|
|
104
|
+
if (targetCommits.has(original)) return [{ original, target: original }];
|
|
105
|
+
const id = originalPatches.get(original);
|
|
106
|
+
const matched = id ? targetByPatch.get(id) : null;
|
|
107
|
+
return matched ? [{ original, target: matched }] : [];
|
|
108
|
+
});
|
|
109
|
+
const matchedTargets = new Set(matches.map((match) => match.target));
|
|
110
|
+
const head = targetOrder.find((sha) => matchedTargets.has(sha)) ?? null;
|
|
111
|
+
const complete = matches.length === originals.length && matches.every((match) => {
|
|
112
|
+
if (match.target === head) return true;
|
|
113
|
+
try { git(target, ["merge-base", "--is-ancestor", match.target, head]); return true; }
|
|
114
|
+
catch { return false; }
|
|
115
|
+
});
|
|
116
|
+
return { matches, complete, head: complete ? head : null };
|
|
117
|
+
}
|
|
118
|
+
|
|
68
119
|
function currentBranch(cwd) {
|
|
69
120
|
const name = git(cwd, ["symbolic-ref", "--short", "-q", "HEAD"]).trim();
|
|
70
121
|
return name || null;
|
|
@@ -176,14 +227,26 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
|
|
|
176
227
|
// them again produces an empty commit and git stops with an error.
|
|
177
228
|
const targetHead = git(target, ["rev-parse", "HEAD"]).trim();
|
|
178
229
|
let alreadyLanded = [];
|
|
230
|
+
let alreadyLandedMatches = [];
|
|
231
|
+
let matchedHead = null;
|
|
232
|
+
let alreadyLandedMatchComplete = true;
|
|
233
|
+
let alreadyLandedMatchError = null;
|
|
179
234
|
if (commits.length > 0) {
|
|
180
235
|
try {
|
|
181
236
|
const workerHead = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
182
237
|
const pending = new Set(lines(git(target, ["rev-list", "--cherry-pick", "--right-only", `${targetHead}...${workerHead}`])));
|
|
183
238
|
alreadyLanded = commits.filter((sha) => !pending.has(sha));
|
|
184
239
|
commits = commits.filter((sha) => pending.has(sha));
|
|
185
|
-
|
|
186
|
-
|
|
240
|
+
try {
|
|
241
|
+
({ matches: alreadyLandedMatches, complete: alreadyLandedMatchComplete, head: matchedHead } = matchAlreadyLanded(
|
|
242
|
+
task.worktree_path, target, targetHead, base, alreadyLanded, workerHead
|
|
243
|
+
));
|
|
244
|
+
} catch (error) {
|
|
245
|
+
alreadyLandedMatchComplete = false;
|
|
246
|
+
alreadyLandedMatchError = gitTail(error);
|
|
247
|
+
}
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return { error: "landing_proof_failed", reason: "could not prove which worker commits remain unlanded", match_error: gitTail(error) };
|
|
187
250
|
}
|
|
188
251
|
}
|
|
189
252
|
if (commits.length === 0 && alreadyLanded.length > 0) {
|
|
@@ -191,6 +254,12 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
|
|
|
191
254
|
error: "nothing_to_land",
|
|
192
255
|
reason: `every commit on this worker's branch is already on ${branch} (landed before, by patch); nothing new to land`,
|
|
193
256
|
already_landed: alreadyLanded,
|
|
257
|
+
already_landed_matches: alreadyLandedMatches,
|
|
258
|
+
matched_head: matchedHead,
|
|
259
|
+
match_error: alreadyLandedMatchError,
|
|
260
|
+
match_complete: alreadyLandedMatchComplete,
|
|
261
|
+
onto: branch,
|
|
262
|
+
target,
|
|
194
263
|
uncommitted,
|
|
195
264
|
base_commit: base
|
|
196
265
|
};
|
|
@@ -242,6 +311,9 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
|
|
|
242
311
|
head: landed.at(-1) ?? before,
|
|
243
312
|
landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
|
|
244
313
|
already_landed: alreadyLanded,
|
|
314
|
+
already_landed_matches: alreadyLandedMatches,
|
|
315
|
+
match_error: alreadyLandedMatchError,
|
|
316
|
+
match_complete: alreadyLandedMatchComplete,
|
|
245
317
|
committed_for_worker: committedForWorker,
|
|
246
318
|
uncommitted
|
|
247
319
|
};
|
package/src/mcp-server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
3
|
import { execFileSync } from "node:child_process";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -222,6 +222,116 @@ function isSettled(task) {
|
|
|
222
222
|
return false;
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
+
async function recordWorkerLanded(task, { head, branch, target, source = "git_land", alreadyLanded = [] }) {
|
|
226
|
+
const now = new Date().toISOString();
|
|
227
|
+
const landed = { ...task, landed_at: now, landed_head: head ?? null, landed_branch: branch ?? null, updated_at: now };
|
|
228
|
+
await upsertTask(landed);
|
|
229
|
+
await updateWorkItemDelivery(task.id, "landed");
|
|
230
|
+
const event = await appendTaskEvent(task.id, {
|
|
231
|
+
type: "supervisor.landed",
|
|
232
|
+
head: head ?? null,
|
|
233
|
+
branch: branch ?? null,
|
|
234
|
+
target: target ?? null,
|
|
235
|
+
source,
|
|
236
|
+
already_landed: alreadyLanded,
|
|
237
|
+
landed_at: now
|
|
238
|
+
}, { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" });
|
|
239
|
+
const workItem = await getWorkItemForTask(task.id);
|
|
240
|
+
if (workItem && head) {
|
|
241
|
+
await recordFact({
|
|
242
|
+
workItemId: workItem.id,
|
|
243
|
+
scopeType: "work_item",
|
|
244
|
+
scopeId: workItem.id,
|
|
245
|
+
key: "landed",
|
|
246
|
+
value: { head, branch: branch ?? null, source },
|
|
247
|
+
state: "verified",
|
|
248
|
+
sourceEventId: event.id,
|
|
249
|
+
validForSha: head,
|
|
250
|
+
watchedPaths: task.owned_paths ?? [],
|
|
251
|
+
verifiedBy: `supervisor.${source}`
|
|
252
|
+
});
|
|
253
|
+
await recordFact({
|
|
254
|
+
workItemId: workItem.id,
|
|
255
|
+
scopeType: "dependency",
|
|
256
|
+
scopeId: workItem.id,
|
|
257
|
+
key: "landed_delivery_summary",
|
|
258
|
+
value: { task_id: task.id, landed_head: head, branch: branch ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed", source },
|
|
259
|
+
state: "verified",
|
|
260
|
+
sourceEventId: event.id,
|
|
261
|
+
validForSha: head,
|
|
262
|
+
watchedPaths: task.owned_paths ?? [],
|
|
263
|
+
verifiedBy: `supervisor.${source}`
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
return { landed, event };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function landOneWorkerTask(taskId, { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false, skipAlreadyLanded = false } = {}) {
|
|
270
|
+
const task = await getTask(taskId);
|
|
271
|
+
if (!task) return { error: "task_not_found", task_id: taskId };
|
|
272
|
+
if (task.workspace_kind && task.workspace_kind !== "legacy" && task.workspace_kind !== "git_worktree") {
|
|
273
|
+
return { error: "workspace_kind_not_landable", task_id: taskId, workspace_kind: task.workspace_kind, reason: `${task.workspace_kind} does not create a Git worktree and cannot be landed` };
|
|
274
|
+
}
|
|
275
|
+
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
276
|
+
if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
|
|
277
|
+
if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
|
|
278
|
+
if (session && task.session_policy_revision !== session.policy_revision) return { error: "session_policy_stale", task_id: taskId, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" };
|
|
279
|
+
if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
|
|
280
|
+
try {
|
|
281
|
+
const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
|
|
282
|
+
if (onto && onto !== targetBranch) return { error: "wrong_branch", task_id: taskId, current_branch: targetBranch };
|
|
283
|
+
if (!ignoreAcceptance && task.acceptance?.length && task.acceptance_results?.passed !== true) {
|
|
284
|
+
return { error: "acceptance_not_run", task_id: taskId };
|
|
285
|
+
}
|
|
286
|
+
git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, "HEAD"]);
|
|
287
|
+
return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, skipped: "already_landed", landed_at: task.landed_at, landed_head: task.landed_head };
|
|
288
|
+
} catch {
|
|
289
|
+
return { error: "landed_commit_unreachable", task_id: taskId, reason: "the removed ancestor worktree cannot be skipped without proving its landed commit is on the current target" };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const outcome = landWorker(task, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned });
|
|
293
|
+
if (outcome.error === "nothing_to_land" && outcome.already_landed?.length > 0
|
|
294
|
+
&& (outcome.uncommitted ?? []).length === 0) {
|
|
295
|
+
const alreadyRecorded = task.landed_at && task.landed_head === outcome.matched_head;
|
|
296
|
+
if (!alreadyRecorded && outcome.matched_head) {
|
|
297
|
+
await recordWorkerLanded(task, {
|
|
298
|
+
head: outcome.matched_head,
|
|
299
|
+
branch: outcome.onto,
|
|
300
|
+
target: outcome.target,
|
|
301
|
+
source: "patch_equivalent",
|
|
302
|
+
alreadyLanded: outcome.already_landed
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
task_id: taskId,
|
|
307
|
+
title: task.title,
|
|
308
|
+
status: task.status,
|
|
309
|
+
branch: `codex/${task.id}`,
|
|
310
|
+
...outcome,
|
|
311
|
+
skipped: "already_in_target",
|
|
312
|
+
lifecycle_recorded: !alreadyRecorded && Boolean(outcome.matched_head)
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
|
|
316
|
+
await recordWorkerLanded(task, { head: outcome.head, branch: outcome.onto, target: outcome.target, alreadyLanded: outcome.already_landed ?? [] });
|
|
317
|
+
return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function followupChainIds(taskId) {
|
|
321
|
+
const ids = [];
|
|
322
|
+
const seen = new Set();
|
|
323
|
+
let current = taskId;
|
|
324
|
+
for (;;) {
|
|
325
|
+
if (seen.has(current)) throw new Error(`followup cycle detected at ${current}`);
|
|
326
|
+
seen.add(current);
|
|
327
|
+
const task = await getTask(current);
|
|
328
|
+
if (!task) throw new Error(`task not found: ${current}`);
|
|
329
|
+
ids.unshift(current);
|
|
330
|
+
if (!task.followup_of) return ids;
|
|
331
|
+
current = task.followup_of;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
225
335
|
// Codex emits nothing while a command runs and nothing while the model
|
|
226
336
|
// thinks, so a snapshot that has not moved for ten minutes looks the same
|
|
227
337
|
// either way. These three fields tell them apart: current_command is set
|
|
@@ -655,7 +765,7 @@ server.registerTool(
|
|
|
655
765
|
);
|
|
656
766
|
server.registerTool("check_workers", {
|
|
657
767
|
title: "Check changed workers",
|
|
658
|
-
description: "Check newly settled runs and
|
|
768
|
+
description: "Check newly settled runs, actionable failures and active threads crossing the handoff threshold; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Handoff reminders occur once per run and never cancel, replace or resume a live worker. Unchanged state is quiet. Call from a host-scheduled loop; it cannot wake a closed host. Set a distinct CODEX_SUPERVISOR_OBSERVER_ID per main thread to retain its cursor across restarts.",
|
|
659
769
|
inputSchema: {}
|
|
660
770
|
}, async () => {
|
|
661
771
|
const read = observerRead.then(async () => {
|
|
@@ -845,7 +955,7 @@ server.registerTool(
|
|
|
845
955
|
{
|
|
846
956
|
title: "Create Codex follow-up worker",
|
|
847
957
|
description:
|
|
848
|
-
"Start a NEW Codex session seeded with the previous worker's prompt, status, and recent events. To continue the same session instead, use resume_codex_worker.",
|
|
958
|
+
"Start a NEW Codex session seeded with the previous worker's prompt, status, and recent events. Unlanded parents contribute their current codex/<parent> checkpoint; landed parents use the current target HEAD. Explicit baseRef overrides either; uncommitted parent edits are not copied. To continue the same session instead, use resume_codex_worker.",
|
|
849
959
|
inputSchema: {
|
|
850
960
|
task_id: z.string().min(1),
|
|
851
961
|
followup_prompt: z.string().min(1),
|
|
@@ -980,12 +1090,13 @@ server.registerTool(
|
|
|
980
1090
|
{
|
|
981
1091
|
title: "Wait for Codex workers",
|
|
982
1092
|
description:
|
|
983
|
-
"Block until selected Codex workers reach a terminal status, then return summaries.
|
|
1093
|
+
"Block until selected Codex workers reach a terminal status, then return summaries. Each call is capped at 60 seconds unless allowLongWait is explicitly true and the caller has verified its MCP timeout supports the requested budget. A spent wait budget returns a snapshot while workers continue; reuse the same task_ids or schedule check_workers for longer monitoring. compact: true returns one line per worker with status, phase, exit_code, changed_file_count, acceptance and liveness. command_running means a command may still be working despite a long idle interval.",
|
|
984
1094
|
inputSchema: {
|
|
985
1095
|
task_ids: z.array(z.string().min(1)).min(1),
|
|
986
1096
|
mode: z.enum(["any", "all"]).default("all"),
|
|
987
1097
|
timeoutMinutes: z.number().int().min(1).max(360).default(1),
|
|
988
1098
|
timeoutMs: z.number().int().min(1000).max(21600000).optional(),
|
|
1099
|
+
allowLongWait: z.boolean().default(false),
|
|
989
1100
|
pollMs: z.number().int().min(250).max(10000).default(1000),
|
|
990
1101
|
emitProgress: z.boolean().default(false),
|
|
991
1102
|
// Off by default. A wait is the call clients background and then replay
|
|
@@ -1011,6 +1122,7 @@ server.registerTool(
|
|
|
1011
1122
|
mode,
|
|
1012
1123
|
timeoutMinutes,
|
|
1013
1124
|
timeoutMs,
|
|
1125
|
+
allowLongWait,
|
|
1014
1126
|
pollMs,
|
|
1015
1127
|
emitProgress,
|
|
1016
1128
|
includeEvents,
|
|
@@ -1021,7 +1133,8 @@ server.registerTool(
|
|
|
1021
1133
|
}, extra) => {
|
|
1022
1134
|
const compact = requestedCompact ?? !includeEvents;
|
|
1023
1135
|
const startedAt = Date.now();
|
|
1024
|
-
const
|
|
1136
|
+
const requestedTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
|
|
1137
|
+
const effectiveTimeoutMs = allowLongWait ? requestedTimeoutMs : Math.min(requestedTimeoutMs, 60000);
|
|
1025
1138
|
let tasks = [];
|
|
1026
1139
|
const progressToken = extra?._meta?.progressToken;
|
|
1027
1140
|
let lastProgressAt = -Infinity;
|
|
@@ -1042,7 +1155,7 @@ server.registerTool(
|
|
|
1042
1155
|
} }).catch(() => {});
|
|
1043
1156
|
lastProgressAt = elapsed;
|
|
1044
1157
|
}
|
|
1045
|
-
await sleep(pollMs);
|
|
1158
|
+
await sleep(Math.min(pollMs, Math.max(0, effectiveTimeoutMs - (Date.now() - startedAt))));
|
|
1046
1159
|
}
|
|
1047
1160
|
|
|
1048
1161
|
await reconcileDetachedActiveTasks();
|
|
@@ -1074,10 +1187,12 @@ server.registerTool(
|
|
|
1074
1187
|
still_running: timedOut,
|
|
1075
1188
|
termination_reason: clientCancelled ? "client_cancelled" : timedOut ? "budget_exhausted" : "settled",
|
|
1076
1189
|
next_step: timedOut
|
|
1077
|
-
? `Workers are still running; the ${budgetLabel} wait budget ran out
|
|
1190
|
+
? `Workers are still running; the ${budgetLabel} wait budget ran out. Reuse the same task_ids for a short wait, or schedule check_workers for long monitoring. Set allowLongWait only after verifying the client's MCP timeout supports the requested budget; do not start another long wait while a background wait is active.`
|
|
1078
1191
|
: null,
|
|
1079
1192
|
waited_ms: Date.now() - startedAt,
|
|
1080
1193
|
timeout_ms: effectiveTimeoutMs,
|
|
1194
|
+
requested_timeout_ms: requestedTimeoutMs,
|
|
1195
|
+
timeout_capped: effectiveTimeoutMs !== requestedTimeoutMs,
|
|
1081
1196
|
timeout_minutes: Math.round(effectiveTimeoutMs / 60000),
|
|
1082
1197
|
missing_ids: missingIds,
|
|
1083
1198
|
completed_count: tasks.filter((task) => task.status === "completed").length,
|
|
@@ -1842,69 +1957,75 @@ server.registerTool(
|
|
|
1842
1957
|
{
|
|
1843
1958
|
title: "Land a worker's commits",
|
|
1844
1959
|
description:
|
|
1845
|
-
"Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes. A malformed report summary is attention, not a separate landing veto when the same run's acceptance passed and the reviewed diff is sound. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
|
|
1960
|
+
"Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. includeFollowupParents lands an unlanded followup chain root-first; commitMessages supplies a per-task checkpoint message when an ancestor has uncommitted edits. Check the work first with get_worker_result and get_worker_diff; land once it passes. A malformed report summary is attention, not a separate landing veto when the same run's acceptance passed and the reviewed diff is sound. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
|
|
1846
1961
|
inputSchema: {
|
|
1847
1962
|
task_id: z.string().min(1),
|
|
1848
1963
|
onto: z.string().min(1).optional(),
|
|
1849
1964
|
commitMessage: z.string().min(1).optional(),
|
|
1965
|
+
includeFollowupParents: z.boolean().default(false),
|
|
1966
|
+
commitMessages: z.record(z.string(), z.string().min(1)).optional(),
|
|
1850
1967
|
ignoreAcceptance: z.boolean().default(false),
|
|
1851
1968
|
allowOutsideOwned: z.boolean().default(false)
|
|
1852
1969
|
}
|
|
1853
1970
|
},
|
|
1854
|
-
async ({ task_id, onto, commitMessage, ignoreAcceptance, allowOutsideOwned }) => {
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1971
|
+
async ({ task_id, onto, commitMessage, includeFollowupParents, commitMessages, ignoreAcceptance, allowOutsideOwned }) => {
|
|
1972
|
+
if (!includeFollowupParents) {
|
|
1973
|
+
const task = await getTask(task_id);
|
|
1974
|
+
if (task?.followup_of) {
|
|
1975
|
+
let ids;
|
|
1976
|
+
try { ids = await followupChainIds(task_id); }
|
|
1977
|
+
catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
|
|
1978
|
+
const unlanded = [];
|
|
1979
|
+
for (const id of ids.slice(0, -1)) {
|
|
1980
|
+
const ancestor = await getTask(id);
|
|
1981
|
+
if (ancestor) {
|
|
1982
|
+
try {
|
|
1983
|
+
if (!ancestor.landed_at || !ancestor.landed_head) throw new Error("parent not landed");
|
|
1984
|
+
git(task.project_root, ["merge-base", "--is-ancestor", ancestor.landed_head, "HEAD"]);
|
|
1985
|
+
} catch { unlanded.push(id); }
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
if (unlanded.length) {
|
|
1989
|
+
return textResult({
|
|
1990
|
+
error: "followup_parents_not_landed",
|
|
1991
|
+
task_id,
|
|
1992
|
+
unlanded,
|
|
1993
|
+
reason: "this follow-up starts from its parent branch; landing only the leaf would integrate a partial chain. Use includeFollowupParents: true after reviewing every task's acceptance and diff."
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
return textResult(await landOneWorkerTask(task_id, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned }));
|
|
1859
1998
|
}
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
const
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
if (
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
state: "verified",
|
|
1888
|
-
sourceEventId: event.id,
|
|
1889
|
-
validForSha: outcome.head,
|
|
1890
|
-
watchedPaths: task.owned_paths ?? [],
|
|
1891
|
-
verifiedBy: "supervisor.git_land"
|
|
1892
|
-
});
|
|
1893
|
-
await recordFact({
|
|
1894
|
-
workItemId: workItem.id,
|
|
1895
|
-
scopeType: "dependency",
|
|
1896
|
-
scopeId: workItem.id,
|
|
1897
|
-
key: "landed_delivery_summary",
|
|
1898
|
-
value: { task_id, landed_head: outcome.head, branch: outcome.onto ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed" },
|
|
1899
|
-
state: "verified",
|
|
1900
|
-
sourceEventId: event.id,
|
|
1901
|
-
validForSha: outcome.head,
|
|
1902
|
-
watchedPaths: task.owned_paths ?? [],
|
|
1903
|
-
verifiedBy: "supervisor.git_land"
|
|
1904
|
-
});
|
|
1999
|
+
let ids;
|
|
2000
|
+
try { ids = await followupChainIds(task_id); }
|
|
2001
|
+
catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
|
|
2002
|
+
const chain = [];
|
|
2003
|
+
for (const id of ids) {
|
|
2004
|
+
let result;
|
|
2005
|
+
try { result = await landOneWorkerTask(id, {
|
|
2006
|
+
onto,
|
|
2007
|
+
commitMessage: commitMessages?.[id] ?? (id === task_id ? commitMessage : null),
|
|
2008
|
+
ignoreAcceptance: id === task_id && ignoreAcceptance,
|
|
2009
|
+
allowOutsideOwned: id === task_id && allowOutsideOwned,
|
|
2010
|
+
skipAlreadyLanded: true
|
|
2011
|
+
}); } catch (error) {
|
|
2012
|
+
result = { task_id: id, error: "landing_failed", reason: error.message };
|
|
2013
|
+
}
|
|
2014
|
+
if (id !== task_id && result.error === "nothing_to_land"
|
|
2015
|
+
&& (result.uncommitted ?? []).length === 0 && !(result.already_landed?.length)) {
|
|
2016
|
+
chain.push({ ...result, error: null, skipped: "no_changes" });
|
|
2017
|
+
continue;
|
|
2018
|
+
}
|
|
2019
|
+
if (result.skipped === "already_in_target" && (result.uncommitted ?? []).length === 0) {
|
|
2020
|
+
chain.push({ ...result, error: null, skipped: "already_in_target" });
|
|
2021
|
+
continue;
|
|
2022
|
+
}
|
|
2023
|
+
chain.push(result);
|
|
2024
|
+
if (result.error) {
|
|
2025
|
+
return textResult({ error: "followup_chain_land_failed", task_id, failed_task_id: id, chain });
|
|
1905
2026
|
}
|
|
1906
2027
|
}
|
|
1907
|
-
return textResult({ task_id,
|
|
2028
|
+
return textResult({ task_id, chain });
|
|
1908
2029
|
}
|
|
1909
2030
|
);
|
|
1910
2031
|
|
package/src/prompt.js
CHANGED
|
@@ -82,7 +82,10 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
|
|
|
82
82
|
// shell as a heredoc; the guard accepts that shape too, so the worker is told
|
|
83
83
|
// about it instead of stalling on a tool it does not have.
|
|
84
84
|
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.";
|
|
85
|
-
|
|
85
|
+
const delivery = sandbox === "workspace-write" && (!workspaceKind || workspaceKind === "git_worktree")
|
|
86
|
+
? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with land_codex_worker({commitMessage}). Leave your edits uncommitted; clean status and commit-count checks belong after landing. If the task or acceptance requires a self-commit or a clean edited worktree, report the contract conflict instead of bypassing the guard."
|
|
87
|
+
: "";
|
|
88
|
+
return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} ${delivery} Safe read-only inspection commands (rg, cat, sed without -i, git status/diff/log, jq without -i, find without -exec/-delete) are allowed and never reserve another worker's paths. Commands that validate, write, execute code or have side effects 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. ${stage}`;
|
|
86
89
|
}
|
|
87
90
|
|
|
88
91
|
// The acceptance commands are shown to the worker. Hiding them would not
|
|
@@ -105,15 +108,15 @@ export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
|
|
|
105
108
|
].join("\n");
|
|
106
109
|
}
|
|
107
110
|
|
|
108
|
-
export function buildReportPreamble({ resume = false, acceptance = null } = {}) {
|
|
111
|
+
export function buildReportPreamble({ resume = false, acceptance = null, outputSchema = true } = {}) {
|
|
109
112
|
const acceptanceBlock = buildAcceptanceBlock(acceptance, { resume });
|
|
110
113
|
const withAcceptance = (text) => (acceptanceBlock ? `${text}\n\n${acceptanceBlock}` : text);
|
|
111
114
|
if (resume) {
|
|
112
|
-
return withAcceptance(
|
|
115
|
+
return withAcceptance(`Report as before using JSON with result string, verification string[] (every command you ran to check, with exit codes), not_done string[] (remaining work and risks). ${outputSchema ? "The output schema enforces these fields. " : "No output schema is active on this resume, so follow the shape yourself. "}Under 2000 characters, no list of changed files, quote raw errors verbatim.`);
|
|
113
116
|
}
|
|
114
117
|
return withAcceptance([
|
|
115
118
|
"Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
|
|
116
|
-
|
|
119
|
+
`Return JSON with exactly result:string, verification:string[], not_done:string[]; ${outputSchema ? "--output-schema enforces these fields" : "no output schema is active, so follow this shape exactly"}. Cover the following content in those fields.`,
|
|
117
120
|
"Write that JSON value on its own: no markdown code fences and nothing before or after it.",
|
|
118
121
|
"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.",
|
|
119
122
|
"1. Result: what is done, in two or three sentences. Say plainly what is not done.",
|
|
@@ -131,8 +134,8 @@ export function withGoalPreamble(prompt, goalOptions) {
|
|
|
131
134
|
}
|
|
132
135
|
|
|
133
136
|
// The whole frame: goal in front, task text, report format at the end.
|
|
134
|
-
export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null } = {}) {
|
|
135
|
-
return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance })}`;
|
|
137
|
+
export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outputSchema = true } = {}) {
|
|
138
|
+
return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance, outputSchema })}`;
|
|
136
139
|
}
|
|
137
140
|
|
|
138
141
|
// Claude's native /goal owns its Stop condition. MCP cannot silently replace
|
package/src/task-store.js
CHANGED
|
@@ -11,6 +11,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
11
11
|
import { captureWorkspaceManifest } from "./workspace-kind.js";
|
|
12
12
|
import { buildHandoff } from "./handoff.js";
|
|
13
13
|
import { readPreflightResult } from "./worker-preflight.js";
|
|
14
|
+
import { parseWorkerReportForRun } from "./worker-report.js";
|
|
14
15
|
|
|
15
16
|
let db;
|
|
16
17
|
|
|
@@ -681,6 +682,80 @@ async function reconcileInterruptedAcceptance() {
|
|
|
681
682
|
|
|
682
683
|
export async function reconcileDetachedActiveTasks() {
|
|
683
684
|
await reconcileInterruptedAcceptance();
|
|
685
|
+
// A run host can disappear after Codex has finished its turn but before it
|
|
686
|
+
// writes the process exit. The terminal event is already durable, and the
|
|
687
|
+
// work did complete; the missing scalar is a supervisor bookkeeping fault,
|
|
688
|
+
// not evidence that the worker vanished. Acceptance keeps its own verdict;
|
|
689
|
+
// recovering the worker completion must never imply that checks passed.
|
|
690
|
+
const recoverTerminalTurn = async (task) => {
|
|
691
|
+
if (task.exit_code != null || task.signal || !task.started_at
|
|
692
|
+
|| isPidAlive(task.pid) || isPidAlive(task.run_host_pid)) return false;
|
|
693
|
+
const runId = runIdFor(task.id, task.run_count);
|
|
694
|
+
const events = openDb().prepare(`
|
|
695
|
+
SELECT payload FROM task_events WHERE task_id = ? AND run_id = ? ORDER BY seq
|
|
696
|
+
`).all(task.id, runId).map((row) => decodeJson(row.payload, null)).filter(Boolean);
|
|
697
|
+
if (!events.some((event) => event.type === "turn.completed")) return false;
|
|
698
|
+
let reportText = null;
|
|
699
|
+
for (const event of events) {
|
|
700
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") reportText = event.item.text ?? null;
|
|
701
|
+
}
|
|
702
|
+
const structuredReport = parseWorkerReportForRun(reportText, { outputSchema: task.guard_policy?.output_schema !== false });
|
|
703
|
+
const recoveredEvidence = task.run_evidence
|
|
704
|
+
? { ...task.run_evidence, structured_report: structuredReport }
|
|
705
|
+
: {
|
|
706
|
+
run: task.run_count,
|
|
707
|
+
commands_run: (task.commands ?? []).length,
|
|
708
|
+
structured_report: structuredReport,
|
|
709
|
+
recovered: "turn_completed_without_process_exit"
|
|
710
|
+
};
|
|
711
|
+
if (!recoveredEvidence.attempt_fingerprint) {
|
|
712
|
+
recoveredEvidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
713
|
+
output_changed: recoveredEvidence.output_changed ?? null,
|
|
714
|
+
commands_run: recoveredEvidence.commands_run ?? (task.commands ?? []).length,
|
|
715
|
+
changed_files: task.changed_files ?? [],
|
|
716
|
+
acceptance_configured: Array.isArray(task.acceptance) && task.acceptance.length > 0,
|
|
717
|
+
workspace_manifest_changed: recoveredEvidence.workspace?.manifest_changed ?? null
|
|
718
|
+
})).digest("hex");
|
|
719
|
+
}
|
|
720
|
+
const reportInvalid = recoveredEvidence.structured_report?.valid === false && !task.guard_policy?.preflight;
|
|
721
|
+
const attentionReason = task.attention_reason ?? (reportInvalid ? "invalid_report" : null);
|
|
722
|
+
const staleExitError = /did not record the process exit|process disappeared/i.test(task.error ?? "");
|
|
723
|
+
const now = new Date().toISOString();
|
|
724
|
+
const acceptanceResults = task.acceptance_results ?? (task.acceptance?.length ? {
|
|
725
|
+
status: "interrupted", passed: null, run: task.run_count, finished_at: now,
|
|
726
|
+
error: "worker completed before its acceptance result was recorded; rerun acceptance"
|
|
727
|
+
} : null);
|
|
728
|
+
const recoveredTask = {
|
|
729
|
+
...task,
|
|
730
|
+
status: "completed",
|
|
731
|
+
phase: null,
|
|
732
|
+
exit_code: 0,
|
|
733
|
+
attention_reason: attentionReason,
|
|
734
|
+
error: reportInvalid
|
|
735
|
+
? (staleExitError ? null : task.error) ?? `Invalid final worker report: ${recoveredEvidence.structured_report.error}`
|
|
736
|
+
: staleExitError ? null : task.error ?? null,
|
|
737
|
+
current_action: attentionReason ? task.current_action : "Completed (exit recovered from the durable turn event)",
|
|
738
|
+
current_command: null,
|
|
739
|
+
acceptance_results: acceptanceResults,
|
|
740
|
+
run_evidence: recoveredEvidence,
|
|
741
|
+
completed_at: task.completed_at ?? now,
|
|
742
|
+
updated_at: now
|
|
743
|
+
};
|
|
744
|
+
await writeTask(recoveredTask);
|
|
745
|
+
await completeRunRecord(recoveredTask, task.run_count);
|
|
746
|
+
await appendTaskEvent(task.id, {
|
|
747
|
+
type: "supervisor.exit_recovered",
|
|
748
|
+
reason: "turn_completed_without_process_exit",
|
|
749
|
+
exit_code: 0,
|
|
750
|
+
recovered_at: now
|
|
751
|
+
}, { runId, actor: "supervisor" }).catch(() => null);
|
|
752
|
+
return true;
|
|
753
|
+
};
|
|
754
|
+
const terminalCandidates = openDb().prepare(`
|
|
755
|
+
SELECT * FROM tasks
|
|
756
|
+
WHERE status IN ('completed','lost') AND exit_code IS NULL AND started_at IS NOT NULL
|
|
757
|
+
`).all().map(rowToTask);
|
|
758
|
+
for (const task of terminalCandidates) await recoverTerminalTurn(task);
|
|
684
759
|
const incomplete = (await readTasks()).filter((task) =>
|
|
685
760
|
["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
|
|
686
761
|
&& !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
|
|
@@ -700,6 +775,7 @@ export async function reconcileDetachedActiveTasks() {
|
|
|
700
775
|
const staleTasks = tasks.filter((task) => !isPidAlive(task.run_host_pid)
|
|
701
776
|
&& ((task.pid && !isPidAlive(task.pid)) || neverStarted(task)));
|
|
702
777
|
for (const task of staleTasks) {
|
|
778
|
+
if (await recoverTerminalTurn(task)) continue;
|
|
703
779
|
const now = new Date().toISOString();
|
|
704
780
|
const vanished = Boolean(task.pid);
|
|
705
781
|
await writeTask({
|
package/src/worker-changes.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { TERMINAL_STATUSES, isGoalNeedingAttention } from "./status.js";
|
|
1
|
+
import { ACTIVE_STATUSES, TERMINAL_STATUSES, isGoalNeedingAttention } from "./status.js";
|
|
2
|
+
import { threadHealth } from "./thread-health.js";
|
|
2
3
|
|
|
3
4
|
// Cursors belong to observers, not workers. A resumed run gets a new receipt;
|
|
4
5
|
// old acceptance cannot produce a current-run completion or failure notice.
|
|
@@ -8,6 +9,25 @@ export function collectWorkerChanges(tasks, cursor = {}) {
|
|
|
8
9
|
const attention = [];
|
|
9
10
|
for (const task of tasks) {
|
|
10
11
|
const acceptance = task.acceptance_results?.run === task.run_count ? task.acceptance_results : null;
|
|
12
|
+
const health = threadHealth(task);
|
|
13
|
+
const healthKey = `${task.id}:thread_health`;
|
|
14
|
+
if (cursor[healthKey]) next[healthKey] = cursor[healthKey];
|
|
15
|
+
if (ACTIVE_STATUSES.has(task.status) && health.state === "handoff_recommended") {
|
|
16
|
+
const healthFingerprint = JSON.stringify([task.run_count, health.state]);
|
|
17
|
+
next[healthKey] = healthFingerprint;
|
|
18
|
+
if (cursor[healthKey] !== healthFingerprint) {
|
|
19
|
+
const receipt = {
|
|
20
|
+
id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
|
|
21
|
+
reason: "handoff_recommended", tokens_used: health.tokens_used, threshold: health.threshold,
|
|
22
|
+
next_step: {
|
|
23
|
+
tool: "get_codex_worker_status", arguments: { task_id: task.id },
|
|
24
|
+
instruction: "Inspect the live command and stage. Let this bounded step settle or explicitly cancel it before preparing a reviewed checkpoint and a fresh follow-up; do not launch a duplicate while it is active."
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
transitions.push(receipt);
|
|
28
|
+
attention.push(receipt);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
11
31
|
let reason = null;
|
|
12
32
|
if (isGoalNeedingAttention(task.goal_status)) reason = `goal_${task.goal_status}`;
|
|
13
33
|
else if (task.attention_reason) reason = task.attention_reason;
|
package/src/worker-report.js
CHANGED
|
@@ -70,3 +70,16 @@ export function parseWorkerReport(text) {
|
|
|
70
70
|
}
|
|
71
71
|
return { format: "json_schema", valid: false, error: parseError?.message ?? "report is not JSON" };
|
|
72
72
|
}
|
|
73
|
+
|
|
74
|
+
export function parseWorkerReportForRun(text, { outputSchema = true } = {}) {
|
|
75
|
+
const parsed = parseWorkerReport(text);
|
|
76
|
+
if (!outputSchema && !parsed.valid && typeof text === "string" && text.trim()) {
|
|
77
|
+
return {
|
|
78
|
+
format: "text",
|
|
79
|
+
valid: true,
|
|
80
|
+
repaired: "output_schema_disabled_text_fallback",
|
|
81
|
+
report: { result: text, verification: [], not_done: [] }
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return parsed;
|
|
85
|
+
}
|