codex-supervisor-mcp 0.13.2 → 0.13.3
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 +12 -4
- package/README.md +11 -5
- package/package.json +1 -1
- package/skills/codex-supervisor/SKILL.md +7 -2
- package/src/codex-runner.js +97 -35
- package/src/landing.js +77 -5
- package/src/mcp-server.js +170 -54
- package/src/prompt.js +5 -5
- package/src/task-store.js +76 -0
- package/src/worker-report.js +13 -0
package/README.en.md
CHANGED
|
@@ -157,14 +157,14 @@ Thirty-nine.
|
|
|
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 |
|
|
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
162
|
| `wait_codex_workers` | `task_ids`, `mode` (any/all), `timeoutMinutes`, `timeoutMs`, `pollMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for terminal states. 60 seconds by default. `termination_reason` distinguishes settled, exhausted budget and client cancellation. `emitProgress: true` emits progress every 30 seconds when the client supplies a progress token. `compact` returns one row per worker |
|
|
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.
|
|
@@ -235,7 +243,7 @@ An `allowedCommands` entry ending in `*` is a prefix match (so `go test ./intern
|
|
|
235
243
|
|
|
236
244
|
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
245
|
|
|
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.
|
|
246
|
+
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
247
|
|
|
240
248
|
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
249
|
|
package/README.md
CHANGED
|
@@ -167,14 +167,14 @@ land_codex_worker 核过了,带 commitMessage 代提交并落进集成
|
|
|
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`
|
|
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
172
|
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `compact`, `emitProgress`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态。默认 60 秒且不推周期 heartbeat;显式 `emitProgress: true` 才每 30 秒通知。`termination_reason` 区分 settled / budget_exhausted / client_cancelled;`compact` 每路一行 |
|
|
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
|
|
|
@@ -251,7 +257,7 @@ wait 默认预算60秒、默认compact;includeEvents会选择详细结果(
|
|
|
251
257
|
|
|
252
258
|
守卫按 worker 形状放权:`git_worktree` 编辑 worker 只放声明过的命令和简单读取;`read_only_in_place` 无写入无网络;`scratch` 的联网草稿只能写在 `SUPERVISOR_HOME/scratch/<taskId>`;`in_place_write` 必须有显式授权、ownedPaths 与 acceptance,并保存前后 manifest。非 Git `workspace-write` 没写 `workspaceKind` 会拒绝,绝不默认写用户目录。
|
|
253
259
|
|
|
254
|
-
check_workers在状态协调后,对已结束的第1轮lost/no_work/invalid_report原子resume一次(invalid_report只要求重发裸JSON
|
|
260
|
+
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
261
|
|
|
256
262
|
context用绝对文件路径与可选sha256声明材料,最多20份、与contracts合计6000字;文件不超过5 MB。首次派单记录实际哈希,resume校验原材料未变,需要新材料时显式传context。handoff最多1800字/16行,截断明确标记;完整约束和引用单独保留,材料不授予写权限。
|
|
257
263
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.3",
|
|
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.",
|
|
@@ -86,9 +86,13 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
86
86
|
2. 读 `get_worker_result`。注意 `commands_run`、命令退出码和 `last_command_failed`,不要只听结论。
|
|
87
87
|
3. 读 `get_worker_diff`。默认先看文件和 hunk 索引,再按 `file` + `hunk`/`cursor` 分页读 patch。
|
|
88
88
|
4. 对不上就问 `ask_codex_worker`。旁路只读,不改 worker 线程。
|
|
89
|
-
5. 要改就 `resume_codex_worker`。不要要求 worker commit 或 amend;主线前进时按需带 `rebaseOnto: "HEAD"`。
|
|
89
|
+
5. 要改就 `resume_codex_worker`。不要要求 worker commit 或 amend;主线前进时按需带 `rebaseOnto: "HEAD"`。原生 goal 未明确 complete 或状态不可读时,supervisor 续跑省略 output schema,避免 `ActiveTurnOutputSchemaMismatch`。
|
|
90
90
|
6. 验收和 diff 都过了,用 `land_codex_worker({commitMessage})` 把未提交改动提交到 worker 分支并 cherry-pick 到当前集成分支。
|
|
91
91
|
|
|
92
|
+
`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。
|
|
93
|
+
|
|
94
|
+
零改动祖先可跳过;`ignoreAcceptance` / `allowOutsideOwned` 只对指定 leaf 生效,不豁免祖先的验收或写入范围。
|
|
95
|
+
|
|
92
96
|
`invalid_report` 不是业务失败。常见情况是单个字符串字段、缺一个 `]`/`}`,或内容完整但 schema 不合规。先让 `check_workers` 做一次 report-only 修复;仍失败时,acceptance 通过且 diff 审过,可以显式 land。报告只是摘要,不是交付证据。
|
|
93
97
|
|
|
94
98
|
## 上下文与事实
|
|
@@ -97,6 +101,7 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
97
101
|
- `session_id` peers、完整事件、完整 diff、历史报告和 candidate facts 不会自动注入。
|
|
98
102
|
- 主线程看事实摘要用 `search_worker_facts`;追溯来源用 `get_fact`;看证据索引用 `get_worker_evidence` / `get_artifact`。
|
|
99
103
|
- worker 的报告先记为 candidate。只有 supervisor acceptance 通过后,才有资格成为当前 work 的 verified outcome。
|
|
104
|
+
- schema-free resume 的纯文本报告只留 candidate;合成的 verification/not_done 空数组不是已验证结论。
|
|
100
105
|
- base SHA、watched path、context hash 或 in-place manifest 变化后,旧 fact 会过期并从后续 capsule 排除。
|
|
101
106
|
|
|
102
107
|
## 中断与恢复
|
|
@@ -104,7 +109,7 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
104
109
|
| 情况 | 处理 |
|
|
105
110
|
|---|---|
|
|
106
111
|
| 主线程挂了 | worker 的独立 run host 会继续记录日志、状态和验收。新窗口用 `get_session_works` 接回 |
|
|
107
|
-
| worker 变 `lost` | `
|
|
112
|
+
| worker 变 `lost` | 当前 run 有 durable `turn.completed` 且 worker/run host 均退出时,reconcile 恢复 completed;验收中断仍需重跑。确实中断才 resume,worktree、改动和 thread id 都保留 |
|
|
108
113
|
| worktree 落后主线 | `resume_codex_worker` 带 `rebaseOnto: "HEAD"` |
|
|
109
114
|
| worker 失败 | 先看 `failure.source` 和 `error`,区分 provider、supervisor、workspace setup、model output、acceptance、worker process |
|
|
110
115
|
| 没有 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
|
|
@@ -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),
|
|
@@ -1842,69 +1952,75 @@ server.registerTool(
|
|
|
1842
1952
|
{
|
|
1843
1953
|
title: "Land a worker's commits",
|
|
1844
1954
|
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.",
|
|
1955
|
+
"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
1956
|
inputSchema: {
|
|
1847
1957
|
task_id: z.string().min(1),
|
|
1848
1958
|
onto: z.string().min(1).optional(),
|
|
1849
1959
|
commitMessage: z.string().min(1).optional(),
|
|
1960
|
+
includeFollowupParents: z.boolean().default(false),
|
|
1961
|
+
commitMessages: z.record(z.string(), z.string().min(1)).optional(),
|
|
1850
1962
|
ignoreAcceptance: z.boolean().default(false),
|
|
1851
1963
|
allowOutsideOwned: z.boolean().default(false)
|
|
1852
1964
|
}
|
|
1853
1965
|
},
|
|
1854
|
-
async ({ task_id, onto, commitMessage, ignoreAcceptance, allowOutsideOwned }) => {
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1966
|
+
async ({ task_id, onto, commitMessage, includeFollowupParents, commitMessages, ignoreAcceptance, allowOutsideOwned }) => {
|
|
1967
|
+
if (!includeFollowupParents) {
|
|
1968
|
+
const task = await getTask(task_id);
|
|
1969
|
+
if (task?.followup_of) {
|
|
1970
|
+
let ids;
|
|
1971
|
+
try { ids = await followupChainIds(task_id); }
|
|
1972
|
+
catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
|
|
1973
|
+
const unlanded = [];
|
|
1974
|
+
for (const id of ids.slice(0, -1)) {
|
|
1975
|
+
const ancestor = await getTask(id);
|
|
1976
|
+
if (ancestor) {
|
|
1977
|
+
try {
|
|
1978
|
+
if (!ancestor.landed_at || !ancestor.landed_head) throw new Error("parent not landed");
|
|
1979
|
+
git(task.project_root, ["merge-base", "--is-ancestor", ancestor.landed_head, "HEAD"]);
|
|
1980
|
+
} catch { unlanded.push(id); }
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
if (unlanded.length) {
|
|
1984
|
+
return textResult({
|
|
1985
|
+
error: "followup_parents_not_landed",
|
|
1986
|
+
task_id,
|
|
1987
|
+
unlanded,
|
|
1988
|
+
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."
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return textResult(await landOneWorkerTask(task_id, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned }));
|
|
1859
1993
|
}
|
|
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
|
-
});
|
|
1994
|
+
let ids;
|
|
1995
|
+
try { ids = await followupChainIds(task_id); }
|
|
1996
|
+
catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
|
|
1997
|
+
const chain = [];
|
|
1998
|
+
for (const id of ids) {
|
|
1999
|
+
let result;
|
|
2000
|
+
try { result = await landOneWorkerTask(id, {
|
|
2001
|
+
onto,
|
|
2002
|
+
commitMessage: commitMessages?.[id] ?? (id === task_id ? commitMessage : null),
|
|
2003
|
+
ignoreAcceptance: id === task_id && ignoreAcceptance,
|
|
2004
|
+
allowOutsideOwned: id === task_id && allowOutsideOwned,
|
|
2005
|
+
skipAlreadyLanded: true
|
|
2006
|
+
}); } catch (error) {
|
|
2007
|
+
result = { task_id: id, error: "landing_failed", reason: error.message };
|
|
2008
|
+
}
|
|
2009
|
+
if (id !== task_id && result.error === "nothing_to_land"
|
|
2010
|
+
&& (result.uncommitted ?? []).length === 0 && !(result.already_landed?.length)) {
|
|
2011
|
+
chain.push({ ...result, error: null, skipped: "no_changes" });
|
|
2012
|
+
continue;
|
|
2013
|
+
}
|
|
2014
|
+
if (result.skipped === "already_in_target" && (result.uncommitted ?? []).length === 0) {
|
|
2015
|
+
chain.push({ ...result, error: null, skipped: "already_in_target" });
|
|
2016
|
+
continue;
|
|
2017
|
+
}
|
|
2018
|
+
chain.push(result);
|
|
2019
|
+
if (result.error) {
|
|
2020
|
+
return textResult({ error: "followup_chain_land_failed", task_id, failed_task_id: id, chain });
|
|
1905
2021
|
}
|
|
1906
2022
|
}
|
|
1907
|
-
return textResult({ task_id,
|
|
2023
|
+
return textResult({ task_id, chain });
|
|
1908
2024
|
}
|
|
1909
2025
|
);
|
|
1910
2026
|
|
package/src/prompt.js
CHANGED
|
@@ -105,15 +105,15 @@ export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
|
|
|
105
105
|
].join("\n");
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
export function buildReportPreamble({ resume = false, acceptance = null } = {}) {
|
|
108
|
+
export function buildReportPreamble({ resume = false, acceptance = null, outputSchema = true } = {}) {
|
|
109
109
|
const acceptanceBlock = buildAcceptanceBlock(acceptance, { resume });
|
|
110
110
|
const withAcceptance = (text) => (acceptanceBlock ? `${text}\n\n${acceptanceBlock}` : text);
|
|
111
111
|
if (resume) {
|
|
112
|
-
return withAcceptance(
|
|
112
|
+
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
113
|
}
|
|
114
114
|
return withAcceptance([
|
|
115
115
|
"Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
|
|
116
|
-
|
|
116
|
+
`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
117
|
"Write that JSON value on its own: no markdown code fences and nothing before or after it.",
|
|
118
118
|
"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
119
|
"1. Result: what is done, in two or three sentences. Say plainly what is not done.",
|
|
@@ -131,8 +131,8 @@ export function withGoalPreamble(prompt, goalOptions) {
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
// 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 })}`;
|
|
134
|
+
export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outputSchema = true } = {}) {
|
|
135
|
+
return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance, outputSchema })}`;
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
// 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-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
|
+
}
|