trantor 0.18.144 → 0.18.148

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.
Files changed (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/canary.mjs +55 -15
  5. package/bin/capacity.mjs +21 -3
  6. package/bin/cli.mjs +6 -2
  7. package/bin/connect.mjs +10 -3
  8. package/bin/crew-runner.mjs +101 -18
  9. package/bin/disk.mjs +8 -5
  10. package/bin/dispatch.mjs +78 -0
  11. package/bin/integrate.mjs +14 -2
  12. package/bin/review.mjs +35 -0
  13. package/bin/wake-nudge.mjs +27 -3
  14. package/configs/dispatcher-policy.json +84 -0
  15. package/docs/FEATURES.md +25 -12
  16. package/hooks/sessionstart.mjs +4 -1
  17. package/hub/routes/capacity.mjs +31 -24
  18. package/hub/routes/cards.mjs +7 -2
  19. package/hub/routes/dispatcher.mjs +97 -0
  20. package/hub/routes/insights.mjs +69 -4
  21. package/hub/routes/worktree-status.mjs +56 -0
  22. package/hub.mjs +2 -1
  23. package/kimi.plugin.json +1 -1
  24. package/lib/canary/canary.mjs +66 -7
  25. package/lib/canary/registry.mjs +153 -4
  26. package/lib/capacity.mjs +113 -18
  27. package/lib/classify-failure.mjs +14 -8
  28. package/lib/dispatcher/acceptance.mjs +314 -0
  29. package/lib/dispatcher/accounts.mjs +442 -0
  30. package/lib/dispatcher/admission.mjs +719 -0
  31. package/lib/dispatcher/breakers.mjs +70 -0
  32. package/lib/dispatcher/executor.mjs +486 -0
  33. package/lib/dispatcher/forecast.mjs +391 -0
  34. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  35. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  36. package/lib/dispatcher/harness/contract.mjs +198 -0
  37. package/lib/dispatcher/harness/crew.mjs +463 -0
  38. package/lib/dispatcher/harness/publication.mjs +188 -0
  39. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  40. package/lib/dispatcher/planner.mjs +516 -0
  41. package/lib/dispatcher/policy.mjs +50 -0
  42. package/lib/dispatcher/preflight.mjs +247 -0
  43. package/lib/dispatcher/resources.mjs +44 -0
  44. package/lib/dispatcher/schemas.mjs +220 -0
  45. package/lib/dispatcher/snapshot.mjs +70 -0
  46. package/lib/dispatcher/spend.mjs +319 -0
  47. package/lib/dispatcher/store.mjs +316 -0
  48. package/lib/fitness.mjs +227 -41
  49. package/lib/launchd.mjs +61 -0
  50. package/lib/review-gate.mjs +63 -0
  51. package/lib/seat-liveness.mjs +41 -0
  52. package/lib/session-liveness.mjs +23 -0
  53. package/lib/telemetry-ship.mjs +8 -7
  54. package/lib/turn-usage.mjs +88 -17
  55. package/lib/worktree-status.mjs +216 -0
  56. package/mcp.mjs +53 -7
  57. package/package.json +1 -1
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
9
- "version": "0.18.144"
9
+ "version": "0.18.148"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "trantor",
14
14
  "source": "./",
15
15
  "description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
16
- "version": "0.18.144",
16
+ "version": "0.18.148",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.144",
3
+ "version": "0.18.148",
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/bin/advise.mjs CHANGED
@@ -241,19 +241,35 @@ export function advise(input, world = loadWorld()) {
241
241
  return recommendation;
242
242
  }
243
243
 
244
- // ---- CLI ----
245
- // is-main guard via PROPERLY ENCODED file URL — a hand-built `file://${argv[1]}` silently no-ops when the
246
- // install path contains a URL-reserved char (e.g. a SPACE in ".../Application Support/..."). See profile.mjs.
244
+ // #14678: stdin carrying {cards|drafts}, or --snapshot/--policy, asks the hub's planner (POST /advise);
245
+ // {task, packages} keeps the legacy advisor above, usable in shadow mode.
246
+ async function hubAdvice(input, argv) {
247
+ const { signedPost, sessionContext } = await import("../hooks/lib/api.mjs");
248
+ const { buildAdviceRequest, requestAdvice, renderAdvice } = await import("../lib/dispatcher/preflight.mjs");
249
+ const flag = (name) => { const i = argv.indexOf(name); return i > -1 ? argv[i + 1] : undefined; };
250
+ const project = input.project || sessionContext().project;
251
+ const request = await buildAdviceRequest({ project, cards: input.cards || [], drafts: input.drafts || [],
252
+ snapshotId: flag("--snapshot") || input.snapshotId, policyVersion: flag("--policy") || input.policyVersion });
253
+ const result = await requestAdvice({ post: (path, body) => signedPost(path, body, { project, timeoutMs: 10000 }), busDir: busDir(), request });
254
+ console.log(argv.includes("--json") ? JSON.stringify(result, null, 2) : renderAdvice(result));
255
+ return result.source === "refused" ? 1 : 0;
256
+ }
257
+
258
+ // ---- CLI ---- is-main guard via an ENCODED file URL: a hand-built `file://${argv[1]}` no-ops when the
259
+ // install path holds a URL-reserved char (a SPACE in ".../Application Support/..."). See profile.mjs.
247
260
  if (import.meta.url === pathToFileURL(process.argv[1]).href) {
248
261
  let input;
249
- if (process.argv.includes("--demo")) {
262
+ const argv = process.argv.slice(2);
263
+ if (!argv.includes("--demo")) {
264
+ const stdin = process.stdin.isTTY ? "" : readFileSync(0, "utf8").trim();
265
+ input = stdin ? JSON.parse(stdin) : { packages: [] };
266
+ if (input.cards || input.drafts || argv.includes("--snapshot") || argv.includes("--policy")) process.exit(await hubAdvice(input, argv));
267
+ }
268
+ if (argv.includes("--demo")) {
250
269
  input = { task: "neon asteroids game", packages: [
251
270
  { title: "engine+integration", difficulty: "hard" }, { title: "render/bloom", difficulty: "hard" },
252
271
  { title: "combat+ui", difficulty: "medium" }, { title: "audio", difficulty: "medium" },
253
272
  { title: "readme+badges", difficulty: "easy" } ] };
254
- } else {
255
- const stdin = readFileSync(0, "utf8").trim();
256
- input = stdin ? JSON.parse(stdin) : { packages: [] };
257
273
  }
258
274
  const world = loadWorld();
259
275
  // #7762: fold this project's seat record into the routing (fail-open — no hub, no record,
package/bin/canary.mjs CHANGED
@@ -1,19 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  // trantor canary — run every docs/FEATURES.md probe (#14655).
3
- // trantor canary [--json] run the probes; read-only, writes nothing, posts nothing
4
- // trantor canary --daily what launchd runs: also records the run and posts new failures once per episode
5
- // trantor canary install | uninstall | plist
3
+ // trantor canary [--json] [--daily] probes only; --daily also records the run and posts new failures
4
+ // trantor canary install | uninstall | plist | check | attach <path…> | brief (#14670: docs/FEATURES.md)
6
5
  import { mkdirSync, writeFileSync, rmSync, existsSync } from "node:fs";
7
6
  import { join } from "node:path";
8
7
  import { homedir } from "node:os";
9
8
  import { execFileSync } from "node:child_process";
10
9
  import { fileURLToPath } from "node:url";
11
10
  import { busDir, resolveHub, knownProjects, checkoutFor, readConfig } from "../lib/project.mjs";
12
- import { loadRegistry } from "../lib/canary/registry.mjs";
11
+ import { loadRegistry, validateRegistry, registryHash, attachProbes } from "../lib/canary/registry.mjs";
12
+ import { PROBES } from "../lib/canary/probes.mjs";
13
13
  import {
14
- runCanary, tally, advanceEpisodes, episodeMessage, readEpisodes, recordRun,
15
- defaultContext, canaryPlist, CANARY_LABEL,
14
+ runCanary, tally, advanceEpisodes, markDelivered, episodeMessage, readEpisodes, readLastRun, recordRun,
15
+ regressionBrief, defaultContext, canaryPlist, CANARY_LABEL,
16
16
  } from "../lib/canary/canary.mjs";
17
+ import { reloadLaunchAgent } from "../lib/launchd.mjs";
17
18
 
18
19
  const SELF = fileURLToPath(import.meta.url);
19
20
  const PROJECT = "trantor";
@@ -35,8 +36,9 @@ if (cmd === "install") {
35
36
  mkdirSync(join(busDir(), "logs"), { recursive: true });
36
37
  mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
37
38
  writeFileSync(PLIST_PATH, canaryPlist({ script: SELF, busDir: busDir() }), { mode: 0o644 });
38
- try { launchctl(["bootout", `gui/${process.getuid()}/${CANARY_LABEL}`]); } catch { /* first install has no prior job */ }
39
- launchctl(["bootstrap", `gui/${process.getuid()}`, PLIST_PATH]);
39
+ // #14661: reload through bootout-wait-bootstrap; a failed bootstrap is an error, not a stack.
40
+ const reloaded = reloadLaunchAgent({ label: CANARY_LABEL, plist: PLIST_PATH, domain: `gui/${process.getuid()}` });
41
+ if (!reloaded.ok) { console.error(reloaded.error); process.exit(1); }
40
42
  console.log(`installed: ${PLIST_PATH}\nruns every day at 09:30; failures post to the ${PROJECT} lane and the app once per episode`);
41
43
  process.exit(0);
42
44
  }
@@ -48,8 +50,41 @@ if (cmd === "uninstall") {
48
50
  process.exit(0);
49
51
  }
50
52
 
53
+ const rows = loadRegistry(process.env.TRANTOR_FEATURES_PATH || undefined);
54
+ const valid = validateRegistry(rows, PROBES);
55
+
56
+ if (cmd === "check") {
57
+ const hash = registryHash(rows);
58
+ if (JSON_MODE) console.log(JSON.stringify({ ...valid, registryHash: hash, rows: rows.length, mapped: rows.filter((r) => r.mapped).length }, null, 2));
59
+ else {
60
+ for (const e of valid.errors) console.log(` ✗ ${e}`);
61
+ console.log(`${rows.length} features, ${rows.filter((r) => r.mapped).length} mapped, registry ${hash.slice(0, 12)}${valid.ok ? ", mappings valid" : `, ${valid.errors.length} malformed`}`);
62
+ }
63
+ process.exit(valid.ok ? 0 : 1);
64
+ }
65
+
66
+ if (cmd === "attach") {
67
+ const at = args.indexOf("--features");
68
+ const featureArg = at >= 0 ? args[at + 1] || "" : "";
69
+ const claims = args.slice(1).filter((a, i, all) => !a.startsWith("--") && all[i - 1] !== "--features");
70
+ const out = attachProbes({ rows, claims, declaredFeatures: featureArg.split(",").map((s) => s.trim()).filter(Boolean) });
71
+ if (JSON_MODE) console.log(JSON.stringify(out, null, 2));
72
+ else {
73
+ console.log(out.probeIds.length ? `required probes: ${out.probeIds.map((p) => `${p} (${out.hosts[p]})`).join(", ")}` : "required probes: none");
74
+ console.log(`features: ${out.features.join(", ") || "none"} registry ${out.registryHash.slice(0, 12)}`);
75
+ for (const p of out.problems) console.log(` ✗ ${p}`);
76
+ }
77
+ process.exit(out.ok && valid.ok ? 0 : 1);
78
+ }
79
+
80
+ if (cmd === "brief") {
81
+ const lines = regressionBrief({ episodes: readEpisodes(busDir()), lastRun: readLastRun(busDir()) });
82
+ console.log(lines.length ? lines.join("\n") : "no open regressions");
83
+ process.exit(0);
84
+ }
85
+
51
86
  if (cmd !== "run") {
52
- console.error("usage: trantor canary [--json] [--daily] | install | uninstall | plist");
87
+ console.error("usage: trantor canary [--json] [--daily] | check | attach <path…> | brief | install | uninstall | plist");
53
88
  process.exit(2);
54
89
  }
55
90
 
@@ -76,25 +111,30 @@ async function post(text) {
76
111
  }
77
112
 
78
113
  const bus = busDir();
79
- const rows = loadRegistry(process.env.TRANTOR_FEATURES_PATH || undefined);
80
114
  const ctx = defaultContext({ busDir: bus, hub: resolveHub(PROJECT), knownProjects, checkoutFor, appRead });
81
115
  const run = await runCanary({ rows, ctx });
116
+ if (!valid.ok) {
117
+ run.results.push({ id: "registry", probeId: "registry", host: "any", feature: "docs/FEATURES.md mappings", status: "fail", detail: valid.errors.join("; ") });
118
+ }
82
119
  const t = tally(run.results);
83
120
 
84
121
  if (DAILY) {
85
122
  const step = advanceEpisodes(readEpisodes(bus), run);
86
123
  const text = episodeMessage(step, run);
87
- const record = { ...run, posted: [] };
124
+ const record = { ...run, posted: [], registryHash: registryHash(rows) };
125
+ const ids = step.announce.map((r) => r.id);
126
+ let episodes = step.episodes;
88
127
  if (text) {
89
- try { await post(text); record.posted = step.announce.map((r) => r.id); }
128
+ try { await post(text); record.posted = ids; episodes = markDelivered(episodes, ids, true); }
90
129
  catch (error) {
91
- // Unannounced episodes stay closed, so tomorrow's run tries again instead of going quiet.
92
- for (const r of step.announce) delete step.episodes[r.id];
130
+ // #14670: the episode stays open marked undelivered, so the next run announces it again and the
131
+ // brief shows the alert never landed, instead of the failure going quiet.
132
+ episodes = markDelivered(episodes, ids, false, error.message);
93
133
  record.postError = error.message;
94
134
  console.error(`canary: could not post: ${error.message}`);
95
135
  }
96
136
  }
97
- recordRun(bus, record, step.episodes);
137
+ recordRun(bus, record, episodes);
98
138
  }
99
139
 
100
140
  if (JSON_MODE) {
package/bin/capacity.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  // Degraded by design: when the hub is unreachable the CLI falls back to the LOCAL provider
7
7
  // balances (same sources `trantor balances` reads) and says it is local-only — machines, seats and
8
8
  // burn rate print unknown, never a guess.
9
- // Usage: trantor capacity [--json]
9
+ // Usage: trantor capacity [--json] [--version 1 [--snapshot <id>]]
10
10
  import { signedGet, sessionContext, relayUrl } from "../hooks/lib/api.mjs";
11
11
  import { fetchBalances, fmtBalance } from "../lib/balances.mjs";
12
12
  import { loadProfile } from "./profile.mjs";
@@ -19,6 +19,22 @@ const asJson = args.includes("--json");
19
19
  const { project } = sessionContext();
20
20
  const hub = relayUrl(project);
21
21
 
22
+ // #14678: --version 1 is the planner's envelope; an unreachable hub gives the cached one, localOnly, no token.
23
+ const versionAt = args.indexOf("--version");
24
+ if (versionAt > -1 && args[versionAt + 1] === "1") {
25
+ const { readCapacity } = await import("../lib/dispatcher/preflight.mjs");
26
+ const { busDir } = await import("../lib/project.mjs");
27
+ const snapshotAt = args.indexOf("--snapshot");
28
+ const envelope = await readCapacity({ get: (path) => signedGet(path, { timeoutMs: 5000, project }), busDir: busDir(), project,
29
+ snapshotId: snapshotAt > -1 ? args[snapshotAt + 1] : null });
30
+ if (asJson) console.log(JSON.stringify(envelope, null, 2));
31
+ else if (envelope.refused) console.log(`hub refused the planning view: ${envelope.code}`);
32
+ else if (envelope.localOnly) console.log(`hub unreachable (${envelope.reason}) — LOCAL ONLY: ${envelope.envelope ? `cached planning view ${Math.round(envelope.sourceAgeMs / 1000)}s old` : "no cached planning view"}; no dispatch token.`);
33
+ else if (!envelope.versioned) console.log("this hub has no planning view yet (it answered with the display ledger); run trantor capacity for that view");
34
+ else console.log(`planning snapshot ${envelope.snapshotId} · policy ${envelope.policyVersion ?? "unknown"}${envelope.degraded?.length ? ` · degraded: ${envelope.degraded.join(", ")}` : ""}`);
35
+ process.exit(envelope.refused ? 1 : 0);
36
+ }
37
+
22
38
  const response = await signedGet(`/capacity?project=${encodeURIComponent(project)}`, { timeoutMs: 5000, project });
23
39
 
24
40
  if (!response.ok && response.status !== 0) {
@@ -36,7 +52,7 @@ if (!response.ok) {
36
52
  const balances = [...detected, ...profileScoped];
37
53
  const reason = response.reason || "unreachable";
38
54
  if (asJson) {
39
- console.log(JSON.stringify({ degraded: "local-only", reason, hub, balances, budgets: null, burn: null, machines: null, seats: null }, null, 2));
55
+ console.log(JSON.stringify({ degraded: "local-only", localOnly: true, reason, hub, balances, budgets: null, burn: null, machines: null, seats: null }, null, 2));
40
56
  } else {
41
57
  console.log(`hub unreachable (${reason}) — LOCAL BALANCES ONLY; machines, seats and burn rate unknown.`);
42
58
  console.log(`hub: ${hub}\n`);
@@ -103,5 +119,7 @@ for (const s of seats) {
103
119
  const live = s.online ? "online" : `last seen ${fmtAge(s.ageMs)}`;
104
120
  const last = s.lastTurn ? `last turn ${fmtAge(s.lastTurn.ageMs)} · ${s.lastTurn.outcome || "unknown"}` : "no turn in 7d";
105
121
  const model = s.model || "cli-default";
106
- console.log(` ${s.session} ${live} · ${model} · ${last}${s.machine ? ` · ${s.machine}` : ""}`);
122
+ const fault = s.fault ? ` · FAULT ${s.fault}: ${s.unconsumedWork?.count || 0} direct message(s) unconsumed for ${fmtAge(s.unconsumedWork?.ageMs)}` : "";
123
+ console.log(` ${s.session} ${live} · ${model} · ${last}${s.machine ? ` · ${s.machine}` : ""}${fault}`);
124
+ if (s.lastTurn?.stderrTail) console.log(` redacted stderr tail:\n${s.lastTurn.stderrTail.split("\n").map(line => ` ${line}`).join("\n")}`);
107
125
  }
package/bin/cli.mjs CHANGED
@@ -30,6 +30,7 @@ switch (cmd) {
30
30
  case "models": run("bin/models.mjs"); break;
31
31
  case "memory": run("bin/memory.mjs"); break;
32
32
  case "advise": run("bin/advise.mjs"); break;
33
+ case "dispatch": run("bin/dispatch.mjs"); break;
33
34
  case "verify": run("bin/crew-verify.mjs"); break;
34
35
  case "up": runCrew(); break;
35
36
  case "open": runCrew(); break;
@@ -38,6 +39,7 @@ switch (cmd) {
38
39
  case "agent-settings": run("bin/agent-settings.mjs"); break;
39
40
  case "adopt": spawn(process.execPath, [join(ROOT, "bin/adopt.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
40
41
  case "integrate": spawn(process.execPath, [join(ROOT, "bin/integrate.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
42
+ case "review": spawn(process.execPath, [join(ROOT, "bin/review.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
41
43
  case "attribution": run("bin/attribution.mjs"); break;
42
44
  case "harvest": run("bin/harvest.mjs"); break;
43
45
  case "sync": run("bin/sync.mjs"); break;
@@ -297,6 +299,7 @@ switch (cmd) {
297
299
  trantor adopt take over a session already running in a Terminal, then open it here
298
300
  trantor takeover the whole move in one command: idle-gate the Terminal session, end it gracefully, adopt, open in the pane — [--force] [--session <id>] [--dry-run]
299
301
  trantor integrate collect the crew's work, merge it, verify it, push it (--dry-run to rehearse)
302
+ trantor review publish publish each seat's diff to the hub for per-hunk review (Mixed mode)
300
303
  trantor harvest receipt for a seat commit you landed on main by hand: harvest <seat-sha> <main-sha> [--card N]
301
304
  trantor sync realign a seat branch with main from the receipts: sync [<seat>] [--dry-run] — refuses and names unharvested commits
302
305
  trantor down tear the crew down (kills processes, closes windows, no dialogs)
@@ -314,10 +317,11 @@ switch (cmd) {
314
317
  trantor new project genesis: new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--json] — creates <parent>/<name>, git main, docs/PRD.md + small CLAUDE.md, hooks, hub brief + first card (never spawns a session)
315
318
  trantor genesis-kickoff internal wake prompt selector from the checkout + signed project board
316
319
  trantor balances how much credit is left on each CONFIGURED provider (from your profile) — refill before you stall — [--json]
317
- trantor capacity the live ledger: budgets and resets, burn rate, machines, seats — [--json]
320
+ trantor capacity the live ledger: budgets and resets, burn rate, machines, seats — [--json] [--version 1 [--snapshot <id>]]
318
321
  trantor recost recompute sub-agent notional cost from on-disk transcripts + reseed the board (repair after upgrade) — [--dry-run]
319
322
  trantor handoff finish this session NOW: write a handoff, open a fresh session that takes over, and close this one (manual baton)
320
- trantor advise ask the Advisor directly (JSON on stdin; --demo to see it)
323
+ trantor advise ask the Advisor directly (JSON on stdin; --demo to see it); {"cards":[...]} asks the hub planner — [--json] [--snapshot <id>] [--policy <v>]
324
+ trantor dispatch admit planned cards through the hub: --decision <id> [--card <n>] · status <attemptId> · preflight — [--json]
321
325
  trantor project this checkout's identity: project [<id>] — records .trantor/project.json so a directory rename cannot orphan the board, pin and sessions
322
326
  project permissions <name> [ask|bypass] — whether <name>'s agents ask before acting or act without asking; no value prints it
323
327
  trantor hub run the hub in the foreground (setup installs it as a service instead)
package/bin/connect.mjs CHANGED
@@ -9,6 +9,7 @@ import { execSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { parseJsonc } from "../lib/jsonc.mjs";
11
11
  import { resolveProjectInfo, resolveHubInfo, gitRoot, writeProjectId, PROJECT_MARKER } from "../lib/project.mjs";
12
+ import { BRIEF_MARKER, upsertBriefBlock } from "../lib/dispatcher/preflight.mjs";
12
13
 
13
14
  const DRY = process.argv.includes("--dry-run");
14
15
  const MCP = join(dirname(dirname(fileURLToPath(import.meta.url))), "mcp.mjs");
@@ -19,9 +20,7 @@ const MCP = join(dirname(dirname(fileURLToPath(import.meta.url))), "mcp.mjs");
19
20
  const PROJECT_INFO = resolveProjectInfo(process.cwd());
20
21
  const PROJECT_AT_CONNECT = PROJECT_INFO.project;
21
22
  const URL_ = resolveHubInfo(PROJECT_AT_CONNECT).url;
22
- // #14536: graft is no longer an agent MCP server (0 calls from Claude sessions in 30 days, a handful
23
- // from seats, ~900 tokens of tool list per turn). The desktop app still runs the graft CLI itself.
24
- // Connect removes the entries older versions wrote.
23
+ // #14536: graft is no longer an agent MCP server; connect removes the entries older versions wrote.
25
24
  // The [mcp_servers.graft] table up to the next table, and the comment line connect wrote for it,
26
25
  // which a later relay env refresh can leave separated from the table.
27
26
  function removeCodexGraft(toml) {
@@ -107,6 +106,14 @@ if (has("codex")) {
107
106
  }
108
107
  report("codex", note, p);
109
108
  }
109
+ // #14678: Codex has no session hook, so the shared orchestrator brief goes in its global instructions file.
110
+ const agentsMd = join(homedir(), ".codex", "AGENTS.md");
111
+ const curMd = existsSync(agentsMd) ? readFileSync(agentsMd, "utf8") : "";
112
+ const nextMd = upsertBriefBlock(curMd);
113
+ if (nextMd !== curMd) {
114
+ if (!DRY) { if (existsSync(agentsMd)) backup(agentsMd); else mkdirSync(dirname(agentsMd), { recursive: true }); writeFileSync(agentsMd, nextMd); }
115
+ report("codex", curMd.includes(BRIEF_MARKER) ? "orchestrator brief refreshed" : "orchestrator brief written", agentsMd);
116
+ }
110
117
  const g = existsSync(p) ? readFileSync(p, "utf8") : "";
111
118
  const ungrafted = removeCodexGraft(g);
112
119
  if (ungrafted !== g) {
@@ -17,6 +17,7 @@ import { signedHeaders } from "../lib/signed-fetch.mjs";
17
17
  import { ensureEnrolled } from "../lib/enroll.mjs";
18
18
  import { redactKeys } from "../lib/redact.mjs";
19
19
  import { writeTurnState } from "../lib/turnstate.mjs";
20
+ import { NON_RUNNABLE_CARD_STATUSES, TURNLESS_AFTER_MS, stampWakeDelivery, turnlessContract } from "../lib/seat-liveness.mjs";
20
21
  import { completeTurnRow, isTurnRow, shipTurnRows } from "../lib/telemetry-ship.mjs";
21
22
  import { alignSeatWorktree, applyWorktreeDeclaration, ensureSeatWorktree, provisioningLines, readWorktreeDeclaration } from "../lib/seat-worktree.mjs";
22
23
  import {
@@ -35,7 +36,7 @@ import {
35
36
  CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
36
37
  } from "../lib/turn-policy.mjs";
37
38
  import { snapshotBeforeCut } from "./cut-snapshot.mjs";
38
- import { ocTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput, codexTurnModel, kimiTurnModel, claudeTurnModel } from "../lib/turn-usage.mjs";
39
+ import { ocTurnUsage, ocSessionId, kimiTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput, codexTurnModel, kimiTurnModel, claudeTurnModel } from "../lib/turn-usage.mjs";
39
40
  import { effortName, isInfraFailure, providerForModel } from "../lib/fitness.mjs";
40
41
  import { capConfig, capDecision, capHandoffPrompt, capPointerLine, capExhaustedNote } from "../lib/context-cap.mjs";
41
42
  import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatPermissionOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
@@ -58,6 +59,7 @@ import {
58
59
  } from "../lib/state/driver.mjs";
59
60
  import { costLine } from "../lib/state/cost.mjs";
60
61
  import { resolveStateFlags, stateFeatureOn } from "../lib/state/flags.mjs";
62
+ import { createWorktreeStatusReporter } from "../lib/worktree-status.mjs";
61
63
 
62
64
  import { awaitSwapRelease } from "./crew/stage.mjs";
63
65
  import { codexRelayFlags } from "./crew/codex-relay.mjs";
@@ -131,6 +133,8 @@ function seatWorktree(sourceDir) {
131
133
  }
132
134
 
133
135
  const TURN_DIR = seatWorktree(DIR);
136
+ const TEST_SANDBOX = /(?:^|\/)test-home-[^/]+(?:\/|$)/.test(DIR);
137
+ const TEST_HUB_DEAD_AFTER_MS = Math.max(100, Number(process.env.TRANTOR_TEST_HUB_DEAD_AFTER_MS) || 120000);
134
138
 
135
139
  // #13921: an explicit contract base wins; without one, fetch the current origin/main instead of
136
140
  // trusting a cached local ref from when this seat worktree was created.
@@ -150,11 +154,7 @@ function ocSid(dir) {
150
154
  // realpath of the /var/... path the runner holds — query both spellings.
151
155
  const dirs = [dir];
152
156
  try { const real = realpathSync(dir); if (real !== dir) dirs.push(real); } catch {}
153
- const list = dirs.map((d) => `'${d.replaceAll("'", "''")}'`).join(", ");
154
- const q = `SELECT id FROM session WHERE directory IN (${list}) ORDER BY time_updated DESC LIMIT 1;`;
155
- const r = spawnSync("sqlite3", ["-readonly", OC_DB, q], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 });
156
- const id = String(r.stdout || "").trim();
157
- return /^ses_[A-Za-z0-9]+$/.test(id) ? id : "";
157
+ return ocSessionId(OC_DB, dirs);
158
158
  } catch { return ""; }
159
159
  }
160
160
  // RUNNER_SESSION override: an orchestrator seat (bin/orchestrate.mjs) runs the same CLI as a crew
@@ -190,6 +190,9 @@ const log = (s) => console.log(`\x1b[38;5;43m[runner]\x1b[0m ${redactKeys(String
190
190
  const LOGDIR = join(homedir(), ".agent-bus", "logs");
191
191
  try { mkdirSync(LOGDIR, { recursive: true }); } catch {}
192
192
  let TURN = releaseState?.turn || 0;
193
+ let lastTurnStartedAt = Number(releaseState?.lastTurnStartedAt) || 0;
194
+ const TURNLESS_MS = Math.max(50, Number(process.env.RUNNER_TURNLESS_MS) || TURNLESS_AFTER_MS);
195
+ let turnlessAlertKey = releaseState?.turnlessAlertKey || "";
193
196
  // #13923: when THIS seat instance started. A seat name is reused across instances and the board's
194
197
  // assignee only knows the name, so the my-cards surfaces (relay_board mine, the own-card reroute)
195
198
  // fence assignments against this stamp — cards assigned before it are a predecessor's (#12138).
@@ -366,6 +369,7 @@ let consecFails = 0;
366
369
  // it every retry costs a turn for every live seat (monitoring doctrine: duration, not repetition).
367
370
  let announced = "";
368
371
  let lastErrText = "";
372
+ let lastFailureTail = "";
369
373
  let lastPermissionReject = null;
370
374
  // #5481: the turn exited 0 with a NULL/empty transcript — the Inception/Mercury trap. The provider
371
375
  // burned its whole max_tokens budget on internal reasoning and returned a null completion; the
@@ -673,9 +677,13 @@ async function balanceRows() {
673
677
  // ---- activity truth (#5965): the RUNNER is the source for this seat ----------------
674
678
  // The runner reports `working · <trigger>` at start and `idle` on a clean landing, bounded to 5s.
675
679
  // #7749: the live phase + its start ride the same call, so /peers answers what the seat does NOW.
676
- // The detached watchdog repeats the working payload once a minute: runTurn blocks this event loop.
677
- const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 60_000);
680
+ // The detached watchdog repeats the working payload every 30s: runTurn blocks this event loop.
681
+ const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 30_000);
678
682
  async function registerStatus(status, extra = {}) {
683
+ if (extra.phase === "working") {
684
+ lastTurnStartedAt = Number(extra.phaseSince) || Date.now();
685
+ turnlessAlertKey = "";
686
+ }
679
687
  const url = HUB + "/register";
680
688
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
681
689
  if (MACHINE_LABEL) payload.machine = MACHINE_LABEL;
@@ -928,7 +936,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
928
936
  await registerStatus(`working · ${trigger}`, { phase: "working", phaseSince: t0 });
929
937
  // #7749: the same boundary on disk — the watchdog refreshes lastBytesAt/lastTranscriptAt while
930
938
  // the turn runs, so a live reader sees the turn advance without waiting for its end.
931
- writeTurnState(PERSONA, PROJ, { turn: TURN, phase: "working", since: t0, card: sessionCard || 0, lastBytesAt: t0, lastTranscriptAt: 0 });
939
+ writeTurnState(PERSONA, PROJ, { turn: TURN, phase: "working", since: t0, card: sessionCard || 0, lastBytesAt: t0, lastTranscriptAt: 0, fault: "", turnless: null, alertDelivery: "" });
932
940
  const pf = join(homedir(), ".agent-bus", `turn-${PERSONA}-${PROJ}.txt`);
933
941
  appendFileSync(pf, "", { flag: "w" }); // truncate
934
942
  appendFileSync(pf, prompt);
@@ -1259,10 +1267,12 @@ exit $turn_exit`;
1259
1267
  // actually carried counts.
1260
1268
  if (c) tokens = c.input + c.output + c.cache_read + c.cache_creation;
1261
1269
  } // #8234: the CLIs that print no usage on stdout keep the counts in their own session records —
1262
- // opencode's db, the session resolved for this turn exactly like the `-s` resume id. Sum this
1263
- // turn's window there; null (unknown) leaves the stdout paths above standing — never 0 ("free").
1270
+ // opencode's db, kimi's wire, the dsh session log. Sum this turn's window there; null (unknown)
1271
+ // leaves the stdout paths above standing — never 0 ("free"). #14663: the sqlite reads go through
1272
+ // node's built-in SQLite (netcup has no sqlite3 binary), else every glm/openrouter turn read ~0.
1264
1273
  const usage = cli.pinned && sid ? ocTurnUsage(OC_DB, sid, t0, Date.now())
1265
1274
  : AGENT === "dsh" ? dshTurnUsage(join(homedir(), ".dsh", "sessions"), TURN_DIR, t0, Date.now())
1275
+ : DRIVER === "kimi" ? kimiTurnUsage(join(homedir(), ".kimi-code", "sessions"), sid, t0, Date.now())
1266
1276
  : null;
1267
1277
  if (usage) tokens = usageTotal(usage);
1268
1278
  // #11559: every token this turn spent rides the card it served. A card-0 turn (kickoff, pulse,
@@ -1320,10 +1330,10 @@ exit $turn_exit`;
1320
1330
  lastNoDelivery = noDelivery;
1321
1331
  lastNoDeliveryStatus = cardStatusAtEnd;
1322
1332
  if (noDelivery) log(`\x1b[33mexit 0 but the turn DELIVERED NOTHING on #${sessionCard} — no new commit, card still ${cardStatusAtEnd || "unknown"}\x1b[0m`);
1323
- // #5868: the verdict rides the telemetry row so a classification survives the pane scrolling
1324
- // away — the same "classified X because Y" shape the runner logs. A silent cut names its own
1325
- // verdict (#7752): the exit under it is the sweep's SIGPIPE. A box cut passes `cut` so its 137
1326
- // reads as the sweep's SIGKILL (#7099); a zero-usage turn names its own verdict too (#9724).
1333
+ // #5868/#14662: the verdict rides telemetry; an unrecognized failure also keeps its redacted
1334
+ // stderr tail on the row and card. A silent cut names its own verdict (#7752): the exit under it
1335
+ // is the sweep's SIGPIPE. A box cut passes `cut` so its 137 reads as SIGKILL (#7099); zero usage
1336
+ // names its own verdict too (#9724).
1327
1337
  const verdict = stallCut ? stallVerdict() : zeroUsage ? zeroUsageVerdict()
1328
1338
  : askVerdict ? askVerdict
1329
1339
  : blockedVerdict ? blockedVerdict
@@ -1335,6 +1345,8 @@ exit $turn_exit`;
1335
1345
  // empty/stalled turns to the card that produced nothing. `cut` stays too: the drills read it.
1336
1346
  const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? (lastPermissionReject ? "rejected" : "api-error") : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
1337
1347
  const finalOutcome = askVerdict ? "asked" : blockedVerdict ? "blocked" : outcome;
1348
+ const failure = effExit !== 0 ? classifyFailure(effExit, ownOut, lastEmptyOutput, lastEmptyTurn, cut) : null;
1349
+ lastFailureTail = failure?.reason === "crashed" ? failure.stderrTail : "";
1338
1350
  const endedAt = Date.now();
1339
1351
  const transcriptModel = DRIVER === "codex" ? codexTurnModel(join(homedir(), ".codex", "sessions"), t0, TURN_DIR)
1340
1352
  : DRIVER === "kimi" ? kimiTurnModel(join(homedir(), ".kimi-code", "sessions"), sid, t0)
@@ -1342,8 +1354,9 @@ exit $turn_exit`;
1342
1354
  // #14654: structured transcript metadata, else the pinned model; free-text model: lines are never read.
1343
1355
  const actualModel = transcriptModel || MODEL || "unknown";
1344
1356
  const telemetryRow = { ts: endedAt, persona: PERSONA, agent: AGENT, project: PROJ, turn: TURN, trigger, card: sessionCard || 0, model: actualModel, duration_ms: endedAt - t0, exit: realExit, effExit, authFailed: effExit !== realExit, emptyOutput: lastEmptyOutput, emptyTurn: lastEmptyTurn, verdict, outcome: finalOutcome, tokens };
1357
+ if (lastFailureTail) telemetryRow.stderrTail = lastFailureTail;
1345
1358
  if (sessionCard > 0) {
1346
- const failure = classifyFailure(effExit, ownOut, lastEmptyOutput, lastEmptyTurn, cut).reason;
1359
+ const failureReason = failure?.reason || classifyFailure(effExit, ownOut, lastEmptyOutput, lastEmptyTurn, cut).reason;
1347
1360
  telemetryRow.attempt = {
1348
1361
  id: `${SESSION}:${t0}:${TURN}`, card: sessionCard, seat: SESSION, project: PROJ,
1349
1362
  provider: providerForModel(DRIVER, actualModel), model: actualModel,
@@ -1351,7 +1364,7 @@ exit $turn_exit`;
1351
1364
  taskKind: cardKind || "unknown", difficulty: cardDifficulty || "unknown",
1352
1365
  machine: MACHINE_LABEL || "unknown", start: new Date(t0).toISOString(), end: new Date(endedAt).toISOString(),
1353
1366
  commit: newCommit ? headAfter : "", outcome: finalOutcome,
1354
- infraFailure: isInfraFailure(finalOutcome, failure), tokens: Number.isFinite(tokens) ? tokens : null,
1367
+ infraFailure: isInfraFailure(finalOutcome, failureReason), tokens: Number.isFinite(tokens) ? tokens : null,
1355
1368
  };
1356
1369
  }
1357
1370
  if (usage) telemetryRow.usage = usage;
@@ -1672,6 +1685,7 @@ async function resolveWakeCard(messages, { session }) {
1672
1685
  const shed = restored.wake.filter(isExpiredHubAlert).length +
1673
1686
  restored.bcast.filter(isExpiredHubAlert).length;
1674
1687
  let pendingWake = restored.wake.filter(shouldWake);
1688
+ stampWakeDelivery(pendingWake);
1675
1689
  let pendingBcast = restored.bcast.filter(m => !isExpiredHubAlert(m) && !isReceipt(m) && !isStatusBroadcast(m));
1676
1690
  if (shed) {
1677
1691
  log(`\x1b[33mdropped ${shed} expired hub staleness alert(s) older than ${Math.round(HUB_ALERT_TTL_MS / 60000)}m — they describe conditions that have long since changed\x1b[0m`);
@@ -1685,6 +1699,16 @@ async function resolveWakeCard(messages, { session }) {
1685
1699
  askReleased = releaseState?.askReleased || false;
1686
1700
  if (pendingWake.length) log(`\x1b[33m${pendingWake.length} message(s) survived from a previous run — redelivering\x1b[0m`);
1687
1701
 
1702
+ const worktreeStatus = createWorktreeStatusReporter({
1703
+ cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: MACHINE_LABEL || hostId(),
1704
+ post: async status => {
1705
+ const result = await api("/worktree-status", status);
1706
+ if (!result?.ok) throw new Error(result?.error || "hub rejected snapshot");
1707
+ },
1708
+ log,
1709
+ });
1710
+ worktreeStatus.start();
1711
+
1688
1712
  // #7060: the turn the boot line was read as a promise about. It is a transcript turn by
1689
1713
  // construction and now says so, in the same breath as the line that armed the mode.
1690
1714
  if (!releaseState) {
@@ -1702,6 +1726,49 @@ async function resolveWakeCard(messages, { session }) {
1702
1726
  await api("/send", { from: SESSION, to: "all", project: PROJ, kind: "status", text }).catch(() => {});
1703
1727
  }
1704
1728
  let lastTurnAt = releaseState?.lastTurnAt || Date.now();
1729
+ async function checkTurnless() {
1730
+ const cardStatuses = {};
1731
+ for (;;) {
1732
+ const candidate = turnlessContract({
1733
+ messages: pendingWake, session: SESSION, nowMs: Date.now(), lastTurnStartedAt,
1734
+ awaitingAsk: !!awaitingAsk, parked: !!parkState,
1735
+ pausedCards: budgetStop ? [budgetStop.card] : [], cardStatuses, stuckAfterMs: TURNLESS_MS,
1736
+ });
1737
+ if (!candidate) return;
1738
+ const key = `${candidate.wakeId}:${candidate.deliveredAt}`;
1739
+ if (turnlessAlertKey === key) return;
1740
+ if (candidate.card && cardStatuses[candidate.card] === undefined) {
1741
+ const status = await api(`/card?project=${encodeURIComponent(PROJ)}&id=${candidate.card}`)
1742
+ .then(r => String(r?.task?.status || "")).catch(() => "");
1743
+ cardStatuses[candidate.card] = status;
1744
+ if (NON_RUNNABLE_CARD_STATUSES.has(status)) continue;
1745
+ }
1746
+ turnlessAlertKey = key;
1747
+ const age = candidate.ageMs >= 60e3 ? `${Math.floor(candidate.ageMs / 60e3)}m` : `${Math.floor(candidate.ageMs / 1000)}s`;
1748
+ const card = candidate.card ? ` card #${candidate.card}` : "";
1749
+ const last = candidate.lastTurnStartedAt ? new Date(candidate.lastTurnStartedAt).toISOString() : "never";
1750
+ const text = `⚠️ ${SESSION} alive-but-turnless — wake #${candidate.wakeId}${card} delivered ${age} ago, no turn started; runner pid ${process.pid}, phase idle, last turn start ${last}. Check wake delivery and the runner process.`;
1751
+ const evidence = { wakeId: candidate.wakeId, card: candidate.card, deliveredAt: candidate.deliveredAt, ageMs: candidate.ageMs, pid: process.pid, lastTurnStartedAt: candidate.lastTurnStartedAt };
1752
+ writeTurnState(PERSONA, PROJ, { phase: "idle", fault: "alive-but-turnless", turnless: evidence, alertDelivery: "sending" });
1753
+ await registerStatus(`FAULT alive-but-turnless · wake #${candidate.wakeId}${card}`, { phase: "idle", fault: "alive-but-turnless" });
1754
+ const orch = `${hostId()}:${PROJ}`;
1755
+ const sender = String(candidate.message.from || "");
1756
+ const to = sender && sender !== SESSION && !sender.startsWith("hub:") ? sender : orch;
1757
+ let delivered = false;
1758
+ try {
1759
+ const response = await api("/send", { from: SESSION, to, text, project: PROJ, kind: "alert" });
1760
+ delivered = !!response && response.ok !== false;
1761
+ } catch {}
1762
+ writeTurnState(PERSONA, PROJ, { alertDelivery: delivered ? "delivered" : "failed" });
1763
+ if (!delivered && candidate.card) {
1764
+ await api("/task/update", { id: candidate.card, by: SESSION,
1765
+ note: `alive-but-turnless: wake #${candidate.wakeId} has had no turn start for ${age}; runner pid ${process.pid}. Alert delivery FAILED; this note and the local turn-state file retain the incident.` }).catch(() => {});
1766
+ }
1767
+ cmuxStatus("turnless", "#ef6a6a", "alert", { alert: true, priority: 90 });
1768
+ log(`${text} · alert delivery ${delivered ? "succeeded" : "FAILED"}`);
1769
+ return;
1770
+ }
1771
+ }
1705
1772
  function restartForRelease() {
1706
1773
  const version = installedVersion();
1707
1774
  if (!newerVersion(version, bootVersion) || attemptedVersions.has(version)) return;
@@ -1717,7 +1784,7 @@ async function resolveWakeCard(messages, { session }) {
1717
1784
  writeFileSync(PENDF, JSON.stringify({ persona: PERSONA, agent: AGENT, project: PROJ, ts: Date.now(),
1718
1785
  wake: pendingWake, bcast: pendingBcast, seen: seenLedger, ask: awaitingAsk?.id || 0, askTo: awaitingAsk?.to || "" }));
1719
1786
  const state = { cursor, turn: TURN, sid, sessionCard, retryAt, deliveryFails,
1720
- noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions], bootTs: BOOT_TS,
1787
+ noDeliveryRetry, askReleased, lastTurnAt, lastTurnStartedAt, turnlessAlertKey, attempted: [...attemptedVersions], bootTs: BOOT_TS,
1721
1788
  cardTokens, cardCommits, cardStartedAt, budgetStop, budgetRetryAt,
1722
1789
  capHandoffs, capLogged, capArmed, capFreshTurn };
1723
1790
  process.execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
@@ -1743,6 +1810,7 @@ async function resolveWakeCard(messages, { session }) {
1743
1810
  log(`machine health heartbeat armed as ${MACHINE_LABEL} every ${Math.round(HEALTH_BEAT_MS / 1000)}s`);
1744
1811
  }
1745
1812
 
1813
+ let hubUnreachableSince = 0;
1746
1814
  while (true) {
1747
1815
  restartForRelease();
1748
1816
  // pulse first: a due mission beat runs even on a silent bus. Measured from the END of the
@@ -1762,6 +1830,7 @@ async function resolveWakeCard(messages, { session }) {
1762
1830
  // is owed but NEVER redelivered. #11559: a budget-paused card paces its own redeliveries on
1763
1831
  // budgetRetryAt - a clock that never delays a poll-delivered contract for a different card.
1764
1832
  if (pendingWake.length && !awaitingAsk && Date.now() >= retryAt && Date.now() >= budgetRetryAt) { await deliverWake(); continue; }
1833
+ await checkTurnless();
1765
1834
  // cap the long-poll hold so neither a due pulse nor a due redelivery waits out a silent 280s window
1766
1835
  const due = [];
1767
1836
  if (PULSE_MS) due.push(PULSE_MS - (Date.now() - lastTurnAt));
@@ -1783,9 +1852,18 @@ async function resolveWakeCard(messages, { session }) {
1783
1852
  // response (stalled event loop, napped machine, dead socket). Reconnect immediately and say
1784
1853
  // so calmly; reserve the scary "hub unreachable" + 5s backoff for real connection failures.
1785
1854
  const expired = e && (e.name === "TimeoutError" || /abort/i.test(String(e.message)));
1855
+ if (TEST_SANDBOX) {
1856
+ hubUnreachableSince ||= Date.now();
1857
+ if (Date.now() - hubUnreachableSince >= TEST_HUB_DEAD_AFTER_MS) {
1858
+ log(`test hub unreachable for ${Math.round((Date.now() - hubUnreachableSince) / 1000)}s — exiting`);
1859
+ process.exit(0);
1860
+ }
1861
+ }
1786
1862
  log(expired ? `long-poll hold expired with no hub response — reconnecting` : `hub unreachable (${e.message}) — retrying in 5s`);
1787
1863
  await new Promise(s => setTimeout(s, expired ? 250 : 5000)); continue;
1788
1864
  }
1865
+ hubUnreachableSince = 0;
1866
+ await worktreeStatus.heartbeat();
1789
1867
  if (!msgs.length) continue; // heartbeat tick, nothing for us
1790
1868
  // never wake on your own broadcasts: a claude seat's report contains "claude:" and matched the
1791
1869
  // @mention filter, buying one echo turn per report (seen live on the first pulsed orchestrator)
@@ -1854,6 +1932,7 @@ async function resolveWakeCard(messages, { session }) {
1854
1932
  if (!wake.length) { if (freshBatch.kept.length) { savePending(pendingWake, pendingBcast); log(`${freshBatch.kept.length} broadcast(s) batched (no wake) — ${pendingBcast.length} pending`); } continue; }
1855
1933
  // Queue BEFORE running the turn, and persist immediately. Everything between here and a clean
1856
1934
  // exit 0 — the CLI dying, the machine losing power — now leaves a record of what this seat owes.
1935
+ stampWakeDelivery(wake);
1857
1936
  pendingWake.push(...wake);
1858
1937
  if (pendingWake.length > PENDING_MAX) {
1859
1938
  const dropped = pendingWake.splice(0, pendingWake.length - PENDING_MAX);
@@ -2224,6 +2303,10 @@ async function resolveWakeCard(messages, { session }) {
2224
2303
  if (reason === "exhausted") quotaReset = quotaResetAt(rows);
2225
2304
  }
2226
2305
  savePending(pendingWake, pendingBcast);
2306
+ if (reason === "crashed" && lastFailureTail && sessionCard > 0) {
2307
+ const note = `turn failed with an unrecognized error (exit ${ec}); redacted stderr tail:\n${lastFailureTail.slice(-1600)}`;
2308
+ await api("/task/update", { id: sessionCard, note, by: SESSION }).catch(() => {});
2309
+ }
2227
2310
  await reportFailure(ec, "message", pendingWake.length, reason);
2228
2311
  // #6289: TWO consecutive failed turns on one contract PARK the seat — "stalled" for a
2229
2312
  // silent chain (#7752), time-box when the chain died to cuts, api-error otherwise —
package/bin/disk.mjs CHANGED
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { mkdirSync, writeFileSync } from "node:fs";
9
9
  import { homedir, platform, userInfo } from "node:os";
10
10
  import { runDisk, formatHuman, launchdPlist, diskSummary } from "../lib/disk.mjs";
11
+ import { reloadLaunchAgent } from "../lib/launchd.mjs";
11
12
 
12
13
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
13
14
 
@@ -40,11 +41,13 @@ async function install() {
40
41
  mkdirSync(dirname(logPath), { recursive: true });
41
42
  writeFileSync(plistPath, launchdPlist({ scriptPath: join(ROOT, "bin", "disk.mjs"), logPath }));
42
43
  const uid = userInfo().uid;
43
- exec("launchctl", ["bootout", `gui/${uid}/com.trantor.disk`]);
44
- const r = exec("launchctl", ["bootstrap", `gui/${uid}`, plistPath]);
45
- if (r.status !== 0) {
46
- // bootout+bootstrap can race an existing job; load -w is the legacy fallback.
47
- exec("launchctl", ["load", "-w", plistPath]);
44
+ // #14661: reload through bootout-wait-bootstrap; if launchd still refuses, the legacy load -w is
45
+ // the fallback — and a bootstrap that fails BOTH ways is an error, never a quiet "installed".
46
+ const launchctl = (argv) => { const r = exec("launchctl", argv); return { status: r.status ?? 1, stdout: String(r.stdout || "") }; };
47
+ const reloaded = reloadLaunchAgent({ label: "com.trantor.disk", plist: plistPath, domain: `gui/${uid}`, launchctl });
48
+ if (!reloaded.ok && exec("launchctl", ["load", "-w", plistPath]).status !== 0) {
49
+ console.error(`trantor disk install: launchctl refused ${plistPath} (bootstrap and load -w both failed) — the daily job is NOT installed`);
50
+ process.exit(1);
48
51
  }
49
52
  console.log(`installed: ${plistPath}\nruns every day at 09:00 (safe tier only); result lands as one bus message. Log: ${logPath}`);
50
53
  }