trantor 0.18.131 → 0.18.132
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/.claude-plugin/plugin.json +1 -1
- package/README.md +3 -0
- package/bin/crew/herdr.mjs +6 -4
- package/bin/crew/open.mjs +10 -3
- package/bin/crew-runner.mjs +58 -17
- package/hub/routes/cards.mjs +2 -0
- package/lib/herdr-integration.mjs +81 -0
- package/lib/machine-health.mjs +1 -1
- package/lib/seat-worktree.mjs +22 -4
- package/lib/turn-policy.mjs +13 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.132",
|
|
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
|
package/bin/crew/herdr.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
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) {
|
|
@@ -91,13 +92,14 @@ export function closePane(ctx, id) {
|
|
|
91
92
|
return herdrCall(ctx, ["pane", "close", id]).ok;
|
|
92
93
|
}
|
|
93
94
|
|
|
94
|
-
export function reportAgent(ctx, pane, agent) {
|
|
95
|
+
export function reportAgent(ctx, pane, agent, { sessionId = "", resumeArgv = [] } = {}) {
|
|
95
96
|
if (!pane) return;
|
|
97
|
+
const args = herdrReportArgs({ pane, agent, state: "working", sessionId, resumeArgv });
|
|
96
98
|
if (ctx.dry) {
|
|
97
|
-
console.log(`[dry]
|
|
99
|
+
console.log(`[dry] ${formatCommand("herdr", args)}`);
|
|
98
100
|
return;
|
|
99
101
|
}
|
|
100
|
-
herdrCall(ctx,
|
|
102
|
+
herdrCall(ctx, args);
|
|
101
103
|
}
|
|
102
104
|
|
|
103
105
|
function runSeat(ctx, pane, agent, command) {
|
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 =
|
|
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,7 +167,7 @@ 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
|
-
|
|
170
|
+
reportOrchestrator(ctx, pane, id);
|
|
164
171
|
console.error(`— orchestrator pane was empty: resumed session ${id} in herdr:${workspace || "?"}/${pane} —`);
|
|
165
172
|
} else console.error(`— orchestrator already hosted: reattached to herdr:${workspace || "?"}/${pane} —`);
|
|
166
173
|
console.log(`herdr:${workspace || "?"}/${pane}`);
|
|
@@ -200,7 +207,7 @@ function hostPane(ctx, chosen, id) {
|
|
|
200
207
|
if (!pane) throw new Error("trantor open: could not create the orchestrator pane");
|
|
201
208
|
herdrCall(ctx, ["pane", "rename", pane, `orchestrator · ${ctx.project}`]);
|
|
202
209
|
herdrCall(ctx, ["pane", "run", pane, orchestratorCommand(ctx, id)]);
|
|
203
|
-
|
|
210
|
+
reportOrchestrator(ctx, pane, id);
|
|
204
211
|
return pane;
|
|
205
212
|
}
|
|
206
213
|
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -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 ||
|
|
91
|
-
const PERSONA = runnerPersona(process.env, AGENT);
|
|
92
|
-
const DIR =
|
|
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
|
-
|
|
253
|
-
|
|
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`,
|
|
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})"`,
|
|
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) {
|
|
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 =
|
|
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, "") }),
|
|
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
|
-
|
|
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 &&
|
|
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/hub/routes/cards.mjs
CHANGED
|
@@ -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
|
|
|
@@ -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
|
+
}
|
package/lib/machine-health.mjs
CHANGED
|
@@ -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());
|
package/lib/seat-worktree.mjs
CHANGED
|
@@ -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
|
-
|
|
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);
|
package/lib/turn-policy.mjs
CHANGED
|
@@ -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
|