codex-supervisor-mcp 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -161,8 +161,8 @@ Nineteen.
161
161
  | `get_orchestration_overview` | `status`, `limit` | Every worker in one table, capped at 7000 bytes. Carries `version` and `update` |
162
162
  | `get_worker_result` | `task_id`, `limit`, `maxChars` | The worker's own full report plus `status` / `exit_code` / `changed_files`. The door for conclusions |
163
163
  | `get_worker_diff` | `task_id`, `maxChars`, `paths` | What the worker actually changed: patches from the worktree's starting commit to its working tree, committed or not, untracked files included. `maxChars` bounds the whole answer; files past it are listed without a patch |
164
- | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `end` | Ask the worker on the side: its thread is forked into a read-only side session and the question goes there, so the worker's own thread is untouched. Without `question` it reads the latest answer; `end` deletes the fork |
165
- | `land_codex_worker` | `task_id`, `onto` | Cherry-pick the worker's commits from `codex/<id>` onto the current branch of the directory it was dispatched from. The target must be clean, `onto` is a check and never a switch, and a conflict rolls back and lists the files |
164
+ | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | Ask the worker on the side. Its thread is forked into a read-only session with no network and no MCP tools; the worker itself is untouched. A resumed worker gets a new fork by itself, `fresh` forces one, `end` deletes it |
165
+ | `land_codex_worker` | `task_id`, `onto`, `commitMessage` | Cherry-pick the worker's commits from `codex/<id>` onto the current branch of the directory it was dispatched from. The target must be clean, `onto` is a check and never a switch, and a conflict rolls back and lists the files. `commitMessage` first commits the worker's uncommitted edits as one commit |
166
166
  | `get_worker_summary` | `task_id` | One paragraph: goal, status, changes, last command and message |
167
167
  | `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | One worker in detail; the prompt is clipped to 300 characters unless asked for |
168
168
  | `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | The raw event stream |
@@ -357,7 +357,8 @@ rm -rf ~/.codex-supervisor
357
357
 
358
358
  ## Known limitations
359
359
 
360
- - A worker's lifetime is tied to the MCP process. Kill the MCP and the worker is left behind, settled as `lost` on the next read. The fix is a resident daemon; see the Roadmap.
360
+ - A worker is a child of the MCP process. Kill the MCP and the worker goes with it, settled as `lost` on the next read. Its worktree and `thread_id` survive: `resume_codex_worker` continues the same thread. Keeping it alive across that takes a resident daemon; see the Roadmap.
361
+ - In the default `workspace-write` sandbox a worker cannot commit: Codex keeps `.git` read-only. Either let it edit only and pass `commitMessage` to `land_codex_worker`, or dispatch with `danger-full-access`.
361
362
  - The worktree is cut from a commit, so uncommitted work in your checkout is not in it. Give the task absolute paths, or commit first.
362
363
  - Only the working directory is isolated. Temp directories, databases and ports are shared; workers that would hit the same dev server need to be kept apart in the task.
363
364
  - `ownedPaths` is checked at dispatch only; it does not stop a worker from creating a file it never listed. Review the diff.
package/README.md CHANGED
@@ -161,8 +161,8 @@ land_codex_worker 核过了,落进集成分支
161
161
  | `get_orchestration_overview` | `status`, `limit` | 全部 worker 的状态表,封顶 7000 字节。带 `version` 和 `update` |
162
162
  | `get_worker_result` | `task_id`, `limit`, `maxChars` | worker 自己的完整汇报,外加 `status` / `exit_code` / `changed_files`。收结论用这个 |
163
163
  | `get_worker_diff` | `task_id`, `maxChars`, `paths` | worker 实际改了什么:从 worktree 起点到工作区的 patch,提交没提交都算,未跟踪的文件也在。`maxChars` 管总量,超了的文件只列名不给 patch |
164
- | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `end` | 旁路问 worker 一句:把它的线程 fork 成只读的侧会话问,worker 自己的线程不动。不带 `question` 读最近一轮的答案,`end` 删 fork |
165
- | `land_codex_worker` | `task_id`, `onto` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标必须干净,`onto` 只核对不切换,冲突就回滚并列出文件 |
164
+ | `ask_codex_worker` | `task_id`, `question`, `timeoutMs`, `maxChars`, `fresh`, `end` | 旁路问 worker 一句。线程 fork 成只读侧会话,没网络、没 MCP 工具,worker 本身不动。worker 被 resume 过会自动换新 fork,`fresh` 强制换,`end` 删 |
165
+ | `land_codex_worker` | `task_id`, `onto`, `commitMessage` | 把 worker 在 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标必须干净,`onto` 只核对不切换,冲突就回滚并列出文件。`commitMessage` 先替它把未提交的改动提交成一笔 |
166
166
  | `get_worker_summary` | `task_id` | 一段话:goal、状态、改动、最后一条命令和消息 |
167
167
  | `get_codex_worker_status` | `task_id`, `includePrompt`, `promptMaxChars` | 单个 worker 的状态细节,prompt 默认截到 300 字 |
168
168
  | `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | 原始事件流 |
@@ -357,7 +357,8 @@ rm -rf ~/.codex-supervisor
357
357
 
358
358
  ## 已知限制
359
359
 
360
- - worker 的命绑在 MCP 进程上。MCP 被 kill,worker 留在那,下次读状态结算成 `lost`。解法是常驻 daemon,在 Roadmap 里。
360
+ - worker 是 MCP 进程的子进程。MCP 被 kill,worker 跟着没了,下次读状态结算成 `lost`。worktree 里的改动和 `thread_id` 都在,`resume_codex_worker` 接回同一个线程继续;让它不跟着死,要常驻 daemon,在 Roadmap 里。
361
+ - 默认的 `workspace-write` 沙箱里 worker 提交不了:Codex 把 `.git` 设成只读。要么让它只改文件,收活时 `land_codex_worker` 带 `commitMessage` 替它提交;要么派单用 `danger-full-access`。
361
362
  - worktree 从一个提交切,你工作区里没 commit 的东西不在里面。要让 worker 读到,给绝对路径或先 commit。
362
363
  - 只隔离工作目录。临时目录、数据库、端口是共用的,多路 worker 要连同一个 dev server 得自己错开。
363
364
  - `ownedPaths` 只在派单时查,拦不住 worker 在自己 worktree 里新建清单外的文件。收活看 diff。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
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",
@@ -88,9 +88,13 @@ worker 回来以后按这个顺序,别跳:
88
88
 
89
89
  1. `get_worker_result`:它说自己做了什么。
90
90
  2. `get_worker_diff`:它实际做了什么。从 worktree 起点到工作区的全部改动,提交没提交都算,按文件给 patch;`maxChars` 管总量,`paths` 缩范围。它说过了不算,diff 对得上才算。
91
- 3. 对不上、看不懂为什么这么改:`ask_codex_worker` 带 `question` 问它。走的是 fork 出来的只读旁路,worker 自己的线程不动;fork 带着它的全部上下文,一句话能答。超过 `timeoutMs` 回 `running`,之后只带 `task_id` 再调一次拿答案。问完 `end: true` 删 fork。
91
+ 3. 对不上、看不懂为什么这么改:`ask_codex_worker` 带 `question` 问它。走的是 fork 出来的只读旁路,worker 自己的线程不动;fork 带着它的全部上下文,一句话能答。fork 没网络、没 MCP 工具,它自己知道,所以别问它"远端跑通了没"这类要联网才能答的事,问"你改了什么、为什么、在哪"。超过 `timeoutMs` 回 `running`,之后只带 `task_id` 再调一次拿答案。worker 被 `resume` 过以后,下一问自动换一个新 fork(返回 `refreshed: "worker_resumed"`);想强制换就 `fresh: true`。问完 `end: true` 删 fork。
92
92
  4. 要它改:`resume_codex_worker`,提示词里写清问题在哪,让它改完 `git commit --amend --no-edit` 并进原来那个提交,保持一步一个提交。旁路只读,改东西永远走 resume。
93
- 5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标脏了、分支不对、冲突,都会拒绝并原样退回,不留半截;未提交的改动只报不落。
93
+ 5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标脏了、分支不对、冲突,都会拒绝并原样退回,不留半截。
94
+
95
+ **worker 在默认的 `workspace-write` 沙箱里提交不了**:Codex 把 `.git` 设成只读,`git add` 就会报 `index.lock: Operation not permitted`。两条路,派单时定一条:
96
+ - 让它只改文件不提交,收活时 `land_codex_worker` 带 `commitMessage`,由 supervisor 在它的分支上替它提交一笔再落。一步一个提交照样成立。
97
+ - 要它自己提交(比如要 `--amend`),派单 `sandbox: "danger-full-access"`。
94
98
 
95
99
  串行做活(第 N+1 步建立在第 N 步上)两种走法:落完第 N 步再派第 N+1 步;或者第 N+1 步派单时 `baseRef: "codex/<第 N 步的 task_id>"`,直接从它的分支开,最后只落最后一路。
96
100
 
@@ -103,6 +107,7 @@ worker 回来以后按这个顺序,别跳:
103
107
  | 想接着**同一个** Codex 会话干 | `resume_codex_worker` | 上下文不丢,`thread_id` 不变 |
104
108
  | 想开**新会话**,带着老活的摘要干 | `create_codex_followup_worker` | 新线程,靠文本重述 |
105
109
  | 主线程自己挂了,要找回那批活 | `get_session_works` | 按 `session_id` 列全部 |
110
+ | worker 变 `lost`(MCP 进程没了把它带走了) | `resume_codex_worker` | 同一线程接着干,worktree 里的改动都在 |
106
111
 
107
112
  主线程重启后第一件事:`get_session_works({ session_id })`。一次拿到那批活的清单和状态,不用凭记忆猜。
108
113
 
@@ -123,7 +128,7 @@ worker 回来以后按这个顺序,别跳:
123
128
  **`failed` 和 `lost` 不是一回事**:
124
129
 
125
130
  - `failed`:跑完了但没成。去看日志和 `error`。
126
- - `lost`:进程被外部信号杀了,或者 MCP 进程自己没了。什么都没说。**直接重跑**,不用查日志。
131
+ - `lost`:进程被外部信号杀了,或者 MCP 进程自己没了(worker 是它的子进程)。worktree 里的改动都还在,`thread_id` 也在库里。**用 `resume_codex_worker` 接回同一个线程**,提示词里说"接着上次的做,先看工作区现状";它被杀时正在做的那一步可能要重做。只有没记到 `thread_id` 的老行才走 `create_codex_followup_worker` 重派。
127
132
 
128
133
  `paused` 和 `blocked` 的 goal 不是结束,是等人管。`get_orchestration_overview` 会把它们列进 `needs_attention`。
129
134
 
package/src/landing.js CHANGED
@@ -39,9 +39,15 @@ function currentBranch(cwd) {
39
39
  // Lands task's commits onto the current branch of its dispatch directory
40
40
  // (task.project_root: the row's cwd is the worktree the worker ran in).
41
41
  // `onto`, when given, must name that branch: it is a guard, not a switch.
42
+ //
43
+ // `commitMessage` commits what the worker left uncommitted in its worktree
44
+ // first, as one commit on codex/<id>. A worker in Codex's workspace-write
45
+ // sandbox cannot commit at all (the sandbox keeps .git read-only), so this
46
+ // is how "one step, one commit" is kept without giving workers full access.
47
+ //
42
48
  // Returns { landed: [{ sha, original, subject }], onto, head } on success;
43
49
  // otherwise { error, reason, ... } with nothing changed in the target.
44
- export function landWorker(task, { onto = null } = {}) {
50
+ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
45
51
  const target = task.project_root;
46
52
  if (!task.worktree_path || !existsSync(task.worktree_path)) {
47
53
  return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
@@ -72,9 +78,29 @@ export function landWorker(task, { onto = null } = {}) {
72
78
  } catch (error) {
73
79
  return { error: "no_base_commit", reason: `the base ${base} no longer resolves in the worktree: ${error.message.split("\n")[0]}` };
74
80
  }
75
- const uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
81
+ let uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
82
+ let committedForWorker = null;
83
+ if (uncommitted.length > 0 && commitMessage) {
84
+ try {
85
+ git(task.worktree_path, ["add", "-A"]);
86
+ git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
87
+ } catch (error) {
88
+ const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
89
+ return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
90
+ }
91
+ committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
92
+ commits.push(committedForWorker);
93
+ uncommitted = [];
94
+ }
76
95
  if (commits.length === 0) {
77
- return { error: "nothing_to_land", reason: "the worker made no commits on its branch; uncommitted edits are not landed", uncommitted, base_commit: base };
96
+ return {
97
+ error: "nothing_to_land",
98
+ reason: uncommitted.length > 0
99
+ ? "the worker made no commits on its branch (a workspace-write worker cannot: the sandbox keeps .git read-only); pass commitMessage to commit its edits as one commit and land that"
100
+ : "the worker made no commits and left no edits on its branch",
101
+ uncommitted,
102
+ base_commit: base
103
+ };
78
104
  }
79
105
 
80
106
  const before = git(target, ["rev-parse", "HEAD"]).trim();
@@ -112,6 +138,7 @@ export function landWorker(task, { onto = null } = {}) {
112
138
  base_commit: base,
113
139
  head: landed.at(-1) ?? before,
114
140
  landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
141
+ committed_for_worker: committedForWorker,
115
142
  uncommitted
116
143
  };
117
144
  }
package/src/mcp-server.js CHANGED
@@ -909,16 +909,17 @@ server.registerTool(
909
909
  {
910
910
  title: "Ask a worker on the side",
911
911
  description:
912
- "Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. It can read the worktree and change nothing; to make the worker change something, use resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
912
+ "Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. The fork has no network and no MCP tools and is told so; it answers from its context and the worktree. Once the worker has been resumed, the next question automatically takes a new fork from the updated thread (refreshed: \"worker_resumed\"); fresh: true forces a new fork. Changes still go through resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
913
913
  inputSchema: {
914
914
  task_id: z.string().min(1),
915
915
  question: z.string().min(1).optional(),
916
916
  timeoutMs: z.number().int().min(1000).max(600000).default(110000),
917
917
  maxChars: z.number().int().min(0).max(1000000).default(8000),
918
+ fresh: z.boolean().default(false),
918
919
  end: z.boolean().default(false)
919
920
  }
920
921
  },
921
- async ({ task_id, question, timeoutMs, maxChars, end }) => {
922
+ async ({ task_id, question, timeoutMs, maxChars, fresh, end }) => {
922
923
  const task = await getTask(task_id);
923
924
  if (!task) return textResult({ error: "task_not_found", task_id });
924
925
  const clipAnswer = (state) => {
@@ -933,7 +934,7 @@ server.registerTool(
933
934
  return textResult({ task_id, ...clipAnswer(await latestSideTurn(task_id)) });
934
935
  }
935
936
  try {
936
- const state = clipAnswer(await askWorker({ task, question, timeoutMs }));
937
+ const state = clipAnswer(await askWorker({ task, question, timeoutMs, fresh }));
937
938
  const next = state.timed_out
938
939
  ? `The side turn is still running; call ask_codex_worker again with only task_id to read the answer when it lands.`
939
940
  : null;
@@ -952,16 +953,17 @@ server.registerTool(
952
953
  {
953
954
  title: "Land a worker's commits",
954
955
  description:
955
- "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from (its cwd). The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. Uncommitted edits in the worker's worktree are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes.",
956
+ "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes.",
956
957
  inputSchema: {
957
958
  task_id: z.string().min(1),
958
- onto: z.string().min(1).optional()
959
+ onto: z.string().min(1).optional(),
960
+ commitMessage: z.string().min(1).optional()
959
961
  }
960
962
  },
961
- async ({ task_id, onto }) => {
963
+ async ({ task_id, onto, commitMessage }) => {
962
964
  const task = await getTask(task_id);
963
965
  if (!task) return textResult({ error: "task_not_found", task_id });
964
- return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto }) });
966
+ return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto, commitMessage: commitMessage ?? null }) });
965
967
  }
966
968
  );
967
969
 
package/src/side-chat.js CHANGED
@@ -24,6 +24,9 @@
24
24
  // session ended ................... fork deleted, history cleared
25
25
  import { execFileSync, spawn } from "node:child_process";
26
26
  import { randomUUID } from "node:crypto";
27
+ import { readFileSync } from "node:fs";
28
+ import { join } from "node:path";
29
+ import { codexHome } from "./paths.js";
27
30
  import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
28
31
  import {
29
32
  closeSideSession,
@@ -38,6 +41,77 @@ import {
38
41
 
39
42
  const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
40
43
  const TURN_TIMEOUT_MS = 10 * 60 * 1000;
44
+
45
+ // What a side question is, said to the fork every time. Without it the fork
46
+ // treats the question as a new task: one real fork spent its whole turn
47
+ // trying to ssh to a build host from inside the read-only sandbox, probing
48
+ // the network, and finally reaching for an MCP tool.
49
+ const SIDE_PREAMBLE = `This is a side question about the work you did in this thread, asked from a read-only fork. Rules for this turn:
50
+ - Answer from what you already know from this thread. You may read files in the working directory to check.
51
+ - The sandbox is read-only and has no network: do not try ssh, curl, builds, tests, package installs or writes; they will fail and waste the turn. MCP tools are disabled here.
52
+ - If answering properly needs something you cannot check from here (a remote machine, a running service, a command), say exactly what and stop; do not retry.
53
+ - Nothing you do here changes the work. If the work needs changing, say what should change; the main thread will ask the worker itself.
54
+ - Be direct and short. Lead with the answer.`;
55
+
56
+ export function sideQuestionText(question) {
57
+ return `${SIDE_PREAMBLE}\n\nQuestion:\n${question}`;
58
+ }
59
+
60
+ // The fork inherits the worker's MCP servers. A side question must not be
61
+ // able to dispatch, resume or cancel anything through them, and a fork that
62
+ // waits on a tool it cannot use burns its turn; every server named in the
63
+ // Codex config is switched off for the turn. Sub-tables
64
+ // ([mcp_servers.x.env]) are not servers and are skipped.
65
+ //
66
+ // The key path is written bare: `-c mcp_servers.name.enabled=false`. A
67
+ // quoted name (`mcp_servers."name".enabled`) is taken by codex as a new
68
+ // server literally called "name", quotes included, with no transport, and
69
+ // the whole config then fails to load.
70
+ export function sideTurnConfigArgs(configText) {
71
+ const names = new Set();
72
+ for (const line of String(configText ?? "").split("\n")) {
73
+ const match = line.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^\].]+))\]\s*(?:#.*)?$/);
74
+ if (match) names.add(match[1] ?? match[2]);
75
+ }
76
+ const args = [];
77
+ for (const name of names) {
78
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) continue; // a name codex cannot take bare on the command line
79
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
80
+ }
81
+ return args;
82
+ }
83
+
84
+ function codexConfigText() {
85
+ try {
86
+ return readFileSync(join(codexHome, "config.toml"), "utf8");
87
+ } catch {
88
+ return "";
89
+ }
90
+ }
91
+
92
+ // The session to ask on. A fork taken before the worker was resumed no
93
+ // longer reflects the worker's thread; it is dropped and a new one taken
94
+ // from the current thread. `fresh` forces that. Returns the session and why
95
+ // it was (re)opened: "requested", "worker_resumed", "first" or null.
96
+ export async function prepareSideSession(task, { fresh = false } = {}) {
97
+ let session = await getSideSession(task.id);
98
+ let refreshed = null;
99
+ const stale =
100
+ session?.fork_thread_id &&
101
+ session.worker_run_count !== null &&
102
+ session.worker_run_count !== undefined &&
103
+ (task.run_count ?? 0) > session.worker_run_count;
104
+ if (session && (fresh || stale)) {
105
+ await endSideSession(task.id);
106
+ session = null;
107
+ refreshed = fresh ? "requested" : "worker_resumed";
108
+ }
109
+ if (!session) {
110
+ session = await openSideSession(task.id, task.run_count ?? 0);
111
+ refreshed = refreshed ?? "first";
112
+ }
113
+ return { session, refreshed };
114
+ }
41
115
  const OUTPUT_CLIP = 4000;
42
116
 
43
117
  // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
@@ -280,19 +354,19 @@ export function attachToTurn(taskId, res) {
280
354
 
281
355
  // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
282
356
  // turn has ended, however it ended.
283
- export async function runSideTurn({ task, text, res = null }) {
357
+ export async function runSideTurn({ task, text, res = null, fresh = false }) {
284
358
  await sweepOnce();
285
359
  if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
286
360
  if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
287
361
  const target = codexTarget();
288
362
  if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
289
363
 
290
- let session = await getSideSession(task.id);
291
- if (!session) session = await openSideSession(task.id);
364
+ const { session, refreshed } = await prepareSideSession(task, { fresh });
292
365
 
293
366
  const args = session.fork_thread_id
294
367
  ? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
295
368
  : ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
369
+ args.push(...sideTurnConfigArgs(codexConfigText()));
296
370
  if (task.model) args.push("-m", task.model);
297
371
  args.push(session.fork_thread_id ?? task.thread_id, "-");
298
372
 
@@ -369,7 +443,7 @@ export async function runSideTurn({ task, text, res = null }) {
369
443
  stderr = (stderr + chunk).slice(-4000);
370
444
  });
371
445
  child.stdin.on("error", () => {});
372
- child.stdin.end(text);
446
+ child.stdin.end(sideQuestionText(text));
373
447
 
374
448
  return new Promise((resolve) => {
375
449
  const finish = async (code, signal) => {
@@ -400,7 +474,7 @@ export async function runSideTurn({ task, text, res = null }) {
400
474
  live.watchers.clear();
401
475
  running.delete(task.id);
402
476
  await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
403
- resolve({ status, turnId, forkThreadId: session.fork_thread_id });
477
+ resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
404
478
  };
405
479
  child.on("error", (error) => {
406
480
  stderr += `\nfailed to start codex: ${error.message}`;
@@ -451,7 +525,10 @@ export async function latestSideTurn(taskId) {
451
525
  // Ask the worker a question on the side, without touching its own thread,
452
526
  // and wait up to `timeoutMs` for the answer. A turn that outlives the budget
453
527
  // keeps running in this process; the caller reads it back with latestSideTurn.
454
- export async function askWorker({ task, question, timeoutMs = 110000 }) {
528
+ export async function askWorker({ task, question, timeoutMs = 110000, fresh = false }) {
529
+ // Decided here, before the race, so a turn that outruns the budget still
530
+ // reports whether the fork was taken anew.
531
+ const { refreshed } = await prepareSideSession(task, { fresh });
455
532
  const turn = runSideTurn({ task, text: question });
456
533
  // runSideTurn throws synchronously-ish (rejected promise) for no_thread,
457
534
  // busy and codex_missing before anything starts; surface those as-is.
@@ -463,11 +540,11 @@ export async function askWorker({ task, question, timeoutMs = 110000 }) {
463
540
  const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
464
541
  if (!outcome.timedOut) {
465
542
  const state = await latestSideTurn(task.id);
466
- return { ...state, timed_out: false };
543
+ return { ...state, timed_out: false, refreshed };
467
544
  }
468
545
  turn.catch(() => {});
469
546
  const state = await latestSideTurn(task.id);
470
- return { ...state, timed_out: true };
547
+ return { ...state, timed_out: true, refreshed };
471
548
  } finally {
472
549
  clearTimeout(timer);
473
550
  }
@@ -492,7 +569,8 @@ export async function endSideSession(taskId) {
492
569
  const target = codexTarget();
493
570
  if (!target.error) {
494
571
  deleted = await new Promise((resolve) => {
495
- const child = spawn(target.cmd, [...target.prefixArgs, "delete", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
572
+ // --force: without a terminal codex asks for confirmation and exits.
573
+ const child = spawn(target.cmd, [...target.prefixArgs, "delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
496
574
  const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
497
575
  child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
498
576
  child.on("error", () => { clearTimeout(t); resolve(false); });
package/src/task-store.js CHANGED
@@ -180,7 +180,8 @@ const SIDE_DDL = `
180
180
  task_id TEXT PRIMARY KEY,
181
181
  fork_thread_id TEXT,
182
182
  created_at TEXT NOT NULL,
183
- ended_at TEXT
183
+ ended_at TEXT,
184
+ worker_run_count INTEGER
184
185
  );
185
186
  CREATE TABLE IF NOT EXISTS side_turns (
186
187
  id TEXT PRIMARY KEY,
@@ -231,6 +232,15 @@ function initializeSchema(dbInstance) {
231
232
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
232
233
  dbInstance.exec(SESSIONS_DDL);
233
234
  dbInstance.exec(SIDE_DDL);
235
+ // Rows written before 0.7.1 have no worker_run_count: the fork is then
236
+
237
+ // never judged stale, which is what those rows did before.
238
+
239
+ if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
240
+
241
+ dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
242
+
243
+ }
234
244
  dbInstance.exec("COMMIT;");
235
245
  } catch (error) {
236
246
  try {
@@ -470,13 +480,15 @@ export async function getSideSession(taskId) {
470
480
  return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
471
481
  }
472
482
 
473
- export async function openSideSession(taskId) {
483
+ // `workerRunCount` is the worker's run_count when the fork is taken; a
484
+ // worker resumed after that has a thread the fork no longer reflects.
485
+ export async function openSideSession(taskId, workerRunCount = null) {
474
486
  await ensureFilesystem();
475
487
  const now = new Date().toISOString();
476
488
  openDb()
477
- .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at) VALUES (?, NULL, ?, NULL)
478
- ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL`)
479
- .run(taskId, now);
489
+ .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at, worker_run_count) VALUES (?, NULL, ?, NULL, ?)
490
+ ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL, worker_run_count = excluded.worker_run_count`)
491
+ .run(taskId, now, workerRunCount);
480
492
  return getSideSession(taskId);
481
493
  }
482
494