trantor 0.18.121 → 0.18.123
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/bin/crew-runner.mjs +54 -16
- package/bin/patrol.mjs +5 -9
- package/hooks/hooks.json +10 -0
- package/hooks/lib/current-state.mjs +139 -0
- package/hooks/lib/handoff-facts.mjs +77 -0
- package/hooks/lib/handoff.mjs +5 -0
- package/hooks/progress-log.mjs +44 -0
- package/hooks/sessionstart.mjs +3 -1
- package/lib/burn-guard.mjs +21 -0
- package/lib/seat-provider.mjs +32 -0
- package/lib/stall-cause.mjs +14 -0
- package/lib/wip-save.mjs +16 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.123",
|
|
4
4
|
"description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
|
|
5
5
|
"mcpServers": {
|
|
6
6
|
"relay": {
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -32,6 +32,10 @@ import { ocTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput,
|
|
|
32
32
|
import { capConfig, capDecision, capHandoffPrompt, capPointerLine, capExhaustedNote } from "../lib/context-cap.mjs";
|
|
33
33
|
import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
|
|
34
34
|
import { seatSignalPrefix } from "../lib/seat-signal-guard.mjs";
|
|
35
|
+
import { providerMismatch } from "../lib/seat-provider.mjs";
|
|
36
|
+
import { burnCeiling, afterTurn, burnVerdict } from "../lib/burn-guard.mjs";
|
|
37
|
+
import { saveWip } from "../lib/wip-save.mjs";
|
|
38
|
+
import { stallCause } from "../lib/stall-cause.mjs";
|
|
35
39
|
import { listContainers, newContainers, recordContainers, statePathFor as dockerStatePathFor, sweep as dockerSweep } from "../lib/docker-janitor.mjs";
|
|
36
40
|
import {
|
|
37
41
|
auditDutyNudges, claimDutyNudges, claudeTranscriptDir, dutyEscalations, dutyNudgeDirective,
|
|
@@ -492,7 +496,16 @@ let parkAnnounced = false;
|
|
|
492
496
|
// #7914: the park this seat is currently sitting in, or null. Read by the poll loop, which ends a
|
|
493
497
|
// bounded one the moment somebody sends a direct message, and cleared by any turn that lands.
|
|
494
498
|
let parkState = null;
|
|
499
|
+
// #13474: uncommitted work in the seat worktree is saved on the seat branch when a turn is cut or
|
|
500
|
+
// the seat parks, so the next seat starts from it. One log line, only when something was saved.
|
|
501
|
+
function saveWipLogged(why) {
|
|
502
|
+
const sha = sessionCard > 0 ? saveWip(TURN_DIR, sessionCard) : "";
|
|
503
|
+
if (sha) log(`\x1b[33msaved uncommitted work as ${sha.slice(0, 8)} on the seat branch (${why})\x1b[0m`);
|
|
504
|
+
return sha;
|
|
505
|
+
}
|
|
506
|
+
|
|
495
507
|
async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "" } = {}) {
|
|
508
|
+
saveWipLogged(`parked: ${reason}`);
|
|
496
509
|
// A seat that went QUIET printed no wall message to parse (#6131), so its own balance row is the
|
|
497
510
|
// only place the reset time exists. Output first when there is any: it is this turn's evidence.
|
|
498
511
|
const resetAt = parseResetAt(lastErrText) || resetHint;
|
|
@@ -764,9 +777,10 @@ let sessionCard = releaseState?.sessionCard || 0;
|
|
|
764
777
|
// provider's session DB when the CLI prints none). A card that crosses its budget pauses — no
|
|
765
778
|
// further turn is bought for THAT card — until the card changes or the seat restarts, both of
|
|
766
779
|
// which reset the counter. The budget itself is an env knob, not a constant in the wall.
|
|
767
|
-
const CARD_TOKEN_BUDGET =
|
|
780
|
+
const CARD_TOKEN_BUDGET = burnCeiling(); // #13474: the ceiling counts tokens since the last commit
|
|
768
781
|
const BUDGET_RETRY_MS = 10 * 60 * 1000; // a paused card's OWN redelivery pace, never other cards'
|
|
769
782
|
let cardTokens = releaseState?.cardTokens || 0;
|
|
783
|
+
let cardCommits = releaseState?.cardCommits || 0; // #13474: commits made on the current contract
|
|
770
784
|
let cardStartedAt = releaseState?.cardStartedAt || 0;
|
|
771
785
|
let budgetStop = releaseState?.budgetStop || null; // { card, tokens } once the card crossed
|
|
772
786
|
let budgetRetryAt = releaseState?.budgetRetryAt || 0; // paces the paused card's OWN redeliveries
|
|
@@ -1045,6 +1059,7 @@ exit $turn_exit`;
|
|
|
1045
1059
|
}
|
|
1046
1060
|
lastTurnCut = cut;
|
|
1047
1061
|
lastTurnStalled = cut && stallCut;
|
|
1062
|
+
if (cut) saveWipLogged("turn cut");
|
|
1048
1063
|
// #7749: the cut boundary lands on disk and on the peer row BEFORE the follow-up turn overwrites
|
|
1049
1064
|
// it — a reader sampling mid-chain sees what actually just happened, not a stale "working".
|
|
1050
1065
|
if (cut) {
|
|
@@ -1143,7 +1158,8 @@ exit $turn_exit`;
|
|
|
1143
1158
|
if (usage) tokens = usageTotal(usage);
|
|
1144
1159
|
// #11559: every token this turn spent rides the card it served. A card-0 turn (kickoff, pulse,
|
|
1145
1160
|
// duty) belongs to no card and adds nothing; the counter resets when the served card changes.
|
|
1146
|
-
|
|
1161
|
+
// #13474: a commit is progress and zeroes the count (burn guard).
|
|
1162
|
+
if (sessionCard > 0) ({ tokens: cardTokens, commits: cardCommits } = afterTurn({ tokens: cardTokens, commits: cardCommits }, { spent: Number.isFinite(tokens) ? tokens : 0, committed: newCommit }));
|
|
1147
1163
|
// #9724: usage RESOLVED to all zeros means no model work happened — never success; null stays
|
|
1148
1164
|
// unknown, never failure, and a shipped commit is real work (stale record, not the turn).
|
|
1149
1165
|
const zeroUsage = realExit === 0 && effExit === 0 && !newCommit && usageSaysNoWork(usage);
|
|
@@ -1556,7 +1572,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1556
1572
|
wake: pendingWake, bcast: pendingBcast, seen: seenLedger, ask: awaitingAsk?.id || 0, askTo: awaitingAsk?.to || "" }));
|
|
1557
1573
|
const state = { cursor, turn: TURN, sid, sessionCard, retryAt, deliveryFails,
|
|
1558
1574
|
noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions],
|
|
1559
|
-
cardTokens, cardStartedAt, budgetStop, budgetRetryAt,
|
|
1575
|
+
cardTokens, cardCommits, cardStartedAt, budgetStop, budgetRetryAt,
|
|
1560
1576
|
capHandoffs, capLogged, capArmed, capFreshTurn };
|
|
1561
1577
|
process.execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
|
|
1562
1578
|
{ ...process.env, CREW_RELEASE_STATE: JSON.stringify(state) });
|
|
@@ -1799,7 +1815,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1799
1815
|
const bp = budgetPause({ paused: budgetStop, status, messages: wakeForTurn, session: SESSION });
|
|
1800
1816
|
if (bp.action === "lift") {
|
|
1801
1817
|
log(`#${budgetStop.card} is ${status} — token-budget pause lifted`);
|
|
1802
|
-
budgetStop = null; budgetRetryAt = 0; cardTokens = 0;
|
|
1818
|
+
budgetStop = null; budgetRetryAt = 0; cardTokens = 0; cardCommits = 0;
|
|
1803
1819
|
} else if (bp.action === "bind") {
|
|
1804
1820
|
log(`#${budgetStop.card} is paused over its token budget — serving the newer contract for #${bp.card}, dropping ${bp.drop.length} stale message(s)`);
|
|
1805
1821
|
wakeForTurn = wakeForTurn.filter(m => !bp.drop.includes(m));
|
|
@@ -1872,6 +1888,17 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1872
1888
|
// (and resets the counter with the fresh session below); the paused card itself never buys
|
|
1873
1889
|
// another CLI session. The wake stays owed and retries on a long clock, so the orchestrator
|
|
1874
1890
|
// sees the pause, not a silent seat.
|
|
1891
|
+
// #13474: never run a metered provider under a subscription label (or any model off its label).
|
|
1892
|
+
// A `trantor swap` (CREW_SWAP_DRIVER) is the operator choosing another provider on purpose.
|
|
1893
|
+
const mismatch = process.env.CREW_SWAP_DRIVER ? null : providerMismatch(AGENT, MODEL);
|
|
1894
|
+
if (mismatch) {
|
|
1895
|
+
const why = `label ${mismatch.label} but the live model is ${mismatch.model} (expected ${mismatch.expected}, got ${mismatch.actual})`;
|
|
1896
|
+
log(`\x1b[31mturn refused: ${why}\x1b[0m`);
|
|
1897
|
+
const first = !parkAnnounced; // one message per episode, not one per redelivery
|
|
1898
|
+
retryAt = await parkSeat("label-mismatch", pendingWake.length, 0, { evidence: why });
|
|
1899
|
+
if (first) await notifyAssigners(assigners,`⛔ your contract is PARKED on ${SESSION} (label-mismatch: ${why}) · asked: "${asked}"`);
|
|
1900
|
+
return;
|
|
1901
|
+
}
|
|
1875
1902
|
if (budgetStop && sessionCardForTurn > 0 && sessionCardForTurn === budgetStop.card) {
|
|
1876
1903
|
log(`\x1b[33mqueued — #${budgetStop.card} is over its token budget (${budgetStop.tokens} ≥ ${CARD_TOKEN_BUDGET}); paused until the card moves or \`trantor up ${AGENT}\` resets the budget\x1b[0m`);
|
|
1877
1904
|
// Pace only the SELF-redelivery path (a non-empty queue with retryAt=0 would otherwise
|
|
@@ -1881,7 +1908,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1881
1908
|
return;
|
|
1882
1909
|
}
|
|
1883
1910
|
if (budgetStop && newCard) { budgetStop = null; budgetRetryAt = 0; }
|
|
1884
|
-
if (newCard) { cardTokens = 0; cardStartedAt = Date.now(); }
|
|
1911
|
+
if (newCard) { cardTokens = 0; cardCommits = 0; cardStartedAt = Date.now(); }
|
|
1885
1912
|
sessionCard = card;
|
|
1886
1913
|
const cited = [...new Set(wakeForTurn.flatMap(m => cardRefs(m.text)))];
|
|
1887
1914
|
const capPointer = capFresh ? capPointerLine(sessionCardForTurn) : "";
|
|
@@ -1917,6 +1944,24 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1917
1944
|
}
|
|
1918
1945
|
finally { stopDutyNudgeWatcher(); }
|
|
1919
1946
|
const secs = Math.round((Date.now() - tStart) / 1000);
|
|
1947
|
+
// #13474: enforced on EVERY turn ending, failed ones included (the burn came from failing turns
|
|
1948
|
+
// the old exit-0-only check never saw). One note and one message per episode: budgetStop latches.
|
|
1949
|
+
const burn = burnVerdict({ card: sessionCard, tokens: cardTokens, commits: cardCommits, ceiling: CARD_TOKEN_BUDGET, agent: AGENT, stopped: !!budgetStop });
|
|
1950
|
+
if (burn) {
|
|
1951
|
+
budgetStop = { card: sessionCard, tokens: cardTokens };
|
|
1952
|
+
log(`\x1b[33m${burn.text}\x1b[0m`);
|
|
1953
|
+
saveWipLogged("burn ceiling");
|
|
1954
|
+
await api("/task/update", { id: sessionCard, note: burn.note, by: SESSION }).catch(() => {});
|
|
1955
|
+
await notifyAssigners(assigners, burn.text);
|
|
1956
|
+
const orch = `${hostId()}:${PROJ}`;
|
|
1957
|
+
if (!assigners.some(a => a.from === orch)) await api("/send", { from: SESSION, to: orch, text: burn.text, project: PROJ, kind: "alert" }).catch(() => {});
|
|
1958
|
+
if (ec) { // the failure ladder would park and message a second time
|
|
1959
|
+
budgetRetryAt = Date.now() + BUDGET_RETRY_MS;
|
|
1960
|
+
savePending(pendingWake, pendingBcast);
|
|
1961
|
+
lastTurnAt = Date.now();
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1920
1965
|
let skippedNudges = [];
|
|
1921
1966
|
if (!ec && dutyPlan.items.length) {
|
|
1922
1967
|
const observedIds = observedDutyNudgeIds(TRANSCRIPT_DIR, tStart);
|
|
@@ -1984,6 +2029,8 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1984
2029
|
// #7914: the park owes its evidence — which turns the box killed, their exits, the box that
|
|
1985
2030
|
// ended them — whatever rung fired it. The THRESHOLD is #6289's and stays #6289's: a chain
|
|
1986
2031
|
// retries once and the second failed chain parks, never the first (its drill B pins that).
|
|
2032
|
+
// #13474: a silent stall also says why, in the park notice and the retry notice alike.
|
|
2033
|
+
const stallWhy = reason === "stalled" ? ` · probable cause: ${stallCause({ text: lastErrText })}` : "";
|
|
1987
2034
|
const evidence = cutChain.length >= CUT_CHAIN_PARK_MIN ? cutChainEvidence(cutChain) : "";
|
|
1988
2035
|
if (PARKING_REASONS.has(reason) || deliveryFails >= 2) {
|
|
1989
2036
|
retryAt = await parkSeat(parkReason, pendingWake.length, quotaReset, { evidence });
|
|
@@ -2007,7 +2054,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2007
2054
|
// has to act on must never be the part that gets eaten.
|
|
2008
2055
|
await notifyAssigners(assigners,
|
|
2009
2056
|
reason === "stalled"
|
|
2010
|
-
? `⛔ your contract is PARKED on ${SESSION} (stalled: two turns silent for the whole watchdog window)${lifts} · asked: "${asked}"`
|
|
2057
|
+
? `⛔ your contract is PARKED on ${SESSION} (stalled: two turns silent for the whole watchdog window)${lifts}${stallWhy} · asked: "${asked}"`
|
|
2011
2058
|
: `⛔ your contract is PARKED on ${SESSION} (${parkReason})${lifts}${evidence ? ` · ${evidence}` : ""} · asked: "${asked}"`);
|
|
2012
2059
|
lastTurnAt = Date.now();
|
|
2013
2060
|
return;
|
|
@@ -2017,7 +2064,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2017
2064
|
// The room hears the broadcast above; the one who is actually blocked hears it directly.
|
|
2018
2065
|
await notifyAssigners(assigners,
|
|
2019
2066
|
reason === "stalled"
|
|
2020
|
-
? `🫥 your contract STALLED on ${SESSION} (no output for the whole watchdog window; ended at the window, not the box) · wake stays owed · retrying in ${Math.round(wait / 1000)}s · asked: "${asked}"`
|
|
2067
|
+
? `🫥 your contract STALLED on ${SESSION} (no output for the whole watchdog window; ended at the window, not the box)${stallWhy} · wake stays owed · retrying in ${Math.round(wait / 1000)}s · asked: "${asked}"`
|
|
2021
2068
|
: `⚠️ your contract FAILED on ${SESSION} (exit ${ec}, ${reason}) · retrying in ${Math.round(wait / 1000)}s · asked: "${asked}"`);
|
|
2022
2069
|
log(`\x1b[31m${pendingWake.length} message(s) still UNDELIVERED — next attempt in ${Math.round(wait / 1000)}s\x1b[0m`);
|
|
2023
2070
|
} else if (turnAsk) {
|
|
@@ -2098,15 +2145,6 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
2098
2145
|
// (ec !== 0) stays in its own ladder, and only a clean-exit turn hands its card to the stop.
|
|
2099
2146
|
// The stop blocks FUTURE turns for THIS card only: a different card starts clean, and the
|
|
2100
2147
|
// alert names the two ways out (move the card, or restart the seat, resetting the counter).
|
|
2101
|
-
if (!budgetStop && CARD_TOKEN_BUDGET > 0 && sessionCard > 0 && cardTokens >= CARD_TOKEN_BUDGET && ec === 0) {
|
|
2102
|
-
budgetStop = { card: sessionCard, tokens: cardTokens };
|
|
2103
|
-
const text = `⛔ #${sessionCard} hit its token budget on ${SESSION}: ${cardTokens} ≥ ${CARD_TOKEN_BUDGET} tokens this card.`
|
|
2104
|
-
+ ` Further turns for THIS card are paused until it moves (new contract, or testing/done) or \`trantor up ${AGENT}\` resets the budget.`;
|
|
2105
|
-
log(`\x1b[33m${text}\x1b[0m`);
|
|
2106
|
-
await notifyAssigners(assigners, text);
|
|
2107
|
-
const orch = `${hostId()}:${PROJ}`;
|
|
2108
|
-
if (!assigners.some(a => a.from === orch)) await api("/send", { from: SESSION, to: orch, text, project: PROJ, kind: "alert" }).catch(() => {});
|
|
2109
|
-
}
|
|
2110
2148
|
lastTurnAt = Date.now();
|
|
2111
2149
|
}
|
|
2112
2150
|
})();
|
package/bin/patrol.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { readdirSync, rmSync, statSync } from "node:fs";
|
|
|
4
4
|
import { join, basename, dirname, resolve, sep } from "node:path";
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { providerMismatch } from "../lib/seat-provider.mjs";
|
|
7
8
|
|
|
8
9
|
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
9
10
|
const DAY = 24 * 60 * 60 * 1000;
|
|
@@ -43,11 +44,6 @@ function rowMatchesRunner(row, runner) {
|
|
|
43
44
|
return !rp || rp === runnerProject(runner);
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
function seatProvider(agent) {
|
|
47
|
-
if (["codex", "kimi", "claude", "gemini", "dsh", "opencode"].includes(agent)) return null;
|
|
48
|
-
return agent === "glm" ? "zai-coding-plan" : agent;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
47
|
function sortedProjects(projects) {
|
|
52
48
|
return [...projects].sort((a, b) => displayProject(a).localeCompare(displayProject(b)));
|
|
53
49
|
}
|
|
@@ -91,15 +87,15 @@ export function buildPatrolReport(rawInventory = {}, reaped = [], { bus = busDir
|
|
|
91
87
|
} else if (!rows.some(row => rowMatchesRunner(row, runner))) {
|
|
92
88
|
orphans.push({ type: "live-runner-without-row", project: p, agent: runner.agent, pid: runner.pid, dir: runner.dir });
|
|
93
89
|
}
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
if (
|
|
90
|
+
// #13474: the same rule the runner refuses a turn on.
|
|
91
|
+
const mm = providerMismatch(String(runner?.agent || ""), runner?.model);
|
|
92
|
+
if (mm) {
|
|
97
93
|
warnings.push({
|
|
98
94
|
type: "seat-model-provider-mismatch",
|
|
99
95
|
project: p,
|
|
100
96
|
agent: runner.agent,
|
|
101
97
|
model: runner.model,
|
|
102
|
-
expectedProvider,
|
|
98
|
+
expectedProvider: mm.expected,
|
|
103
99
|
pid: runner.pid,
|
|
104
100
|
});
|
|
105
101
|
}
|
package/hooks/hooks.json
CHANGED
|
@@ -169,6 +169,16 @@
|
|
|
169
169
|
}
|
|
170
170
|
]
|
|
171
171
|
},
|
|
172
|
+
{
|
|
173
|
+
"matcher": "Bash|mcp__plugin_trantor_relay__relay_task_move",
|
|
174
|
+
"hooks": [
|
|
175
|
+
{
|
|
176
|
+
"type": "command",
|
|
177
|
+
"command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/progress-log.mjs",
|
|
178
|
+
"timeout": 10
|
|
179
|
+
}
|
|
180
|
+
]
|
|
181
|
+
},
|
|
172
182
|
{
|
|
173
183
|
"matcher": "Write|Edit",
|
|
174
184
|
"hooks": [
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// The project's current-state memory file (#13871): handoffs wrote no memory, so every successor
|
|
2
|
+
// read a model summary written at a full context plus whatever dated note the index still named.
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, statSync } from "node:fs";
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import { memoryDirectory } from "../../lib/memory-pins.mjs";
|
|
6
|
+
import { renderFacts } from "./handoff-facts.mjs";
|
|
7
|
+
|
|
8
|
+
export const STATE_FILE = "project_current_state.md";
|
|
9
|
+
const INDEX_LINE_RE = /\(project_current_state\.md\)/;
|
|
10
|
+
const DATED_RE = /^project_session_handoff_.*\.md$/;
|
|
11
|
+
const PROGRESS_HEAD = "## Progress";
|
|
12
|
+
const PROGRESS_KEEP = 40;
|
|
13
|
+
const CAP_WARN_BYTES = 7500;
|
|
14
|
+
|
|
15
|
+
export const currentStatePath = (projectDir) => join(memoryDirectory(projectDir), STATE_FILE);
|
|
16
|
+
|
|
17
|
+
const read = (p) => { try { return readFileSync(p, "utf8"); } catch { return ""; } };
|
|
18
|
+
|
|
19
|
+
/** The progress lines already in a state file, oldest first, so a rewrite keeps them. */
|
|
20
|
+
export function progressLines(text) {
|
|
21
|
+
const at = String(text).indexOf(`\n${PROGRESS_HEAD}`);
|
|
22
|
+
if (at < 0) return [];
|
|
23
|
+
return text.slice(at).split("\n").slice(2).filter(l => l.startsWith("- "));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const section = (title, list) => `## ${title}\n${list.length ? list.join("\n") : "- none recorded"}\n`;
|
|
27
|
+
const items = (list) => (list || []).map(i => `- ${i.id} ${i.text}`);
|
|
28
|
+
|
|
29
|
+
function body({ record, facts, progress }) {
|
|
30
|
+
const st = record.state || null;
|
|
31
|
+
const task = st?.task || (/## TASK\s*\n+([^\n]+)/i.exec(record.summary || "") || [])[1] || "not recorded";
|
|
32
|
+
const when = new Date((record.stamp || 0) * 1000 || Date.now()).toISOString();
|
|
33
|
+
return [
|
|
34
|
+
"---", "name: project_current_state",
|
|
35
|
+
`description: Current task, git and board facts, done, in flight and next for ${record.projectName}, rewritten at every handoff`,
|
|
36
|
+
"metadata:", " node_type: memory", " type: project", "---",
|
|
37
|
+
`# Current state of ${record.projectName}`,
|
|
38
|
+
`Written by handoff ${record.id} at ${when}. Rewritten at every handoff; the Progress list below is appended as the session works.`, "",
|
|
39
|
+
`## Task\n${task}\n`, `## Facts\n${renderFacts(facts)}\n`,
|
|
40
|
+
section("Done", items(st?.done)), section("In flight", items(st?.in_flight)), section("Next", items(st?.next)),
|
|
41
|
+
`${PROGRESS_HEAD}\n${progress.slice(-PROGRESS_KEEP).join("\n")}`.trimEnd(), "",
|
|
42
|
+
].join("\n");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One index line, added if absent, replaced in place if present, extras dropped. */
|
|
46
|
+
export function ensureIndexLine(memDir, id) {
|
|
47
|
+
const p = join(memDir, "MEMORY.md");
|
|
48
|
+
const line = `- [Current state](${STATE_FILE}) — task, git and board facts, progress; rewritten at each handoff (${id || "live"})`;
|
|
49
|
+
const lines = read(p).split("\n");
|
|
50
|
+
const first = lines.findIndex(l => INDEX_LINE_RE.test(l));
|
|
51
|
+
const kept = lines.filter((l, i) => i === first || !INDEX_LINE_RE.test(l));
|
|
52
|
+
if (first < 0) { while (kept.length && kept[kept.length - 1] === "") kept.pop(); kept.push(line); }
|
|
53
|
+
else kept[kept.indexOf(lines[first])] = line;
|
|
54
|
+
writeFileSync(p, kept.join("\n").replace(/\n*$/, "\n"));
|
|
55
|
+
return p;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Dated handoff notes get a superseded line after their frontmatter; never deleted. */
|
|
59
|
+
export function supersedeDatedNotes(memDir) {
|
|
60
|
+
const marked = [];
|
|
61
|
+
const note = `> superseded by ${STATE_FILE}`;
|
|
62
|
+
for (const f of existsSync(memDir) ? readdirSync(memDir) : []) {
|
|
63
|
+
if (!DATED_RE.test(f)) continue;
|
|
64
|
+
const p = join(memDir, f), text = read(p);
|
|
65
|
+
if (text.includes(note)) continue;
|
|
66
|
+
const fm = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(text);
|
|
67
|
+
const at = fm ? fm[0].length : 0;
|
|
68
|
+
writeFileSync(p, `${text.slice(0, at)}${note}\n${text.slice(at)}`);
|
|
69
|
+
marked.push(f);
|
|
70
|
+
}
|
|
71
|
+
return marked;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** READ FIRST: always names the current-state file first, never a dated handoff note. */
|
|
75
|
+
export function readFirstWith(summary, statePath) {
|
|
76
|
+
const out = [];
|
|
77
|
+
let inSec = false, named = false;
|
|
78
|
+
for (const raw of String(summary || "").split(/\r?\n/)) {
|
|
79
|
+
if (!inSec && /^\s*(?:#{1,6}\s*)?[*_]*read[\s-]?first\b/i.test(raw)) {
|
|
80
|
+
inSec = true; named = true;
|
|
81
|
+
out.push(raw, statePath);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (inSec && (raw.trim() === "" || /^#{1,6}\s/.test(raw))) inSec = false;
|
|
85
|
+
if (!inSec) { out.push(raw); continue; }
|
|
86
|
+
const cleaned = raw.replace(/\S*project_session_handoff_\S*/g, "");
|
|
87
|
+
const bare = cleaned.replace(/^\s*(?:[-*]|\d+\.)\s*/, "");
|
|
88
|
+
if (cleaned !== raw && !/[\w~/]/.test(bare)) continue;
|
|
89
|
+
out.push(cleaned);
|
|
90
|
+
}
|
|
91
|
+
return named ? out.join("\n") : `${out.join("\n")}\n\n## READ FIRST\n${statePath}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** One plain line when the index is near its 8 KB cap, "" otherwise. */
|
|
95
|
+
export function memoryCapWarning(memDir) {
|
|
96
|
+
try {
|
|
97
|
+
const size = statSync(join(memDir, "MEMORY.md")).size;
|
|
98
|
+
return size > CAP_WARN_BYTES
|
|
99
|
+
? `MEMORY.md is ${size} bytes of its 8192 byte cap: the index is near its cap and needs pruning.` : "";
|
|
100
|
+
} catch { return ""; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Handoff-time write: file, index line, superseded notes. Mutates `record`; best-effort. */
|
|
104
|
+
export function applyCurrentState({ record, projectDir, facts }) {
|
|
105
|
+
try {
|
|
106
|
+
const memDir = memoryDirectory(projectDir), p = join(memDir, STATE_FILE);
|
|
107
|
+
mkdirSync(memDir, { recursive: true });
|
|
108
|
+
writeFileSync(p, body({ record, facts, progress: progressLines(read(p)) }));
|
|
109
|
+
ensureIndexLine(memDir, record.id);
|
|
110
|
+
record.supersededNotes = supersedeDatedNotes(memDir);
|
|
111
|
+
record.currentStatePath = p;
|
|
112
|
+
record.summary = readFirstWith(record.summary, p);
|
|
113
|
+
record.memoryWarning = memoryCapWarning(memDir);
|
|
114
|
+
return p;
|
|
115
|
+
} catch (e) {
|
|
116
|
+
process.stderr.write(`[trantor] handoff current-state skipped: ${e?.message || e}\n`);
|
|
117
|
+
return "";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** In-session progress: one dated line appended to the state file. Creates a skeleton if absent. */
|
|
122
|
+
export function appendProgress(projectDir, text, now = new Date()) {
|
|
123
|
+
const memDir = memoryDirectory(projectDir);
|
|
124
|
+
if (!existsSync(memDir)) return false;
|
|
125
|
+
const p = join(memDir, STATE_FILE);
|
|
126
|
+
const stamp = now.toISOString().slice(0, 16).replace("T", " ");
|
|
127
|
+
const line = `- ${stamp} ${String(text).replace(/\s+/g, " ").slice(0, 200)}`;
|
|
128
|
+
let cur = read(p);
|
|
129
|
+
if (!cur) {
|
|
130
|
+
cur = body({ record: { id: "none yet", projectName: basename(projectDir), stamp: 0 }, facts: null, progress: [] })
|
|
131
|
+
.replace(/Written by handoff .*\n/, "No handoff has run yet; this file holds in-session progress only.\n");
|
|
132
|
+
}
|
|
133
|
+
const lines = progressLines(cur);
|
|
134
|
+
if (lines.includes(line)) return false;
|
|
135
|
+
const head = cur.slice(0, cur.indexOf(PROGRESS_HEAD));
|
|
136
|
+
writeFileSync(p, `${head}${PROGRESS_HEAD}\n${[...lines, line].slice(-PROGRESS_KEEP).join("\n")}\n`);
|
|
137
|
+
if (!INDEX_LINE_RE.test(read(join(memDir, "MEMORY.md")))) ensureIndexLine(memDir, "");
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Handoff facts computed from git and the board, never from the model (#13871): the model-written
|
|
2
|
+
// summary said 9 unpushed commits when git said 17, because nothing cross-checked it.
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { DERIVED_NOTE } from "../../lib/state/derive.mjs";
|
|
5
|
+
|
|
6
|
+
const git = (dir, args) => execFileSync("git", ["-C", dir, ...args],
|
|
7
|
+
{ encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
8
|
+
|
|
9
|
+
/** Branch, upstream and unpushed count. `ahead` is null (not 0) when it cannot be known. */
|
|
10
|
+
export function gitFacts(projectDir) {
|
|
11
|
+
const out = { branch: "", upstream: "", ahead: null };
|
|
12
|
+
try { out.branch = git(projectDir, ["rev-parse", "--abbrev-ref", "HEAD"]); } catch { return out; }
|
|
13
|
+
try {
|
|
14
|
+
out.upstream = git(projectDir, ["rev-parse", "--abbrev-ref", "@{u}"]);
|
|
15
|
+
out.ahead = Number(git(projectDir, ["rev-list", "--count", "@{u}..HEAD"]));
|
|
16
|
+
} catch { out.upstream = ""; out.ahead = null; }
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const BUCKETS = ["doing", "testing", "blocked", "failed", "todo"];
|
|
21
|
+
|
|
22
|
+
/** The board from a /catchup read. A failed read says so rather than reading as an empty board. */
|
|
23
|
+
export function boardFacts(read) {
|
|
24
|
+
if (!read || !read.ok) return { ok: false, reason: read?.reason || "unreachable", counts: {}, cards: [] };
|
|
25
|
+
const j = read.json || {};
|
|
26
|
+
const cards = [];
|
|
27
|
+
for (const status of BUCKETS) {
|
|
28
|
+
for (const t of Array.isArray(j[status]) ? j[status] : []) {
|
|
29
|
+
cards.push({ id: t.id, title: String(t.title || "").slice(0, 100), status, assignee: t.assignee || "" });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { ok: true, reason: "", counts: j.counts || {}, cards: cards.slice(0, 20) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** @param {{projectDir: string, projectName: string, hubGet: (path: string) => object, now?: number}} a */
|
|
36
|
+
export function computeFacts({ projectDir, projectName, hubGet, now = Date.now() }) {
|
|
37
|
+
const gitPart = gitFacts(projectDir);
|
|
38
|
+
let read = null;
|
|
39
|
+
try { read = hubGet(`/catchup?project=${encodeURIComponent(projectName)}`); } catch (e) { read = { ok: false, reason: e?.message }; }
|
|
40
|
+
return { computedAt: new Date(now).toISOString(), ...gitPart, board: boardFacts(read) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The facts as the successor and the current-state file both read them: plain, labeled as computed. */
|
|
44
|
+
export function renderFacts(facts) {
|
|
45
|
+
if (!facts) return "";
|
|
46
|
+
const rows = [`Computed at handoff (${facts.computedAt}) from git and the board, not written by the model.`];
|
|
47
|
+
if (facts.branch) {
|
|
48
|
+
const sync = facts.upstream
|
|
49
|
+
? `${facts.ahead} commit(s) ahead of ${facts.upstream}, unpushed`
|
|
50
|
+
: "no upstream configured, so the unpushed count is unknown";
|
|
51
|
+
rows.push(`- Branch ${facts.branch}: ${sync}`);
|
|
52
|
+
} else rows.push("- Branch: not a git checkout or git unavailable");
|
|
53
|
+
const b = facts.board || {};
|
|
54
|
+
if (!b.ok) rows.push(`- Board: could not be read at handoff (${b.reason}); read it yourself before trusting any card claim`);
|
|
55
|
+
else {
|
|
56
|
+
const c = b.counts || {};
|
|
57
|
+
rows.push(`- Board: ${BUCKETS.map(s => `${c[s] || 0} ${s}`).join(", ")}`);
|
|
58
|
+
for (const t of b.cards) rows.push(` - #${t.id} ${t.status}${t.assignee ? ` (${t.assignee})` : ""}: ${t.title}`);
|
|
59
|
+
}
|
|
60
|
+
return rows.join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** ", turn N" only when the number is a real one: a state derived at handoff carries a placeholder. */
|
|
64
|
+
export function stateTurnLabel(state) {
|
|
65
|
+
const turn = state?.cursor?.turn;
|
|
66
|
+
const derived = String(state?.notes || "").startsWith(DERIVED_NOTE);
|
|
67
|
+
return Number.isInteger(turn) && turn > 0 && !derived ? `, turn ${turn}` : "";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The successor's facts block; the cap warning rides only the claiming session, once per handoff. */
|
|
71
|
+
export function handoffFactsBlock(handoff, claimed, clean = (x) => x) {
|
|
72
|
+
if (!handoff?.facts) return "";
|
|
73
|
+
let out = `## Facts computed at handoff (git and board, not model-written)\n${clean(renderFacts(handoff.facts))}\n`;
|
|
74
|
+
if (handoff.currentStatePath) out += `Read first: ${clean(handoff.currentStatePath)}\n`;
|
|
75
|
+
if (claimed && handoff.memoryWarning) out += `${clean(handoff.memoryWarning)}\n`;
|
|
76
|
+
return `${out}\n`;
|
|
77
|
+
}
|
package/hooks/lib/handoff.mjs
CHANGED
|
@@ -21,6 +21,8 @@ import { statePath, readState } from "../../lib/state/store.mjs";
|
|
|
21
21
|
import { stateError } from "../../lib/state/schema.mjs";
|
|
22
22
|
import { resolveStateFlags, stateFeatureOn } from "../../lib/state/flags.mjs";
|
|
23
23
|
import { deriveState } from "../../lib/state/derive.mjs";
|
|
24
|
+
import { computeFacts } from "./handoff-facts.mjs";
|
|
25
|
+
import { applyCurrentState } from "./current-state.mjs";
|
|
24
26
|
|
|
25
27
|
// Writer and reader MUST resolve the same directory — see lib/project.mjs busDir(). This used to
|
|
26
28
|
// honour only RELAY_DATA_DIR while the reader honoured neither override.
|
|
@@ -730,6 +732,9 @@ export function writeHandoff({ projectDir, sessionId, transcript, trigger, summa
|
|
|
730
732
|
// sources — and BEFORE the write, so the field lands in the same file the successor loads.
|
|
731
733
|
const seat = resolveSeat(projectName);
|
|
732
734
|
attachState(record, { project: projectName, seat, card: resolveHandoffCard({ projectName, seat }), worktree: projectDir });
|
|
735
|
+
// #13871: facts from git and the board (not the model), then the current-state memory file.
|
|
736
|
+
record.facts = computeFacts({ projectDir, projectName, hubGet: (path) => hubCallSync(path, { project: projectName, session: sessionId || "" }) });
|
|
737
|
+
applyCurrentState({ record, projectDir, facts: record.facts });
|
|
733
738
|
const file = join(HANDOFF_DIR, `${record.id}.json`);
|
|
734
739
|
writeFileSync(file, JSON.stringify(record, null, 2));
|
|
735
740
|
supersedeOlderHandoffs(projectName, record.id);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// trantor PostToolUse(Bash|relay_task_move): one dated line in the project's current-state memory
|
|
3
|
+
// file per commit and per card move, so a weeks-long session is not summarized only at the end
|
|
4
|
+
// (#13871). Fail-silent by contract: never blocks or breaks the tool flow.
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { appendProgress } from "./lib/current-state.mjs";
|
|
7
|
+
import { gitCheckoutRoot } from "./lib/git-checkout.mjs";
|
|
8
|
+
import { readStdinWithin, failOpenAfter } from "./lib/fail-open.mjs";
|
|
9
|
+
|
|
10
|
+
const MOVE_TOOL = /relay_task_move$/;
|
|
11
|
+
const COMMIT_CMD = /\bgit\s+(?:-C\s+\S+\s+)?commit\b/;
|
|
12
|
+
const FRESH_SEC = 120;
|
|
13
|
+
|
|
14
|
+
/** The commit this Bash call just made, or "" when none landed (a failed commit changes HEAD's age not). */
|
|
15
|
+
export function justCommitted(cwd, nowSec = Math.floor(Date.now() / 1000)) {
|
|
16
|
+
try {
|
|
17
|
+
const out = execFileSync("git", ["-C", cwd, "log", "-1", "--format=%h%x09%ct%x09%s"],
|
|
18
|
+
{ encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
19
|
+
const [sha, ct, ...subject] = out.split("\t");
|
|
20
|
+
return nowSec - Number(ct) <= FRESH_SEC ? `commit ${sha} ${subject.join("\t")}` : "";
|
|
21
|
+
} catch { return ""; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The progress line for one hook event, or "". */
|
|
25
|
+
export function progressFor(input) {
|
|
26
|
+
const name = String(input.tool_name || "");
|
|
27
|
+
if (MOVE_TOOL.test(name)) {
|
|
28
|
+
if (JSON.stringify(input.tool_response ?? "").includes("\"isError\":true")) return "";
|
|
29
|
+
const { id, status, note } = input.tool_input || {};
|
|
30
|
+
return id && status ? `card #${id} -> ${status}${note ? `: ${String(note).slice(0, 120)}` : ""}` : "";
|
|
31
|
+
}
|
|
32
|
+
if (name === "Bash" && COMMIT_CMD.test(String(input.tool_input?.command || ""))) return justCommitted(input.cwd || process.cwd());
|
|
33
|
+
return "";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function main() {
|
|
37
|
+
failOpenAfter(4000, "");
|
|
38
|
+
const input = JSON.parse((await readStdinWithin(300)) || "{}");
|
|
39
|
+
const line = progressFor(input);
|
|
40
|
+
const cwd = input.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
41
|
+
if (line) appendProgress(gitCheckoutRoot(cwd) || cwd, line);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (import.meta.url === `file://${process.argv[1]}`) main().catch(() => {}).finally(() => process.exit(0));
|
package/hooks/sessionstart.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, n
|
|
|
11
11
|
import { formatSubagentManifest } from "../lib/subagent-manifest.mjs";
|
|
12
12
|
import { updateAvailable, maybeNotifyDesktop, readConfig } from "./lib/update-check.mjs";
|
|
13
13
|
import { renderStateBlock, capSummary } from "./lib/handoff.mjs";
|
|
14
|
+
import { stateTurnLabel, handoffFactsBlock } from "./lib/handoff-facts.mjs";
|
|
14
15
|
import { loadPendingHandoff } from "./lib/handoff-claims.mjs";
|
|
15
16
|
import { maybeCheckBalances } from "./lib/balance-check.mjs";
|
|
16
17
|
import { getJSON, signedGet, signedPost, loadIdentity } from "./lib/api.mjs";
|
|
@@ -504,9 +505,10 @@ try {
|
|
|
504
505
|
// and the successor sees exactly today's prose handoff.
|
|
505
506
|
const stateBlock = renderStateBlock(handoff.state);
|
|
506
507
|
if (stateBlock) {
|
|
507
|
-
additionalContext += `## Working state (structured, card #${sanitize(String(handoff.state.card || 0))}
|
|
508
|
+
additionalContext += `## Working state (structured, card #${sanitize(String(handoff.state.card || 0))}${stateTurnLabel(handoff.state)})\n`;
|
|
508
509
|
additionalContext += `${sanitize(stateBlock)}\n\n`;
|
|
509
510
|
}
|
|
511
|
+
additionalContext += handoffFactsBlock(handoff, claimed, sanitize);
|
|
510
512
|
additionalContext += `## Handoff summary\n${sanitize(capHandoffSummary(handoff))}\n`;
|
|
511
513
|
if (handoff.gitStatus) additionalContext += `\n## Git working-tree at handoff\n\`\`\`\n${sanitize(handoff.gitStatus)}\n\`\`\`\n`;
|
|
512
514
|
// Sub-agent manifest: LIVE-primary, snapshot-as-fallback. The prior session may have had
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// #13474: tokens spent on one contract since the seat's last commit, judged against a ceiling.
|
|
2
|
+
// Pure: the runner owns the counters and the sends, this decides whether the seat has burned out.
|
|
3
|
+
export const DEFAULT_BURN_CEILING = 1_000_000;
|
|
4
|
+
|
|
5
|
+
export function burnCeiling(env = process.env) {
|
|
6
|
+
return Math.max(0, Number(env.TRANTOR_CARD_TOKEN_BUDGET || DEFAULT_BURN_CEILING));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The counters after a turn: a commit is progress and zeroes the count, anything else adds. */
|
|
10
|
+
export function afterTurn({ tokens, commits }, { spent, committed }) {
|
|
11
|
+
return committed ? { tokens: 0, commits: commits + 1 } : { tokens: tokens + (spent > 0 ? spent : 0), commits };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** null while under the ceiling; else the one message and the one card note for this episode. */
|
|
15
|
+
export function burnVerdict({ card, tokens, commits, ceiling, agent, stopped }) {
|
|
16
|
+
if (stopped || ceiling <= 0 || !(card > 0) || tokens < ceiling) return null;
|
|
17
|
+
const made = `${commits} commit(s) made on this contract`;
|
|
18
|
+
const text = `⛔ #${card} hit its token budget: ${tokens} ≥ ${ceiling} tokens since the last commit, ${made}.`
|
|
19
|
+
+ ` Further turns for THIS card are paused until it moves (new contract, or testing/done) or \`trantor up ${agent}\` resets the budget.`;
|
|
20
|
+
return { text, note: `parked at the burn ceiling: ${tokens} tokens spent since the last commit (ceiling ${ceiling}), ${made}.` };
|
|
21
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// #13474: one definition of "which provider does this seat label promise", shared by patrol (warn)
|
|
2
|
+
// and the runner (refuse the turn), so the two can never disagree about a mismatch.
|
|
3
|
+
const SUBSCRIPTION = new Set(["codex", "kimi", "claude", "gemini"]); // flat-fee plans, never metered
|
|
4
|
+
const METERED = new Set(["deepseek", "openrouter"]); // pay-per-token providers
|
|
5
|
+
const OWN_MODEL = new Set(["dsh", "opencode"]); // label does not pin a provider
|
|
6
|
+
|
|
7
|
+
/** The label's base CLI: "kimi-13" and "host:kimi-13" both read as "kimi". */
|
|
8
|
+
export function seatBase(label) {
|
|
9
|
+
const tail = String(label || "").split(":").pop();
|
|
10
|
+
const base = tail.replace(/-\d+$/, "");
|
|
11
|
+
return SUBSCRIPTION.has(base) || OWN_MODEL.has(base) || base === "glm" ? base : tail;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The provider a provider-labelled seat must run on, or null when the label pins none. */
|
|
15
|
+
export function seatProvider(agent) {
|
|
16
|
+
const base = seatBase(agent);
|
|
17
|
+
if (SUBSCRIPTION.has(base) || OWN_MODEL.has(base)) return null;
|
|
18
|
+
return base === "glm" ? "zai-coding-plan" : base;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** null when label and live model agree; else { label, model, expected, actual } for the refusal. */
|
|
22
|
+
export function providerMismatch(label, model) {
|
|
23
|
+
const m = String(model || "");
|
|
24
|
+
const actual = m.split("/")[0];
|
|
25
|
+
if (!actual) return null;
|
|
26
|
+
const expected = seatProvider(label);
|
|
27
|
+
if (expected) return actual !== expected ? { label, model: m, expected, actual } : null;
|
|
28
|
+
if (SUBSCRIPTION.has(seatBase(label)) && METERED.has(actual)) {
|
|
29
|
+
return { label, model: m, expected: "a subscription provider", actual };
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// #13474: a silent stall used to say only that it was silent. This names the likeliest cause from
|
|
2
|
+
// evidence the runner already holds; load and the clock are injected so tests never read the machine.
|
|
3
|
+
import { loadavg, cpus } from "node:os";
|
|
4
|
+
|
|
5
|
+
const AUTH_RE = /\b(401|403|unauthori[sz]ed|invalid api key|not logged in|authentication)\b/i;
|
|
6
|
+
const QUOTA_RE = /\b(429|rate.?limit|quota|insufficient (credit|balance)|usage limit|exhausted)\b/i;
|
|
7
|
+
|
|
8
|
+
/** One short phrase: high load, a provider signal seen in the turn text, else "unknown". */
|
|
9
|
+
export function stallCause({ text = "", load = loadavg()[0], cpuCount = cpus().length } = {}) {
|
|
10
|
+
if (load > 4 * Math.max(1, cpuCount)) return `machine overloaded (1-min load ${load.toFixed(1)} on ${cpuCount} CPUs)`;
|
|
11
|
+
if (AUTH_RE.test(text)) return "provider auth signal seen in the CLI output";
|
|
12
|
+
if (QUOTA_RE.test(text)) return "provider quota or rate-limit signal seen in the CLI output";
|
|
13
|
+
return "unknown";
|
|
14
|
+
}
|
package/lib/wip-save.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// #13474: a cut or parked seat's uncommitted work is committed on its own branch so the next seat
|
|
2
|
+
// starts from it. Never pushes, never touches main, and a clean tree makes no commit.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
const git = (cwd, args) => spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 20000 });
|
|
6
|
+
|
|
7
|
+
/** The new sha, or "" when nothing was saved (clean tree, detached HEAD, main, or a git failure). */
|
|
8
|
+
export function saveWip(cwd, card) {
|
|
9
|
+
const branch = String(git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]).stdout || "").trim();
|
|
10
|
+
if (!branch || branch === "HEAD" || branch === "main" || branch === "master") return "";
|
|
11
|
+
if (!String(git(cwd, ["status", "--porcelain"]).stdout || "").trim()) return "";
|
|
12
|
+
if (git(cwd, ["add", "-A"]).status !== 0) return "";
|
|
13
|
+
const msg = `WIP(#${card}): saved at cut`;
|
|
14
|
+
const c = git(cwd, ["-c", "user.name=trantor-seat", "-c", "user.email=seat@trantor.local", "commit", "--no-verify", "-qm", msg]);
|
|
15
|
+
return c.status === 0 ? String(git(cwd, ["rev-parse", "HEAD"]).stdout || "").trim() : "";
|
|
16
|
+
}
|