codex-supervisor-mcp 0.11.0 → 0.11.1
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 +3 -3
- package/README.md +5 -5
- package/package.json +1 -1
- package/skills/codex-supervisor/SKILL.md +4 -4
- package/src/codex-runner.js +120 -43
- package/src/context-compiler.js +3 -1
- package/src/handoff.js +9 -1
- package/src/landing.js +16 -4
- package/src/mcp-server.js +6 -1
- package/src/prompt.js +1 -1
- package/src/sandbox-roots.js +19 -3
- package/src/task-store.js +227 -61
- package/src/worker-preflight.js +10 -2
package/README.en.md
CHANGED
|
@@ -170,12 +170,12 @@ Thirty-nine.
|
|
|
170
170
|
| `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | One worker in detail |
|
|
171
171
|
| `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | The raw event stream |
|
|
172
172
|
| `get_context_snapshot_meta` | `task_id` | Worker-only context snapshot metadata: fact IDs, token count and excluded categories, never capsule text |
|
|
173
|
-
| `get_fact` | `fact_id` | Read one fact
|
|
173
|
+
| `get_fact` | `fact_id` | Read one historical fact version and its `effective_state`; revocation and automatic expiry retain the original version |
|
|
174
174
|
| `search_worker_facts` | `task_id`, `query`, `limit`, `cursor` | Search only verified facts scoped to the current work, explicit dependencies and path-matched repository facts; returns coverage and next_cursor, never raw history |
|
|
175
175
|
| `get_worker_evidence` | `task_id`, `limit` | Bounded event metadata and retained artifact IDs for one worker; select an artifact or event explicitly for detail |
|
|
176
176
|
| `get_artifact` | `artifact_id`, `maxChars` | Read one supervisor-managed evidence artifact without expanding a worker capsule into main context |
|
|
177
177
|
| `promote_worker_fact` | `fact_id`, `scope`, `watchedPaths`, `expiresAt` | Explicitly promote a candidate to a new verified fact after main-thread review; repo scope requires watched paths |
|
|
178
|
-
| `revoke_worker_fact` | `fact_id`, `reason` |
|
|
178
|
+
| `revoke_worker_fact` | `fact_id`, `reason` | Append a revocation version and audit event without overwriting the original; the fact is excluded from search and future capsules |
|
|
179
179
|
| `create_independent_verifier` | `task_id`, `title` | Create a fresh read-only, no-network verifier for a settled worker; it receives the objective and current worktree, never the target report or candidate facts |
|
|
180
180
|
| `record_independent_finding` | `verifier_task_id`, `verdict`, `reason` | Persist an independent passes/fails/inconclusive finding with a subject event and retained evidence artifact |
|
|
181
181
|
| `resolve_independent_finding` | `verifier_task_id`, `resolution` | Record how a finding was resolved without deleting the finding or evidence |
|
|
@@ -208,7 +208,7 @@ A model with no separate `apply_patch` tool (measured with Codex 0.162 + DeepSee
|
|
|
208
208
|
|
|
209
209
|
An `allowedCommands` entry ending in `*` is a prefix match (so `go test ./internal/*` covers `go test ./internal/service -run TestX`), valid only for a single command without shell metacharacters. An editor worker may also read with grep/sed (without `-i`)/find (without `-exec`/`-delete`)/jq (without `-i`)/awk, the git read subcommands and pure read pipes such as `cmd | head|tail|wc|sort|uniq`; `tee`, redirects and `env` stay refused. The guard is not a filesystem sandbox: a miss only writes inside the worker's own worktree, and land refuses it.
|
|
210
210
|
|
|
211
|
-
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 fact is expired and excluded from a future worker capsule when its base SHA no longer covers the task, a watched path changed, or its in-place manifest drifted; explicit dependencies provide only delivery summaries.
|
|
211
|
+
The guard relaxes by workspace shape: a `git_worktree` editor with non-empty `ownedPaths` gets only declared commands and simple reads; `read_only_in_place` cannot write or use network; networked research uses `scratch` under `SUPERVISOR_HOME`, never the source directory; `in_place_write` requires explicit authorization, owned paths and acceptance with before/after manifests. A non-Git `workspace-write` request without `workspaceKind` is refused. A worker capsule names its branch and acceptance source without embedding acceptance commands. Repository facts cross checkouts only when canonical `origin`, repository-relative watched paths and base SHA all match; an unrecognized origin leaves them work-scoped. A fact is append-only expired and excluded from a future worker capsule when its base SHA no longer covers the task, a watched path changed, its declared context content hash changed, or its in-place manifest drifted; explicit dependencies provide only delivery summaries.
|
|
212
212
|
|
|
213
213
|
After reconciliation, check_workers atomically resumes a dead first lost/no_work/invalid_report run once and returns recovery receipts (an invalid report only re-asks for the bare JSON; it does not redo the work). Two consecutive no-output/no-command runs with the same fingerprint become `two_stall` and `needs_attention`, never another blind retry; approval, authentication, permission and quota waits are not retried. Final reports use JSON result/verification/not_done; structured_report exposes validation independently of command history and acceptance. Invalid JSON is failed/invalid_report and cannot land. Existing history is labelled legacy_text.
|
|
214
214
|
|
package/README.md
CHANGED
|
@@ -172,12 +172,12 @@ land_codex_worker 核过了,落进集成分支
|
|
|
172
172
|
| `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | 单个 worker 的状态细节 |
|
|
173
173
|
| `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | 原始事件流 |
|
|
174
174
|
| `get_context_snapshot_meta` | `task_id` | 只读 worker context 的 snapshot ID、fact IDs、token 估算和排除项;不返回 capsule 正文或历史记录 |
|
|
175
|
-
| `get_fact` | `fact_id` | 按 ID
|
|
175
|
+
| `get_fact` | `fact_id` | 按 ID 审计原始 fact 版本及 `effective_state`;撤销和自动过期均保留原版本 |
|
|
176
176
|
| `search_worker_facts` | `task_id`, `query`, `limit`, `cursor` | 只检索当前 work、显式依赖和路径命中 repo scope 的 verified facts;返回 coverage / next_cursor,不返回 raw history |
|
|
177
177
|
| `get_worker_evidence` | `task_id`, `limit` | 返回某 worker 的有界 event 元数据和 retained artifact 索引;按需再点查 artifact / event |
|
|
178
178
|
| `get_artifact` | `artifact_id`, `maxChars` | 读取一个 supervisor-managed evidence artifact;不影响 worker capsule 或主线程自动上下文 |
|
|
179
179
|
| `promote_worker_fact` | `fact_id`, `scope`, `watchedPaths`, `expiresAt` | 主线程显式把 candidate 追加为 verified fact;repo scope 必须声明 watchedPaths,worker 不能自升真相 |
|
|
180
|
-
| `revoke_worker_fact` | `fact_id`, `reason` |
|
|
180
|
+
| `revoke_worker_fact` | `fact_id`, `reason` | 主线程审计后追加撤销版本和事件,不覆盖原 fact;被撤销事实从 search / capsule 排除 |
|
|
181
181
|
| `create_independent_verifier` | `task_id`, `title` | 为已结算 worker 创建独立 read-only / 无网络 verifier;只给目标与当前 worktree,不给原 report/candidate facts |
|
|
182
182
|
| `record_independent_finding` | `verifier_task_id`, `verdict`, `reason` | 记录独立 verifier 的 passes/fails/inconclusive finding,写 subject event 和 retained artifact |
|
|
183
183
|
| `resolve_independent_finding` | `verifier_task_id`, `resolution` | 记录 finding 的收口方式,保留原 finding 与证据 |
|
|
@@ -196,7 +196,7 @@ land_codex_worker 核过了,落进集成分支
|
|
|
196
196
|
|
|
197
197
|
普通 worker 启动时会关闭它继承到的 `codex-supervisor` MCP,不能再派 worker、resume、cancel 或改编排状态;主线程是唯一编排者。其他业务 MCP 不受影响;旁问 fork 仍关闭全部 MCP,因为它只允许只读回答。
|
|
198
198
|
|
|
199
|
-
`session_id` 只负责批次、默认门禁和审批,不再把同批 worker 的标题、汇报或 session objective 自动塞进新 worker。worker 只收到内部编译的 context capsule
|
|
199
|
+
`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`。
|
|
200
200
|
|
|
201
201
|
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 自报完成都不会升级成共享真相。
|
|
202
202
|
|
|
@@ -212,7 +212,7 @@ worker 的最终 JSON 报告会先记录为该 run 的 `candidate` fact,不能
|
|
|
212
212
|
|
|
213
213
|
wait 默认预算60秒、默认compact;includeEvents会选择详细结果(显式compact优先)。带progress token的客户端每30秒收到通知;已验证MCP SDK及真实Claude2.1.299:idle35秒、wait65秒,三次progress后正常返回;原生/loop定时调用也已实测。
|
|
214
214
|
|
|
215
|
-
每路临时注入随包PreToolUse守卫:apply_patch核对全部目标路径(含rename和symlink),forbid
|
|
215
|
+
每路临时注入随包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;只读任务不因没改文件判空跑。
|
|
216
216
|
|
|
217
217
|
没有独立 `apply_patch` 工具的模型(实测 Codex 0.162 + DeepSeek/cc-switch)把补丁当 shell 命令发过来:`apply_patch <<'EOF' ... EOF`。守卫认这个形状,用同一套 ownedPaths 规则判每个目标路径,所以这种模型也能改文件;未加引号的 heredoc、后面还接 `&&`/`;` 的都拒绝。
|
|
218
218
|
|
|
@@ -228,7 +228,7 @@ context用绝对文件路径与可选sha256声明材料,最多20份、与contr
|
|
|
228
228
|
|
|
229
229
|
workspace-write默认networkAccess:false;需要ssh/联网验证显式true,随resume/followup继承,不以danger-full-access代替。maxRunMs限制单轮、maxTotalMs限制从派单开始的总时长;超限中止worker并保留needs_attention/partial work,不自动重试。wait预算不改变这些quota。
|
|
230
230
|
|
|
231
|
-
沙箱除工作区和临时目录外,自动放开 OS cache 目录(macOS `~/Library/Caches`、Linux `~/.cache`、Windows `%LOCALAPPDATA%`)、home 下已存在的工具链缓存目录(`.cargo`/`.npm`/`.yarn`/`.pnpm-store`/`.bun`/`.m2`/`.gradle`/`.nuget`/`.ivy2`/`.bundle`/`.composer`/`.pub-cache`/`.mix`/`.hex`/`.stack`/`.cpanm`/`.deno`/`.conda`、`go/pkg
|
|
231
|
+
沙箱除工作区和临时目录外,自动放开 OS cache 目录(macOS `~/Library/Caches`、Linux `~/.cache`、Windows `%LOCALAPPDATA%`)、home 下已存在的工具链缓存目录(`.cargo`/`.npm`/`.yarn`/`.pnpm-store`/`.bun`/`.m2`/`.gradle`/`.nuget`/`.ivy2`/`.bundle`/`.composer`/`.pub-cache`/`.mix`/`.hex`/`.stack`/`.cpanm`/`.deno`/`.conda`、`go/pkg`)。Go build cache(平台默认 `go-build` 或显式 `GOCACHE`)单独 realpath 并放行真实目录,因此 symlink 指向外置盘时也可在 worker sandbox 使用;**凭据目录一律不自动放开**(`.ssh`/`.gnupg`/`.config`/`.aws`/`.docker`/`.kube`/`.netrc`/`.git-credentials`/`~/Library/Keychains`):ssh 连服务器要写 known_hosts、kubectl、推私有镜像、签名提交这类需求,派单时显式传 `writableRoots`,只在这一路生效。`SUPERVISOR_NO_AUTO_CACHE_ROOTS=1` 关掉全部自动缓存根,显式声明的照常生效。Codex 拒绝带软链的可写根,所以自动 cache 和 `writableRoots` 都先按 realpath 解析;解析不出无软链路径的根直接不传。其他 cache 放在别处(`~/.m2`、`~/.gradle`、vendor 镜像)就传 `writableRoots:[绝对路径]`,要求是已存在目录、最多 20 个、只对 workspace-write 生效、随 resume/followup 继承;只读复用就不用传。
|
|
232
232
|
|
|
233
233
|
运行前核验Codex CLI是否具备hooks/output-schema(要求0.162+);能力不足返回start_failed,wait可正常结算。get_worker_goal.native_goal_read区分missing_goal、missing_database、locked和read_error,不能把读取失败当没建goal。原生budget/usage限制也进入needs_attention。cleanup保留ignored artifacts、共享证据和未解决attention。
|
|
234
234
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.1",
|
|
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.",
|
|
@@ -48,7 +48,7 @@ worker 默认不是调度员:启动时会禁用它继承到的 `codex-supervis
|
|
|
48
48
|
|
|
49
49
|
wait默认60秒和compact,带includeEvents则详细返回;客户端带progress token时每30秒收到通知。已实测Claude2.1.299在35秒idle下收到三次progress,65秒wait正常返回;通知不能唤醒关闭的宿主。/loop实测可定时调用,主窗口须保持运行。
|
|
50
50
|
|
|
51
|
-
派单写forbid红线、allowedCommands验证命令;runtime守卫按次注入并随resume/followup继承。apply_patch核对ownedPaths
|
|
51
|
+
派单写forbid红线、allowedCommands验证命令;runtime守卫按次注入并随resume/followup继承。apply_patch核对ownedPaths;安全只读检查(rg/cat/sed无-i/git只读/jq无-i/find无-exec或-delete)默认允许且不占其他 worker 的写路径,写入/执行/有副作用的 Shell 命令必须显式声明;声明脚本可以有副作用,须先核对,不能当万能文件沙箱。no_work表示本轮write无输出变化且没跑命令;先看run_evidence,不拿上轮提交/命令当本轮完成。
|
|
52
52
|
|
|
53
53
|
没有独立 `apply_patch` 工具的模型会把补丁当 shell 命令发过来(`apply_patch <<'EOF' ... EOF`):守卫认这个形状,按同一套 ownedPaths 判路径、同样拒越界,所以模型不需要有那个工具也能改文件。Quoted heredoc 才认;后面跟 `&&`/`;` 的、未加引号的都不算。
|
|
54
54
|
|
|
@@ -73,7 +73,7 @@ check_workers可对已死的第1轮lost/no_work/invalid_report自动resume一次
|
|
|
73
73
|
|
|
74
74
|
远端编译/ssh在workspace-write显式networkAccess:true,默认false,resume/followup继承;不要用danger-full-access代替联网配置。需要时声明maxRunMs/maxTotalMs,超限保留partial work并提示处理,不自动恢复;wait预算与quota分开。
|
|
75
75
|
|
|
76
|
-
沙箱只放工作区、临时目录、OS cache目录(macOS ~/Library/Caches、Linux ~/.cache、Windows %LOCALAPPDATA%)以及home下已存在的工具链缓存目录(.cargo/.npm/.yarn/.pnpm-store/.bun/.m2/.gradle/.nuget/.ivy2/.bundle/.composer/.pub-cache/.mix/.hex/.stack/.cpanm/.deno/.conda、go/pkg
|
|
76
|
+
沙箱只放工作区、临时目录、OS cache目录(macOS ~/Library/Caches、Linux ~/.cache、Windows %LOCALAPPDATA%)以及home下已存在的工具链缓存目录(.cargo/.npm/.yarn/.pnpm-store/.bun/.m2/.gradle/.nuget/.ivy2/.bundle/.composer/.pub-cache/.mix/.hex/.stack/.cpanm/.deno/.conda、go/pkg)。Go build cache(平台默认 `go-build` 或显式 `GOCACHE`)会单独解析 realpath 并放行真实目录,所以它指向外置盘 symlink 时 worker 也能用;其他语言也不需要逐个加环境变量。**凭据目录一律不自动放开**(.ssh/.gnupg/.config/.aws/.docker/.kube/.netrc/.git-credentials/~/Library/Keychains):ssh 连服务器要写 known_hosts、kubectl、推私有镜像、签名提交这类需求,派单时按参数表显式传 writableRoots,只在这一路生效、随 resume/followup 继承。SUPERVISOR_NO_AUTO_CACHE_ROOTS=1 关掉全部自动缓存根,显式声明的照常生效。Codex 拒绝含软链的可写根,所以自动 cache 与 `writableRoots` 都先按 realpath 解析;解析不到无软链路径的根直接不传。其他 cache 在别处(如 ~/.m2、~/.gradle、vendor 镜像)就传 `writableRoots:[绝对路径]`(已存在目录、最多20个、只对workspace-write生效、随resume/followup继承);能只读复用就不用传。
|
|
77
77
|
|
|
78
78
|
Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CLI。goal查询看native_goal_read,missing与locked/read_error分开;budget/usage限制也要处理。cleanup保留ignored成果、共享证据及未解决attention。
|
|
79
79
|
|
|
@@ -133,11 +133,11 @@ Codex需0.162+支持hooks/output-schema,能力不够派单start_failed先修CL
|
|
|
133
133
|
| 找当前任务的已验证事实 | `search_worker_facts`,传 task_id/query/cursor;只回 scope 内 verified summary + coverage,绝不拉 raw history |
|
|
134
134
|
| 找某路的证据索引 | `get_worker_evidence`,再按需 `get_artifact` 或 `get_codex_worker_events` |
|
|
135
135
|
| 主线程确认候选事实 | `promote_worker_fact`;只有主线程审过才会追加 verified,repo scope 必须给 watchedPaths |
|
|
136
|
-
| 主线程推翻事实 | `revoke_worker_fact`;写明 reason
|
|
136
|
+
| 主线程推翻事实 | `revoke_worker_fact`;写明 reason,追加撤销版本保留原始 fact;`get_fact.effective_state` 显示撤销状态,不进入 search 或后续 capsule |
|
|
137
137
|
|
|
138
138
|
默认读回来的长文本都是裁过的(`current_action` 300 字、`prompt` 300 字、`last_message` 400 字),别把裁剪当成活没干。全量在库里。别一次 `limit: 200` 拉全量事件。
|
|
139
139
|
|
|
140
|
-
worker 的 capsule 只在内部 create/resume
|
|
140
|
+
worker 的 capsule 只在内部 create/resume 时生成:L0 身份会标 branch 与 acceptance 来源但不放 acceptance 命令正文、当前 work 的 verified facts、显式 `dependsOn` 的最小交付摘要、路径命中且 SHA 有效的 repo facts。repo fact 跨 checkout 必须 canonical `origin`、repo-relative watched path 与 SHA 同时命中;没有可识别 origin 就不共享。`session_id` peers、raw event、完整 diff/报告、candidate facts 一律不自动注入。base SHA 不再覆盖、watched path 有 Git diff、context 输入 content hash 或 in_place_write manifest 漂移时,旧 fact 自动 append-only `expired` 并排除,保留原始版本。主线程只能看 snapshot 元数据;要查事实用 `search_worker_facts` / `get_fact`,查证据用 `get_worker_evidence` / `get_artifact`,不能把自己变成 worker。
|
|
141
141
|
|
|
142
142
|
worker 最终 JSON 只是 `candidate`:先留在本 run 做审计,绝不因为它自己说“完成”就变共享事实。supervisor acceptance 通过才会派生当前 work 的 `verified` outcome;验收失败/未配置、脏 diff、未 land/push 都不是 verified 交付证据。
|
|
143
143
|
|
package/src/codex-runner.js
CHANGED
|
@@ -6,6 +6,7 @@ import { join, resolve, sep, dirname, isAbsolute } from "node:path";
|
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import {
|
|
8
8
|
appendTaskEvent,
|
|
9
|
+
appendTaskEvents,
|
|
9
10
|
getTask,
|
|
10
11
|
getSession,
|
|
11
12
|
readActiveTasks,
|
|
@@ -48,6 +49,8 @@ const cancelledTasks = new Set();
|
|
|
48
49
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
49
50
|
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
50
51
|
const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
52
|
+
const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
|
|
53
|
+
const WORKTREE_LOCK_TIMEOUT_MS = 120000;
|
|
51
54
|
|
|
52
55
|
async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
|
|
53
56
|
if (!report?.valid) return;
|
|
@@ -63,6 +66,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
63
66
|
state: "candidate",
|
|
64
67
|
sourceEventId: reportEventId,
|
|
65
68
|
validForSha: task.base_commit ?? null,
|
|
69
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
66
70
|
validForManifestHash,
|
|
67
71
|
watchedPaths: task.owned_paths ?? []
|
|
68
72
|
});
|
|
@@ -76,6 +80,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
76
80
|
state: "verified",
|
|
77
81
|
sourceEventId: acceptanceEventId,
|
|
78
82
|
validForSha: task.base_commit ?? null,
|
|
83
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
79
84
|
validForManifestHash,
|
|
80
85
|
watchedPaths: task.owned_paths ?? [],
|
|
81
86
|
supersedesId: candidate.id,
|
|
@@ -162,6 +167,31 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
|
162
167
|
}
|
|
163
168
|
}
|
|
164
169
|
|
|
170
|
+
function sleep(ms) {
|
|
171
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function withWorktreeCreationLock(cwd, work) {
|
|
175
|
+
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
176
|
+
const lockPath = join(worktreesDir, lockName);
|
|
177
|
+
await mkdir(worktreesDir, { recursive: true });
|
|
178
|
+
const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
|
|
179
|
+
while (true) {
|
|
180
|
+
try {
|
|
181
|
+
await mkdir(lockPath);
|
|
182
|
+
break;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`);
|
|
185
|
+
await sleep(100);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
return await work();
|
|
190
|
+
} finally {
|
|
191
|
+
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
165
195
|
function normalizeOwnedPaths(ownedPaths, projectRoot) {
|
|
166
196
|
if (!Array.isArray(ownedPaths)) return [];
|
|
167
197
|
return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
|
|
@@ -238,6 +268,9 @@ function failedStart(record, reason) {
|
|
|
238
268
|
// failed instead of taking the whole MCP process down.
|
|
239
269
|
async function spawnAndAwaitStart(target, args, options) {
|
|
240
270
|
const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
|
|
271
|
+
const earlyOutput = { stdout: [], stderr: [], capture: true };
|
|
272
|
+
child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
|
|
273
|
+
child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
|
|
241
274
|
const spawnError = await new Promise((resolvePromise) => {
|
|
242
275
|
let settled = false;
|
|
243
276
|
child.once("spawn", () => {
|
|
@@ -253,7 +286,7 @@ async function spawnAndAwaitStart(target, args, options) {
|
|
|
253
286
|
}
|
|
254
287
|
});
|
|
255
288
|
});
|
|
256
|
-
return { child, spawnError };
|
|
289
|
+
return { child, spawnError, earlyOutput };
|
|
257
290
|
}
|
|
258
291
|
|
|
259
292
|
// Attaches stream handlers and keeps `record` in the supervisor database.
|
|
@@ -284,7 +317,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
284
317
|
const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
|
|
285
318
|
prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
|
|
286
319
|
|
|
287
|
-
const { child, spawnError } = await spawnAndAwaitStart(target, guardedArgs, {
|
|
320
|
+
const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, guardedArgs, {
|
|
288
321
|
stdio: ["pipe", "pipe", "pipe"],
|
|
289
322
|
env: { ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
|
|
290
323
|
CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) },
|
|
@@ -301,6 +334,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
301
334
|
// the run that was lost, so a worker that was plainly running still showed
|
|
302
335
|
// "process disappeared" until it finished.
|
|
303
336
|
const priorAttemptFingerprint = record.run_evidence?.attempt_fingerprint ?? null;
|
|
337
|
+
const reportOnlyRecovery = record.attention_reason === "invalid_report";
|
|
304
338
|
let live = {
|
|
305
339
|
...record,
|
|
306
340
|
status: "running",
|
|
@@ -369,36 +403,60 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
369
403
|
let terminalEvent = false;
|
|
370
404
|
let rawReport = null;
|
|
371
405
|
let rawReportEventId = null;
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
406
|
+
const handleLines = async (lines) => {
|
|
407
|
+
const events = [];
|
|
408
|
+
for (const line of lines) {
|
|
409
|
+
try {
|
|
410
|
+
const event = JSON.parse(line);
|
|
411
|
+
logStream.write(`${JSON.stringify(event)}\n`);
|
|
412
|
+
events.push(event);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (events.length === 0) return;
|
|
418
|
+
const storedEvents = await appendTaskEvents(record.id, events, { runId, actor: "codex" });
|
|
419
|
+
let next = live;
|
|
420
|
+
for (const [index, event] of events.entries()) {
|
|
421
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") {
|
|
422
|
+
rawReport = event.item.text;
|
|
423
|
+
rawReportEventId = storedEvents[index].id;
|
|
424
|
+
}
|
|
425
|
+
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
426
|
+
next = codexRunner.parseEvent(next, event);
|
|
379
427
|
}
|
|
380
|
-
|
|
381
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReport = event.item.text;
|
|
382
|
-
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
383
|
-
const storedEvent = await appendTaskEvent(record.id, event, { runId, actor: "codex" });
|
|
384
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReportEventId = storedEvent.id;
|
|
385
|
-
await persist(codexRunner.parseEvent(live, event));
|
|
428
|
+
await persist(next);
|
|
386
429
|
};
|
|
387
430
|
|
|
388
431
|
let stdoutRest = "";
|
|
389
|
-
|
|
432
|
+
let pendingLines = [];
|
|
433
|
+
let eventFlushPending = false;
|
|
434
|
+
const queueEventLines = (lines) => {
|
|
435
|
+
pendingLines.push(...lines);
|
|
436
|
+
if (eventFlushPending) return;
|
|
437
|
+
eventFlushPending = true;
|
|
438
|
+
eventChain = eventChain.then(async () => {
|
|
439
|
+
await new Promise((resolveFlush) => setImmediate(resolveFlush));
|
|
440
|
+
const batch = pendingLines;
|
|
441
|
+
pendingLines = [];
|
|
442
|
+
eventFlushPending = false;
|
|
443
|
+
await handleLines(batch);
|
|
444
|
+
}).catch((error) => {
|
|
445
|
+
process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
const handleStdoutChunk = (chunk) => {
|
|
390
449
|
const split = splitLines(stdoutRest, chunk.toString("utf8"));
|
|
391
450
|
stdoutRest = split.rest;
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
});
|
|
451
|
+
const lines = split.lines.filter((line) => line.trim());
|
|
452
|
+
if (lines.length) queueEventLines(lines);
|
|
453
|
+
};
|
|
454
|
+
earlyOutput.capture = false;
|
|
455
|
+
for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
|
|
456
|
+
child.stdout.on("data", handleStdoutChunk);
|
|
399
457
|
child.stdout.on("error", () => {});
|
|
400
458
|
|
|
401
|
-
let stderr = "";
|
|
459
|
+
let stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
|
|
402
460
|
child.stderr.on("data", (chunk) => {
|
|
403
461
|
stderr += chunk.toString("utf8");
|
|
404
462
|
persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
|
|
@@ -413,12 +471,15 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
413
471
|
});
|
|
414
472
|
});
|
|
415
473
|
|
|
416
|
-
|
|
474
|
+
let settleRun;
|
|
475
|
+
const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
|
|
476
|
+
let childSettled = false;
|
|
477
|
+
const finalizeChild = async (code, signal) => {
|
|
478
|
+
if (childSettled) return;
|
|
479
|
+
childSettled = true;
|
|
417
480
|
if (quotaWatch) clearInterval(quotaWatch);
|
|
418
481
|
processes.delete(record.id);
|
|
419
|
-
if (stdoutRest.trim())
|
|
420
|
-
process.stderr.write(`[codex-supervisor] final event failed for ${record.id}: ${error.message}\n`);
|
|
421
|
-
});
|
|
482
|
+
if (stdoutRest.trim()) queueEventLines([stdoutRest]);
|
|
422
483
|
await eventChain.catch(() => {});
|
|
423
484
|
logStream.end();
|
|
424
485
|
const finishedAt = new Date().toISOString();
|
|
@@ -449,10 +510,11 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
449
510
|
completed_at: live.completed_at ?? finishedAt,
|
|
450
511
|
updated_at: finishedAt
|
|
451
512
|
};
|
|
452
|
-
|
|
513
|
+
const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
|
|
514
|
+
if (status === "failed" && (!next.error || stdinEpipe)) {
|
|
453
515
|
next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
|
|
454
516
|
}
|
|
455
|
-
if (status === "lost" && !next.error) {
|
|
517
|
+
if (status === "lost" && (!next.error || stdinEpipe)) {
|
|
456
518
|
next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
|
|
457
519
|
}
|
|
458
520
|
if (status === "cancelled") next.error = null;
|
|
@@ -494,7 +556,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
494
556
|
})).digest("hex");
|
|
495
557
|
if (status === "completed" && code === 0 && live.sandbox !== "read-only"
|
|
496
558
|
&& !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
|
|
497
|
-
&& live.commands.length === 0) {
|
|
559
|
+
&& live.commands.length === 0 && !reportOnlyRecovery) {
|
|
498
560
|
next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
|
|
499
561
|
if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
|
|
500
562
|
}
|
|
@@ -555,8 +617,6 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
555
617
|
: next.current_action,
|
|
556
618
|
updated_at: new Date().toISOString()
|
|
557
619
|
};
|
|
558
|
-
await persist(finalRecord);
|
|
559
|
-
await completeRunRecord(finalRecord, live.run_count);
|
|
560
620
|
await recordOutcomeFacts({
|
|
561
621
|
task: finalRecord,
|
|
562
622
|
runId,
|
|
@@ -566,10 +626,10 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
566
626
|
acceptancePassed: results.passed === true
|
|
567
627
|
});
|
|
568
628
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
569
|
-
} else {
|
|
570
|
-
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
571
629
|
await persist(finalRecord);
|
|
572
630
|
await completeRunRecord(finalRecord, live.run_count);
|
|
631
|
+
} else {
|
|
632
|
+
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
573
633
|
await recordOutcomeFacts({
|
|
574
634
|
task: finalRecord,
|
|
575
635
|
runId,
|
|
@@ -577,9 +637,15 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
577
637
|
reportEventId: rawReportEventId
|
|
578
638
|
});
|
|
579
639
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
640
|
+
await persist(finalRecord);
|
|
641
|
+
await completeRunRecord(finalRecord, live.run_count);
|
|
580
642
|
}
|
|
581
643
|
cancelledTasks.delete(record.id);
|
|
582
|
-
}
|
|
644
|
+
};
|
|
645
|
+
child.once("close", (code, signal) => { void finalizeChild(code, signal).finally(settleRun); });
|
|
646
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
647
|
+
setImmediate(() => { void finalizeChild(child.exitCode, child.signalCode).finally(settleRun); });
|
|
648
|
+
}
|
|
583
649
|
|
|
584
650
|
try {
|
|
585
651
|
child.stdin.end(prompt);
|
|
@@ -591,7 +657,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
591
657
|
});
|
|
592
658
|
}
|
|
593
659
|
|
|
594
|
-
return { ok: true, record: live, child };
|
|
660
|
+
return { ok: true, record: live, child, settled };
|
|
595
661
|
}
|
|
596
662
|
|
|
597
663
|
// The MCP client may disappear at any point. A detached process owns the
|
|
@@ -610,6 +676,7 @@ async function startTrackedRun(job) {
|
|
|
610
676
|
...job.record.input_context,
|
|
611
677
|
context: compiled.sourceRefs,
|
|
612
678
|
source_refs: compiled.sourceRefs,
|
|
679
|
+
content_hash: compiled.contentHash,
|
|
613
680
|
context_snapshot_id: compiled.snapshot.id,
|
|
614
681
|
context_snapshot_tokens: compiled.snapshot.estimated_tokens,
|
|
615
682
|
context_fact_count: compiled.factCount
|
|
@@ -621,7 +688,10 @@ async function startTrackedRun(job) {
|
|
|
621
688
|
env: process.env, windowsHide: true
|
|
622
689
|
});
|
|
623
690
|
const started = await new Promise((resolveStart) => {
|
|
691
|
+
let settled = false;
|
|
624
692
|
const finish = (result) => {
|
|
693
|
+
if (settled) return;
|
|
694
|
+
settled = true;
|
|
625
695
|
clearTimeout(timer);
|
|
626
696
|
host.removeAllListeners("message");
|
|
627
697
|
host.removeAllListeners("exit");
|
|
@@ -632,7 +702,7 @@ async function startTrackedRun(job) {
|
|
|
632
702
|
const timer = setTimeout(() => {
|
|
633
703
|
host.kill();
|
|
634
704
|
finish(failedStart(job.record, "run host startup timed out"));
|
|
635
|
-
},
|
|
705
|
+
}, RUN_HOST_STARTUP_TIMEOUT_MS);
|
|
636
706
|
host.once("message", finish);
|
|
637
707
|
host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
|
|
638
708
|
host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
|
|
@@ -819,7 +889,7 @@ export async function createCodexWorker({
|
|
|
819
889
|
const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
|
|
820
890
|
|
|
821
891
|
const worktree = workspace.kind === "git_worktree"
|
|
822
|
-
? await ensureWorktree(projectRoot, id, baseRef)
|
|
892
|
+
? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
|
|
823
893
|
: { path: null, baseCommit: null };
|
|
824
894
|
const worktreePath = worktree.path;
|
|
825
895
|
if (workspace.kind === "git_worktree" && !worktreePath) {
|
|
@@ -936,7 +1006,12 @@ export async function createCodexWorker({
|
|
|
936
1006
|
if (preflightResult.contract_hash !== contractHash) {
|
|
937
1007
|
const error = new Error(`preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`);
|
|
938
1008
|
error.code = "preflight_mismatch";
|
|
939
|
-
error.details = {
|
|
1009
|
+
error.details = {
|
|
1010
|
+
preflight_id: preflightId,
|
|
1011
|
+
expected_contract_hash: contractHash,
|
|
1012
|
+
actual_contract_hash: preflightResult.contract_hash,
|
|
1013
|
+
preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
|
|
1014
|
+
};
|
|
940
1015
|
throw error;
|
|
941
1016
|
}
|
|
942
1017
|
}
|
|
@@ -1104,6 +1179,7 @@ export async function recoverEligibleRuns() {
|
|
|
1104
1179
|
|
|
1105
1180
|
if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "--run-host") {
|
|
1106
1181
|
process.once("message", async (job) => {
|
|
1182
|
+
const keepAlive = setInterval(() => {}, 1000);
|
|
1107
1183
|
let result;
|
|
1108
1184
|
try {
|
|
1109
1185
|
result = await trackRunInHost(job);
|
|
@@ -1112,9 +1188,10 @@ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "-
|
|
|
1112
1188
|
result = failedStart(job.record, `run host failed: ${error.message}`);
|
|
1113
1189
|
await upsertTask(result.record);
|
|
1114
1190
|
}
|
|
1115
|
-
if (process.connected) process.send({ ok: result.ok, record: result.record },
|
|
1116
|
-
|
|
1117
|
-
|
|
1191
|
+
if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
|
|
1192
|
+
if (result.settled) await result.settled;
|
|
1193
|
+
clearInterval(keepAlive);
|
|
1194
|
+
if (process.connected) process.disconnect();
|
|
1118
1195
|
});
|
|
1119
1196
|
}
|
|
1120
1197
|
|
package/src/context-compiler.js
CHANGED
|
@@ -50,8 +50,10 @@ export async function compileWorkerContext(task, { attempt }) {
|
|
|
50
50
|
`- run_id: ${runIdFor(task.id, attempt)}`,
|
|
51
51
|
`- project_root: ${task.project_root}`,
|
|
52
52
|
`- base_sha: ${task.base_commit ?? "unknown"}`,
|
|
53
|
+
`- branch: ${task.worktree_path ? `codex/${task.id}` : "not applicable (in-place workspace)"}`,
|
|
53
54
|
`- worktree: ${task.worktree_path ?? task.cwd}`,
|
|
54
55
|
`- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
|
|
56
|
+
`- acceptance_source: ${Array.isArray(task.acceptance) && task.acceptance.length > 0 ? "dispatch or session policy; commands stay outside this capsule" : "no acceptance configured"}`,
|
|
55
57
|
"L1 task:",
|
|
56
58
|
`- objective: ${task.goal_objective ?? task.title ?? "unspecified"}`
|
|
57
59
|
];
|
|
@@ -82,5 +84,5 @@ export async function compileWorkerContext(task, { attempt }) {
|
|
|
82
84
|
candidate_facts: "never automatic"
|
|
83
85
|
}
|
|
84
86
|
});
|
|
85
|
-
return { text, snapshot, sourceRefs: handoff.source_refs, factCount: usedFacts.length };
|
|
87
|
+
return { text, snapshot, sourceRefs: handoff.source_refs, contentHash: handoff.content_hash, factCount: usedFacts.length };
|
|
86
88
|
}
|
package/src/handoff.js
CHANGED
|
@@ -2,6 +2,14 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { readFile, lstat } from "node:fs/promises";
|
|
3
3
|
import { isAbsolute } from "node:path";
|
|
4
4
|
|
|
5
|
+
export function contextContentHash(refs = []) {
|
|
6
|
+
if (!Array.isArray(refs) || refs.length === 0) return null;
|
|
7
|
+
const canonical = refs
|
|
8
|
+
.map((ref) => ({ path: String(ref.path), sha256: String(ref.sha256) }))
|
|
9
|
+
.sort((left, right) => left.path.localeCompare(right.path));
|
|
10
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
|
|
5
13
|
export async function buildHandoff({ goal, todo, contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
|
|
6
14
|
if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
|
|
7
15
|
|| contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
|
|
@@ -26,5 +34,5 @@ export async function buildHandoff({ goal, todo, contracts = [], context = [] },
|
|
|
26
34
|
}
|
|
27
35
|
const truncated = lines.length !== candidates.length;
|
|
28
36
|
if (truncated) lines.push(marker);
|
|
29
|
-
return { text: lines.join("\n"), truncated, source_refs: refs };
|
|
37
|
+
return { text: lines.join("\n"), truncated, source_refs: refs, content_hash: contextContentHash(refs) };
|
|
30
38
|
}
|
package/src/landing.js
CHANGED
|
@@ -70,6 +70,16 @@ function currentBranch(cwd) {
|
|
|
70
70
|
return name || null;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
function hasStagedChanges(cwd) {
|
|
74
|
+
try {
|
|
75
|
+
git(cwd, ["diff", "--cached", "--quiet"]);
|
|
76
|
+
return false;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.status === 1) return true;
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
73
83
|
// Lands task's commits onto the current branch of its dispatch directory
|
|
74
84
|
// (task.project_root: the row's cwd is the worktree the worker ran in).
|
|
75
85
|
// `onto`, when given, must name that branch: it is a guard, not a switch.
|
|
@@ -145,14 +155,16 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
|
|
|
145
155
|
if (uncommitted.length > 0 && commitMessage) {
|
|
146
156
|
try {
|
|
147
157
|
git(task.worktree_path, ["add", "-A"]);
|
|
148
|
-
|
|
158
|
+
if (hasStagedChanges(task.worktree_path)) {
|
|
159
|
+
git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
|
|
160
|
+
committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
161
|
+
commits.push(committedForWorker);
|
|
162
|
+
}
|
|
163
|
+
uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
|
|
149
164
|
} catch (error) {
|
|
150
165
|
const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
|
|
151
166
|
return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
|
|
152
167
|
}
|
|
153
|
-
committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
154
|
-
commits.push(committedForWorker);
|
|
155
|
-
uncommitted = [];
|
|
156
168
|
}
|
|
157
169
|
// Commits whose patch is already on the target (a previous land, or the
|
|
158
170
|
// main thread cherry-picked by hand) are skipped by patch id; picking
|
package/src/mcp-server.js
CHANGED
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
getSession,
|
|
17
17
|
getArtifact,
|
|
18
18
|
getFact,
|
|
19
|
+
getFactEffectiveState,
|
|
20
|
+
isFactRevoked,
|
|
19
21
|
getReviewByVerifierTask,
|
|
20
22
|
getTaskForWorkItem,
|
|
21
23
|
getWorkItemForTask,
|
|
@@ -520,6 +522,7 @@ function errorResult(error) {
|
|
|
520
522
|
error: error.code ?? "error",
|
|
521
523
|
message: error.message,
|
|
522
524
|
...(error.conflicts ? { conflicts: error.conflicts } : {}),
|
|
525
|
+
...(error.details?.preflight ? { preflight: error.details.preflight } : {}),
|
|
523
526
|
...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
|
|
524
527
|
});
|
|
525
528
|
}
|
|
@@ -1212,7 +1215,8 @@ server.registerTool(
|
|
|
1212
1215
|
},
|
|
1213
1216
|
async ({ fact_id }) => {
|
|
1214
1217
|
const fact = await getFact(fact_id);
|
|
1215
|
-
|
|
1218
|
+
if (!fact) return textResult({ error: "fact_not_found", fact_id });
|
|
1219
|
+
return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
|
|
1216
1220
|
}
|
|
1217
1221
|
);
|
|
1218
1222
|
|
|
@@ -1246,6 +1250,7 @@ server.registerTool(
|
|
|
1246
1250
|
try {
|
|
1247
1251
|
const source = await getFact(fact_id);
|
|
1248
1252
|
if (!source) return textResult({ error: "fact_not_found", fact_id });
|
|
1253
|
+
if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
|
|
1249
1254
|
const task = await getTaskForWorkItem(source.work_item_id);
|
|
1250
1255
|
if (!task) return textResult({ error: "fact_task_not_found", fact_id });
|
|
1251
1256
|
const event = await appendTaskEvent(task.id, { type: "supervisor.fact_promoted", source_fact_id: fact_id, scope, watched_paths: watchedPaths ?? source.watched_paths ?? [], expires_at: expiresAt ?? null }, {
|
package/src/prompt.js
CHANGED
|
@@ -76,7 +76,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
|
|
|
76
76
|
// shell as a heredoc; the guard accepts that shape too, so the worker is told
|
|
77
77
|
// about it instead of stalling on a tool it does not have.
|
|
78
78
|
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.";
|
|
79
|
-
return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit}
|
|
79
|
+
return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} 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.`;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
// The acceptance commands are shown to the worker. Hiding them would not
|
package/src/sandbox-roots.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { dirname, isAbsolute,
|
|
3
|
+
import { dirname, isAbsolute, posix, resolve, win32 } from "node:path";
|
|
4
|
+
|
|
5
|
+
function pathJoin(platform, ...parts) {
|
|
6
|
+
return (platform === "win32" ? win32 : posix).join(...parts);
|
|
7
|
+
}
|
|
4
8
|
|
|
5
9
|
// Codex refuses a writable root that contains a symlink component: the worker
|
|
6
10
|
// does not merely lose that directory, every command in it fails with
|
|
@@ -72,12 +76,24 @@ export const TOOLCHAIN_CACHE_DIRS = [
|
|
|
72
76
|
export const EXPLICIT_ONLY_DIRS = [".ssh", ".gnupg", ".config", ".aws", ".docker", ".kube", ".netrc", ".git-credentials", "Library/Keychains"];
|
|
73
77
|
function osCacheCandidates({ env, platform, home }) {
|
|
74
78
|
if (platform === "win32") return [env.LOCALAPPDATA];
|
|
75
|
-
return [env.XDG_CACHE_HOME, platform === "darwin" ?
|
|
79
|
+
return [env.XDG_CACHE_HOME, platform === "darwin" ? pathJoin(platform, home, "Library", "Caches") : null, pathJoin(platform, home, ".cache")];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function goBuildCacheCandidate({ env, platform, home }) {
|
|
83
|
+
const configured = env.GOCACHE?.trim();
|
|
84
|
+
if (configured && configured !== "off") return configured;
|
|
85
|
+
if (platform === "win32") return env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "go-build") : null;
|
|
86
|
+
if (platform === "darwin") return pathJoin(platform, home, "Library", "Caches", "go-build");
|
|
87
|
+
return pathJoin(platform, env.XDG_CACHE_HOME?.trim() || pathJoin(platform, home, ".cache"), "go-build");
|
|
76
88
|
}
|
|
77
89
|
|
|
78
90
|
export function cacheRoots({ env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = {}) {
|
|
79
91
|
if (/^(1|true|yes)$/i.test((env.SUPERVISOR_NO_AUTO_CACHE_ROOTS ?? "").trim())) return [];
|
|
80
|
-
const candidates = [
|
|
92
|
+
const candidates = [
|
|
93
|
+
...osCacheCandidates({ env, platform, home }),
|
|
94
|
+
goBuildCacheCandidate({ env, platform, home }),
|
|
95
|
+
...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => pathJoin(platform, home, dir)) : [])
|
|
96
|
+
];
|
|
81
97
|
const roots = [];
|
|
82
98
|
for (const candidate of candidates) {
|
|
83
99
|
if (!candidate?.trim()) continue;
|
package/src/task-store.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
-
import { join, relative, resolve } from "node:path";
|
|
2
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
4
|
import { execFileSync } from "node:child_process";
|
|
5
5
|
import { artifactsDir, dataDir, dbPath, runsDir } from "./paths.js";
|
|
@@ -9,6 +9,7 @@ import { readNativeGoal } from "./goal-store.js";
|
|
|
9
9
|
import { normalizeAcceptance } from "./acceptance.js";
|
|
10
10
|
import { createHash, randomUUID } from "node:crypto";
|
|
11
11
|
import { captureWorkspaceManifest } from "./workspace-kind.js";
|
|
12
|
+
import { buildHandoff } from "./handoff.js";
|
|
12
13
|
|
|
13
14
|
let db;
|
|
14
15
|
|
|
@@ -265,6 +266,7 @@ const CONTROL_DDL = `
|
|
|
265
266
|
verified_by TEXT
|
|
266
267
|
);
|
|
267
268
|
CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
|
|
269
|
+
CREATE INDEX IF NOT EXISTS idx_facts_supersedes ON facts(supersedes_id, state);
|
|
268
270
|
CREATE TABLE IF NOT EXISTS artifacts (
|
|
269
271
|
id TEXT PRIMARY KEY,
|
|
270
272
|
run_id TEXT NOT NULL,
|
|
@@ -465,6 +467,34 @@ function repoIdForRoot(root) {
|
|
|
465
467
|
return stableId("repo", resolve(root));
|
|
466
468
|
}
|
|
467
469
|
|
|
470
|
+
function canonicalizeRemote(value) {
|
|
471
|
+
let raw = String(value ?? "").trim();
|
|
472
|
+
if (!raw) return null;
|
|
473
|
+
const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
|
|
474
|
+
if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
|
|
475
|
+
try {
|
|
476
|
+
const parsed = new URL(raw);
|
|
477
|
+
if (parsed.protocol === "file:") {
|
|
478
|
+
const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
|
|
479
|
+
return `file://${path}`;
|
|
480
|
+
}
|
|
481
|
+
if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
|
|
482
|
+
const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
483
|
+
if (!path) return null;
|
|
484
|
+
return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
|
|
485
|
+
} catch {
|
|
486
|
+
return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function canonicalRemoteForRoot(root) {
|
|
491
|
+
try {
|
|
492
|
+
return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
|
|
493
|
+
} catch {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
468
498
|
function workItemIdForTask(taskId) {
|
|
469
499
|
return `work-${taskId}`;
|
|
470
500
|
}
|
|
@@ -473,24 +503,26 @@ export function runIdFor(taskId, attempt) {
|
|
|
473
503
|
return `run-${taskId}-${attempt}`;
|
|
474
504
|
}
|
|
475
505
|
|
|
476
|
-
function ensureControlRecords(dbInstance, task) {
|
|
506
|
+
function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
477
507
|
if (!task?.id || !task.project_root) return;
|
|
478
508
|
const now = new Date().toISOString();
|
|
479
509
|
const root = resolve(task.project_root);
|
|
480
510
|
const repoId = repoIdForRoot(root);
|
|
481
511
|
const workItemId = workItemIdForTask(task.id);
|
|
482
|
-
dbInstance.prepare(
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
512
|
+
const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
|
|
513
|
+
if (!repo || refreshRepo) {
|
|
514
|
+
const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
|
|
515
|
+
dbInstance.prepare(`
|
|
516
|
+
INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
|
|
517
|
+
VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
|
|
518
|
+
ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
|
|
519
|
+
`).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
|
|
520
|
+
}
|
|
521
|
+
const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
|
|
522
|
+
if (workItem) return;
|
|
487
523
|
dbInstance.prepare(`
|
|
488
524
|
INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
|
|
489
525
|
VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
|
|
490
|
-
ON CONFLICT(task_id) DO UPDATE SET
|
|
491
|
-
objective = COALESCE(excluded.objective, work_items.objective),
|
|
492
|
-
delivery_state = CASE WHEN work_items.delivery_state = 'draft' THEN excluded.delivery_state ELSE work_items.delivery_state END,
|
|
493
|
-
updated_at = excluded.updated_at
|
|
494
526
|
`).run({
|
|
495
527
|
id: workItemId,
|
|
496
528
|
repo_id: repoId,
|
|
@@ -502,7 +534,12 @@ function ensureControlRecords(dbInstance, task) {
|
|
|
502
534
|
}
|
|
503
535
|
|
|
504
536
|
function backfillControlRecords(dbInstance) {
|
|
505
|
-
const rows = dbInstance.prepare(
|
|
537
|
+
const rows = dbInstance.prepare(`
|
|
538
|
+
SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
|
|
539
|
+
FROM tasks AS t
|
|
540
|
+
LEFT JOIN work_items AS w ON w.task_id = t.id
|
|
541
|
+
WHERE w.task_id IS NULL
|
|
542
|
+
`).all();
|
|
506
543
|
for (const row of rows) ensureControlRecords(dbInstance, row);
|
|
507
544
|
}
|
|
508
545
|
|
|
@@ -663,10 +700,10 @@ export async function reconcileDetachedActiveTasks() {
|
|
|
663
700
|
|
|
664
701
|
export async function writeTask(task) {
|
|
665
702
|
await ensureFilesystem();
|
|
666
|
-
return writeTaskNow(task);
|
|
703
|
+
return runWithRetry(openDb(), () => writeTaskNow(task));
|
|
667
704
|
}
|
|
668
705
|
|
|
669
|
-
function writeTaskNow(task) {
|
|
706
|
+
function writeTaskNow(task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
670
707
|
const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
|
|
671
708
|
const updates = TASK_COLUMNS
|
|
672
709
|
.filter((name) => name !== "id" && name !== "created_at")
|
|
@@ -700,7 +737,7 @@ function writeTaskNow(task) {
|
|
|
700
737
|
params.phase = task.phase ?? null;
|
|
701
738
|
|
|
702
739
|
stmt.run(params);
|
|
703
|
-
ensureControlRecords(openDb(), task);
|
|
740
|
+
ensureControlRecords(openDb(), task, { refreshRepo, canonicalRemote });
|
|
704
741
|
return task;
|
|
705
742
|
}
|
|
706
743
|
|
|
@@ -725,10 +762,11 @@ function checkOwnership(taskId, incoming) {
|
|
|
725
762
|
|
|
726
763
|
export async function reserveTaskOwnership(task) {
|
|
727
764
|
await ensureFilesystem();
|
|
765
|
+
const canonicalRemote = task?.project_root ? canonicalRemoteForRoot(resolve(task.project_root)) : null;
|
|
728
766
|
const connection=openDb();
|
|
729
767
|
return runWithRetry(connection,()=>{
|
|
730
768
|
connection.exec("BEGIN IMMEDIATE");
|
|
731
|
-
try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task);connection.exec("COMMIT");return task; }
|
|
769
|
+
try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task, { refreshRepo: true, canonicalRemote });connection.exec("COMMIT");return task; }
|
|
732
770
|
catch(error){connection.exec("ROLLBACK");throw error;}
|
|
733
771
|
});
|
|
734
772
|
}
|
|
@@ -980,35 +1018,38 @@ export async function ensureRunRecord(task, attempt) {
|
|
|
980
1018
|
await ensureFilesystem();
|
|
981
1019
|
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
|
|
982
1020
|
const dbInstance = openDb();
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1021
|
+
return runWithRetry(dbInstance, () => {
|
|
1022
|
+
ensureControlRecords(dbInstance, task);
|
|
1023
|
+
const now = new Date().toISOString();
|
|
1024
|
+
const id = runIdFor(task.id, attempt);
|
|
1025
|
+
dbInstance.prepare(`
|
|
987
1026
|
INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
|
|
988
1027
|
VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
|
|
989
1028
|
ON CONFLICT(task_id, attempt) DO UPDATE SET
|
|
990
1029
|
codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
|
|
991
1030
|
worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
|
|
992
1031
|
base_sha = COALESCE(excluded.base_sha, runs.base_sha)
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1032
|
+
`).run({
|
|
1033
|
+
id,
|
|
1034
|
+
task_id: task.id,
|
|
1035
|
+
work_item_id: workItemIdForTask(task.id),
|
|
1036
|
+
attempt,
|
|
1037
|
+
codex_thread_id: task.thread_id ?? null,
|
|
1038
|
+
worktree_path: task.worktree_path ?? null,
|
|
1039
|
+
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
1040
|
+
base_sha: task.base_commit ?? null,
|
|
1041
|
+
started_at: now
|
|
1042
|
+
});
|
|
1043
|
+
return id;
|
|
1003
1044
|
});
|
|
1004
|
-
return id;
|
|
1005
1045
|
}
|
|
1006
1046
|
|
|
1007
1047
|
export async function completeRunRecord(task, attempt) {
|
|
1008
1048
|
await ensureFilesystem();
|
|
1009
1049
|
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
|
|
1010
1050
|
const now = task.completed_at ?? new Date().toISOString();
|
|
1011
|
-
openDb()
|
|
1051
|
+
const dbInstance = openDb();
|
|
1052
|
+
runWithRetry(dbInstance, () => dbInstance.prepare(`
|
|
1012
1053
|
UPDATE runs SET codex_thread_id = @codex_thread_id,
|
|
1013
1054
|
run_status = @run_status, finished_at = @finished_at
|
|
1014
1055
|
WHERE task_id = @task_id AND attempt = @attempt
|
|
@@ -1018,20 +1059,39 @@ export async function completeRunRecord(task, attempt) {
|
|
|
1018
1059
|
codex_thread_id: task.thread_id ?? null,
|
|
1019
1060
|
run_status: task.status ?? "unknown",
|
|
1020
1061
|
finished_at: now
|
|
1021
|
-
});
|
|
1062
|
+
}));
|
|
1022
1063
|
}
|
|
1023
1064
|
|
|
1024
|
-
export async function
|
|
1065
|
+
export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
|
|
1025
1066
|
await ensureFilesystem();
|
|
1067
|
+
if (!Array.isArray(events) || events.length === 0) return [];
|
|
1026
1068
|
const dbInstance = openDb();
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1069
|
+
return runWithRetry(dbInstance, () => {
|
|
1070
|
+
dbInstance.exec("BEGIN IMMEDIATE");
|
|
1071
|
+
try {
|
|
1072
|
+
const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
|
|
1073
|
+
const insert = dbInstance.prepare(`
|
|
1030
1074
|
INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
|
|
1031
1075
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1076
|
+
`);
|
|
1077
|
+
const createdAt = new Date().toISOString();
|
|
1078
|
+
const records = events.map((event, index) => {
|
|
1079
|
+
const payload = JSON.stringify(event);
|
|
1080
|
+
const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
|
|
1081
|
+
createHash("sha256").update(payload).digest("hex"));
|
|
1082
|
+
return { id: Number(result.lastInsertRowid), run_id: runId, actor };
|
|
1083
|
+
});
|
|
1084
|
+
dbInstance.exec("COMMIT");
|
|
1085
|
+
return records;
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
dbInstance.exec("ROLLBACK");
|
|
1088
|
+
throw error;
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
export async function appendTaskEvent(taskId, event, options = {}) {
|
|
1094
|
+
return (await appendTaskEvents(taskId, [event], options))[0];
|
|
1035
1095
|
}
|
|
1036
1096
|
|
|
1037
1097
|
export async function readTaskEvents(taskId, limit = 100, kinds = null) {
|
|
@@ -1109,7 +1169,7 @@ export async function recordFact({
|
|
|
1109
1169
|
valid_for_sha: validForSha,
|
|
1110
1170
|
valid_for_content_hash: validForContentHash,
|
|
1111
1171
|
valid_for_manifest_hash: validForManifestHash,
|
|
1112
|
-
watched_paths: JSON.stringify(watchedPaths.map((path) => resolve(path))),
|
|
1172
|
+
watched_paths: JSON.stringify(watchedPaths.map((path) => isAbsolute(path) ? resolve(path) : path)),
|
|
1113
1173
|
expires_at: expiresAt,
|
|
1114
1174
|
supersedes_id: supersedesId,
|
|
1115
1175
|
created_at: now,
|
|
@@ -1126,6 +1186,15 @@ function pathsOverlap(left, right) {
|
|
|
1126
1186
|
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
1127
1187
|
}
|
|
1128
1188
|
|
|
1189
|
+
function repoRelativePaths(projectRoot, paths) {
|
|
1190
|
+
return (paths ?? []).flatMap((path) => {
|
|
1191
|
+
if (typeof path !== "string" || !path.trim()) return [];
|
|
1192
|
+
const candidate = isAbsolute(path) ? relative(projectRoot, path) : path;
|
|
1193
|
+
const normalized = candidate.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
1194
|
+
return !normalized || normalized === ".." || normalized.startsWith("../") ? [] : [normalized];
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1129
1198
|
function git(cwd, args) {
|
|
1130
1199
|
return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
|
|
1131
1200
|
encoding: "utf8",
|
|
@@ -1147,7 +1216,7 @@ function shaCoversBase(projectRoot, validForSha, baseSha) {
|
|
|
1147
1216
|
function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
|
|
1148
1217
|
if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
|
|
1149
1218
|
try {
|
|
1150
|
-
const relativePaths =
|
|
1219
|
+
const relativePaths = repoRelativePaths(projectRoot, watchedPaths);
|
|
1151
1220
|
if (relativePaths.length === 0) return true;
|
|
1152
1221
|
return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
|
|
1153
1222
|
} catch {
|
|
@@ -1165,8 +1234,26 @@ async function currentWorkspaceManifest(task) {
|
|
|
1165
1234
|
}
|
|
1166
1235
|
}
|
|
1167
1236
|
|
|
1237
|
+
async function currentContextContentHash(task) {
|
|
1238
|
+
const context = task.input_context?.context ?? [];
|
|
1239
|
+
if (!Array.isArray(context) || context.length === 0) return null;
|
|
1240
|
+
try {
|
|
1241
|
+
return (await buildHandoff({ context }, { maxLines: 1, maxChars: 1 })).content_hash;
|
|
1242
|
+
} catch {
|
|
1243
|
+
return null;
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1168
1247
|
function markFactExpired(id) {
|
|
1169
|
-
openDb().prepare(
|
|
1248
|
+
openDb().prepare(`
|
|
1249
|
+
INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id,
|
|
1250
|
+
valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
|
|
1251
|
+
SELECT ?, source.work_item_id, source.scope_type, source.scope_id, source.key, source.value_json, 'expired', source.source_event_id, source.source_artifact_id,
|
|
1252
|
+
source.valid_for_sha, source.valid_for_content_hash, source.valid_for_manifest_hash, source.watched_paths, source.expires_at, source.id, ?, source.verified_at, source.verified_by
|
|
1253
|
+
FROM facts AS source
|
|
1254
|
+
WHERE source.id = ? AND source.state = 'verified'
|
|
1255
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = source.id AND transition.state IN ('expired', 'revoked'))
|
|
1256
|
+
`).run(randomUUID(), new Date().toISOString(), id);
|
|
1170
1257
|
}
|
|
1171
1258
|
|
|
1172
1259
|
export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
|
|
@@ -1178,31 +1265,45 @@ export async function listContextFacts({ taskId, baseSha, ownedPaths = [], depen
|
|
|
1178
1265
|
const dependencyItems = dependencyTaskIds.length === 0
|
|
1179
1266
|
? []
|
|
1180
1267
|
: openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
|
|
1181
|
-
const rows = openDb().prepare(
|
|
1268
|
+
const rows = openDb().prepare(`
|
|
1269
|
+
SELECT facts.* FROM facts
|
|
1270
|
+
WHERE state = 'verified'
|
|
1271
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1272
|
+
ORDER BY created_at ASC
|
|
1273
|
+
`).all();
|
|
1182
1274
|
const now = Date.now();
|
|
1183
1275
|
const workspaceManifest = await currentWorkspaceManifest(task);
|
|
1276
|
+
const contextContentHash = await currentContextContentHash(task);
|
|
1277
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1278
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1279
|
+
const ownedRelative = repoRelativePaths(task.project_root, ownedPaths);
|
|
1184
1280
|
const visible = [];
|
|
1185
1281
|
for (const row of rows) {
|
|
1282
|
+
const watched = decodeJson(row.watched_paths, []);
|
|
1283
|
+
const watchedRelative = repoRelativePaths(task.project_root, watched);
|
|
1284
|
+
const included = row.scope_type === "work_item" ? row.scope_id === workItem.id
|
|
1285
|
+
: row.scope_type === "dependency" ? dependencyItems.includes(row.scope_id)
|
|
1286
|
+
: row.scope_type === "repo_verified" && canonicalRemote && row.scope_id === canonicalRemote
|
|
1287
|
+
&& watchedRelative.length > 0 && watchedRelative.some((path) => ownedRelative.some((owned) => pathsOverlap(path, owned)));
|
|
1288
|
+
if (!included) continue;
|
|
1186
1289
|
if (row.expires_at && Date.parse(row.expires_at) <= now) {
|
|
1187
1290
|
markFactExpired(row.id);
|
|
1188
1291
|
continue;
|
|
1189
1292
|
}
|
|
1190
|
-
|
|
1191
|
-
if (
|
|
1192
|
-
markFactExpired(row.id);
|
|
1293
|
+
if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha)) continue;
|
|
1294
|
+
if (watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watchedRelative)) {
|
|
1295
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1193
1296
|
continue;
|
|
1194
1297
|
}
|
|
1195
1298
|
if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
|
|
1196
|
-
markFactExpired(row.id);
|
|
1299
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id && workspaceManifest) markFactExpired(row.id);
|
|
1197
1300
|
continue;
|
|
1198
1301
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
})();
|
|
1205
|
-
if (included) visible.push({
|
|
1302
|
+
if (row.valid_for_content_hash && contextContentHash !== row.valid_for_content_hash) {
|
|
1303
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
visible.push({
|
|
1206
1307
|
...row,
|
|
1207
1308
|
value: decodeJson(row.value_json, null),
|
|
1208
1309
|
watched_paths: watched
|
|
@@ -1213,7 +1314,11 @@ export async function listContextFacts({ taskId, baseSha, ownedPaths = [], depen
|
|
|
1213
1314
|
|
|
1214
1315
|
export async function countVerifiedFacts() {
|
|
1215
1316
|
await ensureFilesystem();
|
|
1216
|
-
return openDb().prepare(
|
|
1317
|
+
return openDb().prepare(`
|
|
1318
|
+
SELECT COUNT(*) AS count FROM facts
|
|
1319
|
+
WHERE state = 'verified'
|
|
1320
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1321
|
+
`).get().count;
|
|
1217
1322
|
}
|
|
1218
1323
|
|
|
1219
1324
|
export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
|
|
@@ -1253,10 +1358,29 @@ export async function getTaskForWorkItem(workItemId) {
|
|
|
1253
1358
|
return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
|
|
1254
1359
|
}
|
|
1255
1360
|
|
|
1361
|
+
export async function isFactRevoked(factId) {
|
|
1362
|
+
await ensureFilesystem();
|
|
1363
|
+
return Boolean(openDb().prepare("SELECT 1 FROM facts WHERE supersedes_id = ? AND state = 'revoked'").get(factId));
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
export async function getFactEffectiveState(factId) {
|
|
1367
|
+
await ensureFilesystem();
|
|
1368
|
+
const transition = openDb().prepare(`
|
|
1369
|
+
SELECT state FROM facts WHERE supersedes_id = ? AND state IN ('revoked', 'expired')
|
|
1370
|
+
ORDER BY CASE state WHEN 'revoked' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
|
|
1371
|
+
`).get(factId);
|
|
1372
|
+
return transition?.state ?? null;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1256
1375
|
export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
|
|
1257
1376
|
await ensureFilesystem();
|
|
1258
1377
|
const source = await getFact(factId);
|
|
1259
1378
|
if (!source) throw new Error(`fact not found: ${factId}`);
|
|
1379
|
+
if (await isFactRevoked(factId)) {
|
|
1380
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
1381
|
+
error.code = "fact_already_revoked";
|
|
1382
|
+
throw error;
|
|
1383
|
+
}
|
|
1260
1384
|
if (source.state !== "candidate") {
|
|
1261
1385
|
const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
|
|
1262
1386
|
error.code = "fact_not_candidate";
|
|
@@ -1265,16 +1389,30 @@ export async function promoteCandidateFact({ factId, scopeType = "work_item", wa
|
|
|
1265
1389
|
if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
|
|
1266
1390
|
const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
|
|
1267
1391
|
if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
|
|
1392
|
+
const sourceTask = await getTaskForWorkItem(workItem.id);
|
|
1268
1393
|
const paths = watchedPaths ?? source.watched_paths ?? [];
|
|
1394
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1395
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1396
|
+
const normalizedRepoPaths = sourceTask ? repoRelativePaths(sourceTask.project_root, paths) : [];
|
|
1269
1397
|
if (scopeType === "repo_verified" && paths.length === 0) {
|
|
1270
1398
|
const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
|
|
1271
1399
|
error.code = "repo_fact_requires_paths";
|
|
1272
1400
|
throw error;
|
|
1273
1401
|
}
|
|
1402
|
+
if (scopeType === "repo_verified" && !canonicalRemote) {
|
|
1403
|
+
const error = new Error("repo_verified promotion requires a canonical origin remote; facts from an unrecognized or missing remote stay work-scoped");
|
|
1404
|
+
error.code = "repo_fact_requires_canonical_remote";
|
|
1405
|
+
throw error;
|
|
1406
|
+
}
|
|
1407
|
+
if (scopeType === "repo_verified" && normalizedRepoPaths.length === 0) {
|
|
1408
|
+
const error = new Error("repo_verified watchedPaths must stay inside the repository root");
|
|
1409
|
+
error.code = "repo_fact_paths_outside_root";
|
|
1410
|
+
throw error;
|
|
1411
|
+
}
|
|
1274
1412
|
return recordFact({
|
|
1275
1413
|
workItemId: source.work_item_id,
|
|
1276
1414
|
scopeType,
|
|
1277
|
-
scopeId: scopeType === "repo_verified" ?
|
|
1415
|
+
scopeId: scopeType === "repo_verified" ? canonicalRemote : workItem.id,
|
|
1278
1416
|
key: source.key,
|
|
1279
1417
|
value: source.value,
|
|
1280
1418
|
state: "verified",
|
|
@@ -1283,7 +1421,7 @@ export async function promoteCandidateFact({ factId, scopeType = "work_item", wa
|
|
|
1283
1421
|
validForSha: source.valid_for_sha ?? null,
|
|
1284
1422
|
validForContentHash: source.valid_for_content_hash ?? null,
|
|
1285
1423
|
validForManifestHash: source.valid_for_manifest_hash ?? null,
|
|
1286
|
-
watchedPaths: paths,
|
|
1424
|
+
watchedPaths: scopeType === "repo_verified" ? normalizedRepoPaths : paths,
|
|
1287
1425
|
expiresAt: expiresAt ?? source.expires_at ?? null,
|
|
1288
1426
|
supersedesId: source.id,
|
|
1289
1427
|
verifiedBy
|
|
@@ -1294,8 +1432,33 @@ export async function revokeFact(factId) {
|
|
|
1294
1432
|
await ensureFilesystem();
|
|
1295
1433
|
const source = await getFact(factId);
|
|
1296
1434
|
if (!source) return null;
|
|
1297
|
-
|
|
1298
|
-
|
|
1435
|
+
if (!["candidate", "verified"].includes(source.state)) {
|
|
1436
|
+
const error = new Error(`only candidate or verified facts may be revoked; ${factId} is ${source.state}`);
|
|
1437
|
+
error.code = "fact_not_revocable";
|
|
1438
|
+
throw error;
|
|
1439
|
+
}
|
|
1440
|
+
if (await isFactRevoked(factId)) {
|
|
1441
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
1442
|
+
error.code = "fact_already_revoked";
|
|
1443
|
+
throw error;
|
|
1444
|
+
}
|
|
1445
|
+
return recordFact({
|
|
1446
|
+
workItemId: source.work_item_id,
|
|
1447
|
+
scopeType: source.scope_type,
|
|
1448
|
+
scopeId: source.scope_id,
|
|
1449
|
+
key: source.key,
|
|
1450
|
+
value: source.value,
|
|
1451
|
+
state: "revoked",
|
|
1452
|
+
sourceEventId: source.source_event_id,
|
|
1453
|
+
sourceArtifactId: source.source_artifact_id,
|
|
1454
|
+
validForSha: source.valid_for_sha,
|
|
1455
|
+
validForContentHash: source.valid_for_content_hash,
|
|
1456
|
+
validForManifestHash: source.valid_for_manifest_hash,
|
|
1457
|
+
watchedPaths: source.watched_paths,
|
|
1458
|
+
expiresAt: source.expires_at,
|
|
1459
|
+
supersedesId: source.id,
|
|
1460
|
+
verifiedBy: "main_thread"
|
|
1461
|
+
});
|
|
1299
1462
|
}
|
|
1300
1463
|
|
|
1301
1464
|
export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
|
|
@@ -1322,7 +1485,10 @@ export async function getArtifact(artifactId) {
|
|
|
1322
1485
|
export async function readArtifact(artifactId, maxChars = 12000) {
|
|
1323
1486
|
const artifact = await getArtifact(artifactId);
|
|
1324
1487
|
if (!artifact) return null;
|
|
1325
|
-
|
|
1488
|
+
const artifactPath = relative(artifactsDir, resolve(artifact.uri));
|
|
1489
|
+
if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) {
|
|
1490
|
+
return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
|
|
1491
|
+
}
|
|
1326
1492
|
let content;
|
|
1327
1493
|
try {
|
|
1328
1494
|
content = await readFile(artifact.uri, "utf8");
|
package/src/worker-preflight.js
CHANGED
|
@@ -22,8 +22,16 @@ function uniqueSorted(values) {
|
|
|
22
22
|
|
|
23
23
|
export function normalizeObservedCommand(command) {
|
|
24
24
|
const text = String(command ?? "").trim();
|
|
25
|
-
const wrapped = text.match(/^(?:[^\s]+\/)?(?:zsh|bash|sh)\s+-l?c\s+([
|
|
26
|
-
|
|
25
|
+
const wrapped = text.match(/^(?:[^\s]+\/)?(?:zsh|bash|sh)\s+-l?c\s+([\s\S]+)$/);
|
|
26
|
+
if (!wrapped) return text;
|
|
27
|
+
let body = wrapped[1].trim();
|
|
28
|
+
const quote = body[0];
|
|
29
|
+
if ((quote === "'" || quote === '"') && body.at(-1) === quote) body = body.slice(1, -1);
|
|
30
|
+
// Codex displays a shell command that already contains single quotes by
|
|
31
|
+
// closing and reopening the outer quote around them: -run '"^Test$'"'.
|
|
32
|
+
// Decode that display-only wrapping before comparing it with the contract.
|
|
33
|
+
body = body.replace(/'"'/g, "'");
|
|
34
|
+
return body.trim();
|
|
27
35
|
}
|
|
28
36
|
|
|
29
37
|
export function buildRuntimeContract({
|