trantor 0.18.131 → 0.18.133

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.131",
3
+ "version": "0.18.133",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
5
5
  "mcpServers": {
6
6
  "relay": {
package/README.md CHANGED
@@ -391,6 +391,9 @@ project's own checkout wherever it is called from, handoff-beats-resume, and the
391
391
  prompt so the woken session catches up (handoff, board, memory) and recaps on its own.
392
392
  A reboot can leave herdr with a pane in its layout and no terminal behind it; `trantor open`,
393
393
  the app's Resume and `trantor prune` all treat such a pane as dead and host a fresh one.
394
+ Trantor does not write herdr's global config. To make restored agents start one at a time, add
395
+ `startup_per_agent_delay_ms = 100` under `[session]` in `~/.config/herdr/config.toml`, then restart
396
+ the herdr server.
394
397
 
395
398
  Why crews never exhaust the orchestrator: bus messages are **by reference** (~70 tokens),
396
399
  work products stay in each agent's own context — the orchestrator burns at coordination
@@ -112,6 +112,20 @@ function summary(value, limit = 240) {
112
112
  return oneLine.length > limit ? `${oneLine.slice(0, limit - 1)}…` : oneLine;
113
113
  }
114
114
 
115
+ /** #13913: herdr's own answer is the delivery receipt — text plus Enter are sent before herdr
116
+ * reports anything, so this only names what became of the kickoff. `timeout` is the busy
117
+ * successor (words are in, not picked up yet), never a failure to resend. */
118
+ export function kickoffVerdict(raw) {
119
+ let response;
120
+ try { response = JSON.parse(String(raw)); } catch { return "unreadable_response"; }
121
+ if (response?.result?.type === "agent_prompted") return "agent_prompted";
122
+ if (response?.error) {
123
+ const code = String(response.error.code || "herdr error");
124
+ return code === "timeout" ? "sent, not yet picked up" : `${code} (${summary(response.error.message)})`;
125
+ }
126
+ return "unexpected_response";
127
+ }
128
+
115
129
  async function main() {
116
130
  if (!handoffFile || !existsSync(handoffFile)) { log(`no handoff file (${handoffFile}) — abort`); process.exit(1); }
117
131
  const pane = arg("--pane") || orchPane((() => { try { return readFileSync(join(busDir, "crew-windows.txt"), "utf8"); } catch { return ""; } })(), projectName);
@@ -168,10 +182,14 @@ async function main() {
168
182
  await sleep(3000);
169
183
  }
170
184
  try {
171
- const raw = await socketRequest({ id: "trantor:agent.prompt", method: "agent.prompt", params: { target: pane, text: KICKOFF_PROMPT } });
172
- const response = JSON.parse(raw);
173
- const result = response.result?.type || response.error?.code || "unexpected_response";
174
- log(`kickoff result: ${result}${response.error?.message ? ` (${summary(response.error.message)})` : ""}`);
185
+ // #13913: the same bounded pickup wait the app uses — herdr sends the text and Enter, then
186
+ // holds the answer until the successor shows working/blocked activity (10s budget, well
187
+ // inside this socket's own 30s read timeout).
188
+ const raw = await socketRequest({
189
+ id: "trantor:agent.prompt", method: "agent.prompt",
190
+ params: { target: pane, text: KICKOFF_PROMPT, wait: { until: ["working", "blocked"], timeout_ms: 10_000 } },
191
+ });
192
+ log(`kickoff result: ${kickoffVerdict(raw)}`);
175
193
  } catch (e) {
176
194
  log(`kickoff FAILED (${String(e?.message).slice(0, 120)}) — successor may sit idle until spoken to`);
177
195
  }
package/bin/cli.mjs CHANGED
@@ -43,6 +43,7 @@ switch (cmd) {
43
43
  case "down": runCrew(); break;
44
44
  case "swap": runCrew(); break;
45
45
  case "prune": runCrew(); break;
46
+ case "restore": runCrew(); break;
46
47
  case "hub": {
47
48
  const sub = args[0];
48
49
  if (sub === "timeouts") { args.splice(0, 1); run("bin/hub-timeouts.mjs", process.execPath); break; }
@@ -259,6 +260,7 @@ switch (cmd) {
259
260
  trantor sync realign a seat branch with main from the receipts: sync [<seat>] [--dry-run] — refuses and names unharvested commits
260
261
  trantor down tear the crew down (kills processes, closes windows, no dialogs)
261
262
  trantor prune drop dead crew-window tracking rows (ghost workspaces/panes) without spawning anything
263
+ trantor restore after a reboot, reopen only the orchestrators you opted in: restore [--dry-run] · restore enable|disable <project>
262
264
  trantor ui open the live dashboard (board + flow views)
263
265
  trantor pair pair a phone: mint a trantor://enroll link for the companion app — [--role owner] [--sim] [--json]
264
266
  trantor app the DESKTOP app: status | install | update — pulls the latest DMG from GitHub Releases
@@ -1,10 +1,20 @@
1
- import { call, gridColumns, parseJsonOutput, runnerCommand } from "./core.mjs";
1
+ import { call, formatCommand, gridColumns, parseJsonOutput, runnerCommand } from "./core.mjs";
2
+ import { herdrReportArgs } from "../../lib/herdr-integration.mjs";
2
3
  import { dropState, readRows, recordState } from "./state.mjs";
3
4
 
4
5
  export function herdrCall(ctx, args) {
5
6
  return call("herdr", args, { env: ctx.env });
6
7
  }
7
8
 
9
+ function requireHerdr(ctx, args, execute = herdrCall) {
10
+ const result = execute(ctx, args);
11
+ if (result.ok === false) {
12
+ const detail = result.stderr || result.stdout || "no error output";
13
+ throw new Error(`${formatCommand("herdr", args)} exited ${result.status}: ${detail}`);
14
+ }
15
+ return result;
16
+ }
17
+
8
18
  export function workspaceList(ctx) {
9
19
  if (!ctx.have.herdr) return { proven: false, ids: new Set(), names: new Set(), items: [] };
10
20
  const result = herdrCall(ctx, ["workspace", "list"]);
@@ -20,12 +30,12 @@ export function workspaceList(ctx) {
20
30
  }
21
31
 
22
32
  export function createWorkspace(ctx, cwd, label) {
23
- const parsed = parseJsonOutput(herdrCall(ctx, ["workspace", "create", "--cwd", cwd, "--label", label, "--no-focus"]).stdout);
33
+ const parsed = parseJsonOutput(requireHerdr(ctx, ["workspace", "create", "--cwd", cwd, "--label", label, "--no-focus"]).stdout);
24
34
  const result = parsed?.result || {};
25
- return {
26
- workspace: result.workspace?.workspace_id || "",
27
- pane: result.root_pane?.pane_id || "",
28
- };
35
+ const workspace = result.workspace?.workspace_id || "";
36
+ const pane = result.root_pane?.pane_id || "";
37
+ if (!workspace || !pane) throw new Error("herdr workspace create returned no usable workspace and root pane");
38
+ return { workspace, pane };
29
39
  }
30
40
 
31
41
  export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
@@ -33,7 +43,7 @@ export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
33
43
  if (pane) args.push(pane);
34
44
  args.push("--direction", direction, "--no-focus");
35
45
  if (cwd) args.push("--cwd", cwd);
36
- const parsed = parseJsonOutput(execute(ctx, args).stdout);
46
+ const parsed = parseJsonOutput(requireHerdr(ctx, args, execute).stdout);
37
47
  return parsed?.result?.pane?.pane_id || "";
38
48
  }
39
49
 
@@ -42,9 +52,14 @@ export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
42
52
  // is a layout question; process-info is the terminal question, and only a terminal hosts a session.
43
53
  export function paneAlive(ctx, pane) {
44
54
  if (!pane) return false;
45
- const result = herdrCall(ctx, ["pane", "process-info", "--pane", pane]);
46
- const parsed = parseJsonOutput(result.stdout);
47
- return Boolean(result.ok && parsed && !parsed.error && parsed.result?.process_info);
55
+ return paneReadAlive(ctx, pane);
56
+ }
57
+
58
+ // Herdr can retain a layout row after its terminal has vanished. A readable pane is the
59
+ // authoritative liveness signal shared by CLI callers; process-info can report stale metadata.
60
+ export function paneReadAlive(ctx, pane) {
61
+ if (!pane) return false;
62
+ return herdrCall(ctx, ["pane", "read", pane, "--source", "recent-unwrapped"]).ok;
48
63
  }
49
64
 
50
65
  export function workspacePane(ctx, workspace, preferredCwd) {
@@ -91,19 +106,21 @@ export function closePane(ctx, id) {
91
106
  return herdrCall(ctx, ["pane", "close", id]).ok;
92
107
  }
93
108
 
94
- export function reportAgent(ctx, pane, agent) {
109
+ export function reportAgent(ctx, pane, agent, { sessionId = "", resumeArgv = [] } = {}) {
95
110
  if (!pane) return;
111
+ const args = herdrReportArgs({ pane, agent, state: "working", sessionId, resumeArgv });
96
112
  if (ctx.dry) {
97
- console.log(`[dry] herdr pane report-agent ${pane} --source crew --agent ${agent} --state working`);
113
+ console.log(`[dry] ${formatCommand("herdr", args)}`);
98
114
  return;
99
115
  }
100
- herdrCall(ctx, ["pane", "report-agent", pane, "--source", "crew", "--agent", agent, "--state", "working"]);
116
+ herdrCall(ctx, args);
101
117
  }
102
118
 
103
119
  function runSeat(ctx, pane, agent, command) {
104
- if (!pane || ctx.dry) return;
105
- herdrCall(ctx, ["pane", "rename", pane, `${agent} · ${ctx.project}`]);
106
- herdrCall(ctx, ["pane", "run", pane, command]);
120
+ if (ctx.dry) return;
121
+ if (!pane) throw new Error(`herdr created no pane for ${agent}; the seat runner was not started`);
122
+ requireHerdr(ctx, ["pane", "rename", pane, `${agent} · ${ctx.project}`]);
123
+ requireHerdr(ctx, ["pane", "run", pane, command]);
107
124
  }
108
125
 
109
126
  function trackedWorkspace(ctx) {
package/bin/crew/open.mjs CHANGED
@@ -72,7 +72,7 @@ function humanPromptAfter(transcriptPath, afterSecs) {
72
72
  const at = Date.parse(e.timestamp || "") / 1000;
73
73
  if (!(at >= afterSecs)) continue;
74
74
  const c = e.message?.content;
75
- const body = typeof c === "string" ? c : Array.isArray(c) ? c.map(x => x?.text || "").join("") : "";
75
+ const body = Array.isArray(c) ? c.map(x => x?.text || "").join("") : String(c || "");
76
76
  if (body.startsWith("You have just taken over via handoff")) continue;
77
77
  return at;
78
78
  }
@@ -118,6 +118,13 @@ function orchestratorCommand(ctx, id) {
118
118
  return `${env} claude${harnessFlag(ctx)} ${action}`;
119
119
  }
120
120
 
121
+ function reportOrchestrator(ctx, pane, id) {
122
+ const resumeArgv = ["env", ...STRIP.flatMap(name => ["-u", name]), `TRANTOR_ORCH=${ctx.project}`, "claude"];
123
+ if (harnessFlag(ctx).trim()) resumeArgv.push("--dangerously-skip-permissions");
124
+ resumeArgv.push("--resume", id);
125
+ reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv });
126
+ }
127
+
121
128
  export function paneHasAgent(ctx, pane) {
122
129
  const result = herdrCall(ctx, ["pane", "process-info", "--pane", pane]);
123
130
  const info = parseJsonOutput(result.stdout)?.result?.process_info;
@@ -160,9 +167,12 @@ function reattach(ctx, workspace, pane, id) {
160
167
  if (!paneHasAgent(ctx, pane)) {
161
168
  const started = herdrCall(ctx, ["pane", "run", pane, orchestratorCommand(ctx, id)]);
162
169
  if (!started.ok) throw new Error(`trantor open: could not start the orchestrator in pane ${pane}`);
163
- reportAgent(ctx, pane, "claude");
170
+ reportOrchestrator(ctx, pane, id);
164
171
  console.error(`— orchestrator pane was empty: resumed session ${id} in herdr:${workspace || "?"}/${pane} —`);
165
- } else console.error(`— orchestrator already hosted: reattached to herdr:${workspace || "?"}/${pane} —`);
172
+ } else {
173
+ reportOrchestrator(ctx, pane, id);
174
+ console.error(`— orchestrator already hosted: reattached to herdr:${workspace || "?"}/${pane} —`);
175
+ }
166
176
  console.log(`herdr:${workspace || "?"}/${pane}`);
167
177
  return true;
168
178
  }
@@ -200,7 +210,7 @@ function hostPane(ctx, chosen, id) {
200
210
  if (!pane) throw new Error("trantor open: could not create the orchestrator pane");
201
211
  herdrCall(ctx, ["pane", "rename", pane, `orchestrator · ${ctx.project}`]);
202
212
  herdrCall(ctx, ["pane", "run", pane, orchestratorCommand(ctx, id)]);
203
- reportAgent(ctx, pane, "claude");
213
+ reportOrchestrator(ctx, pane, id);
204
214
  return pane;
205
215
  }
206
216
 
@@ -0,0 +1,88 @@
1
+ import { readFileSync, existsSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { call, parseJsonOutput } from "./core.mjs";
4
+ import { paneAlive, paneHasAgent, herdrCall } from "./herdr.mjs";
5
+ import { readRows } from "./state.mjs";
6
+
7
+ function config(ctx) {
8
+ try { return JSON.parse(readFileSync(join(ctx.home, ".agent-bus", "config.json"), "utf8")); }
9
+ catch { return {}; }
10
+ }
11
+
12
+ function sessionIds(ctx, rows, agents) {
13
+ const result = new Map();
14
+ const file = join(ctx.home, ".agent-bus", "orch-sessions.txt");
15
+ if (!existsSync(file)) return result;
16
+ for (const line of readFileSync(file, "utf8").split("\n")) {
17
+ const [project, id] = line.split("\t");
18
+ if (project && id) result.set(project, id);
19
+ }
20
+ const paneProject = new Map(rows.filter(row => row.kind === "orch").map(row => [row.handle, row.project]));
21
+ for (const agent of agents) {
22
+ const project = paneProject.get(agent.pane_id);
23
+ const nativeId = agent.agent_session?.value;
24
+ if (project && nativeId) result.set(project, nativeId);
25
+ }
26
+ return result;
27
+ }
28
+
29
+ export function restoreCandidates({ rows, configured, frozen = [], dismissed = [], sessions = new Map(), live = new Set() }) {
30
+ const projects = [...new Set(rows.filter(row => row.kind === "orch").map(row => row.project))];
31
+ return projects.filter(project => configured.includes(project)
32
+ && !frozen.includes(project)
33
+ && !live.has(project)
34
+ && !dismissed.some(item => item.project === project && item.sessionId === sessions.get(project)));
35
+ }
36
+
37
+ function dismissedSessions(ctx) {
38
+ try {
39
+ const value = JSON.parse(readFileSync(join(ctx.home, ".agent-bus", "config.json"), "utf8"));
40
+ return Array.isArray(value.dismissedSessions) ? value.dismissedSessions : [];
41
+ } catch { return []; }
42
+ }
43
+
44
+ export async function restoreOrchestrators(ctx, args = []) {
45
+ if (args[0] === "enable" || args[0] === "disable") {
46
+ const [action, project, extra] = args;
47
+ if (!project || extra) throw new Error("usage: trantor restore enable|disable <project>");
48
+ const cfg = config(ctx);
49
+ const set = new Set(Array.isArray(cfg.resumeOnRestore) ? cfg.resumeOnRestore : []);
50
+ if (action === "enable") set.add(project); else set.delete(project);
51
+ cfg.resumeOnRestore = [...set].sort();
52
+ const file = join(ctx.home, ".agent-bus", "config.json");
53
+ mkdirSync(join(ctx.home, ".agent-bus"), { recursive: true });
54
+ const tmp = `${file}.tmp`;
55
+ writeFileSync(tmp, `${JSON.stringify(cfg, null, 2)}\n`);
56
+ renameSync(tmp, file);
57
+ console.log(`${project} ${action}d for Trantor restore`);
58
+ return 0;
59
+ }
60
+ const unknown = args.filter(arg => arg !== "--dry-run");
61
+ if (unknown.length) throw new Error("usage: trantor restore [--dry-run]");
62
+ if (args.includes("--dry-run")) ctx.dry = true;
63
+ if (!ctx.have.herdr) throw new Error("trantor restore needs herdr");
64
+ const cfg = config(ctx);
65
+ const configured = Array.isArray(cfg.resumeOnRestore) ? cfg.resumeOnRestore : [];
66
+ const frozen = Array.isArray(cfg.frozenProjects) ? cfg.frozenProjects : [];
67
+ const rows = readRows(ctx);
68
+ const parsed = parseJsonOutput(herdrCall(ctx, ["agent", "list"]).stdout);
69
+ const agents = parsed?.result?.agents || parsed?.agents || [];
70
+ const sessions = sessionIds(ctx, rows, agents);
71
+ const livePanes = new Set(agents.map(agent => agent.pane_id).filter(Boolean));
72
+ const live = new Set(rows.filter(row => row.kind === "orch" && livePanes.has(row.handle) && paneAlive(ctx, row.handle) && paneHasAgent(ctx, row.handle)).map(row => row.project));
73
+ const selected = restoreCandidates({ rows, configured, frozen, dismissed: dismissedSessions(ctx), sessions, live });
74
+ if (!selected.length) {
75
+ console.log("no configured interrupted orchestrators to restore (use trantor restore enable <project>)");
76
+ return 0;
77
+ }
78
+ for (const project of selected) {
79
+ if (ctx.dry) console.log(`would restore ${project}`);
80
+ else {
81
+ const result = call(process.execPath, [join(ctx.root, "bin/crew.mjs"), "open", project], { env: ctx.env });
82
+ if (!result.ok) throw new Error(`trantor restore: ${project} failed: ${result.stderr || result.stdout}`);
83
+ console.log(`restored ${project}`);
84
+ }
85
+ if (!ctx.dry) await new Promise(resolve => setTimeout(resolve, 1000));
86
+ }
87
+ return 0;
88
+ }
@@ -2,6 +2,7 @@
2
2
  // trantor crew runner — keeps a crew agent alive without burning tokens: it long-polls the bus
3
3
  // (zero tokens) and resumes the CLI with each message. Usage: node crew-runner.mjs <agent> [dir]
4
4
  import { execSync, spawnSync, spawn } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
5
6
  import { readFileSync, writeFileSync, unlinkSync, existsSync, appendFileSync, mkdirSync, realpathSync, statSync, rmSync } from "node:fs";
6
7
  import { join, basename } from "node:path";
7
8
  import { homedir } from "node:os";
@@ -29,6 +30,7 @@ import {
29
30
  cardRefs, servedContractCard, carriesWork, parseTurnTokens, parseResetAt, reasonWithBalances, quotaResetAt, queuedWording, turnDelivered, budgetPause, PARKING_REASONS,
30
31
  senderProjectOf, isLinkedProject, stateSkipReason, isMessageCardTitle, OPEN_CARD_STATUSES,
31
32
  ownCardForInstance, contractedCardIds,
33
+ shouldAlignForContract,
32
34
  CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
33
35
  } from "../lib/turn-policy.mjs";
34
36
  import { snapshotBeforeCut } from "./cut-snapshot.mjs";
@@ -57,6 +59,13 @@ import { resolveStateFlags, stateFeatureOn } from "../lib/state/flags.mjs";
57
59
 
58
60
  import { awaitSwapRelease } from "./crew/stage.mjs";
59
61
  import { codexRelayFlags } from "./crew/codex-relay.mjs";
62
+ import { codexSessionId, geminiSessionId, herdrReportArgs, runnerResumeArgv } from "../lib/herdr-integration.mjs";
63
+
64
+ const RUNNER_ARGV = process.argv.slice(2);
65
+ const runnerOption = (name, fallback = "") => {
66
+ const at = RUNNER_ARGV.indexOf(`--${name}`);
67
+ return at >= 0 ? (RUNNER_ARGV[at + 1] || fallback) : fallback;
68
+ };
60
69
 
61
70
  const releaseState = process.env.CREW_RELEASE_STATE ? JSON.parse(process.env.CREW_RELEASE_STATE) : null;
62
71
  delete process.env.CREW_RELEASE_STATE;
@@ -87,14 +96,14 @@ function newerVersion(next, previous) {
87
96
  return false;
88
97
  }
89
98
  if (!releaseState) await awaitSwapRelease();
90
- const AGENT = process.env.CREW_SWAP_AGENT || process.env.CREW_AGENT || process.argv[2];
91
- const PERSONA = runnerPersona(process.env, AGENT);
92
- const DIR = process.argv[3] || process.cwd();
99
+ const AGENT = process.env.CREW_SWAP_AGENT || process.env.CREW_AGENT || runnerOption("agent") || RUNNER_ARGV[0];
100
+ const PERSONA = runnerPersona({ ...process.env, CREW_PERSONA: process.env.CREW_PERSONA || runnerOption("persona") }, AGENT);
101
+ const DIR = RUNNER_ARGV[1] || process.cwd();
93
102
  // Crew agents MUST share the orchestrator's project key (one repo = one lane).
94
103
  // RELAY_PROJECT is inherited from crew.mjs (the host's resolved key); else fall
95
104
  // back to the git-repo-root basename — never a loose dir basename that could
96
105
  // fork the host's "builtbetter.ai" into a separate "builtbetter" lane.
97
- const PROJ = process.env.RELAY_PROJECT || resolveProject(DIR);
106
+ const PROJ = process.env.RELAY_PROJECT || runnerOption("project") || resolveProject(DIR);
98
107
  let machineConfig = {};
99
108
  try { machineConfig = JSON.parse(readFileSync(join(process.env.AGENT_BUS_DIR || process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus"), "config.json"), "utf8")); } catch {}
100
109
  const MACHINE_LABEL = machineLabel(machineConfig);
@@ -160,6 +169,8 @@ if (!AGENT) { console.error("usage: crew-runner.mjs <agent> [project-dir]"); pro
160
169
  // talked to the remote one — the crew would look alive and record onto a different board entirely.
161
170
  function hubUrl() {
162
171
  if (process.env.RELAY_URL) return process.env.RELAY_URL;
172
+ const argHub = runnerOption("hub");
173
+ if (argHub) return argHub;
163
174
  try { return resolveHub(PROJ); } catch {}
164
175
  return "http://127.0.0.1:4477";
165
176
  }
@@ -249,8 +260,11 @@ function herdrAgent(state) {
249
260
  .filter(c => c.length >= 4 && c[0] === PROJ && c[1] === "herdr" && c[2] === PERSONA)
250
261
  .pop();
251
262
  if (!row || !row[3]) return;
252
- spawnSync("herdr", ["pane", "report-agent", row[3], "--source", "crew", "--agent", AGENT, "--state", state],
253
- { stdio: "ignore", timeout: 1500 });
263
+ const resumeArgv = runnerResumeArgv({ agent: AGENT, driver: cli.pinned ? "opencode" : DRIVER, persona: PERSONA, dir: DIR,
264
+ runnerPath: join(import.meta.dirname, "crew-runner.mjs"), model: MODEL, effort: EFFORT,
265
+ project: PROJ, hub: HUB, sessionId: sid });
266
+ const args = herdrReportArgs({ pane: row[3], agent: AGENT, state, sessionId: sid, resumeArgv });
267
+ spawnSync("herdr", args, { stdio: "ignore", timeout: 1500 });
254
268
  } catch { /* no herdr, or no row for this seat: the cmux/tmux paths do not need it */ }
255
269
  }
256
270
 
@@ -261,7 +275,7 @@ function cmuxLog(message, level = "info") {
261
275
 
262
276
  // ---- per-CLI invocation (first turn vs resume turn). {P} = prompt file path ----
263
277
  // CREW_MODEL env pins the model: each CLI gets its own flag via {M} (empty when unset).
264
- let MODEL = process.env.CREW_MODEL || "";
278
+ let MODEL = process.env.CREW_MODEL || runnerOption("model");
265
279
  // opencode expects provider/model. A BARE id for the `deepseek` agent qualifies to its
266
280
  // own provider; `opencode` ids must already be provider-qualified (e.g.
267
281
  // `zai-coding-plan/glm-5.1`) — never assume `deepseek/` for opencode (that mangled
@@ -269,9 +283,11 @@ let MODEL = process.env.CREW_MODEL || "";
269
283
  if (MODEL && !MODEL.includes("/") && AGENT === "deepseek") MODEL = `deepseek/${MODEL}`;
270
284
  const CLI = {
271
285
  codex: { first: `codex exec{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`,
272
- next: `codex exec resume --last{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`, mflag: " -m " },
286
+ next: `codex exec resume --last{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`,
287
+ nextById: `codex exec resume {SID}{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`, mflag: " -m " },
273
288
  gemini: { first: `gemini --yolo{M} -p "$(cat {P})"`,
274
- next: `gemini --yolo{M} -r latest -p "$(cat {P})"`, mflag: " -m " },
289
+ next: `gemini --yolo{M} -r latest -p "$(cat {P})"`,
290
+ nextById: `gemini --yolo{M} -r {SID} -p "$(cat {P})"`, mflag: " -m " },
275
291
  // kimi-code (successor to kimi-cli) has no --print (-p alone is non-interactive), REJECTS
276
292
  // --yolo in prompt mode (prompt mode auto-approves tools), and emits session_-prefixed ids.
277
293
  kimi: { first: `kimi{M} -p "$(cat {P})" < /dev/null`,
@@ -291,7 +307,9 @@ const CLI = {
291
307
  openrouter: { first: `opencode run --dir {DIR}{M} "$(cat {P})"`,
292
308
  next: `opencode run --dir {DIR} -s {SID}{M} "$(cat {P})"`, mflag: " -m ", pinned: true, env: join(homedir(), ".token-scrooge", ".env") },
293
309
  claude: { first: `claude{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
310
+ firstById: `claude{M} --session-id {SID} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
294
311
  next: `claude -c{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
312
+ nextById: `claude --resume {SID}{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
295
313
  // TDD §4.6: a state step is a fresh `claude -p` (no `-c`) carrying the assembled prefix, held
296
314
  // to the TurnResult grammar by --json-schema; test/state/test-runner-state.mjs pins the strings.
297
315
  stateNext: `claude{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions --output-format json --json-schema "$(cat {S})"`,
@@ -315,12 +333,12 @@ if (!CLI[AGENT]) log(`'${AGENT}' is not a built-in seat — running it as an ope
315
333
  // it as CREW_EFFORT (JSON from bin/crew/core.mjs runnerCommand). The runner applies the
316
334
  // parameters the CLI can carry (codex -c model_reasoning_effort / claude --effort / opencode
317
335
  // --variant) and logs ONE line saying what it set — or that the model is uncatalogued.
318
- const EFFORT = (() => { try { return JSON.parse(process.env.CREW_EFFORT || "null"); } catch { return null; } })();
336
+ const EFFORT = (() => { try { return JSON.parse(process.env.CREW_EFFORT || runnerOption("effort") || "null"); } catch { return null; } })();
319
337
  const EFFORT_FLAG = EFFORT ? cliEffortFlag(DRIVER, EFFORT) : { flag: "", text: "" };
320
338
 
321
339
  // RUNNER_RULES / RUNNER_KICKOFF env overrides: the runner is also the substrate for non-crew
322
340
  // always-on seats (the fleet DUTY agent, bin/duty.mjs) whose doctrine is not "work your card".
323
- const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head, and the runner has already aligned your seat branch to it before your turn starts, saving any unharvested commit to harvest/<card> first (#13961). Never \`git reset\`, \`rebase\` or \`checkout\` your seat branch yourself: a hand reset skips that save and silently drops finished work. If HEAD doesn't contain the base (\`git merge-base --is-ancestor <sha> HEAD\` fails), say \`cannot resolve base <sha>\` on the bus and move the card to blocked instead of working from somewhere else. Every testing/done note names the sha you verified against as \`verified at <sha>\`; a note without it is flagged HOLLOW. Cross-project action is a breach: never \`trantor up\` a crew, register a seat, or send a card/contract into a project other than ${PROJ} unless the operator ran \`trantor policy link ${PROJ} <other> --reason "<why>"\` first — the hub, the CLI and this runner all refuse it mechanically, so ask the operator to link the projects instead of routing around the refusal.`;
341
+ const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head, and the runner has already aligned your seat branch to it before your turn starts, saving any unharvested commit to harvest/<card> first (#13961). Work only on \`seat/<persona>\`; never create branches. Never \`git reset\`, \`rebase\` or \`checkout\` your seat branch yourself: a hand reset skips that save and silently drops finished work. If HEAD doesn't contain the base (\`git merge-base --is-ancestor <sha> HEAD\` fails), say \`cannot resolve base <sha>\` on the bus and move the card to blocked instead of working from somewhere else. Every testing/done note names the sha you verified against as \`verified at <sha>\`; a note without it is flagged HOLLOW. Cross-project action is a breach: never \`trantor up\` a crew, register a seat, or send a card/contract into a project other than ${PROJ} unless the operator ran \`trantor policy link ${PROJ} <other> --reason "<why>"\` first — the hub, the CLI and this runner all refuse it mechanically, so ask the operator to link the projects instead of routing around the refusal.`;
324
342
 
325
343
  // ---- the pulse --------------------------------------------------------------
326
344
  // RUNNER_PULSE_MS re-runs an orchestrator seat's mission note on a cadence when the bus is silent;
@@ -866,7 +884,7 @@ const OC_COMPACTION = ocCompactionContent(process.env, OC_COMPACTION_WINDOW);
866
884
  // #11854: plus every non-relay MCP server of the user's opencode config switched off for the seat.
867
885
  const OC_SEAT_CONFIG = seatConfigContent(OC_COMPACTION, seatMcpOverlay(readOpencodeUserConfig()));
868
886
 
869
- let sid = releaseState?.sid || "";
887
+ let sid = releaseState?.sid || runnerOption("resume");
870
888
  // #6206: the watchdog is DETACHED, so a runner that dies without ending it leaves an orphan
871
889
  // sleeping toward a false alarm against whatever runner comes next.
872
890
  // Every exit path therefore kills it, and the stamp carries this runner's instance id so any
@@ -887,7 +905,11 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
887
905
  // A fresh session must not resume the old one's id: `first` is chosen by isFirst OR a missing
888
906
  // sid, so a stale sid would quietly resume the session this turn exists to leave behind.
889
907
  // #11855: the min-steps guard counts from the last fresh start; a state step never resets it.
890
- if (isFirst) { sid = ""; if (!opts.state) capFreshTurn = TURN; }
908
+ if (isFirst) {
909
+ sid = "";
910
+ if (DRIVER === "claude" && !opts.state) sid = randomUUID();
911
+ if (!opts.state) capFreshTurn = TURN;
912
+ }
891
913
  // #5965 — TURN START. The hub peer row is where the app reads activity from, and the runner is
892
914
  // the only one who knows a turn is starting, so say so before the CLI spawn (awaited: the spawn
893
915
  // below blocks the loop, an unawaited fetch would not leave the machine until the turn ended).
@@ -925,7 +947,9 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
925
947
  const busSeqBefore = await latestBusEventId();
926
948
  // #6154: a pinned seat with no sid yet resumes as FRESH — the guard below fails open, because
927
949
  // a resume without an id must fall back to a new session, never to `next`'s bare resume shape.
928
- let cmd = (isFirst || ((cli.sid || cli.pinned) && !sid)) ? cli.first : cli.next;
950
+ let cmd = isFirst || ((cli.sid || cli.pinned) && !sid)
951
+ ? (sid && cli.firstById ? cli.firstById : cli.first)
952
+ : (runnerOption("resume") && sid && cli.nextById ? cli.nextById : cli.next);
929
953
  // The flagged row (TDD §4.6). `{S}` exists only in `stateNext`, so the replaceAll below is a
930
954
  // no-op on every other path — which is what "flag off = byte-identical" has to mean.
931
955
  if (opts.state && cli.stateNext) cmd = cli.stateNext;
@@ -1150,6 +1174,14 @@ exit $turn_exit`;
1150
1174
  // keyed by the worktree the session was created in. Fail-open: nothing found leaves sid empty,
1151
1175
  // and the next turn starts fresh rather than resuming whatever other project ran last.
1152
1176
  if (cli.pinned) { const found = ocSid(TURN_DIR); if (found) sid = found; }
1177
+ if (DRIVER === "codex") {
1178
+ const found = codexSessionId(join(homedir(), ".codex", "sessions"), TURN_DIR, t0);
1179
+ if (found) sid = found;
1180
+ }
1181
+ if (DRIVER === "gemini") {
1182
+ const found = geminiSessionId(join(homedir(), ".gemini"), TURN_DIR, t0);
1183
+ if (found) sid = found;
1184
+ }
1153
1185
  const realExit = r.status;
1154
1186
  // A zero exit is not proof the turn ran (#5405): an exit-0 auth turn is FAILED when the CLI's own
1155
1187
  // output is short enough to be just the error (#5868). Telemetry keeps the real exit.
@@ -1623,7 +1655,7 @@ async function resolveWakeCard(messages, { session }) {
1623
1655
  // construction and now says so, in the same breath as the line that armed the mode.
1624
1656
  if (!releaseState) {
1625
1657
  stateSkip("kickoff");
1626
- const ec0 = await runTurn(composedTurn({ base: KICKOFF, lessons: pickLessons(LESSONS_RAW, "") }), true, "kickoff");
1658
+ const ec0 = await runTurn(composedTurn({ base: KICKOFF, lessons: pickLessons(LESSONS_RAW, "") }), !runnerOption("resume"), runnerOption("resume") ? "reboot resume" : "kickoff");
1627
1659
  if (ec0) await reportFailure(ec0, "kickoff", pendingWake.length); // a failed kickoff = the "fired up, died, nobody knew" case
1628
1660
  // #7778: the kickoff is a turn like any other — a message that landed mid-kickoff and was read
1629
1661
  // through the session's own inbox is consumed by a successful kickoff, and the first poll must
@@ -1666,7 +1698,12 @@ async function resolveWakeCard(messages, { session }) {
1666
1698
  // by the monitoring doctrine (state not event — a machine that stops beating reads stale on the
1667
1699
  // hub, which IS the honest "unreachable" signal, not an error to alert on).
1668
1700
  if (machineConfig.healthHeartbeat === true && MACHINE_LABEL) {
1669
- const beat = () => api("/machines/health", { ...healthPayload(defaultOs, MACHINE_LABEL), project: PROJ }).catch(() => {});
1701
+ // A throw while building the payload must never reach the process: an unhandled rejection
1702
+ // here took a seat runner down on 0.18.131.
1703
+ const beat = () => {
1704
+ try { return api("/machines/health", { ...healthPayload(defaultOs, MACHINE_LABEL), project: PROJ }).catch(() => {}); }
1705
+ catch { return Promise.resolve(); }
1706
+ };
1670
1707
  beat();
1671
1708
  setInterval(beat, HEALTH_BEAT_MS).unref?.();
1672
1709
  log(`machine health heartbeat armed as ${MACHINE_LABEL} every ${Math.round(HEALTH_BEAT_MS / 1000)}s`);
@@ -1955,6 +1992,10 @@ async function resolveWakeCard(messages, { session }) {
1955
1992
  const baseCard = card || servedContractCard(wakeForTurn, { session: SESSION });
1956
1993
  const statedBase = contractBase(wakeForTurn);
1957
1994
  const base = statedBase || originMainHead();
1995
+ const recentCardCommits = card && !statedBase
1996
+ ? gitOut(["log", "-5", "--format=%s%n%b"], TURN_DIR)
1997
+ : "";
1998
+ const alignForContract = shouldAlignForContract(card, statedBase, sessionCard, recentCardCommits);
1958
1999
  if (base && baseCard && !resolvesHere(base)) {
1959
2000
  const text = `cannot resolve base ${base} in ${TURN_DIR} (git cat-file -e failed) — #${baseCard} moved to blocked; push or fetch that sha, or name one this worktree can reach`;
1960
2001
  log(text);
@@ -1966,7 +2007,7 @@ async function resolveWakeCard(messages, { session }) {
1966
2007
  savePending([], pendingBcast);
1967
2008
  return;
1968
2009
  }
1969
- if (base && TURN_DIR !== DIR && card && gitOut(["rev-parse", "--abbrev-ref", "HEAD"], TURN_DIR) === `seat/${PERSONA}`) {
2010
+ if (base && TURN_DIR !== DIR && card && alignForContract) {
1970
2011
  const aligned = alignSeatWorktree({ dir: TURN_DIR, project: PROJ, agent: PERSONA, base });
1971
2012
  if (!aligned.ok) {
1972
2013
  const text = `cannot align seat worktree for #${card}: ${aligned.reason}`;
package/bin/crew.mjs CHANGED
@@ -7,6 +7,7 @@ import { createCmuxAdapter, spawnCmux } from "./crew/cmux.mjs";
7
7
  import { createHerdrAdapter, spawnHerdr } from "./crew/herdr.mjs";
8
8
  import { resolveSpec, reportSkipped } from "./crew/models.mjs";
9
9
  import { openOrchestrator } from "./crew/open.mjs";
10
+ import { restoreOrchestrators } from "./crew/restore.mjs";
10
11
  import { performSwap, swapOptions, swapRuntime } from "./crew/swap.mjs";
11
12
  import { redactKeys } from "../lib/redact.mjs";
12
13
  import { reapSeat, down, prune, readRows } from "./crew/state.mjs";
@@ -39,7 +40,7 @@ const adapters = {
39
40
  };
40
41
 
41
42
  function usage() {
42
- console.log("usage: crew.mjs up <agent...> | crew.mjs open [<project>] | crew.mjs swap <old> <new[:provider[/model]]> | crew.mjs down [<agent>...] [--all --yes] | crew.mjs prune");
43
+ console.log("usage: crew.mjs up <agent...> | crew.mjs open [<project>] | crew.mjs restore [--dry-run] | crew.mjs swap <old> <new[:provider[/model]]> | crew.mjs down [<agent>...] [--all --yes] | crew.mjs prune");
43
44
  }
44
45
 
45
46
  function parseUpArgs(args) {
@@ -150,6 +151,7 @@ try {
150
151
  if (command === "down") code = await down(ctx, rawArgs, adapters);
151
152
  else if (command === "prune") { prune(ctx, adapters); console.log(`— pruned dead crew rows (${ctx.statePath}) —`); }
152
153
  else if (command === "open") code = openOrchestrator(ctx, rawArgs);
154
+ else if (command === "restore") code = await restoreOrchestrators(ctx, rawArgs);
153
155
  else if (command === "swap") { result = await swap(rawArgs); code = result.ok ? 0 : 1; }
154
156
  else if (command === "up") code = guardCrossProjectUp(ctx) ? await runUp(rawArgs) : 1;
155
157
  else { usage(); code = 1; }
@@ -160,7 +162,9 @@ try {
160
162
  if (!result) result = jsonResult(code);
161
163
  if (!result.ok && !result.reason) result.reason = diagnostics.at(-1) || `${command} failed; see stderr`;
162
164
  if (result.reason) result.reason = redactKeys(result.reason);
163
- if (jsonMode) output(JSON.stringify(result));
164
- else if (result.reason) console.error(result.reason);
165
+ if (jsonMode) {
166
+ if (!result.ok && result.reason) console.error(result.reason);
167
+ output(JSON.stringify(result));
168
+ } else if (result.reason) console.error(result.reason);
165
169
  else if (command === "swap") console.log(`— swapped ${result.seat} → ${result.to}; moved contracts: ${result.moved.join(", ") || "none"} —`);
166
170
  process.exit(code);
@@ -28,6 +28,8 @@ function slimCard(t) {
28
28
  for (const k of Object.keys(t)) if (!SLIM_DROP.has(k)) out[k] = t[k];
29
29
  // Keep the ·N the board renders, so slimming costs a reader nothing visible.
30
30
  out.logCount = Array.isArray(t.log) ? t.log.length : 0;
31
+ out.checklistCount = Array.isArray(t.checklist) ? t.checklist.length : 0;
32
+ out.checklistDone = Array.isArray(t.checklist) ? t.checklist.filter(item => item.done).length : 0;
31
33
  return out;
32
34
  }
33
35
 
@@ -17,7 +17,7 @@ const CLAIM_TTL_MS = 300000;
17
17
  const PROMPT_SWEEP_MS = Number(process.env.RELAY_PROMPT_SWEEP_MS || 30000);
18
18
  const EXPIRED_REASON = "No Mac is relaying this project. Is the Trantor app open?";
19
19
  const CLAIMED_EXPIRED_REASON = "The Mac claimed this prompt but never delivered it. Try sending it again.";
20
- const ACK_OUTCOMES = new Set(["delivered", "blocked", "not_ready", "stalled", "no_agent", "stale"]);
20
+ const ACK_OUTCOMES = new Set(["delivered", "sent", "blocked", "not_ready", "stalled", "no_agent", "stale"]);
21
21
  const ANSWER_PICKS_MAX = 10;
22
22
  const ANSWER_OTHER_MAX = 2000;
23
23
  const ANSWER_ENTRIES_MAX = 4; // CC's question limit per ask (#12912)
@@ -524,8 +524,15 @@ function pruneMachinesHealth() {
524
524
  if (p.kind === "crew") {
525
525
  p.output = stripAnsi(String(b.output || "")).slice(-CREW_OUTPUT_MAX);
526
526
  p.status = outcome; // "done" or "failed"
527
+ } else if (outcome === "delivered") {
528
+ p.status = "delivered";
529
+ } else if (outcome === "sent") {
530
+ // #13913: herdr typed the text and Enter but the session has not picked it up. Terminal
531
+ // for claiming (never re-claimed, never re-typed); phones keep it queued until the
532
+ // transcript itself shows the turn.
533
+ p.status = "sent";
527
534
  } else {
528
- p.status = outcome === "delivered" ? "delivered" : "failed";
535
+ p.status = "failed";
529
536
  }
530
537
  // A terminal row will never be claimed or downloaded again: its bytes go now.
531
538
  unlinkAttachments(p);
@@ -1,6 +1,10 @@
1
1
  // Is herdr's own claude integration installed? Session identity in the desktop app relies on it
2
2
  // reporting the session at SessionStart (pane.report_agent_session), and nothing else checks it.
3
3
  import { spawnSync } from "node:child_process";
4
+ import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { codexRolloutCwd } from "./turn-usage.mjs";
4
8
 
5
9
  export const HERDR_CLAUDE_INSTALL = "herdr integration install claude";
6
10
 
@@ -26,3 +30,80 @@ export function probeClaudeIntegration(run = spawnSync) {
26
30
  if (r.error) return { state: "unknown", detail: String(r.error.message || r.error) };
27
31
  return claudeIntegrationState({ ran: true, status: r.status ?? 1, stdout: r.stdout });
28
32
  }
33
+
34
+ const RESUMABLE = new Set(["claude", "codex", "gemini", "kimi", "opencode"]);
35
+ const validArg = (arg) => ![...arg].some(char => char === "'" || char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127);
36
+ const validArgv = (args) => args.length > 0 && args.length <= 64
37
+ && args.every(validArg)
38
+ && Buffer.byteLength(args.join("\0")) <= 8192;
39
+
40
+ export function runnerResumeArgv({ agent, driver = agent, persona = agent, dir, runnerPath, model = "", effort = null, project, hub, sessionId }) {
41
+ if (!sessionId || !RESUMABLE.has(driver)) return [];
42
+ const args = ["node", runnerPath, persona, dir, "--agent", agent, "--persona", persona,
43
+ "--project", project, "--hub", hub, "--resume", sessionId];
44
+ if (model) args.push("--model", model);
45
+ if (effort) args.push("--effort", JSON.stringify(effort));
46
+ return validArgv(args.map(value => String(value || ""))) ? args.map(value => String(value || "")) : [];
47
+ }
48
+
49
+ export function herdrReportArgs({ pane, agent, state, sessionId = "", resumeArgv = [] }) {
50
+ const args = ["pane", "report-agent", pane, "--source", "crew", "--agent", agent, "--state", state];
51
+ if (sessionId && resumeArgv.length && validArgv(resumeArgv)) {
52
+ args.push("--agent-session-id", sessionId, "--", ...resumeArgv);
53
+ }
54
+ return args;
55
+ }
56
+
57
+ const canonical = path => { try { return realpathSync(path); } catch { return String(path || ""); } };
58
+ const directoryNames = (path) => { try { return readdirSync(path); } catch { return []; } };
59
+
60
+ export function codexSessionId(sessionsRoot, cwd, sinceMs, { nowMs = Date.now(), lookbackDays = 14 } = {}) {
61
+ if (!sessionsRoot || !cwd || !Number.isFinite(sinceMs)) return "";
62
+ const want = canonical(cwd), pad = n => String(n).padStart(2, "0");
63
+ let newest = { id: "", mtime: -1 };
64
+ for (let i = -1; i < lookbackDays; i++) {
65
+ const day = new Date(nowMs - i * 86400000);
66
+ const dir = join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
67
+ for (const name of directoryNames(dir)) {
68
+ const match = /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.jsonl$/i.exec(name);
69
+ if (!match) continue;
70
+ const file = join(dir, name);
71
+ let mtime;
72
+ try { mtime = statSync(file).mtimeMs; } catch { continue; }
73
+ if (mtime < sinceMs || mtime <= newest.mtime || canonical(codexRolloutCwd(file)) !== want) continue;
74
+ newest = { id: match[1], mtime };
75
+ }
76
+ }
77
+ return newest.id;
78
+ }
79
+
80
+ export function geminiSessionId(geminiRoot, cwd, sinceMs) {
81
+ if (!geminiRoot || !cwd || !Number.isFinite(sinceMs)) return "";
82
+ const want = canonical(cwd);
83
+ const dirs = new Set([String(cwd), want].map(path => createHash("sha256").update(path).digest("hex")));
84
+ try {
85
+ const projects = JSON.parse(readFileSync(join(geminiRoot, "projects.json"), "utf8")).projects || {};
86
+ for (const [root, name] of Object.entries(projects)) if (canonical(root) === want) dirs.add(name);
87
+ } catch {}
88
+ let newest = { id: "", mtime: -1 };
89
+ for (const projectDir of dirs) {
90
+ const parent = join(geminiRoot, "tmp", projectDir);
91
+ try { if (canonical(readFileSync(join(parent, ".project_root"), "utf8").trim()) !== want) continue; } catch {}
92
+ const dir = join(parent, "chats");
93
+ for (const name of directoryNames(dir)) {
94
+ if (!name.startsWith("session-") || (!name.endsWith(".json") && !name.endsWith(".jsonl"))) continue;
95
+ const file = join(dir, name);
96
+ let mtime;
97
+ try { mtime = statSync(file).mtimeMs; } catch { continue; }
98
+ if (mtime < sinceMs || mtime <= newest.mtime) continue;
99
+ try {
100
+ const text = readFileSync(file, "utf8");
101
+ const record = JSON.parse(name.endsWith(".jsonl") ? text.split("\n")[0] : text);
102
+ const id = String(record.sessionId || "");
103
+ const roots = Array.isArray(record.directories) ? record.directories.map(canonical) : [];
104
+ if (id && validArg(id) && (!roots.length || roots.includes(want))) newest = { id, mtime };
105
+ } catch {}
106
+ }
107
+ }
108
+ return newest.id;
109
+ }
@@ -9,7 +9,7 @@ export const HEALTH_STALE_MS = Number(process.env.RELAY_HEALTH_STALE_MS || 90_00
9
9
  // cpuPct is the 1-min loadavg over the core count, as a percent — it CAN exceed 100 (a machine
10
10
  // oversubscribed past its cores must not read as a capped, calm 100). Memory is used/total bytes;
11
11
  // "used" is total minus free, the same arithmetic every system monitor shows.
12
- export function healthPayload(osLike, machine, now = Date.now()) {
12
+ export function healthPayload(osLike, machine, now = Date.now) {
13
13
  const cores = Math.max(1, (Array.isArray(osLike.cpus()) ? osLike.cpus() : []).length);
14
14
  const load = Number(osLike.loadavg()?.[0]);
15
15
  const total = Number(osLike.totalmem());
@@ -28,21 +28,39 @@ function gitOut(args, cwd) {
28
28
  // Start a new contract from its pinned base unless that base is already in the seat's history.
29
29
  // Unharvested commits are parked on harvest/<card-or-sha> before moving the seat branch.
30
30
  export function alignSeatWorktree({ dir, project, agent, base, receiptsRoot, log = console.log }) {
31
- const branch = gitOut(["rev-parse", "--abbrev-ref", "HEAD"], dir);
31
+ let branch = gitOut(["rev-parse", "--abbrev-ref", "HEAD"], dir);
32
32
  const expected = `seat/${agent}`;
33
- if (branch !== expected) return { ok: false, reason: `refusing to align ${dir}: expected ${expected}, found ${branch || "detached HEAD"}` };
34
33
  if (!/^[0-9a-f]{7,40}$/i.test(String(base || "")) ||
35
34
  spawnSync("git", ["cat-file", "-e", `${base}^{commit}`], { cwd: dir, stdio: "ignore", timeout: 8000 }).status !== 0)
36
35
  return { ok: false, reason: `base ${base || "(missing)"} is not a commit in ${dir}` };
37
36
  if (gitOut(["status", "--porcelain"], dir)) return { ok: false, reason: `refusing to reset dirty seat worktree ${dir}` };
37
+ const parked = [];
38
+ if (branch !== expected) {
39
+ const tip = gitOut(["rev-parse", "HEAD"], dir);
40
+ const savedRefs = gitOut(["for-each-ref", "--format=%(refname)", "refs/heads/harvest"], dir).split("\n").filter(Boolean);
41
+ const alreadySaved = savedRefs.some(ref => spawnSync("git", ["merge-base", "--is-ancestor", tip, ref], { cwd: dir, stdio: "ignore", timeout: 8000 }).status === 0);
42
+ const coveredByBase = spawnSync("git", ["merge-base", "--is-ancestor", tip, base], { cwd: dir, stdio: "ignore", timeout: 8000 }).status === 0;
43
+ if (!alreadySaved && !coveredByBase) {
44
+ const subject = gitOut(["show", "-s", "--format=%s", tip], dir);
45
+ const key = subject.match(/#(\d+)/)?.[1] || tip.slice(0, 7);
46
+ let name = `harvest/${key}`;
47
+ const existing = gitOut(["rev-parse", "--verify", "--quiet", `refs/heads/${name}`], dir);
48
+ if (existing && existing !== tip) name = `harvest/${key}-${tip.slice(0, 7)}`;
49
+ const save = spawnSync("git", ["update-ref", `refs/heads/${name}`, tip], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 8000 });
50
+ if (save.status !== 0) return { ok: false, reason: `could not park ${tip.slice(0, 7)} at ${name}: ${String(save.stderr || "git update-ref failed").trim()}` };
51
+ parked.push(name);
52
+ }
53
+ const checkout = spawnSync("git", ["checkout", expected], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 8000 });
54
+ if (checkout.status !== 0) return { ok: false, reason: `could not check out ${expected}: ${String(checkout.stderr || checkout.stdout || "git checkout failed").trim()}` };
55
+ branch = expected;
56
+ }
38
57
  if (spawnSync("git", ["merge-base", "--is-ancestor", base, "HEAD"], { cwd: dir, stdio: "ignore", timeout: 8000 }).status === 0) {
39
58
  log(`${branch} branch already contains base ${base}; keeping ${dir} at its current tip`);
40
- return { ok: true, to: gitOut(["rev-parse", "HEAD"], dir), parked: "" };
59
+ return { ok: true, to: gitOut(["rev-parse", "HEAD"], dir), parked: parked.join(", ") };
41
60
  }
42
61
 
43
62
  const receipts = readReceipts(project, receiptsRoot);
44
63
  const audit = auditSeat(dir, { branch, targetRef: base, receipts });
45
- const parked = [];
46
64
  for (const commit of audit.unharvested) {
47
65
  const refs = gitOut(["for-each-ref", "--format=%(refname)", "refs/heads/harvest"], dir).split("\n").filter(Boolean);
48
66
  const saved = refs.some(ref => spawnSync("git", ["merge-base", "--is-ancestor", commit.sha, ref], { cwd: dir, stdio: "ignore", timeout: 8000 }).status === 0);
@@ -36,6 +36,19 @@ export function cardRefs(text) {
36
36
  /// own-card resolution must agree on it, so the set lives in the one file both sides already import.
37
37
  export const OPEN_CARD_STATUSES = ["doing", "testing", "todo"];
38
38
 
39
+ // A follow-up wake may arrive while the seat is already working the same card. In that case an
40
+ // implicit origin/main base would discard the useful meaning of its current branch tip.
41
+ export function sameCardWork(card, activeCard, commitMessages = "") {
42
+ const id = Number(card) || 0;
43
+ if (!(id > 0)) return false;
44
+ if (Number(activeCard) === id) return true;
45
+ return String(commitMessages).split(/\r?\n/).some(line => new RegExp(`(?:^|[^\\d])#${id}(?!\\d)`).test(line));
46
+ }
47
+
48
+ export function shouldAlignForContract(card, statedBase, activeCard, commitMessages = "") {
49
+ return !!statedBase || !sameCardWork(card, activeCard, commitMessages);
50
+ }
51
+
39
52
  /// #7763/#7765: a MESSAGE-CARD is a transcript of a bus message parked on the board ("NEW BUS
40
53
  /// MESSAGE for you: …", the join note "You just joined …"), never work. A wake that cites only one
41
54
  /// of these binds to no card at all — a seat sent chasing one spends the turn on card bookkeeping
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.131",
3
+ "version": "0.18.133",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"