trantor 0.18.128 → 0.18.129

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.128",
3
+ "version": "0.18.129",
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
@@ -521,6 +521,11 @@ npm test # unit + 120+ protocol-level scenario drills + capability-routing, a
521
521
  # difficulty-aware model selection, deps validation, virgin-machine doctor, failure drills
522
522
  ```
523
523
 
524
+ Heavy gates share one machine-wide semaphore: full suites, desktop Vitest, and Cargo test/build.
525
+ The default is `max(1, floor(cores / 4))` slots; set `"heavyGateSlots": 4` in
526
+ `~/.agent-bus/config.json` to override it. Crew runners wire Cargo and package-runner shims into
527
+ each seat. For a heavy command outside a runner, use `node bin/heavy-gate.mjs -- <command> …`.
528
+
524
529
  ## License
525
530
 
526
531
  [MIT](./LICENSE) © 2026 Sasha Bogojevic · Built with [Claude Code](https://claude.com/claude-code) ·
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { constants } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+
6
+ const args = process.argv.slice(2);
7
+ const shimDir = resolve(import.meta.dirname, "heavy-gate-shim");
8
+ const path = (process.env.PATH || "").split(":").filter(entry => resolve(entry) !== shimDir).join(":");
9
+ const env = { ...process.env, PATH: path };
10
+ const heavy = args.includes("test") || args.includes("build");
11
+ const result = heavy
12
+ ? spawnSync(process.execPath, [join(import.meta.dirname, "heavy-gate.mjs"), "--", "cargo", ...args], { env, stdio: "inherit" })
13
+ : spawnSync("cargo", args, { env, stdio: "inherit" });
14
+ if (result.error) {
15
+ console.error(`cargo-gate: ${result.error.message}`);
16
+ process.exit(127);
17
+ }
18
+ if (result.signal) process.exit(128 + (constants.signals[result.signal] || 0));
19
+ process.exit(result.status ?? 1);
@@ -2,7 +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 { readFileSync, writeFileSync, unlinkSync, existsSync, appendFileSync, mkdirSync, realpathSync, statSync } from "node:fs";
5
+ import { readFileSync, writeFileSync, unlinkSync, existsSync, appendFileSync, mkdirSync, realpathSync, statSync, rmSync } from "node:fs";
6
6
  import { join, basename } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { resolveProject, resolveHub, withEnvFiles, hostId } from "../lib/project.mjs";
@@ -509,6 +509,21 @@ let parkAnnounced = false;
509
509
  // #7914: the park this seat is currently sitting in, or null. Read by the poll loop, which ends a
510
510
  // bounded one the moment somebody sends a direct message, and cleared by any turn that lands.
511
511
  let parkState = null;
512
+ // #13949: unpark already told the room the episode ended, so the next reportHealthy must not echo
513
+ // a second "recovered" for the same landing. Consumed on every reportHealthy call, used or not.
514
+ let parkRecovered = false;
515
+ // #13949: is this park call the START of an episode or a retry inside a live one? A window-lift
516
+ // retry that parks AGAIN for the same reason never left the episode, and the room already holds
517
+ // its one notice — re-sending it every window is how one park became 10 identical DMs (#13949).
518
+ // Read BEFORE parkSeat, which overwrites parkState.
519
+ const sameParkEpisode = (reason) => !!(parkState && parkState.reason === reason);
520
+ // #13949: a park notice owes its reader the END of the wait, not only its cause — a bounded park
521
+ // names the resume clock (and the shortcut), a wall says it holds. Read after parkSeat sets it.
522
+ function parkLifts() {
523
+ return parkState?.bounded
524
+ ? ` · resumes ${new Date(parkState.until).toLocaleTimeString()} (a direct message ends it now)`
525
+ : " — not retrying";
526
+ }
512
527
  // #13474: uncommitted work in the seat worktree is saved on the seat branch when a turn is cut or
513
528
  // the seat parks, so the next seat starts from it. One log line, only when something was saved.
514
529
  function saveWipLogged(why) {
@@ -518,6 +533,7 @@ function saveWipLogged(why) {
518
533
  }
519
534
 
520
535
  async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", announce = true } = {}) {
536
+ const renewed = sameParkEpisode(reason); // #13949: a retry re-parking inside a live episode
521
537
  saveWipLogged(`parked: ${reason}`);
522
538
  // A seat that went QUIET printed no wall message to parse (#6131), so its own balance row is the
523
539
  // only place the reset time exists. Output first when there is any: it is this turn's evidence.
@@ -547,8 +563,9 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", ann
547
563
  }
548
564
  log(`\x1b[31mparked (${reason})${when ? ` — retrying after ${when}` : " — no reset time in the output; waiting for a restart"}${evidence ? `\n evidence: ${evidence}` : ""}\x1b[0m`);
549
565
  // The alarm for "the bus is stuck" cannot itself be a bus message, so a park also rings a bell
550
- // the operator can hear out of band, once per park.
551
- notifyOperator(`Trantor: ${SESSION} PARKED (${reason})`,
566
+ // the operator can hear out of band — once per EPISODE (#13949): a window-lift retry that
567
+ // re-parks is the same silence continuing, not a new one starting.
568
+ if (!renewed) notifyOperator(`Trantor: ${SESSION} PARKED (${reason})`,
552
569
  `${undelivered} message(s) held${when ? ` — retrying after ${when}` : ` — needs \`trantor up ${AGENT}\``}`);
553
570
  // #7749: parked is a first-class phase — the file and the peer row both say so, so an
554
571
  // orchestrator stops confusing a quota-held seat with a working or a dead one.
@@ -562,12 +579,21 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", ann
562
579
  // #7914: the park is over — because a direct message asked for a turn now, or because one landed.
563
580
  // The record goes with it, and the announce latch reopens so the NEXT park is heard too (a latch
564
581
  // that never reopens turns a repeating park into one message and then silence).
565
- function unpark(why) {
582
+ // #13949: the END is an event too, once — one "recovered" each to the room and the orchestrator.
583
+ async function unpark(why) {
566
584
  if (!parkState) return;
567
- log(`\x1b[33mpark ended (${parkState.reason}) — ${why}\x1b[0m`);
585
+ const { reason, ts } = parkState;
586
+ log(`\x1b[33mpark ended (${reason}) — ${why}\x1b[0m`);
568
587
  parkState = null;
569
588
  parkAnnounced = false;
570
589
  try { unlinkSync(PARKF); } catch {}
590
+ const durMs = Date.now() - (Number(ts) || Date.now());
591
+ const dur = durMs >= 120_000 ? `${Math.round(durMs / 60_000)}m` : `${Math.max(1, Math.round(durMs / 1000))}s`;
592
+ const text = `✅ ${SESSION} recovered — ${reason} park over after ${dur} (${why})`;
593
+ await api("/send", { from: SESSION, to: "all", text, project: PROJ, kind: "status" }).catch(() => {});
594
+ const orch = `${hostId()}:${PROJ}`;
595
+ if (orch !== SESSION) await api("/send", { from: SESSION, to: orch, text, project: PROJ, kind: "alert" }).catch(() => {});
596
+ parkRecovered = true;
571
597
  }
572
598
 
573
599
  /**
@@ -672,13 +698,17 @@ async function busActivitySince(seq) {
672
698
  }
673
699
 
674
700
  async function reportHealthy() {
701
+ const saidParkRecovered = parkRecovered;
702
+ parkRecovered = false; // #13949: consumed whether used or not — never a stale skip
675
703
  if (consecFails === 0) return; // already healthy — don't spam
676
704
  consecFails = 0;
677
705
  // Recovery is a change too, so the next failure is news again — a park included.
678
706
  announced = "";
679
707
  parkAnnounced = false;
680
708
  await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
681
- await api("/send", { from: SESSION, to: "all", text: `✅ ${SESSION} recovered`, project: PROJ, kind: "status" }).catch(() => {});
709
+ // #13949: a landing that ended a park already said "recovered" once, with the reason and the
710
+ // duration — the ladder's echo would be the second recovery message for one event.
711
+ if (!saidParkRecovered) await api("/send", { from: SESSION, to: "all", text: `✅ ${SESSION} recovered`, project: PROJ, kind: "status" }).catch(() => {});
682
712
  cmuxStatus("ok", "#14b8a6", "check"); herdrAgent("idle");
683
713
  }
684
714
 
@@ -931,6 +961,8 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
931
961
  // ONE stall report, never a kill. #6206: floor 10 min, never derived from TRANTOR_TURN_MAX_MS.
932
962
  const WD_MS = Number(process.env.TRANTOR_TURN_WATCHDOG_MS) || 10 * 60 * 1000;
933
963
  const STAMPF = join(homedir(), ".agent-bus", `turnstamp-${PERSONA}-${PROJ}.json`);
964
+ const HEAVY_WAIT_DIR = join(homedir(), ".agent-bus", `heavy-gate-wait-${PERSONA}-${PROJ}`);
965
+ rmSync(HEAVY_WAIT_DIR, { recursive: true, force: true });
934
966
  // #6206: the CLI's transcript dir (a missing dir is a quiet channel), exported so a drill's fake
935
967
  // CLI can write lines the watchdog sees. CUTF is written by the shell's time box: cut, not crashed.
936
968
  const CUTF = join(homedir(), ".agent-bus", `turncut-${PERSONA}-${PROJ}`);
@@ -946,7 +978,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
946
978
  const EXTF = join(homedir(), ".agent-bus", `turnext-${PERSONA}-${PROJ}`);
947
979
  try { unlinkSync(DEADLINEF); } catch {}
948
980
  try { unlinkSync(EXTF); } catch {}
949
- const boxPlan = TURN_EXTENSIONS_MAX ? {
981
+ const boxPlan = TURN_MAX_MS ? {
950
982
  maxMs: TURN_MAX_MS, extendMs: TURN_EXTEND_MS, ceilingMs: TURN_CEILING_MS, extensionsMax: TURN_EXTENSIONS_MAX,
951
983
  deadlineFile: DEADLINEF, extFile: EXTF, card: sessionCard || 0,
952
984
  assigners: (opts.assigners || []).map(a => ({ from: a.from, id: a.id })),
@@ -970,7 +1002,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
970
1002
  // end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
971
1003
  TURN_MAX_MS ? STALLF : "",
972
1004
  // #7749: the turn-state file the watchdog refreshes mid-turn (lastBytesAt/lastTranscriptAt).
973
- join(homedir(), ".agent-bus", `turnstate-${PERSONA}-${PROJ}.json`)],
1005
+ join(homedir(), ".agent-bus", `turnstate-${PERSONA}-${PROJ}.json`), HEAVY_WAIT_DIR],
974
1006
  { detached: true, stdio: "ignore" });
975
1007
  WD_CHILD = wd;
976
1008
  wd.unref();
@@ -1032,6 +1064,8 @@ exit $turn_exit`;
1032
1064
  // A runner-managed seat must never hand itself a baton: the runner is its lifecycle manager,
1033
1065
  // so a handoff spawn would only leak an unmanaged interactive window.
1034
1066
  TRANTOR_NO_HANDOFF_SPAWN: "1", TRANTOR_NO_BATON_SPAWN: "1",
1067
+ TRANTOR_HEAVY_GATE_WAIT_DIR: HEAVY_WAIT_DIR,
1068
+ PATH: `${join(import.meta.dirname, "heavy-gate-shim")}:${process.env.PATH || ""}`,
1035
1069
  // #6206: the seat's transcript dir — a real CLI ignores it, a drill's fake CLI writes
1036
1070
  // its transcript lines there so the watchdog sees the liveness a real claude shows.
1037
1071
  TRANTOR_TRANSCRIPT_DIR: TRANSCRIPT_DIR };
@@ -1041,16 +1075,12 @@ exit $turn_exit`;
1041
1075
  if (cli.pinned && OC_SEAT_CONFIG) spawnEnv.OPENCODE_CONFIG_CONTENT = OC_SEAT_CONFIG;
1042
1076
  spawnOpts.env = spawnEnv;
1043
1077
  spawnOpts.maxBuffer = 16 * 1024 * 1024;
1044
- // The timeout signals the shell to snapshot before sweeping, just like the normal box.
1045
- // Its 30s margin keeps it out of the normal cut path.
1046
- if (TURN_MAX_MS) { spawnOpts.timeout = (TURN_EXTENSIONS_MAX ? TURN_CEILING_MS : TURN_MAX_MS) + 30000; spawnOpts.killSignal = "SIGTERM"; }
1047
1078
  const r = spawnSync("/bin/bash", ["-c", shell], spawnOpts);
1048
- // The shell's box leaves the marker; the backstop leaves an ETIMEDOUT. Either way the turn was
1049
- // cut, not merely failed. A stall marker (#7752) outranks the box marker: a turn silent for
1050
- // the whole window is a stall however the sweep found it.
1079
+ // A stall marker (#7752) outranks the box marker: a turn silent for the whole window is a stall
1080
+ // however the sweep found it. Heavy-gate waits move DEADLINEF instead of feeding a Node timeout.
1051
1081
  const boxed = existsSync(CUTF);
1052
1082
  const stallCut = existsSync(STALLF);
1053
- const cut = !!TURN_MAX_MS && (boxed || stallCut || r.error?.code === "ETIMEDOUT");
1083
+ const cut = !!TURN_MAX_MS && (boxed || stallCut);
1054
1084
  // #7761: how far the watchdog moved the box, one EXTF row per extension. boxMs is the box the
1055
1085
  // turn actually had, so a ceiling cut reads as the ceiling, never as the 20-minute default.
1056
1086
  let extensions = 0;
@@ -1075,8 +1105,8 @@ exit $turn_exit`;
1075
1105
  try { unlinkSync(CUTF); } catch {}
1076
1106
  try { unlinkSync(STALLF); } catch {}
1077
1107
  if (stallCut) log(`\x1b[33mturn STALLED — no bytes on either stream and no transcript advance for ${Math.round(WD_MS / 60000)}m; ended at the stall window, not the ${Math.round(TURN_MAX_MS / 1000)}s box\x1b[0m`);
1078
- else if (extensions) log(`\x1b[33mturn cut at the ${Math.round(boxMs / 1000)}s box after ${extensions} liveness extension(s) (ceiling ${Math.round(TURN_CEILING_MS / 1000)}s) — CLI and every descendant ended${boxed ? "" : " (node backstop: bash itself was wedged)"}\x1b[0m`);
1079
- else log(`\x1b[33mturn cut at the ${Math.round(TURN_MAX_MS / 1000)}s time box — CLI and every descendant ended${boxed ? "" : " (node backstop: bash itself was wedged)"}\x1b[0m`);
1108
+ else if (extensions) log(`\x1b[33mturn cut at the ${Math.round(boxMs / 1000)}s box after ${extensions} liveness extension(s) (ceiling ${Math.round(TURN_CEILING_MS / 1000)}s) — CLI and every descendant ended\x1b[0m`);
1109
+ else log(`\x1b[33mturn cut at the ${Math.round(TURN_MAX_MS / 1000)}s time box — CLI and every descendant ended\x1b[0m`);
1080
1110
  }
1081
1111
  lastTurnCut = cut;
1082
1112
  lastTurnStalled = cut && stallCut;
@@ -1739,12 +1769,12 @@ async function resolveWakeCard(messages, { session }) {
1739
1769
  // #10197: no-delivery owes the old contract, but its retry delay must not batch away
1740
1770
  // fresh contracts. Only actual CLI failures impose backoff on a new wake.
1741
1771
  if (noDeliveryRetry) {
1742
- unpark("new wake after no-delivery");
1772
+ await unpark("new wake after no-delivery");
1743
1773
  retryAt = 0; deliveryFails = 0; noDeliveryRetry = false;
1744
1774
  }
1745
1775
  if (parkState && directWake.length) {
1746
1776
  if (isBoundedPark(parkState.reason)) {
1747
- unpark(`direct message from ${directWake[0].from || "?"}`);
1777
+ await unpark(`direct message from ${directWake[0].from || "?"}`);
1748
1778
  retryAt = 0; deliveryFails = 0; cutChain = [];
1749
1779
  } else {
1750
1780
  log(`\x1b[33mparked (${parkState.reason}) — a direct message cannot clear this park; it holds until the reset or \`trantor up ${AGENT}\`\x1b[0m`);
@@ -2049,8 +2079,9 @@ async function resolveWakeCard(messages, { session }) {
2049
2079
  const text = `⛔ permission rejected: ${lastPermissionReject.tool} on #${sessionCard} · ${lastPermissionReject.evidence} · card moved to blocked; wake stays owed`;
2050
2080
  savePending(pendingWake, pendingBcast);
2051
2081
  await api("/task/update", { id: sessionCard, status: "blocked", note: text, by: SESSION }).catch(() => {});
2082
+ const renewed = sameParkEpisode("permission-rejected"); // #13949: once per episode
2052
2083
  retryAt = await parkSeat("permission-rejected", pendingWake.length, 0, { announce: false });
2053
- await notifyAssigners(assigners, text);
2084
+ if (!renewed) await notifyAssigners(assigners, text);
2054
2085
  lastTurnAt = Date.now();
2055
2086
  return;
2056
2087
  }
@@ -2084,6 +2115,7 @@ async function resolveWakeCard(messages, { session }) {
2084
2115
  const stallWhy = reason === "stalled" ? ` · probable cause: ${stallCause({ text: lastErrText })}` : "";
2085
2116
  const evidence = cutChain.length >= CUT_CHAIN_PARK_MIN ? cutChainEvidence(cutChain) : "";
2086
2117
  if (PARKING_REASONS.has(reason) || deliveryFails >= 2) {
2118
+ const renewed = sameParkEpisode(parkReason); // #13949: a window-lift retry re-parking
2087
2119
  retryAt = await parkSeat(parkReason, pendingWake.length, quotaReset, { evidence });
2088
2120
  // RUNNER_PARK_MAX_MS is set only by `trantor duty up` (launchd keepalive): past the ceiling,
2089
2121
  // exit so the supervisor restarts clean. Unsupervised seats stay parked; exiting would kill them.
@@ -2098,15 +2130,16 @@ async function resolveWakeCard(messages, { session }) {
2098
2130
  }
2099
2131
  // #7914: what the park is, when it lifts, and the evidence it rests on — in the message
2100
2132
  // that reaches the one who is actually blocked, not only in the card log they never read.
2101
- const lifts = parkState?.bounded
2102
- ? ` · resumes ${new Date(parkState.until).toLocaleTimeString()} (a direct message ends it now)`
2103
- : " — not retrying";
2104
- // The lift time goes BEFORE the evidence: the transport caps the line, and what the reader
2105
- // has to act on must never be the part that gets eaten.
2106
- await notifyAssigners(assigners,
2107
- reason === "stalled"
2108
- ? `⛔ your contract is PARKED on ${SESSION} (stalled: two turns silent for the whole watchdog window)${lifts}${stallWhy} · asked: "${asked}"`
2109
- : `⛔ your contract is PARKED on ${SESSION} (${parkReason})${lifts}${evidence ? ` · ${evidence}` : ""} · asked: "${asked}"`);
2133
+ // #13949: once per episode — the retries inside it are state, not events.
2134
+ const lifts = parkLifts();
2135
+ if (!renewed) {
2136
+ // The lift time goes BEFORE the evidence: the transport caps the line, and what the reader
2137
+ // has to act on must never be the part that gets eaten.
2138
+ await notifyAssigners(assigners,
2139
+ reason === "stalled"
2140
+ ? `⛔ your contract is PARKED on ${SESSION} (stalled: two turns silent for the whole watchdog window)${lifts}${stallWhy} · asked: "${asked}"`
2141
+ : `⛔ your contract is PARKED on ${SESSION} (${parkReason})${lifts}${evidence ? ` · ${evidence}` : ""} · asked: "${asked}"`);
2142
+ }
2110
2143
  lastTurnAt = Date.now();
2111
2144
  return;
2112
2145
  }
@@ -2137,9 +2170,12 @@ async function resolveWakeCard(messages, { session }) {
2137
2170
  savePending(pendingWake, pendingBcast);
2138
2171
  const still = lastNoDeliveryStatus || "unresolved";
2139
2172
  if (deliveryFails >= 2) {
2173
+ // #13949: every window-lift retry inside the episode re-parks HERE. The one notice went
2174
+ // out when the episode started; these retries are state, never another DM.
2175
+ const renewed = sameParkEpisode("no-delivery");
2140
2176
  retryAt = await parkSeat("no-delivery", pendingWake.length);
2141
- await notifyAssigners(assigners,
2142
- `⛔ your contract is PARKED on ${SESSION} (no-delivery: two exit-0 turns with no commit and card #${sessionCard} unmoved) · asked: "${asked}"`);
2177
+ if (!renewed) await notifyAssigners(assigners,
2178
+ `⛔ your contract is PARKED on ${SESSION} (no-delivery: two exit-0 turns with no commit and card #${sessionCard} unmoved)${parkLifts()} · asked: "${asked}"`);
2143
2179
  lastTurnAt = Date.now();
2144
2180
  return;
2145
2181
  }
@@ -2155,9 +2191,10 @@ async function resolveWakeCard(messages, { session }) {
2155
2191
  deliveryFails++;
2156
2192
  savePending(pendingWake, pendingBcast);
2157
2193
  if (deliveryFails >= 2) {
2194
+ const renewed = sameParkEpisode("empty-turn"); // #13949: retries inside the episode stay quiet
2158
2195
  retryAt = await parkSeat("empty-turn", pendingWake.length);
2159
- await notifyAssigners(assigners,
2160
- `⛔ your contract is PARKED on ${SESSION} (empty-turn: two exit-0 turns with no worktree change, substantive output or bus activity) · asked: "${asked}"`);
2196
+ if (!renewed) await notifyAssigners(assigners,
2197
+ `⛔ your contract is PARKED on ${SESSION} (empty-turn: two exit-0 turns with no worktree change, substantive output or bus activity)${parkLifts()} · asked: "${asked}"`);
2161
2198
  lastTurnAt = Date.now();
2162
2199
  return;
2163
2200
  }
@@ -2168,7 +2205,7 @@ async function resolveWakeCard(messages, { session }) {
2168
2205
  `🫥 EMPTY turn on ${SESSION} (exit 0, ${secs}s — no worktree change, no substantive output, no bus activity) · wake stays owed · retrying in ${Math.round(wait / 1000)}s · asked: "${asked}"`);
2169
2206
  } else {
2170
2207
  pendingWake = []; pendingBcast = []; deliveryFails = 0; retryAt = 0;
2171
- unpark("a turn landed"); // #7914: the seat is working again — the park record must not outlive it
2208
+ await unpark("a turn landed"); // #7914: the seat is working again — the park record must not outlive it
2172
2209
  // #7778: reconcile BEFORE the write below so the persisted snapshot carries the seen-set.
2173
2210
  await reconcileSessionReads(cursor);
2174
2211
  savePending([], []);
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ exec node "$(dirname "$0")/../cargo-gate.mjs" "$@"
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ exec node "$(dirname "$0")/../package-runner-gate.mjs" npx "$@"
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ exec node "$(dirname "$0")/../package-runner-gate.mjs" pnpm "$@"
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runHeavyGate } from "../lib/heavy-gate.mjs";
3
+
4
+ process.exit(runHeavyGate(process.argv.slice(2)));
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { constants } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+
6
+ const [tool, ...args] = process.argv.slice(2);
7
+ const shimDir = resolve(import.meta.dirname, "heavy-gate-shim");
8
+ const path = (process.env.PATH || "").split(":").filter(entry => resolve(entry) !== shimDir).join(":");
9
+ const env = { ...process.env, PATH: path };
10
+ const heavy = args.some((arg, index) => arg === "vitest" && args[index + 1] === "run");
11
+ const result = heavy
12
+ ? spawnSync(process.execPath, [join(import.meta.dirname, "heavy-gate.mjs"), "--", tool, ...args], { env, stdio: "inherit" })
13
+ : spawnSync(tool, args, { env, stdio: "inherit" });
14
+ if (result.error) {
15
+ console.error(`package-runner-gate: ${result.error.message}`);
16
+ process.exit(127);
17
+ }
18
+ if (result.signal) process.exit(128 + (constants.signals[result.signal] || 0));
19
+ process.exit(result.status ?? 1);
@@ -9,8 +9,9 @@ import { sessionActivityReader } from "../lib/session-liveness.mjs";
9
9
  import { hostId } from "../lib/project.mjs";
10
10
  import { signedPost } from "../hooks/lib/api.mjs";
11
11
  import { refreshTurnLiveness } from "../lib/turnstate.mjs";
12
+ import { readHeavyGateWait } from "../lib/heavy-gate-wait.mjs";
12
13
 
13
- const [stampFile, errFile, windowMsRaw, session, project, hub, transcriptDir = "", workDir = "", stallFile = "", turnStateFile = ""] = process.argv.slice(2);
14
+ const [stampFile, errFile, windowMsRaw, session, project, hub, transcriptDir = "", workDir = "", stallFile = "", turnStateFile = "", heavyWaitDir = ""] = process.argv.slice(2);
14
15
  // SAFETY: the 10-minute floor lives in crew-runner.mjs (the default when TRANTOR_TURN_WATCHDOG_MS
15
16
  // is unset); this fallback only covers a missing argument. Drills pass tiny windows on purpose.
16
17
  const windowMs = Number(windowMsRaw) || 10 * 60 * 1000;
@@ -30,7 +31,7 @@ function newestMtime(dir) {
30
31
  let rows = [];
31
32
  try { rows = readdirSync(d, { withFileTypes: true }); } catch { return; }
32
33
  for (const e of rows) {
33
- if (++seen > SCAN_CAP || e.name === ".git" || e.name === "node_modules") continue;
34
+ if (++seen > SCAN_CAP || e.name === ".git" || e.name === "node_modules" || e.name === ".agent-bus") continue;
34
35
  const p = join(d, e.name);
35
36
  if (e.isDirectory()) walk(p);
36
37
  else { try { best = Math.max(best, statSync(p).mtimeMs); } catch {} }
@@ -98,9 +99,10 @@ function reportLiveness(now, tr) {
98
99
 
99
100
  // #7752 kill mode: poll liveness; a whole window silent on EVERY channel writes the stall marker
100
101
  // (the shell box sweeps on it), reports once, exits; stderr is measured ROLLING (bytes this window).
101
- // #7761: `armed.box` (step, ceiling, assigners) exists only when a ceiling above the box does; a
102
- // deadline one poll away on a turn that moved within the window is pushed out one step.
103
- const box = stallFile && armed.box && Number(armed.box.extensionsMax) > 0 ? armed.box : null;
102
+ // #7761: `armed.box.extensionsMax` enables liveness extensions; heavy-gate waits move the deadline
103
+ // in both modes, and a deadline one poll away on a moving turn is pushed out one step.
104
+ const timeBox = stallFile && armed.box ? armed.box : null;
105
+ const box = timeBox && Number(timeBox.extensionsMax) > 0 ? timeBox : null;
104
106
  const mins = (ms) => `${Math.max(1, Math.round(ms / 60000))}m`;
105
107
  const secsOrMins = (ms) => (ms >= 60000 ? mins(ms) : `${Math.round(ms / 1000)}s`);
106
108
  async function tellExtension(text) {
@@ -117,7 +119,7 @@ async function tellExtension(text) {
117
119
  if (stallFile) {
118
120
  const poll = Math.max(250, Math.min(windowMs / 4, 10000));
119
121
  let lastErrAt = armedAt;
120
- let deadline = armedAt + (box ? Number(box.maxMs) : 0);
122
+ let deadline = armedAt + (timeBox ? Number(timeBox.maxMs) : 0);
121
123
  let extensions = 0;
122
124
  for (;;) {
123
125
  await sleep(poll);
@@ -125,6 +127,11 @@ if (stallFile) {
125
127
  if (!s || s.turn !== armed.turn || (armed.runner && s.runner !== armed.runner)) process.exit(0); // turn ended, or a NEWER runner owns the stamp now
126
128
  if (!runnerAlive()) process.exit(0); // our runner is gone — never speak for it
127
129
  const now = Date.now();
130
+ const heavyWait = readHeavyGateWait(heavyWaitDir, now);
131
+ if (timeBox) {
132
+ deadline = armedAt + Number(timeBox.maxMs) + heavyWait.totalMs + extensions * Number(timeBox.extendMs);
133
+ try { writeFileSync(timeBox.deadlineFile, String(Math.floor(deadline / 1000))); } catch {}
134
+ }
128
135
  const size = errSize();
129
136
  if (size > baseErr + 200) { baseErr = size; lastErrAt = now; } // new bytes: alive
130
137
  const freshCut = Math.max(armedAt, now - windowMs - SLACK);
@@ -132,6 +139,7 @@ if (stallFile) {
132
139
  const cli = sessionActivity();
133
140
  const wk = workDir ? newestMtime(workDir) : 0;
134
141
  reportLiveness(now, Math.max(tr, cli));
142
+ if (heavyWait.waiting) { lastErrAt = now; continue; }
135
143
  if (tr > freshCut || cli > freshCut || wk > freshCut || now - lastErrAt < windowMs) { // producing work: alive
136
144
  if (box && extensions < Number(box.extensionsMax) && now + poll + SLACK >= deadline) {
137
145
  extensions++;
@@ -168,6 +176,7 @@ for (;;) {
168
176
  const cli = sessionActivity();
169
177
  const wk = workDir ? newestMtime(workDir) : 0;
170
178
  reportLiveness(Date.now(), Math.max(tr, cli));
179
+ if (readHeavyGateWait(heavyWaitDir).waiting) continue;
171
180
  if (errSize() > baseErr + 200 || tr > freshCut || cli > freshCut || wk > freshCut) continue; // producing work: alive, re-arm
172
181
  const mins = Math.round((Date.now() - armedAt) / 60000);
173
182
  const orch = `${hostId()}:${project}`;
@@ -0,0 +1,28 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ const ACTIVE_MS = 15_000;
5
+
6
+ function alive(pid) {
7
+ if (!Number.isInteger(pid) || pid <= 0) return false;
8
+ try { process.kill(pid, 0); return true; }
9
+ catch (error) { return error?.code === "EPERM"; }
10
+ }
11
+
12
+ export function readHeavyGateWait(dir, now = Date.now()) {
13
+ let totalMs = 0, waiting = false;
14
+ if (!dir) return { totalMs, waiting };
15
+ let names = [];
16
+ try { names = readdirSync(dir).filter(name => name.endsWith(".json")).slice(0, 256); } catch { return { totalMs, waiting }; }
17
+ for (const name of names) {
18
+ let row;
19
+ try { row = JSON.parse(readFileSync(join(dir, name), "utf8")); } catch { continue; }
20
+ const recorded = Number(row?.totalMs);
21
+ const updatedAt = Number(row?.updatedAt);
22
+ if (!Number.isFinite(recorded) || recorded < 0 || !Number.isFinite(updatedAt)) continue;
23
+ const active = row.waiting === true && now - updatedAt <= ACTIVE_MS && alive(Number(row.pid));
24
+ totalMs += recorded + (active ? Math.max(0, now - updatedAt) : 0);
25
+ if (active) waiting = true;
26
+ }
27
+ return { totalMs, waiting };
28
+ }
@@ -0,0 +1,139 @@
1
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { constants, cpus, homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+
6
+ const waitArray = new Int32Array(new SharedArrayBuffer(4));
7
+
8
+ function busDir(env) {
9
+ return env.AGENT_BUS_DIR || env.RELAY_DATA_DIR || join(homedir(), ".agent-bus");
10
+ }
11
+
12
+ function slotCount(env) {
13
+ try {
14
+ const value = JSON.parse(readFileSync(join(busDir(env), "config.json"), "utf8")).heavyGateSlots;
15
+ if (Number.isSafeInteger(value) && value > 0) return value;
16
+ } catch {}
17
+ return Math.max(1, Math.floor(cpus().length / 4));
18
+ }
19
+
20
+ function pidAlive(pid) {
21
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
22
+ try {
23
+ process.kill(pid, 0);
24
+ return true;
25
+ } catch (error) {
26
+ return error?.code !== "ESRCH";
27
+ }
28
+ }
29
+
30
+ function readSlot(path) {
31
+ try {
32
+ const row = JSON.parse(readFileSync(path, "utf8"));
33
+ if (Number.isSafeInteger(row.pid) && Number.isFinite(row.startedAt)) return row;
34
+ } catch {}
35
+ return null;
36
+ }
37
+
38
+ function writeWait(waitFile, waitStarted, waiting) {
39
+ if (!waitFile || waitStarted === null) return;
40
+ const now = Date.now();
41
+ const temporary = `${waitFile}.tmp`;
42
+ mkdirSync(dirname(waitFile), { recursive: true });
43
+ writeFileSync(temporary, JSON.stringify({
44
+ pid: process.pid,
45
+ waiting,
46
+ updatedAt: now,
47
+ totalMs: now - waitStarted,
48
+ }));
49
+ try { renameSync(temporary, waitFile); } catch (error) {
50
+ try { unlinkSync(temporary); } catch {}
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ function acquire(slots, env) {
56
+ const lockDir = join(busDir(env), "heavy-gate");
57
+ mkdirSync(lockDir, { recursive: true });
58
+ const waitDir = env.TRANTOR_HEAVY_GATE_WAIT_DIR;
59
+ const waitFile = waitDir ? join(waitDir, `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.json`) : null;
60
+ let waitStarted = null;
61
+ let announced = false;
62
+ let lastBeat = 0;
63
+ let delay = 50;
64
+
65
+ for (;;) {
66
+ let inUse = 0;
67
+ for (let index = 0; index < slots; index += 1) {
68
+ const path = join(lockDir, `slot-${index}.json`);
69
+ let fd;
70
+ try {
71
+ fd = openSync(path, "wx", 0o600);
72
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
73
+ closeSync(fd);
74
+ writeWait(waitFile, waitStarted, false);
75
+ return { path, waitFile };
76
+ } catch (error) {
77
+ if (fd !== undefined) {
78
+ try { closeSync(fd); } catch {}
79
+ try { unlinkSync(path); } catch {}
80
+ }
81
+ if (error?.code !== "EEXIST") throw error;
82
+ }
83
+
84
+ const row = readSlot(path);
85
+ if (row && !pidAlive(row.pid)) {
86
+ try { unlinkSync(path); } catch {}
87
+ try {
88
+ fd = openSync(path, "wx", 0o600);
89
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
90
+ closeSync(fd);
91
+ writeWait(waitFile, waitStarted, false);
92
+ return { path, waitFile };
93
+ } catch (error) {
94
+ if (fd !== undefined) { try { closeSync(fd); } catch {} }
95
+ if (error?.code !== "EEXIST") throw error;
96
+ }
97
+ }
98
+ inUse += 1;
99
+ }
100
+
101
+ if (!announced) {
102
+ waitStarted = Date.now();
103
+ console.log(`waiting for a heavy-gate slot (${inUse} in use)`);
104
+ announced = true;
105
+ }
106
+ const now = Date.now();
107
+ if (now - lastBeat >= 1000) {
108
+ writeWait(waitFile, waitStarted, true);
109
+ lastBeat = now;
110
+ }
111
+ Atomics.wait(waitArray, 0, 0, delay);
112
+ delay = Math.min(1000, Math.ceil(delay * 1.5));
113
+ }
114
+ }
115
+
116
+ export function runHeavyGate(args, env = process.env) {
117
+ const command = args[0] === "--" ? args.slice(1) : args;
118
+ if (!command.length) {
119
+ console.error("usage: heavy-gate.mjs -- <command> [args ...]");
120
+ return 2;
121
+ }
122
+
123
+ let slot = null;
124
+ if (env.TRANTOR_HEAVY_GATE_HELD !== "1") slot = acquire(slotCount(env), env);
125
+ const childEnv = { ...env, TRANTOR_HEAVY_GATE_HELD: "1" };
126
+ try {
127
+ const result = spawnSync(command[0], command.slice(1), { env: childEnv, stdio: "inherit" });
128
+ if (result.error) {
129
+ console.error(`heavy-gate: ${result.error.message}`);
130
+ return 127;
131
+ }
132
+ if (result.signal) return 128 + (constants.signals[result.signal] || 0);
133
+ return result.status ?? 1;
134
+ } finally {
135
+ if (slot) {
136
+ try { unlinkSync(slot.path); } catch {}
137
+ }
138
+ }
139
+ }
@@ -25,9 +25,9 @@ function gitOut(args, cwd) {
25
25
  return r.status === 0 ? String(r.stdout || "").trim() : "";
26
26
  }
27
27
 
28
- // Start a new contract from its pinned base only when the previous branch has no unharvested work.
29
- // Refusing keeps the branch tip reachable and gives the orchestrator a clear reason to harvest it.
30
- export function alignSeatWorktree({ dir, project, agent, base, receiptsRoot }) {
28
+ // Start a new contract from its pinned base unless that base is already in the seat's history.
29
+ // A move over unharvested work is refused, keeping the branch tip reachable for harvesting.
30
+ export function alignSeatWorktree({ dir, project, agent, base, receiptsRoot, log = console.log }) {
31
31
  const branch = gitOut(["rev-parse", "--abbrev-ref", "HEAD"], dir);
32
32
  const expected = `seat/${agent}`;
33
33
  if (branch !== expected) return { ok: false, reason: `refusing to align ${dir}: expected ${expected}, found ${branch || "detached HEAD"}` };
@@ -35,6 +35,10 @@ export function alignSeatWorktree({ dir, project, agent, base, receiptsRoot }) {
35
35
  spawnSync("git", ["cat-file", "-e", `${base}^{commit}`], { cwd: dir, stdio: "ignore", timeout: 8000 }).status !== 0)
36
36
  return { ok: false, reason: `base ${base || "(missing)"} is not a commit in ${dir}` };
37
37
  if (gitOut(["status", "--porcelain"], dir)) return { ok: false, reason: `refusing to reset dirty seat worktree ${dir}` };
38
+ if (spawnSync("git", ["merge-base", "--is-ancestor", base, "HEAD"], { cwd: dir, stdio: "ignore", timeout: 8000 }).status === 0) {
39
+ log(`${branch} branch already contains base ${base}; keeping ${dir} at its current tip`);
40
+ return { ok: true, to: gitOut(["rev-parse", "HEAD"], dir), parked: "" };
41
+ }
38
42
 
39
43
  const receipts = readReceipts(project, receiptsRoot);
40
44
  const audit = auditSeat(dir, { branch, targetRef: base, receipts });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.128",
3
+ "version": "0.18.129",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"