codex-supervisor-mcp 0.13.5 → 0.14.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/README.en.md +2 -2
- package/README.md +2 -2
- package/package.json +19 -63
- package/skills/codex-supervisor/SKILL.md +5 -4
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/auto-cleanup.js +90 -0
- package/src/app/cancel.js +60 -0
- package/src/app/cleanup-facts.js +96 -0
- package/src/app/cleanup-plan.js +164 -0
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +133 -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 +50 -0
- package/src/app/resume.js +181 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +82 -265
- 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 +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- 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/{overview-delta.js → domain/overview-delta.js} +7 -3
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -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 +337 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +56 -41
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +7 -6
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- 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 +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +58 -0
- package/src/interface/mcp/tools/results.js +284 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -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 +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/cleanup-plan.js +0 -158
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
package/README.en.md
CHANGED
|
@@ -28,7 +28,7 @@ codex-supervisor-mcp is an MCP server. A main thread (Claude Code, Codex, or any
|
|
|
28
28
|
| A failed run looks the same as a dead process | The state machine keeps `failed` and `lost` apart, and a failure carries its source and code |
|
|
29
29
|
| A worker says it is done and is not | Dispatch with `acceptance` commands; the supervisor runs them itself after the worker exits and refuses to land on failure |
|
|
30
30
|
| Changes sit on a local branch | `land_codex_worker` merges into the integration branch; `verify_delivery_push` proves the commit is on the remote |
|
|
31
|
-
| Worktrees pile up |
|
|
31
|
+
| Worktrees pile up | Landed or unchanged ones are removed during polling. Unlanded work is kept for 7 days, and its uncommitted edits are committed to its branch before the worktree goes. Branches and evidence stay |
|
|
32
32
|
|
|
33
33
|
A worker is a `codex exec` process and `model` is passed straight through. Keep the main thread on Claude, put the workers on DeepSeek or another provider, and the bills stay separate.
|
|
34
34
|
|
|
@@ -123,7 +123,7 @@ One block of text passes between the two sessions, pasted into the main-brain se
|
|
|
123
123
|
| | `ask_codex_worker` | Asks the worker a side question. Read-only; its thread is untouched |
|
|
124
124
|
| | `land_codex_worker` | Commits on the worker's behalf and cherry-picks onto the integration branch; refuses if acceptance failed |
|
|
125
125
|
| Delivery | `verify_delivery_push` | Proves the landed commit is on the remote. It verifies; it never pushes for you |
|
|
126
|
-
| | `cleanup_plan` / `apply_cleanup` / `cleanup_history` |
|
|
126
|
+
| | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | Shows each worktree as SAFE, REVIEW or BLOCKED with the reason. SAFE ones are removed automatically; you can also remove one right away |
|
|
127
127
|
| Sessions | `get_session_works` / `search_works` | Finds a batch again, or searches history by substring |
|
|
128
128
|
| | `describe_session` | Records a batch's title, objective, default acceptance and approval state |
|
|
129
129
|
| Facts | `search_worker_facts` / `get_fact` | Looks up verified facts and their versions |
|
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ codex-supervisor-mcp 是一个 MCP server。主线程(Claude Code、Codex 或
|
|
|
28
28
|
| 分不清跑失败还是进程没了 | 状态机把 `failed` 和 `lost` 分开,失败带来源和错误码 |
|
|
29
29
|
| worker 说做完了其实没有 | 派单带 `acceptance` 验收命令,supervisor 在 worker 退出后自己跑,不过就拒绝合入 |
|
|
30
30
|
| 改动留在本地没上线 | `land_codex_worker` 合回主分支,`verify_delivery_push` 核对远端真有这笔提交 |
|
|
31
|
-
| worktree 越堆越多 |
|
|
31
|
+
| worktree 越堆越多 | 已合入或没有改动的在轮询时自动清;没合入的留 7 天,删之前先把未提交的改动存进它的分支。分支和证据不删 |
|
|
32
32
|
|
|
33
33
|
worker 跑的是 `codex exec`,`model` 透传。主线程留在 Claude,worker 挂 DeepSeek 或别的 provider,账单分开算。
|
|
34
34
|
|
|
@@ -122,7 +122,7 @@ codex-supervisor-web # 或 npx -p codex-supervisor-mcp codex-supervisor-web
|
|
|
122
122
|
| | `ask_codex_worker` | 旁路问它一句,只读,不动它的线程 |
|
|
123
123
|
| | `land_codex_worker` | 代提交并 cherry-pick 到集成分支,验收没过就拒 |
|
|
124
124
|
| 交付 | `verify_delivery_push` | 证明合入的提交已经在远端。只验证,不替你 push |
|
|
125
|
-
| | `cleanup_plan` / `apply_cleanup` / `cleanup_history` |
|
|
125
|
+
| | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | 看每个 worktree 是 SAFE、REVIEW 还是 BLOCKED 以及原因;SAFE 项平时自动清,也可以手动立刻清 |
|
|
126
126
|
| session | `get_session_works` / `search_works` | 找回一批活,或按关键字搜历史 |
|
|
127
127
|
| | `describe_session` | 给一批活记标题、目标、默认验收和审批状态 |
|
|
128
128
|
| 事实 | `search_worker_facts` / `get_fact` | 查已验证的事实和它的版本 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
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.",
|
|
@@ -25,78 +25,34 @@
|
|
|
25
25
|
],
|
|
26
26
|
"bin": {
|
|
27
27
|
"codex-supervisor-mcp": "src/mcp-server.js",
|
|
28
|
-
"codex-supervisor-accept": "src/acceptance-cli.js",
|
|
29
|
-
"codex-supervisor-setup": "src/setup.js",
|
|
30
|
-
"codex-supervisor-web": "src/web-server.js",
|
|
31
|
-
"codex-supervisor-stage": "src/stage.js"
|
|
28
|
+
"codex-supervisor-accept": "src/interface/bin/acceptance-cli.js",
|
|
29
|
+
"codex-supervisor-setup": "src/interface/bin/setup.js",
|
|
30
|
+
"codex-supervisor-web": "src/interface/bin/web-server.js",
|
|
31
|
+
"codex-supervisor-stage": "src/interface/bin/stage.js",
|
|
32
|
+
"codex-supervisor-cleanup": "src/interface/bin/cleanup.js"
|
|
32
33
|
},
|
|
33
34
|
"files": [
|
|
34
|
-
"src
|
|
35
|
-
"src/bin-resolver.js",
|
|
36
|
-
"src/setup.js",
|
|
37
|
-
"src/skill-sync.js",
|
|
38
|
-
"src/codex-runner.js",
|
|
39
|
-
"src/task-store.js",
|
|
40
|
-
"src/goal-store.js",
|
|
41
|
-
"src/event-parser.js",
|
|
42
|
-
"src/worktree.js",
|
|
43
|
-
"src/landing.js",
|
|
44
|
-
"src/acceptance.js",
|
|
45
|
-
"src/acceptance-cli.js",
|
|
46
|
-
"src/acceptance-baseline.js",
|
|
47
|
-
"src/worker-changes.js",
|
|
48
|
-
"src/owned-changes.js",
|
|
49
|
-
"src/tool-guard.js",
|
|
50
|
-
"src/worker-report.js",
|
|
51
|
-
"src/worker-report.schema.json",
|
|
52
|
-
"src/sandbox-roots.js",
|
|
53
|
-
"src/cleanup-hint.js",
|
|
54
|
-
"src/handoff.js",
|
|
55
|
-
"src/external-output.js",
|
|
56
|
-
"src/truncate.js",
|
|
57
|
-
"src/status.js",
|
|
58
|
-
"src/failure-class.js",
|
|
59
|
-
"src/worker-env.js",
|
|
60
|
-
"src/thread-health.js",
|
|
61
|
-
"src/stage-store.js",
|
|
62
|
-
"src/stage.js",
|
|
63
|
-
"src/paths.js",
|
|
64
|
-
"src/prompt.js",
|
|
65
|
-
"src/cleanup.js",
|
|
66
|
-
"src/cleanup-plan.js",
|
|
67
|
-
"src/worker-preflight.js",
|
|
68
|
-
"src/workspace-kind.js",
|
|
69
|
-
"src/runner-adapter.js",
|
|
70
|
-
"src/mcp-config.js",
|
|
71
|
-
"src/context-compiler.js",
|
|
72
|
-
"src/overview-delta.js",
|
|
73
|
-
"src/monitor.jsx",
|
|
74
|
-
"src/web-server.js",
|
|
75
|
-
"src/web-app.js",
|
|
76
|
-
"src/side-chat.js",
|
|
77
|
-
"src/update-check.js",
|
|
78
|
-
"src/auto-update-worker.js",
|
|
79
|
-
"src/auto-update.js",
|
|
35
|
+
"src",
|
|
80
36
|
"web/dist/",
|
|
81
37
|
"skills/",
|
|
82
38
|
"README.md",
|
|
83
39
|
"LICENSE"
|
|
84
40
|
],
|
|
85
41
|
"scripts": {
|
|
86
|
-
"postinstall": "node ./src/setup.js --auto --quiet",
|
|
87
|
-
"setup": "node ./src/setup.js",
|
|
42
|
+
"postinstall": "node ./src/interface/bin/setup.js --auto --quiet",
|
|
43
|
+
"setup": "node ./src/interface/bin/setup.js",
|
|
88
44
|
"start": "node ./src/mcp-server.js",
|
|
89
|
-
"monitor": "tsx ./src/monitor.jsx",
|
|
90
|
-
"cleanup": "node ./src/cleanup.js",
|
|
45
|
+
"monitor": "tsx ./src/interface/bin/monitor.jsx",
|
|
46
|
+
"cleanup": "node ./src/interface/bin/cleanup.js",
|
|
91
47
|
"lint": "eslint .",
|
|
92
|
-
"test": "node ./
|
|
93
|
-
"test:real": "node ./
|
|
94
|
-
"test:real:multi": "node ./
|
|
95
|
-
"smoke": "node ./
|
|
96
|
-
"smoke:followup": "node ./
|
|
97
|
-
"smoke:mcp": "node ./
|
|
98
|
-
"smoke:mcp-wait": "node ./
|
|
99
|
-
"web": "node ./src/web-server.js",
|
|
48
|
+
"test": "node ./test/scripts/bin-resolver-test.js && node ./test/scripts/truncate-test.js && node ./test/scripts/status-test.js && node ./test/scripts/migration-test.js && node ./test/scripts/setup-test.js && node ./test/scripts/setup-windows-test.js && node ./test/scripts/regression-test.js && node --test test/edge/*.test.js",
|
|
49
|
+
"test:real": "node ./test/scripts/real-codex-test.js",
|
|
50
|
+
"test:real:multi": "node ./test/scripts/multi-project-real-test.js",
|
|
51
|
+
"smoke": "node ./test/scripts/smoke-test.js",
|
|
52
|
+
"smoke:followup": "node ./test/scripts/followup-smoke-test.js",
|
|
53
|
+
"smoke:mcp": "node ./test/scripts/mcp-smoke-test.js",
|
|
54
|
+
"smoke:mcp-wait": "node ./test/scripts/mcp-wait-smoke-test.js",
|
|
55
|
+
"web": "node ./src/interface/bin/web-server.js",
|
|
100
56
|
"web:install": "npm --prefix web install",
|
|
101
57
|
"web:build": "npm --prefix web run build",
|
|
102
58
|
"web:dev": "npm --prefix web run dev",
|
|
@@ -124,10 +124,11 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
124
124
|
|
|
125
125
|
1. 主线程自己的改动要 commit 并 push。用户批准的集成分支也要在 push 后核对远端 SHA。
|
|
126
126
|
2. worker 分支通常不 push。只有用户明确要求保留远端 worker 分支时再推。
|
|
127
|
-
3. push 后用 `verify_delivery_push` 证明 landed head
|
|
128
|
-
4.
|
|
129
|
-
5.
|
|
130
|
-
6.
|
|
127
|
+
3. push 后用 `verify_delivery_push` 证明 landed head 已到远端。
|
|
128
|
+
4. 清理是自动的:`check_workers` / `overview_delta` 会顺带删掉已合入或没有改动的 worktree,返回里的 `cleaned` 就是删了哪些。不用为清理调任何工具。
|
|
129
|
+
5. 没合入的活保留 7 天;到期先把未提交改动存进 `codex/<id>` 分支再删。还想要的活在这之前 land 或 resume。
|
|
130
|
+
6. worktree 被清掉后照常 `resume_codex_worker` / `land_codex_worker` / `get_worker_diff`,会自动从分支切回来。
|
|
131
|
+
7. 想立刻清:`cleanup_plan` 看判定,`apply_cleanup(plan_id, item_ids)` 清 SAFE 项。branch、task、event、JSONL、artifact 永远保留。
|
|
131
132
|
|
|
132
133
|
## 常见坑
|
|
133
134
|
|
|
@@ -11,16 +11,18 @@
|
|
|
11
11
|
// The commands are shell lines written by the main thread, so they run with
|
|
12
12
|
// the supervisor's own privileges, exactly as if the main thread had run
|
|
13
13
|
// them itself. That is the trust model and it is stated in the tool text.
|
|
14
|
-
import {
|
|
14
|
+
import { runSync, spawnProcess } from "../infra/process.js";
|
|
15
15
|
import { existsSync } from "node:fs";
|
|
16
16
|
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
17
17
|
import { randomUUID } from "node:crypto";
|
|
18
18
|
import { dirname, join, isAbsolute, relative, resolve } from "node:path";
|
|
19
|
-
import { findBinaryPath } from "
|
|
20
|
-
import { compareFailureBaseline } from "
|
|
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 };
|
|
21
24
|
|
|
22
25
|
export const DEFAULT_ACCEPTANCE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
23
|
-
export const MAX_ACCEPTANCE_COMMANDS = 10;
|
|
24
26
|
const OUTPUT_TAIL_BYTES = 2000;
|
|
25
27
|
const KILL_GRACE_MS = 3000;
|
|
26
28
|
const ARTIFACT_ONLY = /^(?:test\s+-[efsd]\s+[^;&|]+|\[\[?\s+-[efsd]\s+[^\]]+\]\]?)$/;
|
|
@@ -36,32 +38,6 @@ export function isTestCommand(command) {
|
|
|
36
38
|
return typeof command === "string" && TEST_COMMAND.test(command);
|
|
37
39
|
}
|
|
38
40
|
|
|
39
|
-
// One string or a list; blanks dropped; an empty list is "not configured".
|
|
40
|
-
export function normalizeAcceptance(value) {
|
|
41
|
-
const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
|
|
42
|
-
const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
|
|
43
|
-
if (typeof entry === "string") return entry.trim();
|
|
44
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
|
|
45
|
-
if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("reportPath must stay inside the worktree");
|
|
46
|
-
const validation = compareFailureBaseline(entry.baseline, {
|
|
47
|
-
complete: true, identity: entry.baseline?.identity,
|
|
48
|
-
executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
|
|
49
|
-
skipped: [], failures: entry.baseline?.failures
|
|
50
|
-
});
|
|
51
|
-
// Validation errors concern the contract; diff results concern actual
|
|
52
|
-
// failures, which do not exist at normalization time.
|
|
53
|
-
if (validation.errors.length) throw new Error(`invalid acceptance baseline: ${validation.errors.join("; ")}`);
|
|
54
|
-
return { command: entry.command.trim(), reportPath: entry.reportPath, baseline: structuredClone(entry.baseline) };
|
|
55
|
-
}).filter(Boolean);
|
|
56
|
-
if (commands.length === 0) return null;
|
|
57
|
-
if (commands.length > MAX_ACCEPTANCE_COMMANDS) {
|
|
58
|
-
const error = new Error(`acceptance lists ${commands.length} commands; at most ${MAX_ACCEPTANCE_COMMANDS} are run`);
|
|
59
|
-
error.code = "too_many_acceptance_commands";
|
|
60
|
-
throw error;
|
|
61
|
-
}
|
|
62
|
-
return commands;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
41
|
async function readCheckEvidence(check, cwd, checkId, baseCommit) {
|
|
66
42
|
try {
|
|
67
43
|
const root = await realpath(cwd);
|
|
@@ -95,7 +71,7 @@ function killTree(child) {
|
|
|
95
71
|
if (!child.pid) return;
|
|
96
72
|
if (process.platform === "win32") {
|
|
97
73
|
try {
|
|
98
|
-
|
|
74
|
+
runSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
99
75
|
} catch {
|
|
100
76
|
child.kill();
|
|
101
77
|
}
|
|
@@ -115,6 +91,50 @@ function killTree(child) {
|
|
|
115
91
|
}, KILL_GRACE_MS).unref();
|
|
116
92
|
}
|
|
117
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
|
+
|
|
118
138
|
function runOne(command, { cwd, env, timeoutMs, onSpawn }) {
|
|
119
139
|
return new Promise((resolveRun) => {
|
|
120
140
|
const startedAt = Date.now();
|
|
@@ -122,42 +142,7 @@ function runOne(command, { cwd, env, timeoutMs, onSpawn }) {
|
|
|
122
142
|
let total = 0;
|
|
123
143
|
let child;
|
|
124
144
|
try {
|
|
125
|
-
|
|
126
|
-
// Use one explicit shell contract on every platform, including Windows
|
|
127
|
-
// installations where Git's Bash is not on a GUI client's PATH.
|
|
128
|
-
let bash = "/bin/bash";
|
|
129
|
-
if (process.platform === "win32") {
|
|
130
|
-
const git = findBinaryPath("git", { env });
|
|
131
|
-
const candidates = git ? [
|
|
132
|
-
join(dirname(git), "..", "bin", "bash.exe"),
|
|
133
|
-
join(dirname(git), "..", "usr", "bin", "bash.exe"),
|
|
134
|
-
join(dirname(git), "bash.exe")
|
|
135
|
-
] : [];
|
|
136
|
-
for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs")].filter(Boolean)) {
|
|
137
|
-
candidates.push(join(root, "Git", "bin", "bash.exe"));
|
|
138
|
-
}
|
|
139
|
-
const onPath = findBinaryPath("bash", { env });
|
|
140
|
-
// Windows' System32/WindowsApps launchers start WSL, which cannot run
|
|
141
|
-
// the worker's Windows paths and toolchain under the same contract.
|
|
142
|
-
if (onPath && !/[\\/](?:System32|WindowsApps)[\\/]/i.test(onPath)) candidates.push(onPath);
|
|
143
|
-
bash = candidates.find((candidate) => existsSync(candidate));
|
|
144
|
-
if (!bash) throw new Error("acceptance requires Git for Windows Bash; install Git for Windows or add its bin directory to PATH");
|
|
145
|
-
} else if (!existsSync(bash)) {
|
|
146
|
-
bash = findBinaryPath("bash", { env });
|
|
147
|
-
if (!bash) throw new Error("acceptance requires Bash with pipefail; install Bash or add it to PATH");
|
|
148
|
-
}
|
|
149
|
-
const shellEnv = { ...env };
|
|
150
|
-
// Non-interactive Bash reads BASH_ENV even with --noprofile/--norc. A
|
|
151
|
-
// user's startup file must not switch off the acceptance failure flags.
|
|
152
|
-
delete shellEnv.BASH_ENV;
|
|
153
|
-
delete shellEnv.ENV;
|
|
154
|
-
child = spawn(bash, ["--noprofile", "--norc", "-e", "-o", "pipefail", "-s"], {
|
|
155
|
-
cwd,
|
|
156
|
-
env: shellEnv,
|
|
157
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
158
|
-
windowsHide: true,
|
|
159
|
-
detached: process.platform !== "win32"
|
|
160
|
-
});
|
|
145
|
+
child = spawnAcceptanceShell(cwd, env);
|
|
161
146
|
} catch (error) {
|
|
162
147
|
resolveRun({ command, exit_code: null, signal: null, duration_ms: 0, timed_out: false, output_tail: `spawn failed: ${error.message}` });
|
|
163
148
|
return;
|
|
@@ -224,7 +209,8 @@ function runOne(command, { cwd, env, timeoutMs, onSpawn }) {
|
|
|
224
209
|
// Runs every command in order and returns the verdict. `control.kill` is
|
|
225
210
|
// filled in so a cancel can stop the command that is running; `control.isCancelled`
|
|
226
211
|
// is consulted between commands.
|
|
227
|
-
export async function runAcceptance(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;
|
|
228
214
|
const startedAt = new Date().toISOString();
|
|
229
215
|
if (!cwd || !existsSync(cwd)) {
|
|
230
216
|
return { status: "failed", passed: false, run, started_at: startedAt, finished_at: new Date().toISOString(), error: "cwd_missing", cwd, checks: [] };
|
|
@@ -0,0 +1,90 @@
|
|
|
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 "./compose.js";
|
|
6
|
+
import { holdMsFrom } from "../domain/cleanup-policy.js";
|
|
7
|
+
import { TERMINAL_STATUSES } from "../domain/status.js";
|
|
8
|
+
import { scratchDir } from "../infra/paths.js";
|
|
9
|
+
import { runIdFor } from "../infra/store/db.js";
|
|
10
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
11
|
+
import { claimIdleTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
|
|
12
|
+
import { assessWorktree, recordRemoval, removeSafeWorktree } from "./cleanup-plan.js";
|
|
13
|
+
import { existsSync } from "node:fs";
|
|
14
|
+
import { rm } from "node:fs/promises";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
|
|
17
|
+
const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;
|
|
18
|
+
const SWEEP_LIMIT = 20;
|
|
19
|
+
let lastSweepAt = 0;
|
|
20
|
+
|
|
21
|
+
function intervalMs() {
|
|
22
|
+
const raw = Number(process.env.CODEX_SUPERVISOR_CLEANUP_INTERVAL_MS);
|
|
23
|
+
return Number.isFinite(raw) && raw >= 0 && process.env.CODEX_SUPERVISOR_CLEANUP_INTERVAL_MS !== undefined ? raw : DEFAULT_INTERVAL_MS;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const finishedAt = (task) => Date.parse(task.completed_at ?? task.updated_at ?? "") || 0;
|
|
27
|
+
|
|
28
|
+
async function sweepWorktree(task, tasks, now) {
|
|
29
|
+
const assessed = await assessWorktree(task, tasks, now);
|
|
30
|
+
if (assessed.verdict !== "safe") return null;
|
|
31
|
+
const checkpoint = await removeSafeWorktree(task, assessed.fingerprint);
|
|
32
|
+
// The worktree is gone whether or not the audit row can be written.
|
|
33
|
+
await recordRemoval(task, { actor: "auto_cleanup", checkpoint, reasons: assessed.reasons })
|
|
34
|
+
.catch((error) => process.stderr.write(`[codex-supervisor] removed ${task.id} but could not record it: ${error.message}\n`));
|
|
35
|
+
return { task_id: task.id, kind: "worktree", branch: `codex/${task.id}`, checkpoint_commit: checkpoint, reasons: assessed.reasons };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A scratch directory holds a research worker's drafts; its report is in the
|
|
39
|
+
// store. It goes once the hold period is over.
|
|
40
|
+
async function sweepScratch(task, now) {
|
|
41
|
+
const path = join(scratchDir, task.id);
|
|
42
|
+
const finished = finishedAt(task);
|
|
43
|
+
if (!finished || now < finished + holdMsFrom(process.env.CODEX_SUPERVISOR_CLEANUP_HOLD_DAYS) || !existsSync(path)) return null;
|
|
44
|
+
const claim = await claimIdleTask(task.id);
|
|
45
|
+
if (!claim) return null;
|
|
46
|
+
try {
|
|
47
|
+
await rm(path, { recursive: true, force: true });
|
|
48
|
+
} finally {
|
|
49
|
+
await releaseTaskRun(task.id, claim);
|
|
50
|
+
}
|
|
51
|
+
await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", kind: "scratch", removed_at: new Date(now).toISOString(), retained: ["task", "events", "jsonl", "artifacts"] },
|
|
52
|
+
{ runId: runIdFor(task.id, task.run_count ?? 1), actor: "auto_cleanup" }).catch(() => null);
|
|
53
|
+
return { task_id: task.id, kind: "scratch" };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Returns what was removed. One failure never stops the sweep or the poll.
|
|
57
|
+
export async function sweepCleanup({ now = Date.now(), force = false } = {}) {
|
|
58
|
+
if (process.env.CODEX_SUPERVISOR_NO_AUTO_CLEANUP === "1") return [];
|
|
59
|
+
if (!force && now - lastSweepAt < intervalMs()) return [];
|
|
60
|
+
lastSweepAt = now;
|
|
61
|
+
let tasks;
|
|
62
|
+
try {
|
|
63
|
+
tasks = await readTasks();
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// Cleanup is housekeeping; a store hiccup must not fail the poll it rides on.
|
|
66
|
+
process.stderr.write(`[codex-supervisor] auto cleanup skipped: ${error.message.split("\n")[0]}\n`);
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
const finished = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).sort((a, b) => finishedAt(a) - finishedAt(b));
|
|
70
|
+
const removed = [];
|
|
71
|
+
let examined = 0;
|
|
72
|
+
for (const task of finished) {
|
|
73
|
+
if (examined >= SWEEP_LIMIT) break;
|
|
74
|
+
try {
|
|
75
|
+
if (task.workspace_kind === "scratch") {
|
|
76
|
+
examined += 1;
|
|
77
|
+
const gone = await sweepScratch(task, now);
|
|
78
|
+
if (gone) removed.push(gone);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!task.worktree_path || !existsSync(task.worktree_path)) continue;
|
|
82
|
+
examined += 1;
|
|
83
|
+
const gone = await sweepWorktree(task, tasks, now);
|
|
84
|
+
if (gone) removed.push(gone);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
process.stderr.write(`[codex-supervisor] auto cleanup skipped ${task.id}: ${error.message.split("\n")[0]}\n`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return removed;
|
|
90
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import "./compose.js";
|
|
2
|
+
import { describeProcess } from "../infra/process.js";
|
|
3
|
+
import { getTask, upsertTask } from "../infra/store/tasks.js";
|
|
4
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
5
|
+
import { acceptanceRuns, cancelledTasks, processes } from "./run-state.js";
|
|
6
|
+
|
|
7
|
+
function isLikelyCodexProcess(pid) {
|
|
8
|
+
return codexRunner.ownsPid(pid, describeProcess);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
12
|
+
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
13
|
+
// would leave the real CLI running and the task stuck in `running`.
|
|
14
|
+
export function terminateChild(child) {
|
|
15
|
+
codexRunner.cancelChild(child);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function terminatePid(pid) {
|
|
19
|
+
codexRunner.cancelPid(pid);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function cancelCodexWorker(taskId) {
|
|
23
|
+
const acceptance = acceptanceRuns.get(taskId);
|
|
24
|
+
if (acceptance) {
|
|
25
|
+
acceptance.cancelled = true;
|
|
26
|
+
acceptance.kill?.();
|
|
27
|
+
return { cancelled: true, via: "acceptance", pid: null };
|
|
28
|
+
}
|
|
29
|
+
const child = processes.get(taskId);
|
|
30
|
+
if (child) {
|
|
31
|
+
cancelledTasks.add(taskId);
|
|
32
|
+
terminateChild(child);
|
|
33
|
+
return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
|
|
34
|
+
}
|
|
35
|
+
// Another MCP process owns the handle; fall back to the pid recorded on disk.
|
|
36
|
+
const task = await getTask(taskId);
|
|
37
|
+
if (task?.acceptance_results?.status === "running" && await isPidAlive(task.acceptance_results.supervisor_pid)) {
|
|
38
|
+
await upsertTask({ ...task, cancel_requested_at: new Date().toISOString(), updated_at: new Date().toISOString() });
|
|
39
|
+
return { cancelled: true, via: "acceptance", pid: null };
|
|
40
|
+
}
|
|
41
|
+
if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
|
|
42
|
+
try {
|
|
43
|
+
terminatePid(task.pid);
|
|
44
|
+
return { cancelled: true, via: "pid", pid: task.pid };
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { cancelled: false, reason: "process_not_found" };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function isPidAlive(pid) {
|
|
53
|
+
if (!pid) return false;
|
|
54
|
+
try {
|
|
55
|
+
process.kill(pid, 0);
|
|
56
|
+
return true;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Reads what the cleanup policy needs to know about one worker's worktree.
|
|
2
|
+
import "./compose.js";
|
|
3
|
+
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "../domain/status.js";
|
|
4
|
+
import { gitSucceeds, runGit } from "../infra/git.js";
|
|
5
|
+
import { worktreesDir } from "../infra/paths.js";
|
|
6
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
7
|
+
import { parsePorcelainLine, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
|
|
8
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
9
|
+
import { resolve } from "node:path";
|
|
10
|
+
|
|
11
|
+
// Raw output: porcelain status lines start with a significant space, and a
|
|
12
|
+
// quoted path would never match a setup path. Callers trim single values.
|
|
13
|
+
const git = (cwd, args) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, rawPaths: true, trim: false });
|
|
14
|
+
const lines = (text) => text.split("\n").filter(Boolean);
|
|
15
|
+
|
|
16
|
+
function activeReason(task) {
|
|
17
|
+
if (task.pid && isPidAlive(task.pid)) return "worker process is still active";
|
|
18
|
+
if (task.run_host_pid && isPidAlive(task.run_host_pid)) return "run host process is still active";
|
|
19
|
+
const acceptance = task.acceptance_results;
|
|
20
|
+
if (acceptance?.status === "running" || (acceptance?.supervisor_pid && isPidAlive(acceptance.supervisor_pid))) return "acceptance process is still active";
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Null when the path is this task's managed worktree on its own branch.
|
|
25
|
+
async function identityProblem(task) {
|
|
26
|
+
if (!task.worktree_path || !task.project_root) return "no registered isolated worktree";
|
|
27
|
+
const path = resolve(task.worktree_path);
|
|
28
|
+
const managed = resolve(worktreesDir, task.id);
|
|
29
|
+
if (path !== managed) return "worktree is outside its managed task directory";
|
|
30
|
+
try {
|
|
31
|
+
const info = await lstat(path);
|
|
32
|
+
if (info.isSymbolicLink()) return "worktree is a symlink";
|
|
33
|
+
if (await realpath(path) !== await realpath(managed)) return "worktree realpath is unexpected";
|
|
34
|
+
const branch = git(path, ["symbolic-ref", "--short", "HEAD"]).trim();
|
|
35
|
+
if (branch !== `codex/${task.id}`) return "worktree branch ownership is unexpected";
|
|
36
|
+
const registered = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
|
|
37
|
+
const own = await realpath(path);
|
|
38
|
+
for (const line of registered) {
|
|
39
|
+
// A registration whose directory someone deleted has no realpath; it is not ours either way.
|
|
40
|
+
if (await realpath(line.slice(9)).catch(() => null) === own) return null;
|
|
41
|
+
}
|
|
42
|
+
return "git worktree registration is missing";
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return `cleanup proof failed: ${error.message.split("\n")[0]}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Paths the dispatcher linked into the worktree (node_modules and the like)
|
|
49
|
+
// are setup, not the worker's output.
|
|
50
|
+
function setupFilter(task) {
|
|
51
|
+
const setup = workspaceSetupIgnorePaths(task);
|
|
52
|
+
return (path) => !setup.some((entry) => path === entry || path.startsWith(`${entry}/`));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isLanded(task) {
|
|
56
|
+
if (!task.landed_at || !task.landed_head) return false;
|
|
57
|
+
const target = task.landed_branch ? `refs/heads/${task.landed_branch}` : "HEAD";
|
|
58
|
+
return gitSucceeds(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, target]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function worktreeState(task) {
|
|
62
|
+
const path = resolve(task.worktree_path);
|
|
63
|
+
const keep = setupFilter(task);
|
|
64
|
+
const status = lines(git(path, ["status", "--porcelain", "--untracked-files=all"]));
|
|
65
|
+
const uncommittedPaths = status.map(parsePorcelainLine).filter((entry) => entry && keep(entry));
|
|
66
|
+
// Without the base the worker's own commits cannot be counted, and "nothing
|
|
67
|
+
// to keep" could not be told from "cannot tell".
|
|
68
|
+
const base = resolveWorktreeBase(path, worktreeRef(task));
|
|
69
|
+
if (!base) throw new Error("the commit this worker started from is unknown");
|
|
70
|
+
const unlandedCommits = lines(git(path, ["rev-list", `${base}..HEAD`])).length;
|
|
71
|
+
return { uncommittedPaths, unlandedCommits, head: git(path, ["rev-parse", "HEAD"]).trim() };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function cleanupFacts(task, tasks) {
|
|
75
|
+
const facts = {
|
|
76
|
+
active: activeReason(task),
|
|
77
|
+
dependent: tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id)),
|
|
78
|
+
terminal: TERMINAL_STATUSES.has(task.status),
|
|
79
|
+
identity: null, landed: false, uncommitted: 0, unlandedCommits: 0, uncommittedPaths: [], head: null,
|
|
80
|
+
finishedAt: Date.parse(task.completed_at ?? task.updated_at ?? "") || null
|
|
81
|
+
};
|
|
82
|
+
if (facts.active || facts.dependent || !facts.terminal) return facts;
|
|
83
|
+
facts.identity = await identityProblem(task);
|
|
84
|
+
if (facts.identity) return facts;
|
|
85
|
+
try {
|
|
86
|
+
const state = worktreeState(task);
|
|
87
|
+
facts.landed = isLanded(task);
|
|
88
|
+
facts.uncommittedPaths = state.uncommittedPaths;
|
|
89
|
+
facts.uncommitted = state.uncommittedPaths.length;
|
|
90
|
+
facts.unlandedCommits = state.unlandedCommits;
|
|
91
|
+
facts.head = state.head;
|
|
92
|
+
} catch (error) {
|
|
93
|
+
facts.identity = `cleanup proof failed: ${error.message.split("\n")[0]}`;
|
|
94
|
+
}
|
|
95
|
+
return facts;
|
|
96
|
+
}
|