trantor 0.18.126 → 0.18.128

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.126",
3
+ "version": "0.18.128",
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": {
@@ -19,7 +19,7 @@ import {
19
19
  AUTH_MARKER_RE, classifyFailure, looksLikeAuthDeath,
20
20
  verdictFor, substantiveOutput, stallVerdict, cutSignalFor,
21
21
  BILLING_RE, looksLikeBillingDeath, usageSaysNoWork, zeroUsageVerdict, noDeliveryVerdict,
22
- permissionRejection, looksLikePermissionDeath,
22
+ permissionRejection, permissionTool, looksLikePermissionDeath,
23
23
  readPromptText, stripPromptEcho,
24
24
  } from "../lib/classify-failure.mjs";
25
25
  import { capWake, capBcast, pickLessons, composePrompt, contractBase, baseLine } from "./crew-payload.mjs";
@@ -329,6 +329,7 @@ let consecFails = 0;
329
329
  // it every retry costs a turn for every live seat (monitoring doctrine: duration, not repetition).
330
330
  let announced = "";
331
331
  let lastErrText = "";
332
+ let lastPermissionReject = null;
332
333
  // #5481: the turn exited 0 with a NULL/empty transcript — the Inception/Mercury trap. The provider
333
334
  // burned its whole max_tokens budget on internal reasoning and returned a null completion; the
334
335
  // runner used to read that silence as a clean turn while nothing was produced.
@@ -516,7 +517,7 @@ function saveWipLogged(why) {
516
517
  return sha;
517
518
  }
518
519
 
519
- async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } = {}) {
520
+ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", announce = true } = {}) {
520
521
  saveWipLogged(`parked: ${reason}`);
521
522
  // A seat that went QUIET printed no wall message to parse (#6131), so its own balance row is the
522
523
  // only place the reset time exists. Output first when there is any: it is this turn's evidence.
@@ -531,7 +532,7 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } =
531
532
  // The park is a STATE, and every reader of it is off the bus: `trantor seat-why`, the app, the
532
533
  // operator at a terminal an hour later. The message below is the event; this file is the state.
533
534
  try { writeFileSync(PARKF, JSON.stringify({ session: SESSION, persona: PERSONA, agent: AGENT, project: PROJ, ...parkState })); } catch {}
534
- if (!parkAnnounced) {
535
+ if (announce && !parkAnnounced) {
535
536
  parkAnnounced = true;
536
537
  // #7752: a stalled park names the CLI and its model — the swap decision needs both, and this
537
538
  // line is the one place the room reads them together.
@@ -609,9 +610,10 @@ async function balanceRows() {
609
610
  }
610
611
 
611
612
  // ---- activity truth (#5965): the RUNNER is the source for this seat ----------------
612
- // herdr cannot see a runner-driven CLI mid-turn, so the runner reports turn boundaries to the hub:
613
- // `working · <trigger>` at start, `idle` on a clean landing. Bounded 5s, one call per transition.
613
+ // The runner reports `working · <trigger>` at start and `idle` on a clean landing, bounded to 5s.
614
614
  // #7749: the live phase + its start ride the same call, so /peers answers what the seat does NOW.
615
+ // The detached watchdog repeats the working payload once a minute: runTurn blocks this event loop.
616
+ const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 60_000);
615
617
  async function registerStatus(status, extra = {}) {
616
618
  const url = HUB + "/register";
617
619
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
@@ -842,6 +844,7 @@ let lastEnvelope = "";
842
844
  async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
843
845
  TURN++; banner(trigger);
844
846
  lastEnvelope = "";
847
+ lastPermissionReject = null;
845
848
  const t0 = Date.now();
846
849
  // A fresh session must not resume the old one's id: `first` is chosen by isFirst OR a missing
847
850
  // sid, so a stale sid would quietly resume the session this turn exists to leave behind.
@@ -957,7 +960,11 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
957
960
  kind: cli.pinned ? "opencode" : AGENT, sid, db: OC_DB, workDir: TURN_DIR,
958
961
  home: homedir(), startedAt: t0, transcriptDir: TRANSCRIPT_DIR,
959
962
  } : undefined;
960
- writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity }));
963
+ const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
964
+ agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
965
+ if (MACHINE_LABEL) presencePayload.machine = MACHINE_LABEL;
966
+ writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
967
+ presence: { intervalMs: PRESENCE_MS, payload: presencePayload } }));
961
968
  const wd = spawn(process.execPath, [join(import.meta.dirname, "turn-watchdog.mjs"), STAMPF, ERRF, String(WD_MS), SESSION, PROJ, HUB, TRANSCRIPT_DIR, TURN_DIR,
962
969
  // #7752: the stall marker only exists when a box does — with no box there is no sweep to
963
970
  // end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
@@ -1124,13 +1131,12 @@ exit $turn_exit`;
1124
1131
  effExit = 1;
1125
1132
  log(`\x1b[31mexit 0 but the turn output IS a provider billing rejection — treating as FAILED (exhausted, "${BILLING_RE.exec(ownOut)[0]}")\x1b[0m`);
1126
1133
  }
1127
- // #9919: the same trap in the sandbox family — the seat reached outside its worktree, opencode
1128
- // auto-rejected the permission and killed the turn at exit 0, and glm:ibkr sat 8h on an
1129
- // uncommitted #9859 under a "success" row. Judged on the output TAIL: the rejection prints where
1130
- // the turn ended, so a turn that only quotes the phrase mid-stream stays success.
1131
- if (realExit === 0 && effExit === 0 && looksLikePermissionDeath(ownOut, newCommit)) {
1134
+ // #9919/#13945: a trailing denial is an incomplete turn even when an earlier step committed.
1135
+ // Otherwise verdictFor names permission-rejected while the clean exit still produces "done".
1136
+ if (realExit === 0 && effExit === 0 && looksLikePermissionDeath(ownOut)) {
1132
1137
  effExit = 1;
1133
- log(`\x1b[31mexit 0 but the turn output IS a sandbox permission rejection — treating as FAILED (permission-rejected, "${permissionRejection(ownOut)}")\x1b[0m`);
1138
+ lastPermissionReject = { evidence: permissionRejection(ownOut), tool: permissionTool(ownOut) || "unknown" };
1139
+ log(`\x1b[31mexit 0 but the turn output IS a sandbox permission rejection — treating as FAILED (permission-rejected, "${lastPermissionReject.evidence}")\x1b[0m`);
1134
1140
  }
1135
1141
  // #5481: exit 0 with an empty ERRF (the TOTAL capture, both streams) is the null-completion trap,
1136
1142
  // judged on echo-stripped text (#5868). #6969: on a state step ERRF is stderr only, so silence is normal.
@@ -1238,7 +1244,7 @@ exit $turn_exit`;
1238
1244
  // api-error, completed — and what it cost (0 means "not reported", never "free"). #7762: `card`
1239
1245
  // binds the row to the card the turn worked (0 = kickoff/pulse) so the seat record attributes
1240
1246
  // empty/stalled turns to the card that produced nothing. `cut` stays too: the drills read it.
1241
- const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? "api-error" : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
1247
+ const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? (lastPermissionReject ? "rejected" : "api-error") : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
1242
1248
  const finalOutcome = askVerdict ? "asked" : blockedVerdict ? "blocked" : outcome;
1243
1249
  const telemetryRow = { ts: Date.now(), persona: PERSONA, agent: AGENT, project: PROJ, turn: TURN, trigger, card: sessionCard || 0, model: MODEL || "cli-default", duration_ms: Date.now() - t0, exit: realExit, effExit, authFailed: effExit !== realExit, emptyOutput: lastEmptyOutput, emptyTurn: lastEmptyTurn, verdict, outcome: finalOutcome, tokens };
1244
1250
  if (usage) telemetryRow.usage = usage;
@@ -2039,6 +2045,15 @@ async function resolveWakeCard(messages, { session }) {
2039
2045
  lastTurnAt = Date.now();
2040
2046
  return;
2041
2047
  }
2048
+ if (ec && lastPermissionReject && sessionCard > 0) {
2049
+ const text = `⛔ permission rejected: ${lastPermissionReject.tool} on #${sessionCard} · ${lastPermissionReject.evidence} · card moved to blocked; wake stays owed`;
2050
+ savePending(pendingWake, pendingBcast);
2051
+ await api("/task/update", { id: sessionCard, status: "blocked", note: text, by: SESSION }).catch(() => {});
2052
+ retryAt = await parkSeat("permission-rejected", pendingWake.length, 0, { announce: false });
2053
+ await notifyAssigners(assigners, text);
2054
+ lastTurnAt = Date.now();
2055
+ return;
2056
+ }
2042
2057
  if (ec) {
2043
2058
  deliveryFails++;
2044
2059
  // #7752: a SILENT cut is a stall, whatever the captured text contains — the qwen
@@ -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/hub/duty.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export function createDuty({ state, now, appendEvent, appendTaskLog, canon, markDirty, pushToStreams, OVERSEER_TICK_MS }) {
1
+ export function createDuty({ state, now, appendEvent, appendTaskLog, copyTask, canon, markDirty, pushToStreams, OVERSEER_TICK_MS }) {
2
2
  let DUTY_SESSION = String(process.env.RELAY_DUTY_SESSION || state.dutySession || "");
3
3
  // Escalate after two minutes so idle recipients can be woken before collaboration stalls.
4
4
  const DUTY_UNDELIVERED_MS = Number(process.env.RELAY_DUTY_UNDELIVERED_MS || 2 * 60 * 1000);
@@ -61,8 +61,9 @@ function recordFailure({ project, recipient, kind, detail }) {
61
61
  .sort((a, b) => (b.updated || b.ts || 0) - (a.updated || a.ts || 0))[0] || null;
62
62
  const ts = now();
63
63
  if (focus) {
64
- appendTaskLog(focus, DUTY_SESSION || "hub:duty", text, ts);
65
- focus.updated = ts;
64
+ const updated = copyTask(focus);
65
+ appendTaskLog(updated, DUTY_SESSION || "hub:duty", text, ts);
66
+ updated.updated = ts;
66
67
  }
67
68
  const meta = state.projectMeta[target] || {};
68
69
  meta.dutyFailure = { ts, project: target, recipient: String(recipient || "").slice(0, 120), kind: String(kind || "skipped-nudge"), text, focusCard: focus?.id || null };
package/hub/reaper.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  export function createReaper({
2
- state, now, canon, appendCardEvent, appendEvent, appendTaskLog, markDirty, sweepPresence,
2
+ state, now, canon, appendCardEvent, appendEvent, appendTaskLog, copyTask, markDirty, sweepPresence,
3
3
  ONLINE_MS, PEER_TTL_MS, PEER_FORGET_MS, FOCUS_OFFLINE_MS, FOCUS_IDLE_MS,
4
4
  REAP_GRACE_MS, TODO_STALE_MS, REAP_INTERVAL_MS,
5
5
  CONTRACT_ABANDON_MS, CONTRACT_WINDOW_MS,
6
6
  }) {
7
7
  function closeFocusCard(t, by) {
8
8
  if (!t || t.status === "done") return false;
9
+ t = copyTask(t);
9
10
  (t.history ||= []).push({ from: t.status, to: "done", by, ts: now() });
10
11
  if (t.history.length > 60) t.history.splice(0, 20);
11
12
  appendCardEvent("moved", t, by, t.status, "done");
@@ -17,7 +18,8 @@ function closeFocusCard(t, by) {
17
18
  // old single-card `find` left the rest sitting in `doing` forever.
18
19
  function closeFocus(session) {
19
20
  let closed = false;
20
- for (const t of state.tasks) {
21
+ for (const original of state.tasks) {
22
+ let t = original;
21
23
  if (t.source === "session" && t.assignee === session && t.status !== "done") closed = closeFocusCard(t, session) || closed;
22
24
  }
23
25
  return closed;
@@ -36,8 +38,9 @@ function linkCommitToFocus(commitCard, by) {
36
38
  const open = state.tasks
37
39
  .filter(x => x.source === "session" && x.status !== "done" && x.assignee === owner && canon(x.project) === proj)
38
40
  .sort((a, b2) => (b2.updated || 0) - (a.updated || 0));
39
- const focus = open[0];
40
- if (!focus) return false;
41
+ const found = open[0];
42
+ if (!found) return false;
43
+ const focus = copyTask(found);
41
44
  focus.commitCard = commitCard.id; // the two halves point at each other, so the
42
45
  commitCard.focusCard = focus.id; // card drawer can walk either way
43
46
  (focus.history ||= []).push({ from: focus.status, to: "done", by: owner, ts: now(), note: `closed by commit — ${String(commitCard.title || "").slice(0, 80)}` });
@@ -106,10 +109,12 @@ function reapStaleCards() {
106
109
  const idleCut = now() - FOCUS_IDLE_MS;
107
110
  const graceCut = now() - REAP_GRACE_MS;
108
111
  let changed = false;
109
- for (const t of state.tasks) {
112
+ for (const original of state.tasks) {
113
+ let t = original;
110
114
  if (t.status === "done" || t.status === "stale") continue;
111
115
  if (t.status === "testing") continue;
112
116
  if (t.status === "todo" && (t.updated || t.ts || 0) < now() - TODO_STALE_MS) {
117
+ t = copyTask(t);
113
118
  const from = t.status;
114
119
  const untouchedAt = t.updated || t.ts || 0;
115
120
  const agedDays = Math.floor((now() - untouchedAt) / 86400000);
@@ -133,6 +138,7 @@ function reapStaleCards() {
133
138
  if (t.status === "doing" // (b) offline-owner work cards → stale
134
139
  && (t.updated || t.ts || 0) < graceCut
135
140
  && !cardOwnerOnline(t, onCut)) {
141
+ t = copyTask(t);
136
142
  const reapedAt = now();
137
143
  (t.history ||= []).push({ from: t.status, to: "stale", by: "reaper", ts: reapedAt });
138
144
  if (t.history.length > 60) t.history.splice(0, 20);
@@ -146,8 +146,9 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
146
146
  // it comes back on load and overwrites the real row id.
147
147
  state.eventSeq = Math.max(Number(state.eventSeq || 0), Number(last?.id) || 0) + 1;
148
148
  const ev = { ...e, id: state.eventSeq, project: proj };
149
- if (ev.taskId != null && remap.has(Number(ev.taskId))) ev.taskId = remap.get(Number(ev.taskId));
150
- state.events.push(ev); added.events++;
149
+ const taskId = ev.taskId != null ? remap.get(Number(ev.taskId)) : undefined;
150
+ const importedEvent = taskId === undefined ? ev : { ...ev, taskId };
151
+ state.events.push(importedEvent); added.events++;
151
152
  }
152
153
  if (state.events.length > EVENT_CAP) state.events.splice(0, state.events.length - EVENT_CAP);
153
154
  for (const m of (Array.isArray(b.messages) ? b.messages : [])) {
@@ -305,9 +306,10 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
305
306
  }
306
307
  if (req.method === "POST" && P === "/overseer/narrate") {
307
308
  const b = await body(req);
308
- const ev = state.events.find(e => e.id === Number(b.eventId) && e.type === "overseer.warn");
309
- if (!ev) return json(res, 404, { error: "no such overseer.warn event" });
310
- ev.narrated = true; ev.narration = String(b.text || "").slice(0, 300);
309
+ const index = state.events.findIndex(e => e.id === Number(b.eventId) && e.type === "overseer.warn");
310
+ if (index < 0) return json(res, 404, { error: "no such overseer.warn event" });
311
+ const ev = state.events[index];
312
+ state.events[index] = { ...ev, narrated: true, narration: String(b.text || "").slice(0, 300) };
311
313
  markDirty();
312
314
  return json(res, 200, { ok: true });
313
315
  }
@@ -35,7 +35,7 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
35
35
  const {
36
36
  state, body, json, crossProjectGuard, touch, canon, filterReadable,
37
37
  appendEvent, appendCardEvent, now, markDirty, stripNulText,
38
- appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, linkCommitToFocus,
38
+ appendTaskLog, appendTaskNote, copyTask, copyMessage, cleanChecklist, cleanDrill, hasDrillLine, linkCommitToFocus,
39
39
  derivePhases, PROPOSAL_CAP, propFp, healthOf, REAP_GRACE_MS, subFp,
40
40
  prunePeers, canRead, HUB_VERSION, cmpSemver, isCardEvent, fmtAge, hubSend,
41
41
  ONLINE_MS, PEER_TTL_MS, AUTH_MODE, scopeAllows,
@@ -75,10 +75,11 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
75
75
  if (!agentId) return json(res, 200, { ok: true, ignored: "enrich-without-agentId" });
76
76
  const already = state.tasks.find(x => x.source === "cc-subagent" && x.project === proj0 && x._aid === agentId);
77
77
  if (already) return json(res, 200, { ok: true, task: already, deduped: true, enriched: true });
78
- const cand = state.tasks
78
+ let cand = state.tasks
79
79
  .filter(x => x.source === "cc-subagent" && x.project === proj0 && !x._aid && x.status === "doing" && (atype ? x._atype === atype : true))
80
80
  .sort((a, c) => (c.ts || 0) - (a.ts || 0))[0];
81
81
  if (cand) {
82
+ cand = copyTask(cand);
82
83
  cand._aid = agentId; if (parent && !cand.parent) cand.parent = parent; cand.updated = ts0;
83
84
  appendTaskNote(cand, b, ts0);
84
85
  markDirty(); return json(res, 200, { ok: true, task: cand, deduped: true, enriched: true });
@@ -100,9 +101,10 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
100
101
  const fp = subFp(b.title);
101
102
  // Pair by agent_id first (robust — survives title differences between start & stop); fall back to the
102
103
  // title fingerprint for legacy clients / the PreToolUse-only path that predates agent_id.
103
- const ex = (agentId && state.tasks.find(x => x.source === "cc-subagent" && x.project === proj0 && x._aid === agentId))
104
+ let ex = (agentId && state.tasks.find(x => x.source === "cc-subagent" && x.project === proj0 && x._aid === agentId))
104
105
  || state.tasks.find(x => x.source === "cc-subagent" && x.project === proj0 && x._fp === fp);
105
106
  if (ex) {
107
+ ex = copyTask(ex);
106
108
  if (parent && !ex.parent) ex.parent = parent;
107
109
  if (agentId && !ex._aid) ex._aid = agentId;
108
110
  if (isStart) {
@@ -146,8 +148,9 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
146
148
  }
147
149
  const nt = String(b.notificationType || "").slice(0, 40);
148
150
  const target = nt === "agent_completed" ? "done" : (nt === "agent_needs_input" ? "blocked" : "doing");
149
- const ex = bgId && state.tasks.find(x => x.source === "cc-bg-agent" && x.project === proj0 && x._aid === bgId);
151
+ let ex = bgId && state.tasks.find(x => x.source === "cc-bg-agent" && x.project === proj0 && x._aid === bgId);
150
152
  if (ex) {
153
+ ex = copyTask(ex);
151
154
  const from = ex.status; ex.status = target; ex.ts = ts0; ex.updated = ts0;
152
155
  if (b.parent && !ex.parent) ex.parent = String(b.parent).slice(0, 120);
153
156
  if (b.title && b.title.length > (ex.title || "").length) ex.title = String(b.title).slice(0, 200);
@@ -199,7 +202,8 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
199
202
  markDirty(); return json(res, 200, { ok: true, task: t });
200
203
  }
201
204
  if (req.method === "POST" && P === "/task/update") { // move/edit a card
202
- const b = await body(req); const t = state.tasks.find(x => x.id === Number(b.id));
205
+ const b = await body(req); const found = state.tasks.find(x => x.id === Number(b.id));
206
+ const t = found && copyTask(found);
203
207
  if (!t) return json(res, 404, { error: "no such task" });
204
208
  const cpg = crossProjectGuard(auth, P, b);
205
209
  if (!cpg.ok) return json(res, cpg.code, { error: cpg.error });
@@ -271,7 +275,8 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
271
275
  // #5624: toggle ONE acceptance item. Index-addressed against the card's current checklist —
272
276
  // a stale index 400s instead of silently toggling the wrong item.
273
277
  if (req.method === "POST" && P === "/task/checklist-toggle") {
274
- const b = await body(req); const t = state.tasks.find(x => x.id === Number(b.id));
278
+ const b = await body(req); const found = state.tasks.find(x => x.id === Number(b.id));
279
+ const t = found && copyTask(found);
275
280
  if (!t) return json(res, 404, { error: "no such task" });
276
281
  const i = Number(b.index);
277
282
  if (!Array.isArray(t.checklist) || !Number.isInteger(i) || i < 0 || i >= t.checklist.length) {
@@ -296,10 +301,11 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
296
301
  status: t.status, source: t.source || "", ageMs: now() - (t.updated || t.ts || 0) }));
297
302
  if (b.dryRun) return json(res, 200, { ok: true, dryRun: true, count: view.length, candidates: view });
298
303
  for (const t of cand) {
299
- (t.history ||= []).push({ from: t.status, to: "stale", by: b.by || "sweep", ts: now() });
300
- if (t.history.length > 60) t.history.splice(0, 20);
301
- appendCardEvent("moved", t, b.by || "sweep", t.status, "stale");
302
- t.status = "stale"; t.updated = now(); t._reaped = true;
304
+ const copy = copyTask(t);
305
+ (copy.history ||= []).push({ from: copy.status, to: "stale", by: b.by || "sweep", ts: now() });
306
+ if (copy.history.length > 60) copy.history.splice(0, 20);
307
+ appendCardEvent("moved", copy, b.by || "sweep", copy.status, "stale");
308
+ copy.status = "stale"; copy.updated = now(); copy._reaped = true;
303
309
  }
304
310
  if (cand.length) markDirty();
305
311
  return json(res, 200, { ok: true, swept: view.length, candidates: view });
@@ -330,6 +336,7 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
330
336
  history: [{ to: want, by: session, ts: now() }] };
331
337
  state.tasks.push(t); appendCardEvent("created", t, session, null, want); markDirty();
332
338
  } else if (t.status !== want) {
339
+ t = copyTask(t);
333
340
  (t.history ||= []).push({ from: t.status, to: want, by: session, ts: now() });
334
341
  if (t.history.length > 40) t.history.splice(0, 10);
335
342
  appendCardEvent("moved", t, session, t.status, want); t.status = want; t.updated = now(); markDirty();
@@ -365,6 +372,7 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
365
372
  || state.tasks.find(x => x.source === "session" && !x.cc && x.assignee === session && canon(x.project) === project && x.status !== "done")
366
373
  : state.tasks.find(x => x.source === "session" && x.assignee === session && canon(x.project) === project && x.status !== "done");
367
374
  if (t) {
375
+ t = copyTask(t);
368
376
  if (t.title !== title) { // refocus: re-title in place + record the shift (keeps the trail)
369
377
  (t.history ||= []).push({ from: t.status, to: t.status, by: session, ts: now(), note: title.slice(0, 90) });
370
378
  if (t.history.length > 60) t.history.splice(0, 20);
@@ -490,10 +498,13 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
490
498
  const from = String(b.from || "").slice(0, 80), to = String(b.to || "").slice(0, 80);
491
499
  if (!from || !to || from === to) return json(res, 400, { error: "distinct from+to required" });
492
500
  let cards = 0, events = 0, peers = 0, msgs = 0;
493
- for (const t of state.tasks) if (t.project === from) { t.project = to; cards++; }
494
- for (const e of state.events) if (e.project === from) { e.project = to; events++; }
501
+ for (const t of state.tasks) if (t.project === from) { const copy = copyTask(t); copy.project = to; cards++; }
502
+ for (let i = 0; i < state.events.length; i++) {
503
+ const e = state.events[i];
504
+ if (e.project === from) { state.events[i] = { ...e, project: to }; events++; }
505
+ }
495
506
  for (const v of Object.values(state.peers)) if (v.project === from) { v.project = to; peers++; }
496
- for (const m of state.messages) if ((m.project || "") === from) { m.project = to; msgs++; }
507
+ for (const m of state.messages) if ((m.project || "") === from) { const copy = copyMessage(m); copy.project = to; msgs++; }
497
508
  if (state.projectMeta[from]) {
498
509
  if (!state.projectMeta[to]) state.projectMeta[to] = state.projectMeta[from];
499
510
  else if (!state.projectMeta[to].brief && state.projectMeta[from].brief) state.projectMeta[to].brief = state.projectMeta[from].brief;
@@ -32,21 +32,33 @@ export async function routeContractTransfer({ req, res, q, P, auth, ctx }) {
32
32
  return ctx.json(res, 409, { error: "replacement has not registered on this project's bus" });
33
33
  }
34
34
  // IDs and original senders survive the move, so replies settle the assigner's original ledger.
35
- for (const message of messages) message.to = to;
35
+ for (let i = 0; i < messages.length; i++) {
36
+ const message = ctx.copyMessage(messages[i]);
37
+ messages[i] = message;
38
+ message.to = to;
39
+ }
36
40
  const ids = new Set(messages.map(m => m.id));
37
- for (const message of ctx.state.messages) {
41
+ for (const [index, original] of ctx.state.messages.entries()) {
42
+ let message = original;
38
43
  if (message.project !== project) continue;
44
+ const mutate = () => { message = ctx.copyMessage(message); ctx.state.messages[index] = message; };
39
45
  if (message.kind === "ask" && message.from === from && (ids.has(message.re) || message.id === b.heldAsk)) {
46
+ mutate();
40
47
  message.from = to;
41
48
  for (const answer of ctx.state.messages) {
42
49
  if (answer.re !== message.id || answer.to !== from) continue;
43
- answer.to = to;
44
- if (!ids.has(answer.id)) { messages.push(answer); ids.add(answer.id); }
50
+ const answerIndex = ctx.state.messages.indexOf(answer);
51
+ const copy = ctx.copyMessage(answer);
52
+ ctx.state.messages[answerIndex] = copy;
53
+ copy.to = to;
54
+ if (!ids.has(copy.id)) { messages.push(copy); ids.add(copy.id); }
45
55
  }
46
56
  }
47
57
  }
48
- for (const card of ctx.state.tasks) {
58
+ for (const original of ctx.state.tasks) {
59
+ let card = original;
49
60
  if (card.project !== project || card.assignee !== from || !["todo", "doing", "testing", "blocked", "failed"].includes(card.status)) continue;
61
+ card = ctx.copyTask(card);
50
62
  card.assignee = to;
51
63
  card.updated = ctx.now();
52
64
  ctx.appendTaskLog(card, signer || from, `swap reassigned ${from} → ${to}`);
@@ -5,7 +5,7 @@ import { setTimeout, setInterval, clearInterval } from "node:timers";
5
5
  export async function routeMessages({ req, res, q, P, auth, ctx }) {
6
6
  if (await routeContractTransfer({ req, res, q, P, auth, ctx })) return true;
7
7
  const {
8
- state, body, json, stripNulText, crossProjectGuard, touch, pushToStreams,
8
+ state, body, json, stripNulText, copyTask, crossProjectGuard, touch, pushToStreams,
9
9
  appendEvent, appendCardEvent, appendTaskLog, markDelivered, contractsFor, canUseInboxSession, inboxWindow,
10
10
  deliverable, inboxReadable, inboxResponse, filterReadable, canRead, streams, UI,
11
11
  AUTH_MODE, persistHealth, duty, now, markDirty, assertNoSecrets, PEER_TTL_MS,
@@ -44,8 +44,9 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
44
44
  // #7756: the ask primitive's board half — a kind:ask blocks the card it cites (the question is
45
45
  // the note, so the board reads why nothing moves); the answer (re = the ask's id) unblocks it.
46
46
  const askCardMove = (cardId, to, noteText) => {
47
- const t = cardId && state.tasks.find(x => x.id === cardId && x.project === msg.project);
48
- if (!t || t.status === to || (to === "doing" && t.status !== "blocked")) return;
47
+ const found = cardId && state.tasks.find(x => x.id === cardId && x.project === msg.project);
48
+ if (!found || found.status === to || (to === "doing" && found.status !== "blocked")) return;
49
+ const t = copyTask(found);
49
50
  const from = t.status;
50
51
  (t.history ||= []).push({ from, to, by: msg.from, ts: now() });
51
52
  if (t.history.length > 40) t.history.splice(0, 10);
package/hub/store.mjs CHANGED
@@ -44,6 +44,21 @@ function appendTaskNote(t, b, ts = Date.now()) {
44
44
  if (!b || typeof b.note !== "string") return false;
45
45
  return appendTaskLog(t, b.by || "", b.note, ts);
46
46
  }
47
+ function copyTask(task) {
48
+ const index = state.tasks.indexOf(task);
49
+ if (index < 0) return task;
50
+ const copy = JSON.parse(JSON.stringify(task));
51
+ state.tasks[index] = copy;
52
+ return copy;
53
+ }
54
+ function copyMessage(message) {
55
+ const index = state.messages.indexOf(message);
56
+ if (index < 0) return message;
57
+ const copy = { ...message };
58
+ if (Array.isArray(message.refs)) copy.refs = message.refs.slice();
59
+ state.messages[index] = copy;
60
+ return copy;
61
+ }
47
62
  // #6452: a card's drill line (build doctrine rule 1) — the `drill` field, a checklist item or a log
48
63
  // note starting "Drill:", or the move's own note; that note also counts when it names the gate
49
64
  // command it ran (the orchestrator closes with "verified at <sha>" + the gate). The command shapes
@@ -172,15 +187,29 @@ const persistHealth = createPersistHealth({
172
187
  maxMs: process.env.RELAY_PERSIST_RETRY_MAX_MS,
173
188
  logIntervalMs: process.env.RELAY_PERSIST_LOG_INTERVAL_MS,
174
189
  });
175
- const snapshotState = () => JSON.parse(JSON.stringify({ ...state, cardEvents: state.events.filter(e => ["created", "moved", "updated"].includes(e?.type)) }));
190
+ // Events are append-only: share rows between PG snapshots so unchanged rows skip JSON stringifying.
191
+ // Copy the array so later appends/trims cannot change prior membership. JSON writes stringify now,
192
+ // so sharing immutable event rows is safe there too.
193
+ const snapshotState = () => {
194
+ const events = state.events.slice();
195
+ const cardEvents = events.filter(e => ["created", "moved", "updated"].includes(e?.type));
196
+ const messages = state.messages.slice();
197
+ const tasks = state.tasks.slice();
198
+ const snapshot = JSON.parse(JSON.stringify({ ...state, events: [], cardEvents: [], messages: [], tasks: [] }));
199
+ snapshot.events = events;
200
+ snapshot.cardEvents = cardEvents;
201
+ snapshot.messages = messages;
202
+ snapshot.tasks = tasks;
203
+ return snapshot;
204
+ };
176
205
  // This hub's writer id: saveDelta stamps it into every NOTIFY so we can tell our own change
177
206
  // notifications apart from a second writer's (importer, admin psql, another hub instance).
178
207
  const HUB_SRC = `hub-${process.pid}-${randomBytes(4).toString("hex")}`;
179
208
  // What the DB currently holds, as of our last successful persist. saveDelta diffs against this and
180
209
  // writes ONLY the difference — it never deletes rows it has not seen, so a second writer's rows
181
210
  // survive our persist ticks (the old saveSnapshot wholesale delete+rewrite destroyed them).
182
- let lastPersisted = durableStore ? snapshotState() : null;
183
211
  if (runTaskBootMigrations()) dirty = true;
212
+ let lastPersisted = durableStore ? snapshotState() : null;
184
213
  const recordPersistFailure = (kind, error) => {
185
214
  dirty = true;
186
215
  const failure = persistHealth.failed(error);
@@ -262,7 +291,7 @@ setInterval(persist, persistTickMs).unref?.();
262
291
  };
263
292
 
264
293
  return {
265
- state, durableStore, persist, persistHealth, markDirty, reload, startChangeSubscription,
294
+ state, durableStore, persist, persistHealth, markDirty, copyTask, copyMessage, reload, startChangeSubscription,
266
295
  HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
267
296
  };
268
297
  }
package/hub.mjs CHANGED
@@ -87,13 +87,13 @@ if (process.argv.includes("--smoke")) {
87
87
  const reaper = createReaper({
88
88
  state: store.state, markDirty: store.markDirty, canon: authRuntime.canon,
89
89
  now: events.now, appendCardEvent: events.appendCardEvent, appendEvent: events.appendEvent,
90
- appendTaskLog: store.appendTaskLog, sweepPresence: events.sweepPresence, ONLINE_MS, PEER_TTL_MS, PEER_FORGET_MS,
90
+ appendTaskLog: store.appendTaskLog, copyTask: store.copyTask, sweepPresence: events.sweepPresence, ONLINE_MS, PEER_TTL_MS, PEER_FORGET_MS,
91
91
  FOCUS_OFFLINE_MS, FOCUS_IDLE_MS, REAP_GRACE_MS, TODO_STALE_MS, REAP_INTERVAL_MS,
92
92
  CONTRACT_ABANDON_MS, CONTRACT_WINDOW_MS,
93
93
  });
94
94
  const duty = createDuty({
95
95
  state: store.state, now: events.now, appendEvent: events.appendEvent,
96
- appendTaskLog: store.appendTaskLog, canon: authRuntime.canon,
96
+ appendTaskLog: store.appendTaskLog, copyTask: store.copyTask, canon: authRuntime.canon,
97
97
  markDirty: store.markDirty, pushToStreams: events.pushToStreams, OVERSEER_TICK_MS,
98
98
  });
99
99
  const overseer = createOverseer({
@@ -179,14 +179,18 @@ export function permissionRejection(ownText) {
179
179
  return path ? `the sandbox auto-rejected permission for ${path}` : m[0];
180
180
  }
181
181
 
182
- /** #9919: a sandbox permission rejection on a clean exit is the turn dying mid-step. Same doctrine
183
- * as looksLikeBillingDeath (a shipped commit is a live turn), but judged on the TAIL: the capture
184
- * above the rejection is real work, not the answer floor's "just the error" shape. */
185
- export function looksLikePermissionDeath(ownText, realWork = false) {
186
- if (realWork) return false;
182
+ /** #9919/#13945: a trailing rejection ends the turn even when earlier steps committed work.
183
+ * Judge the TAIL so a phrase quoted mid-stream does not relabel a healthy turn. */
184
+ export function looksLikePermissionDeath(ownText) {
187
185
  return permissionRejection(ownText) !== null;
188
186
  }
189
187
 
188
+ export function permissionTool(ownText) {
189
+ const tail = String(ownText || "").slice(-PERMISSION_TAIL);
190
+ if (!permissionRejection(tail)) return null;
191
+ return (tail.match(/permission requested:\s*(\S+)/i) || [])[1] || "this specific tool call";
192
+ }
193
+
190
194
  /** #9724/#8234: a usage record that RESOLVED (the #8234 lookup found the session's record) to all
191
195
  * zeros means no model work happened. Null usage — the CLI prints none and keeps none — stays
192
196
  * unknown and is never failure. */
package/lib/store-pg.mjs CHANGED
@@ -14,9 +14,27 @@ const num = (v) => (v == null ? v : Number(v));
14
14
  // below every caller, so an old client or an imported nested payload cannot poison the delta.
15
15
  export function stripNulDeep(value) {
16
16
  if (typeof value === "string") return value.replace(/\u0000/g, "");
17
- if (Array.isArray(value)) return value.map(stripNulDeep);
17
+ if (Array.isArray(value)) {
18
+ let changed = false;
19
+ const clean = value.map(child => {
20
+ const next = stripNulDeep(child);
21
+ if (next !== child) changed = true;
22
+ return next;
23
+ });
24
+ return changed ? clean : value;
25
+ }
18
26
  if (value && typeof value === "object") {
19
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key.replace(/\u0000/g, ""), stripNulDeep(child)]));
27
+ const entries = Object.entries(value);
28
+ let changed = false;
29
+ const clean = {};
30
+ for (const [key, child] of entries) {
31
+ const nextKey = key.replace(/\u0000/g, "");
32
+ const nextValue = stripNulDeep(child);
33
+ if (nextKey !== key || nextValue !== child) changed = true;
34
+ clean[nextKey] = nextValue;
35
+ }
36
+ if (!changed && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) return value;
37
+ return clean;
20
38
  }
21
39
  return value;
22
40
  }
@@ -187,18 +205,21 @@ function kvFromState(state) {
187
205
  // untouched by construction: that is the property that makes multi-writer safe.
188
206
  function diffById(prevArr, nextArr, idOf) {
189
207
  const prevMap = new Map();
190
- for (const x of prevArr || []) prevMap.set(idOf(x), JSON.stringify(x));
208
+ for (const x of prevArr || []) prevMap.set(idOf(x), x);
191
209
  const upserts = [];
210
+ const added = [];
211
+ const updated = [];
192
212
  const nextIds = new Set();
193
213
  for (const x of nextArr || []) {
194
214
  const id = idOf(x);
195
215
  nextIds.add(id);
196
216
  const p = prevMap.get(id);
197
- if (p === undefined || p !== JSON.stringify(x)) upserts.push(x);
217
+ if (p === undefined) { upserts.push(x); added.push(x); }
218
+ else if (p !== x && JSON.stringify(p) !== JSON.stringify(x)) { upserts.push(x); updated.push(x); }
198
219
  }
199
220
  const deletes = [];
200
221
  for (const id of prevMap.keys()) if (!nextIds.has(id)) deletes.push(id);
201
- return { upserts, deletes };
222
+ return { upserts, added, updated, deletes };
202
223
  }
203
224
 
204
225
  export class PgStore {
@@ -558,8 +579,8 @@ export class PgStore {
558
579
  async saveDelta(orgId, prev, next, { src = "" } = {}) {
559
580
  orgId = String(stripNulDeep(orgId));
560
581
  src = String(stripNulDeep(src));
561
- prev = stripNulDeep(prev || {});
562
- next = stripNulDeep(next || {});
582
+ prev ||= {};
583
+ next ||= {};
563
584
  const tasks = diffById(prev.tasks, next.tasks, t => Number(t.id));
564
585
  const events = diffById(prev.events, next.events, e => Number(e.id));
565
586
  const messages = diffById(prev.messages, next.messages, m => Number(m.id));
@@ -570,7 +591,7 @@ export class PgStore {
570
591
  );
571
592
  const identities = diffById(Object.values(prev.identities || {}), Object.values(next.identities || {}), i => i.pubkey);
572
593
  const devices = diffById(prev.devices, next.devices, d => d.apns_token);
573
- const prevKv = kvFromState(prev), nextKv = kvFromState(next);
594
+ const prevKv = stripNulDeep(kvFromState(prev)), nextKv = stripNulDeep(kvFromState(next));
574
595
  const kvChanged = KV_KEYS.filter(k => JSON.stringify(prevKv[k] ?? null) !== JSON.stringify(nextKv[k] ?? null));
575
596
 
576
597
  const changed = tasks.upserts.length + tasks.deletes.length + events.upserts.length + events.deletes.length
@@ -581,7 +602,8 @@ export class PgStore {
581
602
  const c = await this.pool.connect();
582
603
  try {
583
604
  await c.query("BEGIN");
584
- for (const t of tasks.upserts) {
605
+ for (const raw of tasks.upserts) {
606
+ const t = stripNulDeep(raw);
585
607
  await c.query(
586
608
  `INSERT INTO tasks(id, org_id, project, title, status, assignee, source, difficulty, model, phase, cost_usd, deps, history, created, updated, extra)
587
609
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb,$13::jsonb,$14,$15,$16::jsonb)
@@ -600,7 +622,8 @@ export class PgStore {
600
622
  );
601
623
  }
602
624
  if (tasks.deletes.length) await c.query("DELETE FROM tasks WHERE org_id=$1 AND id = ANY($2::bigint[])", [orgId, tasks.deletes]);
603
- for (const e of events.upserts) {
625
+ for (const raw of events.added) {
626
+ const e = stripNulDeep(raw);
604
627
  const r = await c.query(
605
628
  `INSERT INTO events(id, org_id, ts, type, project, by_session, task_id, payload)
606
629
  VALUES($1,$2,$3,$4,$5,$6,$7,$8::jsonb)
@@ -614,9 +637,17 @@ export class PgStore {
614
637
  this.onDroppedEvent?.({ id: Number(e.id), type: e.type || "", orgId });
615
638
  }
616
639
  }
640
+ for (const raw of events.updated) {
641
+ const e = stripNulDeep(raw);
642
+ await c.query(
643
+ `UPDATE events SET ts=$3, type=$4, project=$5, by_session=$6, task_id=$7, payload=$8::jsonb WHERE id=$1 AND org_id=$2`,
644
+ [Number(e.id), orgId, ms(e.ts), e.type || "", e.project || "", e.by || "", e.taskId ?? null, JSON.stringify(stripEventPayload(e))],
645
+ );
646
+ }
617
647
  if (events.deletes.length) await c.query("DELETE FROM events WHERE org_id=$1 AND id = ANY($2::bigint[])", [orgId, events.deletes]);
618
- if (events.upserts.length) await c.query("SELECT setval(pg_get_serial_sequence('events','id'), GREATEST((SELECT COALESCE(MAX(id),0) FROM events), 1), true)");
619
- for (const m of messages.upserts) {
648
+ if (events.added.length) await c.query("SELECT setval(pg_get_serial_sequence('events','id'), GREATEST((SELECT COALESCE(MAX(id),0) FROM events), 1), true)");
649
+ for (const raw of messages.upserts) {
650
+ const m = stripNulDeep(raw);
620
651
  await c.query(
621
652
  `INSERT INTO messages(id, org_id, ts, from_session, to_session, project, text, refs, re, wake, kind)
622
653
  VALUES($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11)
@@ -626,7 +657,8 @@ export class PgStore {
626
657
  );
627
658
  }
628
659
  if (messages.deletes.length) await c.query("DELETE FROM messages WHERE org_id=$1 AND id = ANY($2::bigint[])", [orgId, messages.deletes]);
629
- for (const p of peers.upserts) {
660
+ for (const raw of peers.upserts) {
661
+ const p = stripNulDeep(raw);
630
662
  await c.query(
631
663
  `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind)
632
664
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
@@ -640,7 +672,8 @@ export class PgStore {
640
672
  );
641
673
  }
642
674
  if (peers.deletes.length) await c.query("DELETE FROM peers WHERE org_id=$1 AND session = ANY($2::text[])", [orgId, peers.deletes]);
643
- for (const d of devices.upserts) {
675
+ for (const raw of devices.upserts) {
676
+ const d = stripNulDeep(raw);
644
677
  await c.query(
645
678
  `INSERT INTO devices(org_id, pubkey, apns_token, env, bundle_id, name, created, last_ok, muted_projects)
646
679
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9::jsonb)
@@ -651,7 +684,8 @@ export class PgStore {
651
684
  );
652
685
  }
653
686
  if (devices.deletes.length) await c.query("DELETE FROM devices WHERE org_id=$1 AND apns_token = ANY($2::text[])", [orgId, devices.deletes]);
654
- for (const id of identities.upserts) {
687
+ for (const raw of identities.upserts) {
688
+ const id = stripNulDeep(raw);
655
689
  await c.query(
656
690
  `INSERT INTO identities(pubkey, org_id, name, kind, scopes, enrolled_by, created_at, revoked_at)
657
691
  VALUES($1,$2,$3,$4,$5::jsonb,$6,$7,$8)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.126",
3
+ "version": "0.18.128",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"