trantor 0.18.127 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -0
- package/bin/cargo-gate.mjs +19 -0
- package/bin/crew-runner.mjs +90 -43
- package/bin/heavy-gate-shim/cargo +2 -0
- package/bin/heavy-gate-shim/npx +2 -0
- package/bin/heavy-gate-shim/pnpm +2 -0
- package/bin/heavy-gate.mjs +4 -0
- package/bin/package-runner-gate.mjs +19 -0
- package/bin/turn-watchdog.mjs +15 -6
- package/hub/duty.mjs +4 -3
- package/hub/reaper.mjs +11 -5
- package/hub/routes/admin.mjs +7 -5
- package/hub/routes/cards.mjs +24 -13
- package/hub/routes/contract-transfer.mjs +17 -5
- package/hub/routes/messages.mjs +4 -3
- package/hub/store.mjs +32 -3
- package/hub.mjs +2 -2
- package/lib/classify-failure.mjs +9 -5
- package/lib/heavy-gate-wait.mjs +28 -0
- package/lib/heavy-gate.mjs +139 -0
- package/lib/seat-worktree.mjs +7 -3
- package/lib/store-pg.mjs +49 -15
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
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);
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -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";
|
|
@@ -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.
|
|
@@ -508,6 +509,21 @@ let parkAnnounced = false;
|
|
|
508
509
|
// #7914: the park this seat is currently sitting in, or null. Read by the poll loop, which ends a
|
|
509
510
|
// bounded one the moment somebody sends a direct message, and cleared by any turn that lands.
|
|
510
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
|
+
}
|
|
511
527
|
// #13474: uncommitted work in the seat worktree is saved on the seat branch when a turn is cut or
|
|
512
528
|
// the seat parks, so the next seat starts from it. One log line, only when something was saved.
|
|
513
529
|
function saveWipLogged(why) {
|
|
@@ -516,7 +532,8 @@ function saveWipLogged(why) {
|
|
|
516
532
|
return sha;
|
|
517
533
|
}
|
|
518
534
|
|
|
519
|
-
async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } = {}) {
|
|
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
|
|
520
537
|
saveWipLogged(`parked: ${reason}`);
|
|
521
538
|
// A seat that went QUIET printed no wall message to parse (#6131), so its own balance row is the
|
|
522
539
|
// only place the reset time exists. Output first when there is any: it is this turn's evidence.
|
|
@@ -531,7 +548,7 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } =
|
|
|
531
548
|
// The park is a STATE, and every reader of it is off the bus: `trantor seat-why`, the app, the
|
|
532
549
|
// operator at a terminal an hour later. The message below is the event; this file is the state.
|
|
533
550
|
try { writeFileSync(PARKF, JSON.stringify({ session: SESSION, persona: PERSONA, agent: AGENT, project: PROJ, ...parkState })); } catch {}
|
|
534
|
-
if (!parkAnnounced) {
|
|
551
|
+
if (announce && !parkAnnounced) {
|
|
535
552
|
parkAnnounced = true;
|
|
536
553
|
// #7752: a stalled park names the CLI and its model — the swap decision needs both, and this
|
|
537
554
|
// line is the one place the room reads them together.
|
|
@@ -546,8 +563,9 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } =
|
|
|
546
563
|
}
|
|
547
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`);
|
|
548
565
|
// The alarm for "the bus is stuck" cannot itself be a bus message, so a park also rings a bell
|
|
549
|
-
// the operator can hear out of band
|
|
550
|
-
|
|
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})`,
|
|
551
569
|
`${undelivered} message(s) held${when ? ` — retrying after ${when}` : ` — needs \`trantor up ${AGENT}\``}`);
|
|
552
570
|
// #7749: parked is a first-class phase — the file and the peer row both say so, so an
|
|
553
571
|
// orchestrator stops confusing a quota-held seat with a working or a dead one.
|
|
@@ -561,12 +579,21 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } =
|
|
|
561
579
|
// #7914: the park is over — because a direct message asked for a turn now, or because one landed.
|
|
562
580
|
// The record goes with it, and the announce latch reopens so the NEXT park is heard too (a latch
|
|
563
581
|
// that never reopens turns a repeating park into one message and then silence).
|
|
564
|
-
|
|
582
|
+
// #13949: the END is an event too, once — one "recovered" each to the room and the orchestrator.
|
|
583
|
+
async function unpark(why) {
|
|
565
584
|
if (!parkState) return;
|
|
566
|
-
|
|
585
|
+
const { reason, ts } = parkState;
|
|
586
|
+
log(`\x1b[33mpark ended (${reason}) — ${why}\x1b[0m`);
|
|
567
587
|
parkState = null;
|
|
568
588
|
parkAnnounced = false;
|
|
569
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;
|
|
570
597
|
}
|
|
571
598
|
|
|
572
599
|
/**
|
|
@@ -671,13 +698,17 @@ async function busActivitySince(seq) {
|
|
|
671
698
|
}
|
|
672
699
|
|
|
673
700
|
async function reportHealthy() {
|
|
701
|
+
const saidParkRecovered = parkRecovered;
|
|
702
|
+
parkRecovered = false; // #13949: consumed whether used or not — never a stale skip
|
|
674
703
|
if (consecFails === 0) return; // already healthy — don't spam
|
|
675
704
|
consecFails = 0;
|
|
676
705
|
// Recovery is a change too, so the next failure is news again — a park included.
|
|
677
706
|
announced = "";
|
|
678
707
|
parkAnnounced = false;
|
|
679
708
|
await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
|
|
680
|
-
|
|
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(() => {});
|
|
681
712
|
cmuxStatus("ok", "#14b8a6", "check"); herdrAgent("idle");
|
|
682
713
|
}
|
|
683
714
|
|
|
@@ -843,6 +874,7 @@ let lastEnvelope = "";
|
|
|
843
874
|
async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
844
875
|
TURN++; banner(trigger);
|
|
845
876
|
lastEnvelope = "";
|
|
877
|
+
lastPermissionReject = null;
|
|
846
878
|
const t0 = Date.now();
|
|
847
879
|
// A fresh session must not resume the old one's id: `first` is chosen by isFirst OR a missing
|
|
848
880
|
// sid, so a stale sid would quietly resume the session this turn exists to leave behind.
|
|
@@ -929,6 +961,8 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
929
961
|
// ONE stall report, never a kill. #6206: floor 10 min, never derived from TRANTOR_TURN_MAX_MS.
|
|
930
962
|
const WD_MS = Number(process.env.TRANTOR_TURN_WATCHDOG_MS) || 10 * 60 * 1000;
|
|
931
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 });
|
|
932
966
|
// #6206: the CLI's transcript dir (a missing dir is a quiet channel), exported so a drill's fake
|
|
933
967
|
// CLI can write lines the watchdog sees. CUTF is written by the shell's time box: cut, not crashed.
|
|
934
968
|
const CUTF = join(homedir(), ".agent-bus", `turncut-${PERSONA}-${PROJ}`);
|
|
@@ -944,7 +978,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
944
978
|
const EXTF = join(homedir(), ".agent-bus", `turnext-${PERSONA}-${PROJ}`);
|
|
945
979
|
try { unlinkSync(DEADLINEF); } catch {}
|
|
946
980
|
try { unlinkSync(EXTF); } catch {}
|
|
947
|
-
const boxPlan =
|
|
981
|
+
const boxPlan = TURN_MAX_MS ? {
|
|
948
982
|
maxMs: TURN_MAX_MS, extendMs: TURN_EXTEND_MS, ceilingMs: TURN_CEILING_MS, extensionsMax: TURN_EXTENSIONS_MAX,
|
|
949
983
|
deadlineFile: DEADLINEF, extFile: EXTF, card: sessionCard || 0,
|
|
950
984
|
assigners: (opts.assigners || []).map(a => ({ from: a.from, id: a.id })),
|
|
@@ -968,7 +1002,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
968
1002
|
// end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
|
|
969
1003
|
TURN_MAX_MS ? STALLF : "",
|
|
970
1004
|
// #7749: the turn-state file the watchdog refreshes mid-turn (lastBytesAt/lastTranscriptAt).
|
|
971
|
-
join(homedir(), ".agent-bus", `turnstate-${PERSONA}-${PROJ}.json`)],
|
|
1005
|
+
join(homedir(), ".agent-bus", `turnstate-${PERSONA}-${PROJ}.json`), HEAVY_WAIT_DIR],
|
|
972
1006
|
{ detached: true, stdio: "ignore" });
|
|
973
1007
|
WD_CHILD = wd;
|
|
974
1008
|
wd.unref();
|
|
@@ -1030,6 +1064,8 @@ exit $turn_exit`;
|
|
|
1030
1064
|
// A runner-managed seat must never hand itself a baton: the runner is its lifecycle manager,
|
|
1031
1065
|
// so a handoff spawn would only leak an unmanaged interactive window.
|
|
1032
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 || ""}`,
|
|
1033
1069
|
// #6206: the seat's transcript dir — a real CLI ignores it, a drill's fake CLI writes
|
|
1034
1070
|
// its transcript lines there so the watchdog sees the liveness a real claude shows.
|
|
1035
1071
|
TRANTOR_TRANSCRIPT_DIR: TRANSCRIPT_DIR };
|
|
@@ -1039,16 +1075,12 @@ exit $turn_exit`;
|
|
|
1039
1075
|
if (cli.pinned && OC_SEAT_CONFIG) spawnEnv.OPENCODE_CONFIG_CONTENT = OC_SEAT_CONFIG;
|
|
1040
1076
|
spawnOpts.env = spawnEnv;
|
|
1041
1077
|
spawnOpts.maxBuffer = 16 * 1024 * 1024;
|
|
1042
|
-
// The timeout signals the shell to snapshot before sweeping, just like the normal box.
|
|
1043
|
-
// Its 30s margin keeps it out of the normal cut path.
|
|
1044
|
-
if (TURN_MAX_MS) { spawnOpts.timeout = (TURN_EXTENSIONS_MAX ? TURN_CEILING_MS : TURN_MAX_MS) + 30000; spawnOpts.killSignal = "SIGTERM"; }
|
|
1045
1078
|
const r = spawnSync("/bin/bash", ["-c", shell], spawnOpts);
|
|
1046
|
-
//
|
|
1047
|
-
//
|
|
1048
|
-
// 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.
|
|
1049
1081
|
const boxed = existsSync(CUTF);
|
|
1050
1082
|
const stallCut = existsSync(STALLF);
|
|
1051
|
-
const cut = !!TURN_MAX_MS && (boxed || stallCut
|
|
1083
|
+
const cut = !!TURN_MAX_MS && (boxed || stallCut);
|
|
1052
1084
|
// #7761: how far the watchdog moved the box, one EXTF row per extension. boxMs is the box the
|
|
1053
1085
|
// turn actually had, so a ceiling cut reads as the ceiling, never as the 20-minute default.
|
|
1054
1086
|
let extensions = 0;
|
|
@@ -1073,8 +1105,8 @@ exit $turn_exit`;
|
|
|
1073
1105
|
try { unlinkSync(CUTF); } catch {}
|
|
1074
1106
|
try { unlinkSync(STALLF); } catch {}
|
|
1075
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`);
|
|
1076
|
-
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
|
|
1077
|
-
else log(`\x1b[33mturn cut at the ${Math.round(TURN_MAX_MS / 1000)}s time box — CLI and every descendant ended
|
|
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`);
|
|
1078
1110
|
}
|
|
1079
1111
|
lastTurnCut = cut;
|
|
1080
1112
|
lastTurnStalled = cut && stallCut;
|
|
@@ -1129,13 +1161,12 @@ exit $turn_exit`;
|
|
|
1129
1161
|
effExit = 1;
|
|
1130
1162
|
log(`\x1b[31mexit 0 but the turn output IS a provider billing rejection — treating as FAILED (exhausted, "${BILLING_RE.exec(ownOut)[0]}")\x1b[0m`);
|
|
1131
1163
|
}
|
|
1132
|
-
// #9919:
|
|
1133
|
-
//
|
|
1134
|
-
|
|
1135
|
-
// the turn ended, so a turn that only quotes the phrase mid-stream stays success.
|
|
1136
|
-
if (realExit === 0 && effExit === 0 && looksLikePermissionDeath(ownOut, newCommit)) {
|
|
1164
|
+
// #9919/#13945: a trailing denial is an incomplete turn even when an earlier step committed.
|
|
1165
|
+
// Otherwise verdictFor names permission-rejected while the clean exit still produces "done".
|
|
1166
|
+
if (realExit === 0 && effExit === 0 && looksLikePermissionDeath(ownOut)) {
|
|
1137
1167
|
effExit = 1;
|
|
1138
|
-
|
|
1168
|
+
lastPermissionReject = { evidence: permissionRejection(ownOut), tool: permissionTool(ownOut) || "unknown" };
|
|
1169
|
+
log(`\x1b[31mexit 0 but the turn output IS a sandbox permission rejection — treating as FAILED (permission-rejected, "${lastPermissionReject.evidence}")\x1b[0m`);
|
|
1139
1170
|
}
|
|
1140
1171
|
// #5481: exit 0 with an empty ERRF (the TOTAL capture, both streams) is the null-completion trap,
|
|
1141
1172
|
// judged on echo-stripped text (#5868). #6969: on a state step ERRF is stderr only, so silence is normal.
|
|
@@ -1243,7 +1274,7 @@ exit $turn_exit`;
|
|
|
1243
1274
|
// api-error, completed — and what it cost (0 means "not reported", never "free"). #7762: `card`
|
|
1244
1275
|
// binds the row to the card the turn worked (0 = kickoff/pulse) so the seat record attributes
|
|
1245
1276
|
// empty/stalled turns to the card that produced nothing. `cut` stays too: the drills read it.
|
|
1246
|
-
const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? "api-error" : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
|
|
1277
|
+
const outcome = cut ? (stallCut ? "stalled" : "cut") : (effExit !== 0 ? (lastPermissionReject ? "rejected" : "api-error") : noDelivery ? "no-delivery" : lastEmptyTurn ? "empty" : "completed");
|
|
1247
1278
|
const finalOutcome = askVerdict ? "asked" : blockedVerdict ? "blocked" : outcome;
|
|
1248
1279
|
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 };
|
|
1249
1280
|
if (usage) telemetryRow.usage = usage;
|
|
@@ -1738,12 +1769,12 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1738
1769
|
// #10197: no-delivery owes the old contract, but its retry delay must not batch away
|
|
1739
1770
|
// fresh contracts. Only actual CLI failures impose backoff on a new wake.
|
|
1740
1771
|
if (noDeliveryRetry) {
|
|
1741
|
-
unpark("new wake after no-delivery");
|
|
1772
|
+
await unpark("new wake after no-delivery");
|
|
1742
1773
|
retryAt = 0; deliveryFails = 0; noDeliveryRetry = false;
|
|
1743
1774
|
}
|
|
1744
1775
|
if (parkState && directWake.length) {
|
|
1745
1776
|
if (isBoundedPark(parkState.reason)) {
|
|
1746
|
-
unpark(`direct message from ${directWake[0].from || "?"}`);
|
|
1777
|
+
await unpark(`direct message from ${directWake[0].from || "?"}`);
|
|
1747
1778
|
retryAt = 0; deliveryFails = 0; cutChain = [];
|
|
1748
1779
|
} else {
|
|
1749
1780
|
log(`\x1b[33mparked (${parkState.reason}) — a direct message cannot clear this park; it holds until the reset or \`trantor up ${AGENT}\`\x1b[0m`);
|
|
@@ -2044,6 +2075,16 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2044
2075
|
lastTurnAt = Date.now();
|
|
2045
2076
|
return;
|
|
2046
2077
|
}
|
|
2078
|
+
if (ec && lastPermissionReject && sessionCard > 0) {
|
|
2079
|
+
const text = `⛔ permission rejected: ${lastPermissionReject.tool} on #${sessionCard} · ${lastPermissionReject.evidence} · card moved to blocked; wake stays owed`;
|
|
2080
|
+
savePending(pendingWake, pendingBcast);
|
|
2081
|
+
await api("/task/update", { id: sessionCard, status: "blocked", note: text, by: SESSION }).catch(() => {});
|
|
2082
|
+
const renewed = sameParkEpisode("permission-rejected"); // #13949: once per episode
|
|
2083
|
+
retryAt = await parkSeat("permission-rejected", pendingWake.length, 0, { announce: false });
|
|
2084
|
+
if (!renewed) await notifyAssigners(assigners, text);
|
|
2085
|
+
lastTurnAt = Date.now();
|
|
2086
|
+
return;
|
|
2087
|
+
}
|
|
2047
2088
|
if (ec) {
|
|
2048
2089
|
deliveryFails++;
|
|
2049
2090
|
// #7752: a SILENT cut is a stall, whatever the captured text contains — the qwen
|
|
@@ -2074,6 +2115,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2074
2115
|
const stallWhy = reason === "stalled" ? ` · probable cause: ${stallCause({ text: lastErrText })}` : "";
|
|
2075
2116
|
const evidence = cutChain.length >= CUT_CHAIN_PARK_MIN ? cutChainEvidence(cutChain) : "";
|
|
2076
2117
|
if (PARKING_REASONS.has(reason) || deliveryFails >= 2) {
|
|
2118
|
+
const renewed = sameParkEpisode(parkReason); // #13949: a window-lift retry re-parking
|
|
2077
2119
|
retryAt = await parkSeat(parkReason, pendingWake.length, quotaReset, { evidence });
|
|
2078
2120
|
// RUNNER_PARK_MAX_MS is set only by `trantor duty up` (launchd keepalive): past the ceiling,
|
|
2079
2121
|
// exit so the supervisor restarts clean. Unsupervised seats stay parked; exiting would kill them.
|
|
@@ -2088,15 +2130,16 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2088
2130
|
}
|
|
2089
2131
|
// #7914: what the park is, when it lifts, and the evidence it rests on — in the message
|
|
2090
2132
|
// that reaches the one who is actually blocked, not only in the card log they never read.
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
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
|
+
}
|
|
2100
2143
|
lastTurnAt = Date.now();
|
|
2101
2144
|
return;
|
|
2102
2145
|
}
|
|
@@ -2127,9 +2170,12 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2127
2170
|
savePending(pendingWake, pendingBcast);
|
|
2128
2171
|
const still = lastNoDeliveryStatus || "unresolved";
|
|
2129
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");
|
|
2130
2176
|
retryAt = await parkSeat("no-delivery", pendingWake.length);
|
|
2131
|
-
await notifyAssigners(assigners,
|
|
2132
|
-
`⛔ 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}"`);
|
|
2133
2179
|
lastTurnAt = Date.now();
|
|
2134
2180
|
return;
|
|
2135
2181
|
}
|
|
@@ -2145,9 +2191,10 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2145
2191
|
deliveryFails++;
|
|
2146
2192
|
savePending(pendingWake, pendingBcast);
|
|
2147
2193
|
if (deliveryFails >= 2) {
|
|
2194
|
+
const renewed = sameParkEpisode("empty-turn"); // #13949: retries inside the episode stay quiet
|
|
2148
2195
|
retryAt = await parkSeat("empty-turn", pendingWake.length);
|
|
2149
|
-
await notifyAssigners(assigners,
|
|
2150
|
-
`⛔ 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}"`);
|
|
2151
2198
|
lastTurnAt = Date.now();
|
|
2152
2199
|
return;
|
|
2153
2200
|
}
|
|
@@ -2158,7 +2205,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2158
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}"`);
|
|
2159
2206
|
} else {
|
|
2160
2207
|
pendingWake = []; pendingBcast = []; deliveryFails = 0; retryAt = 0;
|
|
2161
|
-
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
|
|
2162
2209
|
// #7778: reconcile BEFORE the write below so the persisted snapshot carries the seen-set.
|
|
2163
2210
|
await reconcileSessionReads(cursor);
|
|
2164
2211
|
savePending([], []);
|
|
@@ -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);
|
package/bin/turn-watchdog.mjs
CHANGED
|
@@ -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`
|
|
102
|
-
// deadline one poll away on a turn
|
|
103
|
-
const
|
|
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 + (
|
|
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}`;
|
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
|
-
|
|
65
|
-
|
|
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
|
|
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
|
|
40
|
-
if (!
|
|
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
|
|
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);
|
package/hub/routes/admin.mjs
CHANGED
|
@@ -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
|
-
|
|
150
|
-
|
|
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
|
|
309
|
-
if (
|
|
310
|
-
|
|
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
|
}
|
package/hub/routes/cards.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
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 (
|
|
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 (
|
|
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
|
|
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
|
-
|
|
44
|
-
|
|
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
|
|
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}`);
|
package/hub/routes/messages.mjs
CHANGED
|
@@ -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
|
|
48
|
-
if (!
|
|
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
|
-
|
|
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({
|
package/lib/classify-failure.mjs
CHANGED
|
@@ -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
|
|
183
|
-
*
|
|
184
|
-
|
|
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. */
|
|
@@ -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
|
+
}
|
package/lib/seat-worktree.mjs
CHANGED
|
@@ -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
|
|
29
|
-
//
|
|
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/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))
|
|
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
|
-
|
|
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),
|
|
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
|
|
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
|
|
562
|
-
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
|
|
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
|
|
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.
|
|
619
|
-
for (const
|
|
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
|
|
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
|
|
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
|
|
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)
|