agent-supervisor-mcp 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +208 -0
- package/README.md +206 -2
- package/package.json +76 -4
- package/skills/agent-supervisor/SKILL.md +139 -0
- package/src/app/acceptance.js +263 -0
- package/src/app/auto-cleanup.js +91 -0
- package/src/app/cancel.js +57 -0
- package/src/app/cleanup-facts.js +101 -0
- package/src/app/cleanup-plan.js +166 -0
- package/src/app/compose.js +17 -0
- package/src/app/context-compiler.js +83 -0
- package/src/app/dispatch.js +398 -0
- package/src/app/followup.js +104 -0
- package/src/app/land-chain.js +134 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/restore-worktree.js +51 -0
- package/src/app/resume.js +179 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/app/side-chat.js +370 -0
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +114 -0
- package/src/app/worktree-setup.js +218 -0
- package/src/domain/acceptance-baseline.js +65 -0
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/cleanup-policy.js +44 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/domain/failure-class.js +63 -0
- package/src/domain/owned-changes.js +27 -0
- package/src/domain/prompt.js +161 -0
- package/src/domain/side-turn-view.js +73 -0
- package/src/domain/status.js +50 -0
- package/src/domain/thread-health.js +33 -0
- package/src/domain/truncate.js +148 -0
- package/src/domain/worker-branch.js +6 -0
- package/src/domain/worker-changes.js +58 -0
- package/src/domain/worker-env.js +14 -0
- package/src/domain/worker-preflight.js +167 -0
- package/src/domain/worker-report.js +85 -0
- package/src/domain/worker-report.schema.json +10 -0
- package/src/infra/bin-resolver.js +287 -0
- package/src/infra/cleanup-hint.js +29 -0
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/external-output.js +29 -0
- package/src/infra/git.js +61 -0
- package/src/infra/handoff.js +38 -0
- package/src/infra/paths.js +34 -0
- package/src/infra/process.js +59 -0
- package/src/infra/sandbox-roots.js +106 -0
- package/src/infra/skill-sync.js +109 -0
- package/src/infra/stage-store.js +39 -0
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +149 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +173 -0
- package/src/infra/store/records.js +171 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +351 -0
- package/src/infra/update/auto-update-worker.js +186 -0
- package/src/infra/update/auto-update.js +143 -0
- package/src/infra/update/update-check.js +246 -0
- package/src/infra/workspace-kind.js +165 -0
- package/src/infra/worktree.js +361 -0
- package/src/interface/bin/acceptance-cli.js +62 -0
- package/src/interface/bin/cleanup.js +81 -0
- package/src/interface/bin/monitor.jsx +301 -0
- package/src/interface/bin/setup.js +342 -0
- package/src/interface/bin/stage.js +17 -0
- package/src/interface/bin/web-server.js +53 -0
- package/src/interface/mcp/handlers/delivery.js +165 -0
- package/src/interface/mcp/handlers/dispatch.js +236 -0
- package/src/interface/mcp/handlers/facts.js +204 -0
- package/src/interface/mcp/handlers/overview.js +106 -0
- package/src/interface/mcp/handlers/results.js +262 -0
- package/src/interface/mcp/handlers/review.js +115 -0
- package/src/interface/mcp/handlers/wait.js +141 -0
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +64 -0
- package/src/interface/mcp/tools/deliver.js +48 -0
- package/src/interface/mcp/tools/dispatch.js +90 -0
- package/src/interface/mcp/tools/optional.js +57 -0
- package/src/interface/mcp/tools/read.js +115 -0
- package/src/interface/mcp/tools/run.js +57 -0
- package/src/interface/mcp/tools/shapes.js +67 -0
- package/src/interface/mcp/tools/track.js +84 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +224 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +227 -0
- package/src/mcp-server.js +4 -0
- package/src/run-host/entry.js +26 -0
- package/src/run-host/finalize.js +243 -0
- package/src/run-host/launch.js +49 -0
- package/src/run-host/live-run.js +76 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +102 -0
- package/src/run-host/track.js +132 -0
- package/src/runners/claude/adapter.js +118 -0
- package/src/runners/claude/events.js +100 -0
- package/src/runners/claude/tool-guard.js +48 -0
- package/src/runners/codex/adapter.js +157 -0
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/runners/codex/event-parser.js +266 -0
- package/src/runners/codex/goal-store.js +54 -0
- package/src/runners/codex/mcp-config.js +39 -0
- package/src/runners/codex/tool-guard.js +184 -0
- package/src/runners/contract-check.js +82 -0
- package/src/runners/contract.js +53 -0
- package/src/runners/registry.js +45 -0
- package/web/dist/assets/index-D-A2xlpx.js +154 -0
- package/web/dist/assets/index-f8esISCp.css +2 -0
- package/web/dist/index.html +15 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: agent-supervisor
|
|
3
|
+
description: 用 Codex CLI 或 Claude Code 当 worker,并行做可独立验收的功能包,每路一个 Git worktree,能派单、等待、验收、恢复、合入和清理。用户说“派 codex”“派 claude”“并行跑”“多 agent”“接回旧 worker”时使用。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# agent-supervisor
|
|
7
|
+
|
|
8
|
+
主线程负责拆包、定写集、准备环境、验收和合入。worker 只在自己的 worktree 里完成一个功能包,不负责编排,也不负责交付到远端。
|
|
9
|
+
|
|
10
|
+
## 什么时候用
|
|
11
|
+
|
|
12
|
+
适合能拆成几路、每路能单独验收的活,也适合耗时长、中途可能断、需要保留证据的工作。纯问答、单文件小改、需要频繁来回确认的活,主线程自己做更快。
|
|
13
|
+
|
|
14
|
+
## 14 个工具
|
|
15
|
+
|
|
16
|
+
| 阶段 | 工具 |
|
|
17
|
+
|---|---|
|
|
18
|
+
| 派单前 | `preflight_worker` |
|
|
19
|
+
| 派单 | `create_worker`、`resume_worker`、`cancel_worker` |
|
|
20
|
+
| 盯进度 | `poll_workers`、`wait_workers` |
|
|
21
|
+
| 收活 | `get_worker`、`get_worker_diff`、`ask_worker` |
|
|
22
|
+
| 交付 | `land_worker`、`verify_push`、`cleanup` |
|
|
23
|
+
| 批次 | `find_works`、`describe_session` |
|
|
24
|
+
|
|
25
|
+
参数全是 snake_case,写错名字会被直接拒绝,不会被悄悄忽略。失败的调用带 `isError` 和一个稳定的 `error` 码。`facts`、`review`、`get_artifact` 默认不开,要用时让用户设 `AGENT_SUPERVISOR_TOOLS=all`。
|
|
26
|
+
|
|
27
|
+
## 派单前必须确认
|
|
28
|
+
|
|
29
|
+
1. 先 `find_works`,确认没有重复派工。
|
|
30
|
+
2. 按功能闭环拆包,不按 DTO、方法或单个测试拆。每路要有清楚的输入、产出和 acceptance。
|
|
31
|
+
3. `owned_paths` 要覆盖完整写集:实现、测试、路由、注册表、DI、配置、迁移、i18n、模板接线都算。拿不准就给唯一模块目录。
|
|
32
|
+
4. 依赖必须提前放进 worktree,用 `workspace.setup`。前端链接 `node_modules` 并执行 `nuxi prepare`;后端初始化 submodule。不要等主线程事后补。
|
|
33
|
+
5. 写 worker 先用同一套参数跑 `preflight_worker`(带 `probe_commands`)。`get_worker` 的 `include: ["preflight"]` 必须是 `passed`,再把那个 task id 填进 `preflight_id`。只给 `acceptance` 的 preflight 只是试跑验收命令,不能代替环境预检。
|
|
34
|
+
6. 只要 worker 会 land,就必须有能证明结果的 acceptance。文件存在检查只能当附加条件。
|
|
35
|
+
7. `workspace-write` worker 不执行 `git add`、`git commit` 或 `amend`。验收通过后由主线程 `land_worker` 带 `commit_message` 代提交并落地。Git 干净、提交数量和提交信息由主线程在 land 后检查。
|
|
36
|
+
8. worker 不 push、不合并、不再派生 worker。`worker/<id>` 分支不是交付物。
|
|
37
|
+
|
|
38
|
+
## create_worker 的参数
|
|
39
|
+
|
|
40
|
+
顶层:`task`、`cwd`、`owned_paths`、`goal`、`title`、`followup_of`、`depends_on`、`preflight_id`、`runner`、`model`、`reasoning_effort`。其余按组放进对象:
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"task": "背景、文档出处、完整写集、验证命令、输出格式",
|
|
45
|
+
"cwd": "/repo",
|
|
46
|
+
"owned_paths": ["src/feature", "test/feature"],
|
|
47
|
+
"goal": { "objective": "一句话说清做完是什么样" },
|
|
48
|
+
"session": { "id": "batch-1", "title": "补单测" },
|
|
49
|
+
"workspace": {
|
|
50
|
+
"setup": {
|
|
51
|
+
"links": [{ "path": "node_modules", "source": "node_modules" }],
|
|
52
|
+
"submodules": true,
|
|
53
|
+
"commands": ["npx nuxi prepare"]
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"sandbox": { "allowed_commands": ["pnpm vitest run test/feature/*"] },
|
|
57
|
+
"acceptance": { "commands": ["pnpm vitest run test/feature"] }
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| 参数 | 怎么填 |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `task` | 写清目标、背景、要改的交付面、边界和验收。最终报告格式由 supervisor 追加,不在这里重复 |
|
|
64
|
+
| `owned_paths` | 完整写入范围;不同 worker 不能重叠,读取不排他。`[]` 只用于不 land 的只读或研究 worker |
|
|
65
|
+
| `goal.objective` | worker 会创建 Codex 原生 goal。`goal.token_budget` 不传就是不限;别传 `0`、`1` 或 `null` |
|
|
66
|
+
| `session.id` | 同一批用同一个值。只负责分组、默认验收和审批,不会把同批 worker 的上下文互相注入 |
|
|
67
|
+
| `workspace.kind` | Git 代码默认 `git_worktree`;非 Git 只读用 `read_only_in_place`;联网研究用 `scratch`;明确授权才用 `in_place_write` |
|
|
68
|
+
| `workspace.base_ref` | worktree 从哪个提交切。要包含上一步时填上一路的 `worker/<task_id>` 或已集成分支 |
|
|
69
|
+
| `workspace.setup` | `links.source` 按 `cwd` 解析,也可写绝对路径。验收用了 npm、pnpm、vitest、eslint、nuxi 这类本地工具却没给 setup,会直接返回 `workspace_setup_required` |
|
|
70
|
+
| `sandbox.mode` | 默认 `workspace-write`。这个沙箱不能 commit,是正常边界;不要为了提交改用 `danger-full-access` |
|
|
71
|
+
| `sandbox.allowed_commands` | 会执行、会写入或有副作用的验证命令。只读命令有白名单;末尾 `*` 表示前缀匹配 |
|
|
72
|
+
| `sandbox.forbid` | 明确禁止的命令片段,优先于 allowed_commands 和 acceptance |
|
|
73
|
+
| `acceptance.commands` | worker 退出后由 supervisor 在 worktree 里执行,全部退出 0 才算过。worker 自查统一跑 `node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI"`,不要手抄命令 |
|
|
74
|
+
| `depends_on` | 上游 task id。上游必须已结算、验收通过并 land,且本路 base 包含它 |
|
|
75
|
+
| `followup_of` | 接着一路已结束的 worker 干:从它的分支切新 worktree,没给的参数沿用它的 |
|
|
76
|
+
| `runner` | 用哪个 CLI 当 worker:`codex`(默认)或 `claude`。`claude` 没有系统沙箱:只能 `git_worktree` 或 `read_only_in_place`,shell 只放行只读命令和 `sandbox.allowed_commands` 里声明的命令,不支持 `ask_worker`。preflight 和正式派单要用同一个 runner |
|
|
77
|
+
| `preflight_id` | 写 worker 必填。base、workspace、sandbox、owned_paths、context 有任何变化都要重跑 preflight |
|
|
78
|
+
|
|
79
|
+
回执不回传 task 原文,带 `id`、`worktree_path`、`branch`、`owned_paths`、`status`。
|
|
80
|
+
|
|
81
|
+
| worker 形状 | 参数 | 用途 |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| Git 编辑 | 默认 workspace,非空 `owned_paths` | 改代码、跑 acceptance、等主线程 land |
|
|
84
|
+
| 只读验收 | `workspace.kind: "read_only_in_place"`、`sandbox.mode: "read-only"`、`owned_paths: []` | 无写入、无网络,只给结论 |
|
|
85
|
+
| 联网研究 | `workspace.kind: "scratch"`、`sandbox.network_access: true`、`owned_paths: []` | 可以 curl/gh,只写 scratch,永不 land |
|
|
86
|
+
| 非 Git 写入 | `workspace.kind: "in_place_write"`、`workspace.in_place_authorization`、acceptance | 只改明确授权的非 Git 目录 |
|
|
87
|
+
|
|
88
|
+
## 等待与状态
|
|
89
|
+
|
|
90
|
+
- `poll_workers` 不带 `cursor` 返回全表和一个 `next_cursor`,只读,不启动任何东西。
|
|
91
|
+
- 带上那个 `cursor` 再调,只返回这之后的变化:`transitions` 里是结束、失败或需要关注的 worker 和下一步;`quiet: true` 表示没事发生。带 cursor 的调用还会顺带做两件事:把已死的第一轮恢复一次,把可以清的 worktree 清掉。
|
|
92
|
+
- 长任务用宿主 `/loop 5m` 调带 cursor 的 `poll_workers`。cursor 存在状态库里,主线程重启后接着用。
|
|
93
|
+
- 短等用 `wait_workers`,一次最多 60 秒;`timeout_capped` 表示请求被限成短等,`still_running` 只表示预算用完。确认宿主允许长调用才传 `allow_long_wait: true`。
|
|
94
|
+
- `idle_seconds` 是距上一条事件的时间。`command_running: true` 时长命令可能还在跑;没有命令又长时间无事件,再用 `get_worker` 的 `include: ["events"]` 查。
|
|
95
|
+
- 活跃线程超过交接阈值时每个 run 提醒一次;先看状态,等当前步骤结算或明确取消后再用 `followup_of` 接续,不要因为 token 多就重复起同一个任务。
|
|
96
|
+
- 不要用 shell 循环 grep `data/runs/*.jsonl` 判断状态,以 supervisor 状态机为准。
|
|
97
|
+
|
|
98
|
+
## 收活顺序
|
|
99
|
+
|
|
100
|
+
1. `get_worker` 的 `include: ["result"]`:先看 `acceptance`,再看它真跑过的命令和退出码。失败时把 `checks[].output_tail` 原样带回 resume,不改验收标准。
|
|
101
|
+
2. `get_worker_diff`:先看文件和 hunk 索引,再按 `file` + `hunk` / `cursor` 分页读 patch。它说做了什么不算,diff 里有才算。
|
|
102
|
+
3. 对不上就 `ask_worker`。旁路只读,不改 worker 线程。
|
|
103
|
+
4. 要改就 `resume_worker`。主线前进时带 `rebase_onto: "HEAD"`。原生 goal 未明确 complete 时,续跑会省略 output schema,避免 `ActiveTurnOutputSchemaMismatch`。
|
|
104
|
+
5. 验收和 diff 都过了,`land_worker` 带 `commit_message`。
|
|
105
|
+
|
|
106
|
+
接续链:整条链先审各路 acceptance 和 diff,再 `land_worker` 带 `include_followup_parents: true` 和 `commit_messages`,按 root-first 落地;途中失败保留已落地部分,修复后重调。`ignore_acceptance`、`allow_outside_owned` 只对指定的那一路生效,只在用户明说时用。
|
|
107
|
+
|
|
108
|
+
`invalid_report` 不是业务失败,通常是报告 JSON 不合规。带 cursor 的 `poll_workers` 会自动让它重发一次;仍失败时,acceptance 通过且 diff 审过,可以直接 land。报告只是摘要,不是交付证据。
|
|
109
|
+
|
|
110
|
+
## 中断与恢复
|
|
111
|
+
|
|
112
|
+
| 情况 | 处理 |
|
|
113
|
+
|---|---|
|
|
114
|
+
| 主线程挂了 | worker 的独立进程会继续记录日志、状态和验收。新窗口用 `find_works` 按 session 接回 |
|
|
115
|
+
| worker 变 `lost` | 确实中断才 `resume_worker`;worktree、改动和线程都保留 |
|
|
116
|
+
| worker 变 `timed_out` | 时间预算用完被停掉,不会自动重试。先看已有改动;`run_time_limit` 可以 `resume_worker`(每轮重新计时),`total_time_limit` 只能 `followup_of` 带新 `limits` 接续 |
|
|
117
|
+
| worktree 落后主线 | `resume_worker` 带 `rebase_onto: "HEAD"` |
|
|
118
|
+
| worker 失败 | 先看 `failure`:`source` 是 `auth`(登录或 key,重试没用)、`provider`(上游,`retryable` 为 true 就等一会再 resume)、`runner_config`(配置或模型名)、`workspace_setup`、`model_output`、`acceptance`、`time_limit`、`worker_process`。进程非零退出时 `failure.detail` 是它 stderr 的最后一行 |
|
|
119
|
+
| worktree 被清掉了 | 照常 `resume_worker` / `land_worker` / `get_worker_diff` / `ask_worker`,会从分支切回来 |
|
|
120
|
+
|
|
121
|
+
审批、认证、权限、quota 和时间限制造成的停顿不会被自动重试。
|
|
122
|
+
|
|
123
|
+
## 落地、push 和清理
|
|
124
|
+
|
|
125
|
+
`land_worker` 只完成本地集成,不等于远端交付。
|
|
126
|
+
|
|
127
|
+
1. 主线程自己的改动要 commit 并 push。集成分支 push 后用 `verify_push` 证明 landed head 已到远端。它只验证,不替你 push。
|
|
128
|
+
2. worker 分支通常不 push。
|
|
129
|
+
3. 清理是自动的:已合入或没有改动的 worktree 在轮询时直接删;没合入的保留 7 天,到期先把未提交改动存进它的分支再删。分支、事件、日志、证据永远保留。
|
|
130
|
+
4. 想知道某个 worktree 为什么还在,或想立刻清:`cleanup` 的 `action: "plan"` 看判定,`action: "apply"` 带 `plan_id` 和 `item_ids` 清 SAFE 项。
|
|
131
|
+
|
|
132
|
+
## 常见坑
|
|
133
|
+
|
|
134
|
+
- worktree 从提交创建。主工作区未提交的东西 worker 看不到,先 commit。
|
|
135
|
+
- `exit_code: 0` 不等于业务完成;acceptance 和 diff 才是证据。
|
|
136
|
+
- `owned_paths` 的冲突在派单时预留,运行时守卫拦直接写文件,land 再查完整 diff。你放行的脚本仍可能有清单外的副作用,它不是文件系统沙箱。
|
|
137
|
+
- worktree 只隔离工作目录。端口、数据库、临时目录仍然共享。
|
|
138
|
+
- 看板用 `agent-supervisor-web` 打开 `http://127.0.0.1:7877`。看板只看,不派单、不取消。
|
|
139
|
+
- 安装或升级后要重开会话,MCP 和 skill 才会加载新版本。
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// The supervisor's own run of a worker's acceptance commands.
|
|
2
|
+
//
|
|
3
|
+
// A worker's report says what it did; its command history says what it ran.
|
|
4
|
+
// Neither says whether the work is right. The one thing a harness can check
|
|
5
|
+
// is a criterion the dispatcher wrote down: run these commands in the
|
|
6
|
+
// worktree once the worker has exited, every one must exit 0. The worker
|
|
7
|
+
// never grades its own homework here: the commands run after it is gone,
|
|
8
|
+
// in a process it did not start, and the verdict is recorded next to its
|
|
9
|
+
// report so a reviewer sees both.
|
|
10
|
+
//
|
|
11
|
+
// The commands are shell lines written by the main thread, so they run with
|
|
12
|
+
// the supervisor's own privileges, exactly as if the main thread had run
|
|
13
|
+
// them itself. That is the trust model and it is stated in the tool text.
|
|
14
|
+
import { runSync, spawnProcess } from "../infra/process.js";
|
|
15
|
+
import { existsSync } from "node:fs";
|
|
16
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { dirname, join, isAbsolute, relative, resolve } from "node:path";
|
|
19
|
+
import { findBinaryPath } from "../infra/bin-resolver.js";
|
|
20
|
+
import { compareFailureBaseline } from "../domain/acceptance-baseline.js";
|
|
21
|
+
import { MAX_ACCEPTANCE_COMMANDS, normalizeAcceptance } from "../domain/acceptance-spec.js";
|
|
22
|
+
|
|
23
|
+
export { MAX_ACCEPTANCE_COMMANDS, normalizeAcceptance };
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_ACCEPTANCE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
26
|
+
const OUTPUT_TAIL_BYTES = 2000;
|
|
27
|
+
const KILL_GRACE_MS = 3000;
|
|
28
|
+
const ARTIFACT_ONLY = /^(?:test\s+-[efsd]\s+[^;&|]+|\[\[?\s+-[efsd]\s+[^\]]+\]\]?)$/;
|
|
29
|
+
const TEST_COMMAND = /(?:^|\s)(?:go\s+test|node\s+--test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|vitest|jest|pytest|python(?:3)?\s+-m\s+pytest|mvn\s+(?:test|verify)|gradle(?:w)?\s+(?:test|check))(?:\s|$)/i;
|
|
30
|
+
const EMPTY_TEST_OUTPUT = /(?:no\s+tests?\s+to\s+run|no\s+test\s+files|\[no\s+test\s+files\]|0\s+tests?\s+(?:found|collected|run))/i;
|
|
31
|
+
|
|
32
|
+
export function isArtifactOnlyAcceptance(check) {
|
|
33
|
+
const command = typeof check === "string" ? check : check?.command;
|
|
34
|
+
return typeof command === "string" && ARTIFACT_ONLY.test(command.trim());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isTestCommand(command) {
|
|
38
|
+
return typeof command === "string" && TEST_COMMAND.test(command);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function readCheckEvidence(check, cwd, checkId, baseCommit) {
|
|
42
|
+
try {
|
|
43
|
+
const root = await realpath(cwd);
|
|
44
|
+
const path = resolve(cwd, check.reportPath);
|
|
45
|
+
const canonical = await realpath(path);
|
|
46
|
+
const outside = relative(root, canonical);
|
|
47
|
+
if (outside === ".." || outside.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(outside)) throw new Error("report_path escapes the worktree");
|
|
48
|
+
const info = await lstat(path);
|
|
49
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) throw new Error("report must be a regular file of at most 1 MiB");
|
|
50
|
+
const report = JSON.parse(await readFile(path, "utf8"));
|
|
51
|
+
if (report.check_id !== checkId) throw new Error("report check_id does not belong to this check; reused evidence is invalid");
|
|
52
|
+
if (baseCommit && check.baseline.identity.base_commit !== baseCommit) throw new Error("approved baseline base_commit differs from the current run base");
|
|
53
|
+
const baseline = compareFailureBaseline(check.baseline, report);
|
|
54
|
+
return { passed: baseline.passed, baseline };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return { passed: false, error: `acceptance evidence: ${error.message}` };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function tail(buffer) {
|
|
61
|
+
if (buffer.length <= OUTPUT_TAIL_BYTES) return buffer.toString("utf8").trim();
|
|
62
|
+
let start = buffer.length - OUTPUT_TAIL_BYTES;
|
|
63
|
+
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start += 1;
|
|
64
|
+
return `…${buffer.subarray(start).toString("utf8").trim()}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Kills the command and everything it started. A test runner forks its own
|
|
68
|
+
// processes; killing only the shell would leave them running in the
|
|
69
|
+
// worktree, where the next git read or land would trip over them.
|
|
70
|
+
function killTree(child) {
|
|
71
|
+
if (!child.pid) return;
|
|
72
|
+
if (process.platform === "win32") {
|
|
73
|
+
try {
|
|
74
|
+
runSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
75
|
+
} catch {
|
|
76
|
+
child.kill();
|
|
77
|
+
}
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
process.kill(-child.pid, "SIGTERM");
|
|
82
|
+
} catch {
|
|
83
|
+
child.kill("SIGTERM");
|
|
84
|
+
}
|
|
85
|
+
setTimeout(() => {
|
|
86
|
+
try {
|
|
87
|
+
process.kill(-child.pid, "SIGKILL");
|
|
88
|
+
} catch {
|
|
89
|
+
// already gone
|
|
90
|
+
}
|
|
91
|
+
}, KILL_GRACE_MS).unref();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// cmd.exe and the default POSIX sh report only the last pipeline stage. Use one
|
|
95
|
+
// explicit shell contract on every platform, including Windows installations
|
|
96
|
+
// where Git's Bash is not on a GUI client's PATH.
|
|
97
|
+
function resolveBash(env) {
|
|
98
|
+
if (process.platform !== "win32") {
|
|
99
|
+
if (existsSync("/bin/bash")) return "/bin/bash";
|
|
100
|
+
const found = findBinaryPath("bash", { env });
|
|
101
|
+
if (!found) throw new Error("acceptance requires Bash with pipefail; install Bash or add it to PATH");
|
|
102
|
+
return found;
|
|
103
|
+
}
|
|
104
|
+
const git = findBinaryPath("git", { env });
|
|
105
|
+
const candidates = git ? [
|
|
106
|
+
join(dirname(git), "..", "bin", "bash.exe"),
|
|
107
|
+
join(dirname(git), "..", "usr", "bin", "bash.exe"),
|
|
108
|
+
join(dirname(git), "bash.exe")
|
|
109
|
+
] : [];
|
|
110
|
+
for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs")].filter(Boolean)) {
|
|
111
|
+
candidates.push(join(root, "Git", "bin", "bash.exe"));
|
|
112
|
+
}
|
|
113
|
+
const onPath = findBinaryPath("bash", { env });
|
|
114
|
+
// Windows' System32/WindowsApps launchers start WSL, which cannot run
|
|
115
|
+
// the worker's Windows paths and toolchain under the same contract.
|
|
116
|
+
if (onPath && !/[\\/](?:System32|WindowsApps)[\\/]/i.test(onPath)) candidates.push(onPath);
|
|
117
|
+
const bash = candidates.find((candidate) => existsSync(candidate));
|
|
118
|
+
if (!bash) throw new Error("acceptance requires Git for Windows Bash; install Git for Windows or add its bin directory to PATH");
|
|
119
|
+
return bash;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function spawnAcceptanceShell(cwd, env) {
|
|
123
|
+
const bash = resolveBash(env);
|
|
124
|
+
const shellEnv = { ...env };
|
|
125
|
+
// Non-interactive Bash reads BASH_ENV even with --noprofile/--norc. A
|
|
126
|
+
// user's startup file must not switch off the acceptance failure flags.
|
|
127
|
+
delete shellEnv.BASH_ENV;
|
|
128
|
+
delete shellEnv.ENV;
|
|
129
|
+
return spawnProcess(bash, ["--noprofile", "--norc", "-e", "-o", "pipefail", "-s"], {
|
|
130
|
+
cwd,
|
|
131
|
+
env: shellEnv,
|
|
132
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
133
|
+
windowsHide: true,
|
|
134
|
+
detached: process.platform !== "win32"
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function runOne(command, { cwd, env, timeoutMs, onSpawn }) {
|
|
139
|
+
return new Promise((resolveRun) => {
|
|
140
|
+
const startedAt = Date.now();
|
|
141
|
+
const chunks = [];
|
|
142
|
+
let total = 0;
|
|
143
|
+
let child;
|
|
144
|
+
try {
|
|
145
|
+
child = spawnAcceptanceShell(cwd, env);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
resolveRun({ command, exit_code: null, signal: null, duration_ms: 0, timed_out: false, output_tail: `spawn failed: ${error.message}` });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const collect = (chunk) => {
|
|
151
|
+
// Keep the pipe drained; only the tail is kept.
|
|
152
|
+
chunks.push(chunk);
|
|
153
|
+
total += chunk.length;
|
|
154
|
+
while (total - chunks[0].length > OUTPUT_TAIL_BYTES && chunks.length > 1) total -= chunks.shift().length;
|
|
155
|
+
};
|
|
156
|
+
child.stdout.on("data", collect);
|
|
157
|
+
child.stderr.on("data", collect);
|
|
158
|
+
child.stdout.on("error", () => {});
|
|
159
|
+
child.stderr.on("error", () => {});
|
|
160
|
+
let timedOut = false;
|
|
161
|
+
let killed = false;
|
|
162
|
+
let spawnError = null;
|
|
163
|
+
let spawned = false;
|
|
164
|
+
const timer = setTimeout(() => {
|
|
165
|
+
if (killed) return;
|
|
166
|
+
timedOut = true;
|
|
167
|
+
killTree(child);
|
|
168
|
+
}, timeoutMs);
|
|
169
|
+
timer.unref();
|
|
170
|
+
const kill = () => {
|
|
171
|
+
killed = true;
|
|
172
|
+
if (spawned) killTree(child);
|
|
173
|
+
};
|
|
174
|
+
let finished = false;
|
|
175
|
+
const finish = (code, signal) => {
|
|
176
|
+
if (finished) return;
|
|
177
|
+
finished = true;
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
resolveRun({
|
|
180
|
+
command,
|
|
181
|
+
exit_code: code,
|
|
182
|
+
signal: signal ?? null,
|
|
183
|
+
duration_ms: Date.now() - startedAt,
|
|
184
|
+
timed_out: timedOut,
|
|
185
|
+
cancelled: killed && !timedOut,
|
|
186
|
+
output_tail: spawnError ? `spawn failed: ${spawnError.message}` : tail(Buffer.concat(chunks))
|
|
187
|
+
});
|
|
188
|
+
};
|
|
189
|
+
child.on("error", (error) => {
|
|
190
|
+
spawnError = error;
|
|
191
|
+
finish(null, null);
|
|
192
|
+
});
|
|
193
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
194
|
+
child.stdin.on("error", () => {});
|
|
195
|
+
child.once("spawn", () => {
|
|
196
|
+
spawned = true;
|
|
197
|
+
// The shell cannot create pipeline children until this process has
|
|
198
|
+
// registered cancellation. An immediate cancel closes its script input
|
|
199
|
+
// without ever launching the command, avoiding taskkill's startup race.
|
|
200
|
+
if (killed) child.stdin.end();
|
|
201
|
+
else child.stdin.end(`${command}\n`);
|
|
202
|
+
});
|
|
203
|
+
// Register close/error handlers before exposing cancellation. Cancelling
|
|
204
|
+
// before spawn is observed is remembered and applied at the spawn event.
|
|
205
|
+
onSpawn?.(kill);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Runs every command in order and returns the verdict. `control.kill` is
|
|
210
|
+
// filled in so a cancel can stop the command that is running; `control.isCancelled`
|
|
211
|
+
// is consulted between commands.
|
|
212
|
+
export async function runAcceptance(commands, options = {}) {
|
|
213
|
+
const { cwd, env = process.env, timeoutMs = DEFAULT_ACCEPTANCE_TIMEOUT_MS, run = null, taskId = null, baseCommit = null, control = {} } = options;
|
|
214
|
+
const startedAt = new Date().toISOString();
|
|
215
|
+
if (!cwd || !existsSync(cwd)) {
|
|
216
|
+
return { status: "failed", passed: false, run, started_at: startedAt, finished_at: new Date().toISOString(), error: "cwd_missing", cwd, checks: [] };
|
|
217
|
+
}
|
|
218
|
+
const checks = [];
|
|
219
|
+
let passed = true;
|
|
220
|
+
const checkEnv = {
|
|
221
|
+
...env,
|
|
222
|
+
NO_COLOR: "1",
|
|
223
|
+
CI: env.CI ?? "1",
|
|
224
|
+
AGENT_SUPERVISOR_TASK_ID: taskId ?? "",
|
|
225
|
+
AGENT_SUPERVISOR_BASE_COMMIT: baseCommit ?? "",
|
|
226
|
+
AGENT_SUPERVISOR_RUN: run == null ? "" : String(run)
|
|
227
|
+
};
|
|
228
|
+
for (const check of normalizeAcceptance(commands) ?? []) {
|
|
229
|
+
const command = typeof check === "string" ? check : check.command;
|
|
230
|
+
if (control.isCancelled?.()) {
|
|
231
|
+
return { status: "cancelled", passed: null, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
232
|
+
}
|
|
233
|
+
const checkId = randomUUID();
|
|
234
|
+
const result = await runOne(command, {
|
|
235
|
+
cwd,
|
|
236
|
+
env: { ...checkEnv, AGENT_SUPERVISOR_CHECK_ID: checkId },
|
|
237
|
+
timeoutMs,
|
|
238
|
+
onSpawn: (kill) => {
|
|
239
|
+
control.kill = kill;
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
control.kill = null;
|
|
243
|
+
result.empty_test_run = isTestCommand(command) && EMPTY_TEST_OUTPUT.test(result.output_tail ?? "");
|
|
244
|
+
result.passed = result.exit_code === 0 && !result.timed_out && !result.cancelled && !result.empty_test_run;
|
|
245
|
+
if (typeof check !== "string" && result.passed) Object.assign(result, await readCheckEvidence(check, cwd, checkId, baseCommit));
|
|
246
|
+
checks.push(result);
|
|
247
|
+
if (result.cancelled) {
|
|
248
|
+
return { status: "cancelled", passed: null, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
249
|
+
}
|
|
250
|
+
if (!result.passed) {
|
|
251
|
+
passed = false;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return { status: passed ? "passed" : "failed", passed, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// The one-word view for a status row: what the last run concluded.
|
|
259
|
+
export function acceptanceVerdict(task) {
|
|
260
|
+
const results = task?.acceptance_results;
|
|
261
|
+
if (!results) return null;
|
|
262
|
+
return results.status ?? null;
|
|
263
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Removes safe worktrees and expired scratch directories without being asked.
|
|
2
|
+
// It rides on the polling tools, so a batch that is never cleaned up by hand
|
|
3
|
+
// does not grow without bound. A sweep is throttled and bounded: it must never
|
|
4
|
+
// make a poll slow.
|
|
5
|
+
import { branchOf } from "../domain/worker-branch.js";
|
|
6
|
+
import "./compose.js";
|
|
7
|
+
import { holdMsFrom } from "../domain/cleanup-policy.js";
|
|
8
|
+
import { TERMINAL_STATUSES } from "../domain/status.js";
|
|
9
|
+
import { scratchDir } from "../infra/paths.js";
|
|
10
|
+
import { runIdFor } from "../infra/store/db.js";
|
|
11
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
12
|
+
import { claimIdleTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
|
|
13
|
+
import { assessWorktree, recordRemoval, removeSafeWorktree } from "./cleanup-plan.js";
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import { rm } from "node:fs/promises";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;
|
|
19
|
+
const SWEEP_LIMIT = 20;
|
|
20
|
+
let lastSweepAt = 0;
|
|
21
|
+
|
|
22
|
+
function intervalMs() {
|
|
23
|
+
const raw = Number(process.env.AGENT_SUPERVISOR_CLEANUP_INTERVAL_MS);
|
|
24
|
+
return Number.isFinite(raw) && raw >= 0 && process.env.AGENT_SUPERVISOR_CLEANUP_INTERVAL_MS !== undefined ? raw : DEFAULT_INTERVAL_MS;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const finishedAt = (task) => Date.parse(task.completed_at ?? task.updated_at ?? "") || 0;
|
|
28
|
+
|
|
29
|
+
async function sweepWorktree(task, tasks, now) {
|
|
30
|
+
const assessed = await assessWorktree(task, tasks, now);
|
|
31
|
+
if (assessed.verdict !== "safe") return null;
|
|
32
|
+
const checkpoint = await removeSafeWorktree(task, assessed.fingerprint);
|
|
33
|
+
// The worktree is gone whether or not the audit row can be written.
|
|
34
|
+
await recordRemoval(task, { actor: "auto_cleanup", checkpoint, reasons: assessed.reasons })
|
|
35
|
+
.catch((error) => process.stderr.write(`[agent-supervisor] removed ${task.id} but could not record it: ${error.message}\n`));
|
|
36
|
+
return { task_id: task.id, kind: "worktree", branch: branchOf(task), checkpoint_commit: checkpoint, reasons: assessed.reasons };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A scratch directory holds a research worker's drafts; its report is in the
|
|
40
|
+
// store. It goes once the hold period is over.
|
|
41
|
+
async function sweepScratch(task, now) {
|
|
42
|
+
const path = join(scratchDir, task.id);
|
|
43
|
+
const finished = finishedAt(task);
|
|
44
|
+
if (!finished || now < finished + holdMsFrom(process.env.AGENT_SUPERVISOR_CLEANUP_HOLD_DAYS) || !existsSync(path)) return null;
|
|
45
|
+
const claim = await claimIdleTask(task.id);
|
|
46
|
+
if (!claim) return null;
|
|
47
|
+
try {
|
|
48
|
+
await rm(path, { recursive: true, force: true });
|
|
49
|
+
} finally {
|
|
50
|
+
await releaseTaskRun(task.id, claim);
|
|
51
|
+
}
|
|
52
|
+
await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", kind: "scratch", removed_at: new Date(now).toISOString(), retained: ["task", "events", "jsonl", "artifacts"] },
|
|
53
|
+
{ runId: runIdFor(task.id, task.run_count ?? 1), actor: "auto_cleanup" }).catch(() => null);
|
|
54
|
+
return { task_id: task.id, kind: "scratch" };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Returns what was removed. One failure never stops the sweep or the poll.
|
|
58
|
+
export async function sweepCleanup({ now = Date.now(), force = false } = {}) {
|
|
59
|
+
if (process.env.AGENT_SUPERVISOR_NO_AUTO_CLEANUP === "1") return [];
|
|
60
|
+
if (!force && now - lastSweepAt < intervalMs()) return [];
|
|
61
|
+
lastSweepAt = now;
|
|
62
|
+
let tasks;
|
|
63
|
+
try {
|
|
64
|
+
tasks = await readTasks();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
// Cleanup is housekeeping; a store hiccup must not fail the poll it rides on.
|
|
67
|
+
process.stderr.write(`[agent-supervisor] auto cleanup skipped: ${error.message.split("\n")[0]}\n`);
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
const finished = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).sort((a, b) => finishedAt(a) - finishedAt(b));
|
|
71
|
+
const removed = [];
|
|
72
|
+
let examined = 0;
|
|
73
|
+
for (const task of finished) {
|
|
74
|
+
if (examined >= SWEEP_LIMIT) break;
|
|
75
|
+
try {
|
|
76
|
+
if (task.workspace_kind === "scratch") {
|
|
77
|
+
examined += 1;
|
|
78
|
+
const gone = await sweepScratch(task, now);
|
|
79
|
+
if (gone) removed.push(gone);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!task.worktree_path || !existsSync(task.worktree_path)) continue;
|
|
83
|
+
examined += 1;
|
|
84
|
+
const gone = await sweepWorktree(task, tasks, now);
|
|
85
|
+
if (gone) removed.push(gone);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
process.stderr.write(`[agent-supervisor] auto cleanup skipped ${task.id}: ${error.message.split("\n")[0]}\n`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return removed;
|
|
91
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import "./compose.js";
|
|
2
|
+
import { describeProcess } from "../infra/process.js";
|
|
3
|
+
import { getTask, upsertTask } from "../infra/store/tasks.js";
|
|
4
|
+
import { loadRunner } from "../runners/registry.js";
|
|
5
|
+
import { acceptanceRuns, cancelledTasks, processes } from "./run-state.js";
|
|
6
|
+
|
|
7
|
+
// A pid on a row may have been reused; only a process that looks like this runner's CLI is signalled.
|
|
8
|
+
const isWorkerProcess = (task, runner) => runner.ownsPid(task.pid, describeProcess);
|
|
9
|
+
|
|
10
|
+
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
11
|
+
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
12
|
+
// would leave the real CLI running and the task stuck in `running`.
|
|
13
|
+
export function terminateChild(child, runner) {
|
|
14
|
+
runner.cancelChild(child);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function cancelCodexWorker(taskId) {
|
|
18
|
+
const acceptance = acceptanceRuns.get(taskId);
|
|
19
|
+
if (acceptance) {
|
|
20
|
+
acceptance.cancelled = true;
|
|
21
|
+
acceptance.kill?.();
|
|
22
|
+
return { cancelled: true, via: "acceptance", pid: null };
|
|
23
|
+
}
|
|
24
|
+
const task = await getTask(taskId);
|
|
25
|
+
// A runner from outside the package may not be loaded in this process yet.
|
|
26
|
+
const runner = await loadRunner(task?.worker);
|
|
27
|
+
const child = processes.get(taskId);
|
|
28
|
+
if (child) {
|
|
29
|
+
cancelledTasks.add(taskId);
|
|
30
|
+
terminateChild(child, runner);
|
|
31
|
+
return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
|
|
32
|
+
}
|
|
33
|
+
// Another MCP process owns the handle; fall back to the pid recorded on disk.
|
|
34
|
+
if (task?.acceptance_results?.status === "running" && await isPidAlive(task.acceptance_results.supervisor_pid)) {
|
|
35
|
+
await upsertTask({ ...task, cancel_requested_at: new Date().toISOString(), updated_at: new Date().toISOString() });
|
|
36
|
+
return { cancelled: true, via: "acceptance", pid: null };
|
|
37
|
+
}
|
|
38
|
+
if (task?.pid && (await isPidAlive(task.pid)) && isWorkerProcess(task, runner)) {
|
|
39
|
+
try {
|
|
40
|
+
runner.cancelPid(task.pid);
|
|
41
|
+
return { cancelled: true, via: "pid", pid: task.pid };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { cancelled: false, reason: "process_not_found" };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function isPidAlive(pid) {
|
|
50
|
+
if (!pid) return false;
|
|
51
|
+
try {
|
|
52
|
+
process.kill(pid, 0);
|
|
53
|
+
return true;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Reads what the cleanup policy needs to know about one worker's worktree.
|
|
2
|
+
import { branchOf } from "../domain/worker-branch.js";
|
|
3
|
+
import "./compose.js";
|
|
4
|
+
import { ACTIVE_STATUSES, TERMINAL_STATUSES, runIsOver } from "../domain/status.js";
|
|
5
|
+
import { gitSucceedsAsync, runGitAsync } from "../infra/git.js";
|
|
6
|
+
import { worktreesDir } from "../infra/paths.js";
|
|
7
|
+
import { isGroupAlive, isPidAlive } from "../infra/store/tasks.js";
|
|
8
|
+
import { parsePorcelainLine, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
|
|
9
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
10
|
+
import { resolve } from "node:path";
|
|
11
|
+
|
|
12
|
+
// Raw output: porcelain status lines start with a significant space, and a
|
|
13
|
+
// quoted path would never match a setup path. Callers trim single values.
|
|
14
|
+
const git = (cwd, args) => runGitAsync(cwd, args, { timeout: 15000, noOptionalLocks: true, rawPaths: true, trim: false });
|
|
15
|
+
const lines = (text) => text.split("\n").filter(Boolean);
|
|
16
|
+
|
|
17
|
+
function activeReason(task) {
|
|
18
|
+
// Once the run is over its pids may belong to anyone.
|
|
19
|
+
const settled = runIsOver(task);
|
|
20
|
+
if (!settled && task.pid && isPidAlive(task.pid)) return "worker process is still active";
|
|
21
|
+
if (!settled && task.run_host_pid && isPidAlive(task.run_host_pid)) return "run host process is still active";
|
|
22
|
+
// A lost run can leave a process behind that still writes in the worktree; only a recorded exit rules that out.
|
|
23
|
+
if (task.exit_code == null && isGroupAlive(task.run_host_pid)) return "a process of the worker's run is still active";
|
|
24
|
+
const acceptance = task.acceptance_results;
|
|
25
|
+
if (acceptance?.status === "running" || (acceptance?.supervisor_pid && isPidAlive(acceptance.supervisor_pid))) return "acceptance process is still active";
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Null when the path is this task's managed worktree on its own branch.
|
|
30
|
+
async function identityProblem(task) {
|
|
31
|
+
if (!task.worktree_path || !task.project_root) return "no registered isolated worktree";
|
|
32
|
+
const path = resolve(task.worktree_path);
|
|
33
|
+
const managed = resolve(worktreesDir, task.id);
|
|
34
|
+
if (path !== managed) return "worktree is outside its managed task directory";
|
|
35
|
+
try {
|
|
36
|
+
const info = await lstat(path);
|
|
37
|
+
if (info.isSymbolicLink()) return "worktree is a symlink";
|
|
38
|
+
if (await realpath(path) !== await realpath(managed)) return "worktree realpath is unexpected";
|
|
39
|
+
const branch = (await git(path, ["symbolic-ref", "--short", "HEAD"])).trim();
|
|
40
|
+
if (branch !== branchOf(task)) return "worktree branch ownership is unexpected";
|
|
41
|
+
const registered = (await git(task.project_root, ["worktree", "list", "--porcelain", "-z"])).split("\0").filter((line) => line.startsWith("worktree "));
|
|
42
|
+
const own = await realpath(path);
|
|
43
|
+
for (const line of registered) {
|
|
44
|
+
// A registration whose directory someone deleted has no realpath; it is not ours either way.
|
|
45
|
+
if (await realpath(line.slice(9)).catch(() => null) === own) return null;
|
|
46
|
+
}
|
|
47
|
+
return "git worktree registration is missing";
|
|
48
|
+
} catch (error) {
|
|
49
|
+
return `cleanup proof failed: ${error.message.split("\n")[0]}`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Paths the dispatcher linked into the worktree (node_modules and the like)
|
|
54
|
+
// are setup, not the worker's output.
|
|
55
|
+
function setupFilter(task) {
|
|
56
|
+
const setup = workspaceSetupIgnorePaths(task);
|
|
57
|
+
return (path) => !setup.some((entry) => path === entry || path.startsWith(`${entry}/`));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isLanded(task) {
|
|
61
|
+
if (!task.landed_at || !task.landed_head) return false;
|
|
62
|
+
const target = task.landed_branch ? `refs/heads/${task.landed_branch}` : "HEAD";
|
|
63
|
+
return gitSucceedsAsync(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, target]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function worktreeState(task) {
|
|
67
|
+
const path = resolve(task.worktree_path);
|
|
68
|
+
const keep = setupFilter(task);
|
|
69
|
+
const status = lines(await git(path, ["status", "--porcelain", "--untracked-files=all"]));
|
|
70
|
+
const uncommittedPaths = status.map(parsePorcelainLine).filter((entry) => entry && keep(entry));
|
|
71
|
+
// Without the base the worker's own commits cannot be counted, and "nothing
|
|
72
|
+
// to keep" could not be told from "cannot tell".
|
|
73
|
+
const base = resolveWorktreeBase(path, worktreeRef(task));
|
|
74
|
+
if (!base) throw new Error("the commit this worker started from is unknown");
|
|
75
|
+
const unlandedCommits = lines(await git(path, ["rev-list", `${base}..HEAD`])).length;
|
|
76
|
+
return { uncommittedPaths, unlandedCommits, head: (await git(path, ["rev-parse", "HEAD"])).trim() };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function cleanupFacts(task, tasks) {
|
|
80
|
+
const facts = {
|
|
81
|
+
active: activeReason(task),
|
|
82
|
+
dependent: tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id)),
|
|
83
|
+
terminal: TERMINAL_STATUSES.has(task.status),
|
|
84
|
+
identity: null, landed: false, uncommitted: 0, unlandedCommits: 0, uncommittedPaths: [], head: null,
|
|
85
|
+
finishedAt: Date.parse(task.completed_at ?? task.updated_at ?? "") || null
|
|
86
|
+
};
|
|
87
|
+
if (facts.active || facts.dependent || !facts.terminal) return facts;
|
|
88
|
+
facts.identity = await identityProblem(task);
|
|
89
|
+
if (facts.identity) return facts;
|
|
90
|
+
try {
|
|
91
|
+
const state = await worktreeState(task);
|
|
92
|
+
facts.landed = await isLanded(task);
|
|
93
|
+
facts.uncommittedPaths = state.uncommittedPaths;
|
|
94
|
+
facts.uncommitted = state.uncommittedPaths.length;
|
|
95
|
+
facts.unlandedCommits = state.unlandedCommits;
|
|
96
|
+
facts.head = state.head;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
facts.identity = `cleanup proof failed: ${error.message.split("\n")[0]}`;
|
|
99
|
+
}
|
|
100
|
+
return facts;
|
|
101
|
+
}
|