codex-supervisor-mcp 0.5.4 → 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 CHANGED
@@ -186,13 +186,13 @@ 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 |
193
193
  | `get_orchestration_overview` | `status`, `limit` | A compact status table for every worker, meant for the main thread |
194
- | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for a terminal state, then return summaries. The default wait is 2 minutes: when it runs out you get a progress snapshot and the workers keep going, so call it again |
195
- | `get_codex_worker_status` | `task_id` | The full record for one worker |
194
+ | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for a terminal state, then return summaries. The default wait is 2 minutes: when it runs out you get a progress snapshot and the workers keep going, so call it again. Events are **off** by default (`includeEvents: false`) |
195
+ | `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | Status for one worker: lifecycle, phase, current action, changed files, goal, recent commands, with the prompt clipped. Pass `includePrompt: true` for the full prompt |
196
196
  | `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | Read the raw event stream |
197
197
  | `get_worker_goal` | `task_id` | Read a worker's goal (supervisor side and native Codex side) |
198
198
  | `get_worker_summary` | `task_id` | One paragraph about a worker; what the main thread reads when wrapping up |
@@ -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 two sources: Codex's `file_change` events, and reading `git status --porcelain` in the worker's own worktree after it exits. The second exists because a worker that edits files through a shell command (`printf > file`) never emits a `file_change` event, and only the worktree knows the truth.
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,13 @@ 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 `HEAD`, so uncommitted work isn't in it.** `ensureWorktree` runs `git worktree add --detach <dir> HEAD` (`src/codex-runner.js:64`). 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.
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
+ - **`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.
310
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.
311
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.
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.
312
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.
313
316
  - **Native goals depend on the model complying.** `codex exec` does not create a goal on its own; the instruction at dispatch time is what makes the worker create one. The model occasionally skips it, in which case `native_goal` is `null` and `get_worker_goal` falls back to the copy recorded at dispatch. The state machine is unaffected.
314
317
  - **`search_works` is substring matching, not a full-text index.** At a few hundred works, a `LIKE` scan is fast enough and costs nothing to maintain. Talk about something else at tens of thousands.
package/README.md CHANGED
@@ -186,13 +186,13 @@ 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,默认只看在跑的 |
193
193
  | `get_orchestration_overview` | `status`, `limit` | 全部 worker 的紧凑状态表,默认给主线程用 |
194
- | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态,回摘要。默认只等 2 分钟,到点带进度快照返回,worker 照跑;接着调同一个工具继续等 |
195
- | `get_codex_worker_status` | `task_id` | 单个 worker 的完整记录 |
194
+ | `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态,回摘要。默认只等 2 分钟,到点带进度快照返回,worker 照跑;接着调同一个工具继续等。默认**不带**事件(`includeEvents: false`),要事件就自己开 |
195
+ | `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | 单个 worker 的状态:生命周期、phase、当前动作、改动文件、goal、最近的命令,prompt 默认截断。要 prompt 全文传 `includePrompt: true` |
196
196
  | `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | 读原始事件流 |
197
197
  | `get_worker_goal` | `task_id` | 读 worker 的 goal(supervisor 侧 + Codex 原生) |
198
198
  | `get_worker_summary` | `task_id` | 单个 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` 有两个来源:Codex 的 `file_change` 事件,以及 worker 结束后读自己 worktree 的 `git status --porcelain`。后者是兜底——worker 用 shell 命令(`printf > file`)改文件时不会产生 `file_change` 事件,只有 worktree 知道真相。
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,13 @@ 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 从 `HEAD` 建,未提交的改动不在里面**:`ensureWorktree` 走的是 `git worktree add --detach <dir> HEAD`(`src/codex-runner.js:64`)。主线程工作区里没 commit 的修改和未跟踪文件,worker 在自己的 worktree 里看不到。要让它读写这些文件,就在 task 里给绝对路径,或者先把改动 commit。worker 的改动落在 `codex/<taskId>` 分支上,不碰主线程的工作区。
308
+ - **worktree 从一个提交建,未提交的改动不在里面**:默认从仓库 `HEAD` 切,传 `baseRef` 可以换成任何分支、tag 或 sha(解析不到就拒绝派单,错误码 `invalid_base_ref`,不会悄悄退回 `HEAD`)。主线程工作区里没 commit 的修改和未跟踪文件,worker 在自己的 worktree 里看不到。要让它读写这些文件,就在 task 里给绝对路径,或者先把改动 commit。worker 的改动落在 `codex/<taskId>` 分支上,不碰主线程的工作区。
309
309
  - **只隔离工作目录**:临时目录(`TMPDIR`)、数据库、端口这些进程级资源是共用的,多个 worker 同时写同一个临时文件照样互相踩。要隔开得自己在 task 里指定各自的临时目录、库名和端口。
310
+ - **`ownedPaths` 是派单前的冲突检测,不是运行时沙箱**:它只挡「两路活登记写同一个文件」,拦不住 worker 在自己 worktree 里新建清单外的文件——sandbox 是 `workspace-write`,写自己 worktree 里的任何路径都合法。校验产出还是得看 diff。
310
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` 就是这种情况,过一会再读。
311
313
  - **长任务别指望一次 `wait_codex_workers` 等到底**:客户端给 MCP 工具调用设的超时是硬墙(`.mcp.json` 里的 `timeout`,或 `MCP_TOOL_TIMEOUT`),撞上就把这次调用掐掉。默认 2 分钟带进度返回,靠反复调而不是一次等到黑。
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——客户端把超时调用挪到后台、再把结果当通知回灌一次时,这份代价小得多。
312
315
  - **不往 Codex 原生 goal 写数据**:`goals_1.sqlite` 归 Codex 所有,本 MCP 只读。worker 起来后由它自己调 Codex 的 `create_goal` 建原生 goal,本 MCP 只负责在派单时把这段指令拼进 prompt。
313
316
  - **原生 goal 依赖模型照做**:`codex exec` 不会自动建 goal,是派单时那段指令让 worker 建的。模型偶尔漏调,这时 `native_goal` 为 `null`,`get_worker_goal` 退回派单时记录的那份,不影响状态机。
314
317
  - **`search_works` 是子串匹配,不是全文索引**:几百条 work 的规模下 `LIKE` 扫描足够快,也省掉一套索引的维护成本。上到几万条再谈别的。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.5.4",
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",
@@ -19,7 +19,7 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
19
19
 
20
20
  1. 拆活。每路写清楚:干什么、能写哪些文件、怎么算做完。
21
21
  2. `create_codex_worker` 派出去。返回的是一张精简回执(`id`、`worktree_path`、`branch`、`owned_paths`、`status`),任务原文不回传,派十一路也不会把你的提示词抄十一遍。
22
- 3. 派完就 `wait_codex_workers` 等。默认只等 2 分钟,到点返回进度快照,worker 照跑;拿同一批 `task_ids` 接着调,直到 `timed_out: false`。
22
+ 3. 派完就 `wait_codex_workers` 等。默认只等 2 分钟,到点返回进度快照,worker 照跑;拿同一批 `task_ids` 接着调,直到 `timed_out: false`。默认**不带**事件(`includeEvents: false`),返回只够看状态,要事件得自己开。
23
23
  4. 收结果走 `get_worker_result`,拿完整汇报,别一上来读事件流。
24
24
 
25
25
  `ownedPaths` 和 `goal` 必填,不是可选项。
@@ -52,11 +52,13 @@ wait_codex_workers (task_ids: [...], mode: "all")
52
52
  | 收一路活的完整结论 | `get_worker_result` | 汇报全文,大活可能上万字 |
53
53
  | 只想知道活着还是完了 | `get_worker_summary` | 一段话 |
54
54
  | 看某个 worker 干了什么 | `get_codex_worker_events` | 用 `limit` / `kinds` / `maxChars` 压 |
55
- | 看某个 worker 的完整记录 | `get_codex_worker_status` | 中等,比 overview 一行细 |
55
+ | 看某个 worker 的状态 | `get_codex_worker_status` | 比 overview 一行细,命令和 prompt 都裁过 |
56
56
  | 看 goal 和 token 消耗 | `get_worker_goal` | 很小 |
57
57
 
58
58
  **收结论必须走 `get_worker_result`。** `wait_codex_workers` 返回里的 `last_message` 会被截到 400 字只留开头,`get_orchestration_overview` 干脆不给这一列。拿截断版当结论,后面的证据、数字和结论全会漏掉。`get_worker_result` 还会带回 `status`、`exit_code`、`changed_files`,顺便就能判断是真跑完还是崩了。
59
59
 
60
+ **默认读回来的长文本都是裁过的**,别把裁剪当成"活没干":`current_action` 截 300 字(一条 heredoc 命令能写一整个文件,原样回传一次就是几万字)、`get_codex_worker_status` 的 `prompt` 截 300 字(要全文传 `includePrompt: true`)、`last_message` 在 overview 和 wait 里截 400 字、在 status 里截 4000 字。全量在库里:命令流看 `get_codex_worker_events`,结论看 `get_worker_result`。
61
+
60
62
  `get_codex_worker_events` 的三个闸门:`kinds` 先过滤再取 `limit`;`maxChars` 把超长字符串中间截断;不知道有哪些 `kinds` 时先看返回里的 `available_kinds`。
61
63
 
62
64
  **别做**:一次 `limit: 200` 拉全量事件。那是几万 token。
@@ -105,9 +107,11 @@ wait_codex_workers (task_ids: [...], mode: "all")
105
107
  ## 常见坑
106
108
 
107
109
  - **worker 的命绑在 MCP 进程上**。MCP 被 kill,正在跑的 worker 会被留下,下次读状态时结算成 `lost`。
108
- - **worktree 是从 `HEAD` 建的,你工作区里没 commit 的东西不在里面**。未提交的修改和未跟踪文件 worker 既看不到也写不到。要让它读到就把绝对路径写进 `task`,或者先把改动 commit。它自己的改动落在 `codex/<taskId>` 分支上,不碰你的工作区。
110
+ - **worktree 是从一个提交建的,你工作区里没 commit 的东西不在里面**。默认从 `HEAD` 切;要让第 5 步接着还没合进主线的第 4 步干,派单时传 `baseRef: "codex/<第4步的taskId>"`,不用自己垫临时分支。未提交的修改和未跟踪文件 worker 既看不到也写不到。要让它读到就把绝对路径写进 `task`,或者先把改动 commit。它自己的改动落在 `codex/<taskId>` 分支上,不碰你的工作区。
109
111
  - **它只管"跑完了",不管写得对不对**。终态来自 Codex 的 `turn.completed` 和进程退出码,`exit_code: 0` 只说明没崩。每批活回来,验收得自己做:跑校验、抽看内容。
112
+ - **`completed` 配 `exit_code: null` 是中间态,不是崩了**。`turn.completed` 先写状态,进程退出才写退出码。`wait_codex_workers` 会等到退出码落了再返回;直接读 status 撞上这个组合就过一会再读。
110
113
  - **`ownedPaths` 冲突是好事**。说明两路活会踩同一个文件,这时候该改拆法,不是绕过检测。
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`。
111
115
  - **worktree 只隔离工作区,不隔离端口和数据库**。多路活要是都会连同一个 dev server 或同一个库,得自己错开。
112
116
  - **`cancel_codex_worker` 跨进程靠 pid**。要求那个 pid 的命令行里带 `codex`,防止误杀复用 pid 的进程。
113
117
 
@@ -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 { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
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
- async function ensureWorktree(cwd, taskId) {
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
- return null;
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, "HEAD"]);
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
- return null;
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: mergeChangedFiles(live.changed_files, readWorktreeChanges(live.worktree_path)),
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 worktreePath = useWorktree ? await ensureWorktree(projectRoot, id) : null;
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
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
2
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
5
  import { z } from "zod";
@@ -11,6 +12,7 @@ import {
11
12
  import {
12
13
  getTask,
13
14
  getTasks,
15
+ isPidAlive,
14
16
  listTaskEventKinds,
15
17
  readAgentMessages,
16
18
  readTaskEvents,
@@ -21,13 +23,19 @@ import {
21
23
  upsertTask
22
24
  } from "./task-store.js";
23
25
  import { readNativeGoal } from "./goal-store.js";
24
- import { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
26
+ import { readTaskChanges } from "./worktree.js";
25
27
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
26
28
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
27
29
 
30
+ // Report the real package version. This string had drifted to 0.4.0 while the
31
+ // package shipped 0.5.x, so the handshake named a version nobody was running.
32
+ const packageVersion = JSON.parse(
33
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
34
+ ).version;
35
+
28
36
  const server = new McpServer({
29
37
  name: "codex-supervisor",
30
- version: "0.4.0"
38
+ version: packageVersion
31
39
  });
32
40
 
33
41
  const OVERVIEW_BYTE_BUDGET = 7000;
@@ -38,6 +46,20 @@ const OVERVIEW_CAP_LEVELS = [
38
46
  { title: 12, goal: 16, action: 16, path: 16 }
39
47
  ];
40
48
 
49
+ // `current_action` is "Running <command>", and a command can be a heredoc that
50
+ // writes a whole file. Returning it whole put tens of thousands of characters
51
+ // into every wait response, which then blew past the client's MCP output cap
52
+ // and came back a second time as a notification. The full command stays in
53
+ // current_command / commands and is readable through get_codex_worker_events.
54
+ const ACTION_PREVIEW_CHARS = 300;
55
+ const COMMAND_PREVIEW_CHARS = 300;
56
+ const COMMAND_TAIL = 20;
57
+ const PROMPT_PREVIEW_CHARS = 300;
58
+ // The single-worker status read is the drill-in for one worker, so its copy of
59
+ // the last message stays much larger than the overview's 400. The full report
60
+ // is still get_worker_result's job.
61
+ const STATUS_MESSAGE_CHARS = 4000;
62
+
41
63
  function textResult(value) {
42
64
  return {
43
65
  content: [
@@ -59,6 +81,19 @@ function sleep(ms) {
59
81
  return new Promise((resolve) => setTimeout(resolve, ms));
60
82
  }
61
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
+
62
97
  function summarizeTask(task) {
63
98
  return {
64
99
  id: task.id,
@@ -83,7 +118,7 @@ function summarizeTask(task) {
83
118
  changed_file_count: (task.changed_files ?? []).length,
84
119
  command_count: (task.commands ?? []).length,
85
120
  run_count: task.run_count ?? 0,
86
- current_action: task.current_action,
121
+ current_action: clip(task.current_action, ACTION_PREVIEW_CHARS),
87
122
  last_event_type: task.last_event_type,
88
123
  last_message: clip(task.last_message, 400),
89
124
  notices: clip(task.notices, 400),
@@ -96,6 +131,31 @@ function summarizeTask(task) {
96
131
  };
97
132
  }
98
133
 
134
+ // The status read used to hand back the stored row verbatim. For a follow-up
135
+ // worker that row carries the parent prompt plus the whole command history and
136
+ // the events folded into it; one real call returned 180k characters, past the
137
+ // client's MCP output cap, so the reply landed on disk and had to be grepped.
138
+ // This is the same status surface the other reads use, plus explicitly bounded
139
+ // extras. includePrompt is the escape hatch for the full task text.
140
+ function statusView(task, { includePrompt, promptMaxChars }) {
141
+ const promptText = task.prompt ?? null;
142
+ const promptBudget = includePrompt ? promptMaxChars : PROMPT_PREVIEW_CHARS;
143
+ const commands = (task.commands ?? []).slice(-COMMAND_TAIL);
144
+ return {
145
+ ...summarizeTask(task),
146
+ last_message: clip(task.last_message, STATUS_MESSAGE_CHARS),
147
+ session_id: task.session_id ?? null,
148
+ pid: task.pid ?? null,
149
+ run_log: task.run_log ?? null,
150
+ base_commit: task.base_commit ?? null,
151
+ changed_files: readTaskChanges(task),
152
+ current_command: clip(task.current_command, COMMAND_PREVIEW_CHARS),
153
+ commands: commands.map((entry) => ({ ...entry, command: clip(entry.command, COMMAND_PREVIEW_CHARS) })),
154
+ prompt: clip(promptText, promptBudget),
155
+ prompt_truncated: Boolean(promptText) && String(promptText).length > promptBudget
156
+ };
157
+ }
158
+
99
159
  // The dispatch receipt. Dispatch used to return the whole task record, which
100
160
  // echoes the task text - and for a follow-up, the parent prompt plus 20 raw
101
161
  // events - back to the caller on every call. Dispatching eleven workers made
@@ -113,6 +173,7 @@ function receipt(task) {
113
173
  project_root: task.project_root,
114
174
  worktree_path: task.worktree_path,
115
175
  branch: task.worktree_path ? `codex/${task.id}` : null,
176
+ base_commit: task.base_commit ?? null,
116
177
  sandbox: task.sandbox,
117
178
  model: task.model,
118
179
  reasoning_effort: task.reasoning_effort,
@@ -208,7 +269,7 @@ function buildOverview(tasks) {
208
269
  function buildWorkerSummary(task, nativeGoal) {
209
270
  // Read the worktree too: a worker that edits via shell commands emits no
210
271
  // file_change events, so the checkout is the authoritative diff.
211
- const changed = mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path));
272
+ const changed = readTaskChanges(task);
212
273
  const commands = task.commands ?? [];
213
274
  const lines = [
214
275
  `${task.title ?? task.id} — status=${task.status}${task.phase ? `, phase=${task.phase}` : ""}`,
@@ -218,7 +279,7 @@ function buildWorkerSummary(task, nativeGoal) {
218
279
  : "codex goal: none recorded for this thread",
219
280
  `changed files (${changed.length}): ${changed.slice(0, 10).join(", ") || "-"}`,
220
281
  `last command: ${commands.at(-1)?.command ?? "-"}`,
221
- `last action: ${task.current_action ?? "-"}`,
282
+ `last action: ${clip(task.current_action, ACTION_PREVIEW_CHARS) ?? "-"}`,
222
283
  `runs: ${task.run_count ?? 0}${task.resumed_from ? `, resumed from ${task.resumed_from}` : ""}`,
223
284
  task.error ? `error: ${task.error}` : null
224
285
  ].filter(Boolean);
@@ -277,7 +338,11 @@ server.registerTool(
277
338
  objective: z.string().min(1),
278
339
  tokenBudget: z.number().int().positive().optional()
279
340
  }),
280
- 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()
281
346
  }
282
347
  },
283
348
  async (input) => {
@@ -311,7 +376,8 @@ server.registerTool(
311
376
  objective: z.string().min(1),
312
377
  tokenBudget: z.number().int().positive().optional()
313
378
  })
314
- .optional()
379
+ .optional(),
380
+ baseRef: z.string().min(1).optional()
315
381
  }
316
382
  },
317
383
  async ({ task_id, followup_prompt, session_id, ...options }) => {
@@ -404,9 +470,17 @@ server.registerTool(
404
470
  timeoutMinutes: z.number().int().min(1).max(360).default(2),
405
471
  timeoutMs: z.number().int().min(1000).max(21600000).optional(),
406
472
  pollMs: z.number().int().min(250).max(10000).default(1000),
407
- includeEvents: z.boolean().default(true),
473
+ // Off by default. A wait is the call clients background and then replay
474
+ // as a notification, so its payload has to stay small; ten events per
475
+ // worker was the bulk of it. Ask for events explicitly, or read
476
+ // get_codex_worker_events for one worker.
477
+ includeEvents: z.boolean().default(false),
408
478
  eventLimit: z.number().int().min(1).max(50).default(10),
409
- eventMaxChars: z.number().int().min(0).max(1000000).optional(),
479
+ // Events used to come back whole: one command event can carry a heredoc
480
+ // that is tens of KB, and ten of those made a single wait response
481
+ // unreadable. The default bounds each string; pass a bigger number when
482
+ // you actually want the raw text.
483
+ eventMaxChars: z.number().int().min(0).max(1000000).default(800),
410
484
  eventKinds: z.array(z.string().min(1)).optional()
411
485
  }
412
486
  },
@@ -428,8 +502,8 @@ server.registerTool(
428
502
  while (Date.now() - startedAt < effectiveTimeoutMs) {
429
503
  await reconcileDetachedActiveTasks();
430
504
  tasks = (await getTasks(task_ids)).filter(Boolean);
431
- const terminalCount = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).length;
432
- const isDone = mode === "any" ? terminalCount > 0 : terminalCount === task_ids.length;
505
+ const settledCount = tasks.filter(isSettled).length;
506
+ const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
433
507
  if (isDone) break;
434
508
  await sleep(pollMs);
435
509
  }
@@ -437,9 +511,9 @@ server.registerTool(
437
511
  await reconcileDetachedActiveTasks();
438
512
  tasks = (await getTasks(task_ids)).filter(Boolean);
439
513
  const missingIds = task_ids.filter((taskId) => !tasks.some((task) => task.id === taskId));
440
- const terminalTasks = tasks.filter((task) => TERMINAL_STATUSES.has(task.status));
514
+ const settledTasks = tasks.filter(isSettled);
441
515
  const timedOut =
442
- mode === "any" ? terminalTasks.length === 0 : terminalTasks.length !== task_ids.length;
516
+ mode === "any" ? settledTasks.length === 0 : settledTasks.length !== task_ids.length;
443
517
 
444
518
  const summaries = await Promise.all(
445
519
  tasks.map(async (task) => ({
@@ -524,15 +598,18 @@ server.registerTool(
524
598
  "get_codex_worker_status",
525
599
  {
526
600
  title: "Get Codex worker status",
527
- description: "Read the latest normalized status for one Codex worker.",
601
+ description:
602
+ "Read the latest normalized status for one Codex worker: lifecycle, phase, current action, changed files, goal, recent commands, and the task prompt (clipped by default). Set includePrompt to read the prompt in full, or use get_codex_worker_events for the raw stream.",
528
603
  inputSchema: {
529
- task_id: z.string().min(1)
604
+ task_id: z.string().min(1),
605
+ includePrompt: z.boolean().default(false),
606
+ promptMaxChars: z.number().int().min(0).max(1000000).default(5000)
530
607
  }
531
608
  },
532
- async ({ task_id }) => {
609
+ async ({ task_id, includePrompt, promptMaxChars }) => {
533
610
  const task = await getTask(task_id);
534
611
  if (!task) return textResult({ error: "task_not_found", task_id });
535
- return textResult(task);
612
+ return textResult(statusView(task, { includePrompt, promptMaxChars }));
536
613
  }
537
614
  );
538
615
 
@@ -634,7 +711,7 @@ server.registerTool(
634
711
  source = "task_row";
635
712
  }
636
713
  const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
637
- const changed = mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path));
714
+ const changed = readTaskChanges(task);
638
715
  return textResult({
639
716
  task_id,
640
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: "Worker process disappeared without a terminal event",
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 ?? "Codex worker process disappeared before a terminal event was recorded.",
289
- completed_at: task.completed_at ?? now,
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 `git status` inside it is exactly that worker's diff.
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
- export function readWorktreeChanges(worktreePath) {
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 = execFileSync(defaultGitBin, ["-C", worktreePath, "status", "--porcelain"], {
28
- encoding: "utf8",
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
+ }