codex-supervisor-mcp 0.5.5 → 0.5.6
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 +4 -3
- package/README.md +4 -3
- package/package.json +1 -1
- package/skills/codex-supervisor/SKILL.md +3 -2
- package/src/codex-runner.js +51 -12
- package/src/mcp-server.js +31 -10
- package/src/task-store.js +29 -7
- package/src/worktree.js +61 -12
package/README.en.md
CHANGED
|
@@ -186,7 +186,7 @@ Fourteen of them.
|
|
|
186
186
|
|
|
187
187
|
| Tool | Arguments | What it does |
|
|
188
188
|
|---|---|---|
|
|
189
|
-
| `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `session_id`, `dependsOn`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Start a worker |
|
|
189
|
+
| `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `session_id`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Start a worker. `baseRef` picks the commit the worktree is cut from (default: the repository's `HEAD`); pass another worker's `codex/<id>` branch to build on work that isn't on the main line yet |
|
|
190
190
|
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, plus the same arguments | Start a **new session**, seeded with the old worker's prompt, status, and recent events |
|
|
191
191
|
| `resume_codex_worker` | `task_id`, `prompt` | Continue the **same** Codex session |
|
|
192
192
|
| `list_codex_workers` | `status`, `includeHistory`, `includeDetails` | List workers; running ones only by default |
|
|
@@ -277,7 +277,7 @@ By default under `~/.codex-supervisor/`:
|
|
|
277
277
|
|
|
278
278
|
A database from 0.1.x migrates automatically the first time it's opened. Process values that used to live in `status` (`editing`, `command`, `command_completed`, `reporting`) move into `phase`, and `status` becomes `running`. Nothing is dropped. The migration runs inside one `BEGIN IMMEDIATE` transaction, so if several processes start at once only one of them actually migrates.
|
|
279
279
|
|
|
280
|
-
`changed_files` has
|
|
280
|
+
`changed_files` has three sources: Codex's `file_change` events, `git status --porcelain` in the worker's own worktree (the uncommitted part), and `git diff --name-only <base_commit> HEAD` (the committed part). The last two exist because a worker that edits files through a shell command (`printf > file`) never emits a `file_change` event, and once it commits on its branch `git status` is clean again - a real batch of five workers did exactly that and every read came back empty. `base_commit` is recorded on the row at dispatch; rows older than that column fall back to the oldest reflog entry of the `codex/<taskId>` branch, which is where the branch was created.
|
|
281
281
|
|
|
282
282
|
## Environment variables
|
|
283
283
|
|
|
@@ -305,10 +305,11 @@ When the MCP client starts without `codex` on `PATH`, which is common for GUI-la
|
|
|
305
305
|
## Known limitations
|
|
306
306
|
|
|
307
307
|
- **A worker's lifetime is tied to the MCP process.** `codex` is a child of the MCP process, so killing the MCP process leaves workers behind. They get settled as `lost` on the next `list_codex_workers` / `get_orchestration_overview`. The real fix is a resident daemon, see the Roadmap.
|
|
308
|
-
- **The worktree is created from
|
|
308
|
+
- **The worktree is created from a commit, so uncommitted work isn't in it.** The default is the repository's `HEAD`; `baseRef` accepts any branch, tag or sha (one that doesn't resolve refuses the dispatch with `invalid_base_ref` instead of quietly falling back to `HEAD`). Modified and untracked files sitting in the main thread's checkout don't exist inside the worker's worktree. Give the task absolute paths, or commit first. The worker's own changes land on the `codex/<taskId>` branch and never touch the main checkout.
|
|
309
309
|
- **Only the working directory is isolated.** Temp directories (`TMPDIR`), databases, and ports are process-level resources and stay shared, so two workers writing the same temp file still collide. Give each one its own paths, database name, and port in the task if you need that.
|
|
310
310
|
- **`ownedPaths` is a pre-dispatch conflict check, not a runtime sandbox.** It stops two workers from registering the same file; it does not stop a worker from creating a file it never listed, because the sandbox is `workspace-write` and any path inside its own worktree is writable. Verify the output from the diff.
|
|
311
311
|
- **It reports "it finished", not "it's correct".** Terminal states come from Codex's `turn.completed` and the process exit code; `exit_code: 0` only means it didn't crash. Judging the output is the main thread's job: run the checks, spot-read the content.
|
|
312
|
+
- **A terminal state lands in two steps, and wait only returns once both have.** `turn.completed` flips `status` to `completed` first; `exit_code` is written when the process exits. `wait_codex_workers` counts a worker as finished only once `exit_code` is recorded (or nobody is left to record it), so the snapshot it returns matches the next `get_codex_worker_status` read. A direct status read can still land between the two steps: `completed` with `exit_code: null` is that gap, read again a moment later.
|
|
312
313
|
- **Don't expect one `wait_codex_workers` call to cover a long job.** Your client's MCP tool timeout is a hard wall (the `timeout` field in `.mcp.json`, or `MCP_TOOL_TIMEOUT`), and hitting it kills the call. The default wait returns after 2 minutes with a progress snapshot; loop instead of waiting once.
|
|
313
314
|
- **Long text comes back clipped by default.** `current_action` is cut at 300 characters, the prompt inside `get_codex_worker_status` is cut at 300 (`includePrompt: true` lifts that), and `last_message` is cut at 400 in the overview and the wait response (4000 in the status response). Nothing is lost: the full command stream is in `get_codex_worker_events` and the full report is in `get_worker_result`. This is what takes one `wait_codex_workers` round trip from tens of KB down to a few KB - which matters because a client that backgrounds a timed-out call replays the whole result as a notification.
|
|
314
315
|
- **Nothing is written to Codex's native goal store.** `goals_1.sqlite` belongs to Codex and this MCP only reads it. Once a worker starts, it calls Codex's own `create_goal`; this MCP only splices that instruction into the prompt at dispatch time.
|
package/README.md
CHANGED
|
@@ -186,7 +186,7 @@ rm -rf ~/.codex-supervisor # 状态目录:sqlite、事件流、worktree
|
|
|
186
186
|
|
|
187
187
|
| 工具 | 入参 | 作用 |
|
|
188
188
|
|---|---|---|
|
|
189
|
-
| `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `session_id`, `dependsOn`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | 起一个 worker |
|
|
189
|
+
| `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `session_id`, `dependsOn`, `baseRef`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | 起一个 worker。`baseRef` 指定 worktree 从哪个提交切(默认仓库 `HEAD`),要接着另一路还没合进主线的 `codex/<id>` 分支干就传它 |
|
|
190
190
|
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, + 同上 | 起一个**新会话**,把老 worker 的 prompt、状态、近期事件拼进去 |
|
|
191
191
|
| `resume_codex_worker` | `task_id`, `prompt` | 接**同一个** Codex 会话继续跑 |
|
|
192
192
|
| `list_codex_workers` | `status`, `includeHistory`, `includeDetails` | 列出 worker,默认只看在跑的 |
|
|
@@ -277,7 +277,7 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
277
277
|
|
|
278
278
|
老版本(0.1.x)的库会在第一次打开时自动迁移:`editing` / `command` / `command_completed` / `reporting` 这些原本塞在 `status` 里的过程值会被拆到 `phase`,`status` 归到 `running`,一行不丢。迁移在一个 `BEGIN IMMEDIATE` 事务里做,多个进程同时启动也只会有一个真的迁移。
|
|
279
279
|
|
|
280
|
-
`changed_files`
|
|
280
|
+
`changed_files` 有三个来源:Codex 的 `file_change` 事件、worker 自己 worktree 里的 `git status --porcelain`(未提交的部分)、以及 `git diff --name-only <base_commit> HEAD`(已提交的部分)。后两个是兜底——worker 用 shell 命令(`printf > file`)改文件时不会产生 `file_change` 事件;它自己在分支上 commit 之后 `git status` 又是干净的,一批五路 worker 全这么干过,读回来全是空数组。`base_commit` 在派单时记在行上;更早的行没有这列,就退回去读 `codex/<taskId>` 分支 reflog 里最老的那条,那是分支建出来的位置。
|
|
281
281
|
|
|
282
282
|
## 环境变量
|
|
283
283
|
|
|
@@ -305,10 +305,11 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
305
305
|
## 已知限制
|
|
306
306
|
|
|
307
307
|
- **worker 的生命周期绑在 MCP 进程上**:`codex` 是 MCP 进程的子进程,MCP 被 kill 时 worker 会被留下。这些 worker 会在下一次 `list_codex_workers` / `get_orchestration_overview` 时被结算成 `lost`。真正的解法是常驻 daemon,见 Roadmap。
|
|
308
|
-
- **worktree
|
|
308
|
+
- **worktree 从一个提交建,未提交的改动不在里面**:默认从仓库 `HEAD` 切,传 `baseRef` 可以换成任何分支、tag 或 sha(解析不到就拒绝派单,错误码 `invalid_base_ref`,不会悄悄退回 `HEAD`)。主线程工作区里没 commit 的修改和未跟踪文件,worker 在自己的 worktree 里看不到。要让它读写这些文件,就在 task 里给绝对路径,或者先把改动 commit。worker 的改动落在 `codex/<taskId>` 分支上,不碰主线程的工作区。
|
|
309
309
|
- **只隔离工作目录**:临时目录(`TMPDIR`)、数据库、端口这些进程级资源是共用的,多个 worker 同时写同一个临时文件照样互相踩。要隔开得自己在 task 里指定各自的临时目录、库名和端口。
|
|
310
310
|
- **`ownedPaths` 是派单前的冲突检测,不是运行时沙箱**:它只挡「两路活登记写同一个文件」,拦不住 worker 在自己 worktree 里新建清单外的文件——sandbox 是 `workspace-write`,写自己 worktree 里的任何路径都合法。校验产出还是得看 diff。
|
|
311
311
|
- **只管「跑完了」,不管写得对不对**:终态来自 Codex 的 `turn.completed` 和进程退出码,`exit_code: 0` 只说明它没崩。产出对不对得主线程自己核,跑校验、抽看内容。
|
|
312
|
+
- **终态分两步落盘,但 wait 只在落稳后返回**:`turn.completed` 先把 `status` 置成 `completed`,进程退出后才写 `exit_code`。`wait_codex_workers` 要等到 `exit_code` 写入(或者进程已经不在)才算这一路到了终态,所以它返回的快照和下一次 `get_codex_worker_status` 读到的是同一份。直接读 status 仍然可能撞上中间态,看到 `completed` 配 `exit_code: null` 就是这种情况,过一会再读。
|
|
312
313
|
- **长任务别指望一次 `wait_codex_workers` 等到底**:客户端给 MCP 工具调用设的超时是硬墙(`.mcp.json` 里的 `timeout`,或 `MCP_TOOL_TIMEOUT`),撞上就把这次调用掐掉。默认 2 分钟带进度返回,靠反复调而不是一次等到黑。
|
|
313
314
|
- **默认读回来的长文本是裁过的**:`current_action` 截到 300 字、`get_codex_worker_status` 的 prompt 截到 300 字(`includePrompt: true` 放开)、`last_message` 在总览和 wait 里截到 400 字(status 里是 4000)。全量都在库里:命令流看 `get_codex_worker_events`,结论看 `get_worker_result`。这样一条 `wait_codex_workers` 往返从几十 KB 降到几 KB——客户端把超时调用挪到后台、再把结果当通知回灌一次时,这份代价小得多。
|
|
314
315
|
- **不往 Codex 原生 goal 写数据**:`goals_1.sqlite` 归 Codex 所有,本 MCP 只读。worker 起来后由它自己调 Codex 的 `create_goal` 建原生 goal,本 MCP 只负责在派单时把这段指令拼进 prompt。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -107,10 +107,11 @@ wait_codex_workers (task_ids: [...], mode: "all")
|
|
|
107
107
|
## 常见坑
|
|
108
108
|
|
|
109
109
|
- **worker 的命绑在 MCP 进程上**。MCP 被 kill,正在跑的 worker 会被留下,下次读状态时结算成 `lost`。
|
|
110
|
-
- **worktree
|
|
110
|
+
- **worktree 是从一个提交建的,你工作区里没 commit 的东西不在里面**。默认从 `HEAD` 切;要让第 5 步接着还没合进主线的第 4 步干,派单时传 `baseRef: "codex/<第4步的taskId>"`,不用自己垫临时分支。未提交的修改和未跟踪文件 worker 既看不到也写不到。要让它读到就把绝对路径写进 `task`,或者先把改动 commit。它自己的改动落在 `codex/<taskId>` 分支上,不碰你的工作区。
|
|
111
111
|
- **它只管"跑完了",不管写得对不对**。终态来自 Codex 的 `turn.completed` 和进程退出码,`exit_code: 0` 只说明没崩。每批活回来,验收得自己做:跑校验、抽看内容。
|
|
112
|
+
- **`completed` 配 `exit_code: null` 是中间态,不是崩了**。`turn.completed` 先写状态,进程退出才写退出码。`wait_codex_workers` 会等到退出码落了再返回;直接读 status 撞上这个组合就过一会再读。
|
|
112
113
|
- **`ownedPaths` 冲突是好事**。说明两路活会踩同一个文件,这时候该改拆法,不是绕过检测。
|
|
113
|
-
- **`ownedPaths` 是派单前的冲突检测,不是运行时的沙箱**。它只挡「两路活登记写同一个文件」,拦不住 worker 在自己 worktree 里新建清单外的文件——sandbox 是 `workspace-write`,写自己 worktree 里的任何路径都合法。收活时该看 diff 还得看:`
|
|
114
|
+
- **`ownedPaths` 是派单前的冲突检测,不是运行时的沙箱**。它只挡「两路活登记写同一个文件」,拦不住 worker 在自己 worktree 里新建清单外的文件——sandbox 是 `workspace-write`,写自己 worktree 里的任何路径都合法。收活时该看 diff 还得看:`get_worker_result` / `get_worker_summary` 里的 `changed_files` 已经包含 worker 在自己分支上 commit 过的文件(按 `base_commit` 和 `HEAD` 比),不用再去 worktree 里跑 `git show --stat`。
|
|
114
115
|
- **worktree 只隔离工作区,不隔离端口和数据库**。多路活要是都会连同一个 dev server 或同一个库,得自己错开。
|
|
115
116
|
- **`cancel_codex_worker` 跨进程靠 pid**。要求那个 pid 的命令行里带 `codex`,防止误杀复用 pid 的进程。
|
|
116
117
|
|
package/src/codex-runner.js
CHANGED
|
@@ -15,7 +15,7 @@ import { applyCodexEvent } from "./event-parser.js";
|
|
|
15
15
|
import { TERMINAL_STATUSES } from "./status.js";
|
|
16
16
|
import { worktreesDir } from "./paths.js";
|
|
17
17
|
import { withGoalPreamble } from "./prompt.js";
|
|
18
|
-
import {
|
|
18
|
+
import { readTaskChanges } from "./worktree.js";
|
|
19
19
|
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
20
20
|
|
|
21
21
|
const processes = new Map();
|
|
@@ -51,21 +51,53 @@ function runCommand(command, args, options = {}) {
|
|
|
51
51
|
});
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
function resolveCommit(cwd, ref) {
|
|
55
|
+
return execFileSync(defaultGitBin, ["-C", cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
|
56
|
+
encoding: "utf8",
|
|
57
|
+
timeout: 15000,
|
|
58
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
59
|
+
}).trim();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function invalidBaseRefError(cwd, baseRef) {
|
|
63
|
+
const error = new Error(`baseRef "${baseRef}" does not resolve to a commit in ${cwd}`);
|
|
64
|
+
error.code = "invalid_base_ref";
|
|
65
|
+
return error;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// The worktree is cut from baseRef when given, else from the repository's
|
|
69
|
+
// HEAD. The resolved commit is recorded on the task: it is what
|
|
70
|
+
// readWorktreeChanges diffs against, so committed work stays visible. An
|
|
71
|
+
// explicit baseRef that does not resolve is an error, not a silent fallback
|
|
72
|
+
// to HEAD - the caller asked for a specific baseline for a reason.
|
|
73
|
+
async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
55
74
|
const taskWorktreeDir = join(worktreesDir, taskId);
|
|
56
75
|
await mkdir(worktreesDir, { recursive: true });
|
|
57
76
|
const gitDir = join(cwd, ".git");
|
|
58
77
|
if (!(await exists(cwd)) || !(await exists(gitDir))) {
|
|
59
|
-
|
|
78
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
79
|
+
return { path: null, baseCommit: null };
|
|
80
|
+
}
|
|
81
|
+
let baseCommit;
|
|
82
|
+
try {
|
|
83
|
+
baseCommit = resolveCommit(cwd, baseRef ?? "HEAD");
|
|
84
|
+
} catch {
|
|
85
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
86
|
+
return { path: null, baseCommit: null };
|
|
87
|
+
}
|
|
88
|
+
if (!baseCommit) {
|
|
89
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
90
|
+
return { path: null, baseCommit: null };
|
|
60
91
|
}
|
|
61
92
|
try {
|
|
62
93
|
await rm(taskWorktreeDir, { recursive: true, force: true });
|
|
63
94
|
const branch = `codex/${taskId}`;
|
|
64
|
-
await runCommand(defaultGitBin, ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir,
|
|
95
|
+
await runCommand(defaultGitBin, ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
|
|
65
96
|
await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
|
|
66
|
-
return taskWorktreeDir;
|
|
67
|
-
} catch {
|
|
68
|
-
|
|
97
|
+
return { path: taskWorktreeDir, baseCommit };
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (baseRef) throw error;
|
|
100
|
+
return { path: null, baseCommit: null };
|
|
69
101
|
}
|
|
70
102
|
}
|
|
71
103
|
|
|
@@ -298,7 +330,7 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
|
|
|
298
330
|
...live,
|
|
299
331
|
status,
|
|
300
332
|
phase: null,
|
|
301
|
-
changed_files:
|
|
333
|
+
changed_files: readTaskChanges(live),
|
|
302
334
|
exit_code: code,
|
|
303
335
|
signal,
|
|
304
336
|
current_command: null,
|
|
@@ -363,7 +395,8 @@ export async function createCodexWorker({
|
|
|
363
395
|
goal,
|
|
364
396
|
dependsOn = [],
|
|
365
397
|
followupOf = null,
|
|
366
|
-
useWorktree = true
|
|
398
|
+
useWorktree = true,
|
|
399
|
+
baseRef = null
|
|
367
400
|
}) {
|
|
368
401
|
if (!task || typeof task !== "string") throw new Error("task is required");
|
|
369
402
|
if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
|
|
@@ -381,7 +414,10 @@ export async function createCodexWorker({
|
|
|
381
414
|
if (conflicts.length > 0) throw ownershipConflictError(conflicts);
|
|
382
415
|
|
|
383
416
|
const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
384
|
-
const
|
|
417
|
+
const worktree = useWorktree
|
|
418
|
+
? await ensureWorktree(projectRoot, id, baseRef)
|
|
419
|
+
: { path: null, baseCommit: null };
|
|
420
|
+
const worktreePath = worktree.path;
|
|
385
421
|
const effectiveCwd = worktreePath ?? projectRoot;
|
|
386
422
|
|
|
387
423
|
const record = {
|
|
@@ -410,6 +446,7 @@ export async function createCodexWorker({
|
|
|
410
446
|
goal_updated_at: null,
|
|
411
447
|
run_count: 0,
|
|
412
448
|
worktree_path: worktreePath,
|
|
449
|
+
base_commit: worktree.baseCommit,
|
|
413
450
|
prompt: task,
|
|
414
451
|
changed_files: [],
|
|
415
452
|
commands: [],
|
|
@@ -596,7 +633,8 @@ export async function createFollowupWorker({
|
|
|
596
633
|
model,
|
|
597
634
|
reasoningEffort,
|
|
598
635
|
ownedPaths,
|
|
599
|
-
goal
|
|
636
|
+
goal,
|
|
637
|
+
baseRef
|
|
600
638
|
}) {
|
|
601
639
|
const parent = await getTask(taskId);
|
|
602
640
|
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
@@ -637,6 +675,7 @@ export async function createFollowupWorker({
|
|
|
637
675
|
goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
|
|
638
676
|
dependsOn: [parent.id],
|
|
639
677
|
followupOf: parent.id,
|
|
640
|
-
useWorktree: true
|
|
678
|
+
useWorktree: true,
|
|
679
|
+
baseRef: baseRef ?? null
|
|
641
680
|
});
|
|
642
681
|
}
|
package/src/mcp-server.js
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
import {
|
|
13
13
|
getTask,
|
|
14
14
|
getTasks,
|
|
15
|
+
isPidAlive,
|
|
15
16
|
listTaskEventKinds,
|
|
16
17
|
readAgentMessages,
|
|
17
18
|
readTaskEvents,
|
|
@@ -22,7 +23,7 @@ import {
|
|
|
22
23
|
upsertTask
|
|
23
24
|
} from "./task-store.js";
|
|
24
25
|
import { readNativeGoal } from "./goal-store.js";
|
|
25
|
-
import {
|
|
26
|
+
import { readTaskChanges } from "./worktree.js";
|
|
26
27
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
|
|
27
28
|
import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
|
|
28
29
|
|
|
@@ -80,6 +81,19 @@ function sleep(ms) {
|
|
|
80
81
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
// A terminal status is written in two steps. Codex's turn.completed event
|
|
85
|
+
// flips status to completed while the process is still alive and exit_code is
|
|
86
|
+
// still null; the process exit then writes exit_code. A wait that returned on
|
|
87
|
+
// the first step handed the caller a snapshot with exit_code: null, and the
|
|
88
|
+
// next read said 0 - two answers for one worker. A row counts as settled once
|
|
89
|
+
// the exit is recorded, or once nobody is left to record it.
|
|
90
|
+
function isSettled(task) {
|
|
91
|
+
if (!TERMINAL_STATUSES.has(task.status)) return false;
|
|
92
|
+
if (task.status !== "completed" && task.status !== "failed") return true;
|
|
93
|
+
if (task.exit_code !== null && task.exit_code !== undefined) return true;
|
|
94
|
+
return !isPidAlive(task.pid);
|
|
95
|
+
}
|
|
96
|
+
|
|
83
97
|
function summarizeTask(task) {
|
|
84
98
|
return {
|
|
85
99
|
id: task.id,
|
|
@@ -133,7 +147,8 @@ function statusView(task, { includePrompt, promptMaxChars }) {
|
|
|
133
147
|
session_id: task.session_id ?? null,
|
|
134
148
|
pid: task.pid ?? null,
|
|
135
149
|
run_log: task.run_log ?? null,
|
|
136
|
-
|
|
150
|
+
base_commit: task.base_commit ?? null,
|
|
151
|
+
changed_files: readTaskChanges(task),
|
|
137
152
|
current_command: clip(task.current_command, COMMAND_PREVIEW_CHARS),
|
|
138
153
|
commands: commands.map((entry) => ({ ...entry, command: clip(entry.command, COMMAND_PREVIEW_CHARS) })),
|
|
139
154
|
prompt: clip(promptText, promptBudget),
|
|
@@ -158,6 +173,7 @@ function receipt(task) {
|
|
|
158
173
|
project_root: task.project_root,
|
|
159
174
|
worktree_path: task.worktree_path,
|
|
160
175
|
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
176
|
+
base_commit: task.base_commit ?? null,
|
|
161
177
|
sandbox: task.sandbox,
|
|
162
178
|
model: task.model,
|
|
163
179
|
reasoning_effort: task.reasoning_effort,
|
|
@@ -253,7 +269,7 @@ function buildOverview(tasks) {
|
|
|
253
269
|
function buildWorkerSummary(task, nativeGoal) {
|
|
254
270
|
// Read the worktree too: a worker that edits via shell commands emits no
|
|
255
271
|
// file_change events, so the checkout is the authoritative diff.
|
|
256
|
-
const changed =
|
|
272
|
+
const changed = readTaskChanges(task);
|
|
257
273
|
const commands = task.commands ?? [];
|
|
258
274
|
const lines = [
|
|
259
275
|
`${task.title ?? task.id} — status=${task.status}${task.phase ? `, phase=${task.phase}` : ""}`,
|
|
@@ -322,7 +338,11 @@ server.registerTool(
|
|
|
322
338
|
objective: z.string().min(1),
|
|
323
339
|
tokenBudget: z.number().int().positive().optional()
|
|
324
340
|
}),
|
|
325
|
-
dependsOn: z.array(z.string().min(1)).optional()
|
|
341
|
+
dependsOn: z.array(z.string().min(1)).optional(),
|
|
342
|
+
// Which commit the worktree is cut from. Defaults to the repository's
|
|
343
|
+
// HEAD; pass a branch, tag or sha to build on work that is not on the
|
|
344
|
+
// main line yet (for example another worker's codex/<id> branch).
|
|
345
|
+
baseRef: z.string().min(1).optional()
|
|
326
346
|
}
|
|
327
347
|
},
|
|
328
348
|
async (input) => {
|
|
@@ -356,7 +376,8 @@ server.registerTool(
|
|
|
356
376
|
objective: z.string().min(1),
|
|
357
377
|
tokenBudget: z.number().int().positive().optional()
|
|
358
378
|
})
|
|
359
|
-
.optional()
|
|
379
|
+
.optional(),
|
|
380
|
+
baseRef: z.string().min(1).optional()
|
|
360
381
|
}
|
|
361
382
|
},
|
|
362
383
|
async ({ task_id, followup_prompt, session_id, ...options }) => {
|
|
@@ -481,8 +502,8 @@ server.registerTool(
|
|
|
481
502
|
while (Date.now() - startedAt < effectiveTimeoutMs) {
|
|
482
503
|
await reconcileDetachedActiveTasks();
|
|
483
504
|
tasks = (await getTasks(task_ids)).filter(Boolean);
|
|
484
|
-
const
|
|
485
|
-
const isDone = mode === "any" ?
|
|
505
|
+
const settledCount = tasks.filter(isSettled).length;
|
|
506
|
+
const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
|
|
486
507
|
if (isDone) break;
|
|
487
508
|
await sleep(pollMs);
|
|
488
509
|
}
|
|
@@ -490,9 +511,9 @@ server.registerTool(
|
|
|
490
511
|
await reconcileDetachedActiveTasks();
|
|
491
512
|
tasks = (await getTasks(task_ids)).filter(Boolean);
|
|
492
513
|
const missingIds = task_ids.filter((taskId) => !tasks.some((task) => task.id === taskId));
|
|
493
|
-
const
|
|
514
|
+
const settledTasks = tasks.filter(isSettled);
|
|
494
515
|
const timedOut =
|
|
495
|
-
mode === "any" ?
|
|
516
|
+
mode === "any" ? settledTasks.length === 0 : settledTasks.length !== task_ids.length;
|
|
496
517
|
|
|
497
518
|
const summaries = await Promise.all(
|
|
498
519
|
tasks.map(async (task) => ({
|
|
@@ -690,7 +711,7 @@ server.registerTool(
|
|
|
690
711
|
source = "task_row";
|
|
691
712
|
}
|
|
692
713
|
const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
|
|
693
|
-
const changed =
|
|
714
|
+
const changed = readTaskChanges(task);
|
|
694
715
|
return textResult({
|
|
695
716
|
task_id,
|
|
696
717
|
title: task.title,
|
package/src/task-store.js
CHANGED
|
@@ -23,7 +23,8 @@ const POST_V1_COLUMNS = [
|
|
|
23
23
|
["run_count", "INTEGER NOT NULL DEFAULT 0"],
|
|
24
24
|
["cancel_requested_at", "TEXT"],
|
|
25
25
|
["notices", "TEXT"],
|
|
26
|
-
["session_id", "TEXT"]
|
|
26
|
+
["session_id", "TEXT"],
|
|
27
|
+
["base_commit", "TEXT"]
|
|
27
28
|
];
|
|
28
29
|
|
|
29
30
|
const TASKS_DDL = `
|
|
@@ -72,6 +73,7 @@ const TASKS_DDL = `
|
|
|
72
73
|
cancel_requested_at TEXT,
|
|
73
74
|
notices TEXT,
|
|
74
75
|
worktree_path TEXT,
|
|
76
|
+
base_commit TEXT,
|
|
75
77
|
run_log TEXT NOT NULL
|
|
76
78
|
);
|
|
77
79
|
`;
|
|
@@ -84,7 +86,7 @@ const TASK_COLUMNS = [
|
|
|
84
86
|
"current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
|
|
85
87
|
"depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
|
|
86
88
|
"goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
|
|
87
|
-
"notices", "worktree_path", "run_log"
|
|
89
|
+
"notices", "worktree_path", "base_commit", "run_log"
|
|
88
90
|
];
|
|
89
91
|
|
|
90
92
|
function tableColumns(dbInstance, tableName) {
|
|
@@ -251,7 +253,7 @@ function rowToTask(row) {
|
|
|
251
253
|
};
|
|
252
254
|
}
|
|
253
255
|
|
|
254
|
-
function isPidAlive(pid) {
|
|
256
|
+
export function isPidAlive(pid) {
|
|
255
257
|
if (!pid) return false;
|
|
256
258
|
try {
|
|
257
259
|
process.kill(pid, 0);
|
|
@@ -274,19 +276,39 @@ export async function readActiveTasks() {
|
|
|
274
276
|
|
|
275
277
|
// A worker whose process is gone and that never wrote a terminal event is not
|
|
276
278
|
// "failed": nothing told us it failed. It is lost, and the fix is to re-run it.
|
|
279
|
+
// A row can also be active without ever having had a process: the dispatch
|
|
280
|
+
// wrote the row and then died before the spawn was recorded (one real store
|
|
281
|
+
// carried such a row for days, pid 0 and no created_at, forever "running").
|
|
282
|
+
// Only a row old enough that the dispatch cannot still be in flight is judged
|
|
283
|
+
// this way; a row with an unreadable created_at is treated as old.
|
|
284
|
+
const NEVER_STARTED_GRACE_MS = 5 * 60 * 1000;
|
|
285
|
+
|
|
286
|
+
function neverStarted(task, now = Date.now()) {
|
|
287
|
+
if (task.pid) return false;
|
|
288
|
+
if (task.started_at) return false;
|
|
289
|
+
const created = Date.parse(task.created_at ?? "");
|
|
290
|
+
if (Number.isNaN(created)) return true;
|
|
291
|
+
return now - created > NEVER_STARTED_GRACE_MS;
|
|
292
|
+
}
|
|
293
|
+
|
|
277
294
|
export async function reconcileDetachedActiveTasks() {
|
|
278
295
|
const tasks = await readActiveTasks();
|
|
279
|
-
const staleTasks = tasks.filter((task) => task.pid && !isPidAlive(task.pid));
|
|
296
|
+
const staleTasks = tasks.filter((task) => (task.pid && !isPidAlive(task.pid)) || neverStarted(task));
|
|
280
297
|
for (const task of staleTasks) {
|
|
281
298
|
const now = new Date().toISOString();
|
|
299
|
+
const vanished = Boolean(task.pid);
|
|
282
300
|
await writeTask({
|
|
283
301
|
...task,
|
|
284
302
|
status: "lost",
|
|
285
303
|
phase: null,
|
|
286
|
-
current_action:
|
|
304
|
+
current_action: vanished
|
|
305
|
+
? "Worker process disappeared without a terminal event"
|
|
306
|
+
: "Worker was never started: no process was recorded for this row",
|
|
287
307
|
current_command: null,
|
|
288
|
-
error: task.error ??
|
|
289
|
-
|
|
308
|
+
error: task.error ?? (vanished
|
|
309
|
+
? "Codex worker process disappeared before a terminal event was recorded."
|
|
310
|
+
: "Codex worker row was written but no process was ever recorded for it."),
|
|
311
|
+
completed_at: task.completed_at || now,
|
|
290
312
|
updated_at: now
|
|
291
313
|
});
|
|
292
314
|
}
|
package/src/worktree.js
CHANGED
|
@@ -3,13 +3,27 @@
|
|
|
3
3
|
// Codex reports edits as file_change items only when it uses its own patch
|
|
4
4
|
// tool. A worker that edits through shell commands produces no such item, so
|
|
5
5
|
// the worktree itself is the authoritative source: every worker gets its own
|
|
6
|
-
// checkout, so
|
|
6
|
+
// checkout, so the diff inside it is exactly that worker's work.
|
|
7
|
+
//
|
|
8
|
+
// Two reads are needed. `git status` covers what is still uncommitted. A
|
|
9
|
+
// worker that commits on its branch leaves a clean status, and one real batch
|
|
10
|
+
// of five workers all did exactly that and reported no changed files at all -
|
|
11
|
+
// so the committed part is read as `git diff --name-only <base> HEAD`, where
|
|
12
|
+
// base is the commit the worktree was created from.
|
|
7
13
|
import { execFileSync } from "node:child_process";
|
|
8
14
|
import { existsSync } from "node:fs";
|
|
9
15
|
import { join } from "node:path";
|
|
10
16
|
|
|
11
17
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
12
18
|
|
|
19
|
+
function git(worktreePath, args) {
|
|
20
|
+
return execFileSync(defaultGitBin, ["-C", worktreePath, ...args], {
|
|
21
|
+
encoding: "utf8",
|
|
22
|
+
timeout: 15000,
|
|
23
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
13
27
|
function parsePorcelainLine(line) {
|
|
14
28
|
// " M path", "?? path", "R old -> new"
|
|
15
29
|
const trimmed = line.replace(/\s+$/, "");
|
|
@@ -21,24 +35,59 @@ function parsePorcelainLine(line) {
|
|
|
21
35
|
return rest.trim() || null;
|
|
22
36
|
}
|
|
23
37
|
|
|
24
|
-
|
|
38
|
+
function nonEmptyLines(output) {
|
|
39
|
+
return output.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The commit the worker started from. Rows written by this version carry it
|
|
43
|
+
// as base_commit. Older rows do not, but the branch reflog still has it: the
|
|
44
|
+
// oldest reflog entry of `codex/<id>` is the branch's creation point.
|
|
45
|
+
export function resolveWorktreeBase(worktreePath, { baseCommit = null, branch = null } = {}) {
|
|
46
|
+
if (baseCommit) return baseCommit;
|
|
47
|
+
if (!branch) return null;
|
|
48
|
+
try {
|
|
49
|
+
const entries = nonEmptyLines(git(worktreePath, ["reflog", "show", "--format=%H", branch]));
|
|
50
|
+
return entries.at(-1) ?? null;
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function readWorktreeChanges(worktreePath, { baseCommit = null, branch = null } = {}) {
|
|
25
57
|
if (!worktreePath || !existsSync(worktreePath)) return [];
|
|
58
|
+
const found = new Set();
|
|
26
59
|
try {
|
|
27
|
-
const output =
|
|
28
|
-
|
|
29
|
-
timeout: 15000,
|
|
30
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
31
|
-
});
|
|
32
|
-
const relative = output
|
|
33
|
-
.split("\n")
|
|
34
|
-
.map(parsePorcelainLine)
|
|
35
|
-
.filter(Boolean);
|
|
36
|
-
return Array.from(new Set(relative.map((entry) => join(worktreePath, entry))));
|
|
60
|
+
const output = git(worktreePath, ["status", "--porcelain"]);
|
|
61
|
+
for (const entry of output.split("\n").map(parsePorcelainLine).filter(Boolean)) found.add(entry);
|
|
37
62
|
} catch {
|
|
38
63
|
return [];
|
|
39
64
|
}
|
|
65
|
+
const base = resolveWorktreeBase(worktreePath, { baseCommit, branch });
|
|
66
|
+
if (base) {
|
|
67
|
+
try {
|
|
68
|
+
for (const entry of nonEmptyLines(git(worktreePath, ["diff", "--name-only", base, "HEAD"]))) found.add(entry);
|
|
69
|
+
} catch {
|
|
70
|
+
// A base that no longer resolves (history rewritten) leaves only the
|
|
71
|
+
// uncommitted part. Better a partial answer than none.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return Array.from(found, (entry) => join(worktreePath, entry));
|
|
40
75
|
}
|
|
41
76
|
|
|
42
77
|
export function mergeChangedFiles(existing, discovered) {
|
|
43
78
|
return Array.from(new Set([...(existing ?? []), ...(discovered ?? [])]));
|
|
44
79
|
}
|
|
80
|
+
|
|
81
|
+
// What a task row knows about its own worktree, in the shape
|
|
82
|
+
// readWorktreeChanges wants. Kept here so every caller derives the branch
|
|
83
|
+
// name the same way the runner creates it.
|
|
84
|
+
export function worktreeRef(task) {
|
|
85
|
+
return {
|
|
86
|
+
baseCommit: task.base_commit ?? null,
|
|
87
|
+
branch: task.worktree_path ? `codex/${task.id}` : null
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function readTaskChanges(task) {
|
|
92
|
+
return mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path, worktreeRef(task)));
|
|
93
|
+
}
|