trantor 0.18.125 → 0.18.127

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.125",
3
+ "version": "0.18.127",
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": {
@@ -14,7 +14,7 @@ import { signedHeaders } from "../lib/signed-fetch.mjs";
14
14
  import { ensureEnrolled } from "../lib/enroll.mjs";
15
15
  import { redactKeys } from "../lib/redact.mjs";
16
16
  import { writeTurnState } from "../lib/turnstate.mjs";
17
- import { applyWorktreeDeclaration, ensureSeatWorktree, provisioningLines, readWorktreeDeclaration } from "../lib/seat-worktree.mjs";
17
+ import { alignSeatWorktree, applyWorktreeDeclaration, ensureSeatWorktree, provisioningLines, readWorktreeDeclaration } from "../lib/seat-worktree.mjs";
18
18
  import {
19
19
  AUTH_MARKER_RE, classifyFailure, looksLikeAuthDeath,
20
20
  verdictFor, substantiveOutput, stallVerdict, cutSignalFor,
@@ -118,9 +118,12 @@ function seatWorktree(sourceDir) {
118
118
 
119
119
  const TURN_DIR = seatWorktree(DIR);
120
120
 
121
- // #7754: the integration head is the orchestrator's LOCAL main, which this linked worktree already
122
- // holds as the ref `main`; origin/main trails it whenever integration commits are unpushed.
123
- const localMainHead = () => gitOut(["rev-parse", "--verify", "--quiet", "main^{commit}"], TURN_DIR);
121
+ // #13921: an explicit contract base wins; without one, fetch the current origin/main instead of
122
+ // trusting a cached local ref from when this seat worktree was created.
123
+ const originMainHead = () => {
124
+ spawnSync("git", ["fetch", "-q", "origin", "+refs/heads/main:refs/remotes/origin/main"], { cwd: TURN_DIR, stdio: "ignore", timeout: 20000 });
125
+ return gitOut(["rev-parse", "--verify", "--quiet", "refs/remotes/origin/main^{commit}"], TURN_DIR);
126
+ };
124
127
  const resolvesHere = (sha) =>
125
128
  spawnSync("git", ["cat-file", "-e", `${sha}^{commit}`], { cwd: TURN_DIR, stdio: "ignore", timeout: 8000 }).status === 0;
126
129
 
@@ -606,9 +609,10 @@ async function balanceRows() {
606
609
  }
607
610
 
608
611
  // ---- activity truth (#5965): the RUNNER is the source for this seat ----------------
609
- // herdr cannot see a runner-driven CLI mid-turn, so the runner reports turn boundaries to the hub:
610
- // `working · <trigger>` at start, `idle` on a clean landing. Bounded 5s, one call per transition.
612
+ // The runner reports `working · <trigger>` at start and `idle` on a clean landing, bounded to 5s.
611
613
  // #7749: the live phase + its start ride the same call, so /peers answers what the seat does NOW.
614
+ // The detached watchdog repeats the working payload once a minute: runTurn blocks this event loop.
615
+ const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 60_000);
612
616
  async function registerStatus(status, extra = {}) {
613
617
  const url = HUB + "/register";
614
618
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
@@ -954,7 +958,11 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
954
958
  kind: cli.pinned ? "opencode" : AGENT, sid, db: OC_DB, workDir: TURN_DIR,
955
959
  home: homedir(), startedAt: t0, transcriptDir: TRANSCRIPT_DIR,
956
960
  } : undefined;
957
- writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity }));
961
+ const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
962
+ agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
963
+ if (MACHINE_LABEL) presencePayload.machine = MACHINE_LABEL;
964
+ writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
965
+ presence: { intervalMs: PRESENCE_MS, payload: presencePayload } }));
958
966
  const wd = spawn(process.execPath, [join(import.meta.dirname, "turn-watchdog.mjs"), STAMPF, ERRF, String(WD_MS), SESSION, PROJ, HUB, TRANSCRIPT_DIR, TURN_DIR,
959
967
  // #7752: the stall marker only exists when a box does — with no box there is no sweep to
960
968
  // end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
@@ -1516,6 +1524,11 @@ async function resolveWakeCard(messages, { session }) {
1516
1524
  signal: AbortSignal.timeout(2500),
1517
1525
  });
1518
1526
  } catch {}
1527
+ if (releaseState) {
1528
+ const since = Date.now();
1529
+ writeTurnState(PERSONA, PROJ, { phase: "idle", since });
1530
+ await registerStatus("idle", { phase: "idle", phaseSince: since });
1531
+ }
1519
1532
 
1520
1533
  // Wake messages this seat has PULLED off the bus but not yet worked successfully, plus the
1521
1534
  // broadcasts batched behind them. Restored from disk first: a runner that was killed mid-turn
@@ -1873,7 +1886,8 @@ async function resolveWakeCard(messages, { session }) {
1873
1886
  // served contract cites: #7763's rebinding covers confirmed message-card ids only, never a
1874
1887
  // card cited in the text, so the unresolvable-base branch blocks the cited card.
1875
1888
  const baseCard = card || servedContractCard(wakeForTurn, { session: SESSION });
1876
- const base = contractBase(wakeForTurn) || localMainHead();
1889
+ const statedBase = contractBase(wakeForTurn);
1890
+ const base = statedBase || originMainHead();
1877
1891
  if (base && baseCard && !resolvesHere(base)) {
1878
1892
  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`;
1879
1893
  log(text);
@@ -1885,6 +1899,21 @@ async function resolveWakeCard(messages, { session }) {
1885
1899
  savePending([], pendingBcast);
1886
1900
  return;
1887
1901
  }
1902
+ if (base && TURN_DIR !== DIR && card && gitOut(["rev-parse", "--abbrev-ref", "HEAD"], TURN_DIR) === `seat/${PERSONA}`) {
1903
+ const aligned = alignSeatWorktree({ dir: TURN_DIR, project: PROJ, agent: PERSONA, base });
1904
+ if (!aligned.ok) {
1905
+ const text = `cannot align seat worktree for #${card}: ${aligned.reason}`;
1906
+ log(text);
1907
+ await api("/task/update", { id: card, status: "blocked", note: text, by: SESSION }).catch(() => {});
1908
+ const owed = assigners.map(a => a.from).filter(f => f && f !== SESSION);
1909
+ for (const to of (owed.length ? owed : ["all"]))
1910
+ await api("/send", { from: SESSION, to, text, project: PROJ, kind: "alert" }).catch(() => {});
1911
+ pendingWake = [];
1912
+ savePending([], pendingBcast);
1913
+ return;
1914
+ }
1915
+ if (aligned.parked) log(`preserved unharvested work at ${aligned.parked} before aligning to ${base}`);
1916
+ }
1888
1917
  const baseText = base ? `\n${baseLine(base)}\n` : "";
1889
1918
  // #6289: the session SHAPE (fresh vs resume) reads the served contract's raw citation — a wake
1890
1919
  // whose card the board lacks still opens fresh, never a bare resume of the kickoff's CLI.
package/bin/sync.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // `trantor sync [<seat>]` (#7748): realign a seat branch with main from the harvest receipts.
3
- // Every commit main lacks must carry a receipt; otherwise the sync refuses and names them.
3
+ // Commits absent from main must have a receipt or an equivalent patch on main; otherwise sync refuses.
4
4
  import { existsSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { resolveProject, busDir } from "../lib/project.mjs";
@@ -27,15 +27,17 @@ const short = (s) => String(s || "").slice(0, 7);
27
27
  if (r.refused) {
28
28
  console.log(`${RED}sync refused${R} · ${r.branch} carries ${r.unharvested.length} commit(s) ${r.target.ref} does not, with no harvest receipt:`);
29
29
  for (const c of r.unharvested) console.log(` ${short(c.sha)} ${c.subject}`);
30
- if (r.harvested.length) console.log(`${D}${r.harvested.length} other commit(s) are receipted and would be dropped once these are.${R}`);
30
+ if (r.harvested.length) console.log(`${D}${r.harvested.length} other commit(s) are already harvested and would be dropped once these are.${R}`);
31
31
  console.log(`${D}Harvest them (trantor harvest <seat-sha> <main-sha> --card N) or park them on another branch first. Receipts: ${receiptsPath(project)}${R}`);
32
32
  process.exit(1);
33
33
  }
34
34
  if (!r.ok) { console.error(`${RED}sync failed${R}: ${r.reason}`); process.exit(1); }
35
35
  if (r.noop) { console.log(`${D}${r.branch} already at ${r.target.ref} (${short(r.head)})${R}`); process.exit(0); }
36
- const dropped = r.harvested.map(c => `${short(c.sha)}→${short(c.receipt.main)}`).join(", ");
36
+ const dropped = r.harvested.map(c => c.receipt
37
+ ? `${short(c.sha)}→${short(c.receipt.main)}`
38
+ : `${short(c.sha)} (patch already in target)`).join(", ");
37
39
  if (r.dry) {
38
- console.log(`${Y}[dry]${R} would move ${r.branch} ${short(r.head)} → ${r.target.ref} ${short(r.target.sha)}${dropped ? ` ${D}(receipted: ${dropped})${R}` : ""}`);
40
+ console.log(`${Y}[dry]${R} would move ${r.branch} ${short(r.head)} → ${r.target.ref} ${short(r.target.sha)}${dropped ? ` ${D}(harvested: ${dropped})${R}` : ""}`);
39
41
  process.exit(0);
40
42
  }
41
- console.log(`${G}synced${R} ${r.branch} ${short(r.from)} → ${r.target.ref} ${short(r.to)}${dropped ? ` ${D}(receipted: ${dropped})${R}` : ""}`);
43
+ console.log(`${G}synced${R} ${r.branch} ${short(r.from)} → ${r.target.ref} ${short(r.to)}${dropped ? ` ${D}(harvested: ${dropped})${R}` : ""}`);
@@ -52,6 +52,22 @@ const runnerAlive = () => {
52
52
  try { process.kill(runnerPid, 0); return true; } catch { return false; }
53
53
  };
54
54
 
55
+ // The runner is blocked in spawnSync for the whole turn, so presence beats from this helper.
56
+ // The stamp check pins every beat to this runner and turn; killing the watchdog clears the timer.
57
+ const presence = armed.presence;
58
+ let presenceBusy = false;
59
+ async function beatPresence() {
60
+ if (!presence || presenceBusy) return;
61
+ const current = readStamp();
62
+ if (!current || current.turn !== armed.turn || (armed.runner && current.runner !== armed.runner) || !runnerAlive()) return;
63
+ presenceBusy = true;
64
+ try {
65
+ await signedPost(`${hub}/register`, presence.payload, { session, timeoutMs: 5000 });
66
+ } catch {} finally { presenceBusy = false; }
67
+ }
68
+ const presenceTimer = presence ? setInterval(beatPresence, Math.max(100, Number(presence.intervalMs) || 60000)) : null;
69
+ process.on("exit", () => { if (presenceTimer) clearInterval(presenceTimer); });
70
+
55
71
  // One observation of every liveness channel: stderr growth, transcript mtime, worktree mtime.
56
72
  const ago = (t) => (t > 0 ? `${Math.max(1, Math.round((Date.now() - t) / 60000))}m ago` : "never");
57
73
  const describeLast = (b) => {
package/lib/harvest.mjs CHANGED
@@ -64,12 +64,14 @@ export function syncTarget(dir, base) {
64
64
  // Every commit the seat branch carries that the target does not, split by whether a receipt covers it.
65
65
  export function auditSeat(dir, { branch, targetRef, receipts }) {
66
66
  const log = out(dir, ["log", "--reverse", "--format=%H%x09%s", `${targetRef}..${branch}`]);
67
+ const cherry = out(dir, ["cherry", targetRef, branch]);
68
+ const equivalent = new Set(cherry.split("\n").filter(line => line.startsWith("- ")).map(line => line.slice(2).trim()));
67
69
  const harvested = [], unharvested = [];
68
70
  for (const line of log.split("\n").filter(Boolean)) {
69
71
  const [sha, ...rest] = line.split("\t");
70
72
  const subject = rest.join("\t");
71
73
  const receipt = receipts.find(r => shaMatches(r.seat, sha));
72
- (receipt ? harvested : unharvested).push({ sha, subject, receipt });
74
+ (receipt || equivalent.has(sha) ? harvested : unharvested).push({ sha, subject, receipt });
73
75
  }
74
76
  return { harvested, unharvested };
75
77
  }
@@ -6,6 +6,7 @@ import {
6
6
  } from "node:fs";
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
9
+ import { auditSeat, readReceipts } from "./harvest.mjs";
9
10
 
10
11
  export const DECLARATION_PATH = join(".trantor", "worktree.json");
11
12
  export const PREFLIGHT_CAP_MS = 5 * 60 * 1000;
@@ -24,6 +25,28 @@ function gitOut(args, cwd) {
24
25
  return r.status === 0 ? String(r.stdout || "").trim() : "";
25
26
  }
26
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 }) {
31
+ const branch = gitOut(["rev-parse", "--abbrev-ref", "HEAD"], dir);
32
+ const expected = `seat/${agent}`;
33
+ if (branch !== expected) return { ok: false, reason: `refusing to align ${dir}: expected ${expected}, found ${branch || "detached HEAD"}` };
34
+ if (!/^[0-9a-f]{7,40}$/i.test(String(base || "")) ||
35
+ spawnSync("git", ["cat-file", "-e", `${base}^{commit}`], { cwd: dir, stdio: "ignore", timeout: 8000 }).status !== 0)
36
+ return { ok: false, reason: `base ${base || "(missing)"} is not a commit in ${dir}` };
37
+ if (gitOut(["status", "--porcelain"], dir)) return { ok: false, reason: `refusing to reset dirty seat worktree ${dir}` };
38
+
39
+ const receipts = readReceipts(project, receiptsRoot);
40
+ const audit = auditSeat(dir, { branch, targetRef: base, receipts });
41
+ if (audit.unharvested.length) {
42
+ const commits = audit.unharvested.map(c => `${c.sha.slice(0, 7)} (${c.subject})`).join(", ");
43
+ return { ok: false, reason: `refusing to move ${branch}: ${audit.unharvested.length} unharvested commit(s) would be lost: ${commits}` };
44
+ }
45
+ const reset = spawnSync("git", ["reset", "--hard", base], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15000 });
46
+ if (reset.status !== 0) return { ok: false, reason: `could not align to ${base}: ${String(reset.stderr || reset.stdout || "git reset failed").trim()}` };
47
+ return { ok: true, to: gitOut(["rev-parse", "HEAD"], dir), parked: "" };
48
+ }
49
+
27
50
  // Returns { dir, created }: dir is the seat worktree, or sourceDir when no worktree applies
28
51
  // (non-git source, opt-out, or a creation failure — loud, never fatal: stale beats broken).
29
52
  export function ensureSeatWorktree({ sourceDir, project, agent, home = homedir(), env = process.env, log = console.log }) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.125",
3
+ "version": "0.18.127",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"