benignswarm 0.12.166 → 0.12.168

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.
@@ -0,0 +1,393 @@
1
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { createConnection } from "node:net";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { CliError } from "./errors.js";
7
+ import { retryGitFetchSync } from "./git-fetch.js";
8
+ import { fullSha, isAncestor } from "./git.js";
9
+ import { parseFailedGateStep } from "./merge-train.js";
10
+ export const SCOPED_GATE_STAGE_ORDER = [
11
+ "pg baseline",
12
+ "migration preflight",
13
+ "deployment script tests",
14
+ "typecheck",
15
+ "api tests",
16
+ "cli build",
17
+ "cli tests",
18
+ "web tests",
19
+ "web build",
20
+ "published CLI contract",
21
+ ];
22
+ export function gateCommandUsesGateSh(gateCommand) {
23
+ if (gateCommand === null)
24
+ return true;
25
+ return /(?:^|\s)scripts\/gate\.sh(?:\s|$)/.test(gateCommand);
26
+ }
27
+ function normalizeRepoPath(path) {
28
+ return path.replaceAll("\\", "/").replace(/^\.\//, "");
29
+ }
30
+ function isNonGateDocOrAssetPath(path) {
31
+ if (path.startsWith("docs/")
32
+ || path.startsWith(".agents/")
33
+ || path.startsWith(".bschat/")
34
+ || path.startsWith(".github/")
35
+ || path.startsWith("logo/")
36
+ || path.startsWith("artifacts/")
37
+ || path.startsWith("apps/web/public/")
38
+ || path.startsWith("scripts/ux-tasks/")
39
+ || path.startsWith("scripts/carbon-")
40
+ || path.startsWith("scripts/ux-")) {
41
+ return true;
42
+ }
43
+ if (path.endsWith(".md") && !path.startsWith("apps/api/") && !path.startsWith("packages/skill/") && !path.startsWith("packages/skill-admin/")) {
44
+ return true;
45
+ }
46
+ return false;
47
+ }
48
+ function isMigrationPath(path) {
49
+ return path.startsWith("apps/api/migrations/")
50
+ || path.startsWith("apps/api/pg-migrations/")
51
+ || path === "apps/api/scripts/migration-preflight.mjs"
52
+ || path === "apps/api/scripts/generate-pg-baseline.mjs";
53
+ }
54
+ function isPgApiTestPath(path) {
55
+ return path.startsWith("apps/api/src/node/")
56
+ || path === "apps/api/vitest.pg-suite.config.ts"
57
+ || path === "apps/api/scripts/d1-to-postgres.mjs"
58
+ || path.startsWith("apps/api/pg-migrations/");
59
+ }
60
+ /**
61
+ * Determine which train gate stages must pass locally before `wu submit` for the given changed paths.
62
+ * Must stay synchronized with `apps/api/src/scoped-gate.ts` and `scripts/gate.sh`.
63
+ */
64
+ export function scopedGatePlan(changedPaths, merge) {
65
+ const stageSet = new Set();
66
+ const postgresReasons = new Set();
67
+ let hasCodePath = false;
68
+ for (const rawPath of changedPaths) {
69
+ const p = normalizeRepoPath(rawPath);
70
+ if (!p || isNonGateDocOrAssetPath(p))
71
+ continue;
72
+ hasCodePath = true;
73
+ if (isMigrationPath(p)) {
74
+ stageSet.add("pg baseline");
75
+ stageSet.add("migration preflight");
76
+ stageSet.add("typecheck");
77
+ stageSet.add("api tests");
78
+ postgresReasons.add('stage "migration preflight" requires a reachable local PostgreSQL server (PG_ADMIN_URL or 127.0.0.1:15432)');
79
+ continue;
80
+ }
81
+ if (p.startsWith("apps/api/")) {
82
+ stageSet.add("typecheck");
83
+ stageSet.add("api tests");
84
+ if (p === "apps/api/wrangler.jsonc") {
85
+ stageSet.add("cli build");
86
+ stageSet.add("published CLI contract");
87
+ }
88
+ if (isPgApiTestPath(p)) {
89
+ postgresReasons.add('PostgreSQL server/suite changes require a reachable local PostgreSQL server (PG_ADMIN_URL or 127.0.0.1:15432) for PostgreSQL API tests');
90
+ }
91
+ continue;
92
+ }
93
+ if (p.startsWith("apps/web/")) {
94
+ stageSet.add("typecheck");
95
+ stageSet.add("web tests");
96
+ stageSet.add("web build");
97
+ continue;
98
+ }
99
+ if (p.startsWith("packages/cli/")) {
100
+ stageSet.add("typecheck");
101
+ stageSet.add("cli build");
102
+ stageSet.add("cli tests");
103
+ continue;
104
+ }
105
+ if (p.startsWith("packages/skill/") || p.startsWith("packages/skill-admin/")) {
106
+ stageSet.add("typecheck");
107
+ stageSet.add("api tests");
108
+ stageSet.add("cli tests");
109
+ continue;
110
+ }
111
+ if (p.startsWith("packages/signing-worker/")) {
112
+ stageSet.add("typecheck");
113
+ continue;
114
+ }
115
+ if (p.startsWith("scripts/deploy-main") || p.startsWith("scripts/migration-fault-guard")) {
116
+ stageSet.add("deployment script tests");
117
+ continue;
118
+ }
119
+ if (p.startsWith("scripts/gate") || p === "scripts/verify-gate-baseline.sh") {
120
+ stageSet.add("deployment script tests");
121
+ stageSet.add("typecheck");
122
+ stageSet.add("cli tests");
123
+ continue;
124
+ }
125
+ if (p.startsWith("scripts/published-cli-contract")) {
126
+ stageSet.add("cli build");
127
+ stageSet.add("published CLI contract");
128
+ continue;
129
+ }
130
+ if (p.startsWith("scripts/vitest-scratch") || p === "scripts/ensure-tenant-migrations.mjs") {
131
+ stageSet.add("typecheck");
132
+ stageSet.add("api tests");
133
+ continue;
134
+ }
135
+ if (p === "package.json" || p === "package-lock.json" || /^tsconfig(?:\.[^/]+)?\.json$/.test(p)) {
136
+ stageSet.add("pg baseline");
137
+ stageSet.add("typecheck");
138
+ stageSet.add("api tests");
139
+ stageSet.add("cli build");
140
+ stageSet.add("cli tests");
141
+ stageSet.add("web tests");
142
+ stageSet.add("web build");
143
+ continue;
144
+ }
145
+ stageSet.add("typecheck");
146
+ }
147
+ if (!hasCodePath) {
148
+ return {
149
+ required: false,
150
+ mode: "none",
151
+ stages: [],
152
+ customCommand: null,
153
+ postgresRequiredReasons: [],
154
+ };
155
+ }
156
+ if (!gateCommandUsesGateSh(merge.gate_command)) {
157
+ return {
158
+ required: merge.require_gate_receipt,
159
+ mode: "custom",
160
+ stages: ["gate"],
161
+ customCommand: merge.gate_command,
162
+ postgresRequiredReasons: [],
163
+ };
164
+ }
165
+ // CLI tests exercise the built entry points and need dist in a fresh checkout.
166
+ if (stageSet.has("cli tests"))
167
+ stageSet.add("cli build");
168
+ const orderedStages = SCOPED_GATE_STAGE_ORDER.filter((stage) => stageSet.has(stage));
169
+ return {
170
+ required: merge.require_gate_receipt && orderedStages.length > 0,
171
+ mode: orderedStages.length > 0 ? "gate_sh" : "none",
172
+ stages: orderedStages,
173
+ customCommand: null,
174
+ postgresRequiredReasons: [...postgresReasons],
175
+ };
176
+ }
177
+ export function resolvePostgresTarget(env = process.env) {
178
+ const configured = env.PG_ADMIN_URL?.trim() || env.DATABASE_URL?.trim();
179
+ const fallback = "postgresql://benignswarm:benignswarm@127.0.0.1:15432/postgres";
180
+ const raw = configured || fallback;
181
+ try {
182
+ const url = new URL(raw);
183
+ const host = url.hostname === "[::1]" ? "::1" : (url.hostname || "127.0.0.1");
184
+ const port = Number(url.port || (configured ? 5432 : 15432));
185
+ const adminUrl = `${url.protocol}//${url.username ? `${url.username}${url.password ? `:${url.password}` : ""}@` : ""}${url.host}/postgres`;
186
+ return { host, port, adminUrl };
187
+ }
188
+ catch {
189
+ return { host: "127.0.0.1", port: 15432, adminUrl: fallback };
190
+ }
191
+ }
192
+ export async function probeLocalPostgres(env = process.env) {
193
+ const { host, port, adminUrl } = resolvePostgresTarget(env);
194
+ if (!["127.0.0.1", "localhost", "::1"].includes(host)) {
195
+ return {
196
+ available: false,
197
+ host,
198
+ port,
199
+ adminUrl,
200
+ reason: `configured PostgreSQL host ${host} is not local (expected 127.0.0.1, localhost, or ::1)`,
201
+ };
202
+ }
203
+ return await new Promise((resolve) => {
204
+ const socket = createConnection({ host, port });
205
+ let settled = false;
206
+ const finish = (result) => {
207
+ if (settled)
208
+ return;
209
+ settled = true;
210
+ socket.destroy();
211
+ resolve(result);
212
+ };
213
+ socket.setTimeout(500);
214
+ socket.once("connect", () => finish({ available: true, host, port, adminUrl }));
215
+ socket.once("timeout", () => finish({ available: false, host, port, adminUrl, reason: `timed out connecting to PostgreSQL at ${host}:${port}` }));
216
+ socket.once("error", (error) => finish({ available: false, host, port, adminUrl, reason: error.message }));
217
+ });
218
+ }
219
+ function withGitIdentityEnv(env) {
220
+ return {
221
+ ...env,
222
+ GIT_AUTHOR_NAME: env.GIT_AUTHOR_NAME ?? "BenignSwarm Worker Gate",
223
+ GIT_AUTHOR_EMAIL: env.GIT_AUTHOR_EMAIL ?? "worker-gate@benignswarm.org",
224
+ GIT_COMMITTER_NAME: env.GIT_COMMITTER_NAME ?? "BenignSwarm Worker Gate",
225
+ GIT_COMMITTER_EMAIL: env.GIT_COMMITTER_EMAIL ?? "worker-gate@benignswarm.org",
226
+ };
227
+ }
228
+ export function prepareMergedWorktreeForSubmit(targetBranch, unitHeadInput, cwd = process.cwd(), env = process.env) {
229
+ const gitEnv = withGitIdentityEnv(env);
230
+ const fetched = retryGitFetchSync(["fetch", "--quiet", "--no-tags", "origin", `+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`], cwd);
231
+ if (fetched.status !== 0) {
232
+ throw new CliError("target_fetch_failed", `cannot fetch origin/${targetBranch} before running scoped submit gate: ${fetched.stderr?.trim() || "git fetch failed"}`, "Check origin connectivity and retry b9s wu submit");
233
+ }
234
+ const targetRef = `refs/remotes/origin/${targetBranch}`;
235
+ const targetSha = fullSha(`${targetRef}^{commit}`, cwd);
236
+ const unitHead = fullSha(`${unitHeadInput}^{commit}`, cwd);
237
+ if (!targetSha || !unitHead) {
238
+ throw new CliError("target_unavailable", `cannot resolve ${targetRef} or unit head commit before scoped submit gate`);
239
+ }
240
+ const tempRoot = mkdtempSync(join(tmpdir(), "b9s-submit-gate-"));
241
+ const worktreeDir = join(tempRoot, "repo");
242
+ const cleanup = () => {
243
+ spawnSync("git", ["-C", cwd, "worktree", "remove", "--force", worktreeDir], { cwd, env: gitEnv, encoding: "utf8" });
244
+ rmSync(tempRoot, { recursive: true, force: true });
245
+ spawnSync("git", ["-C", cwd, "worktree", "prune"], { cwd, env: gitEnv, encoding: "utf8" });
246
+ };
247
+ try {
248
+ const add = spawnSync("git", ["-C", cwd, "worktree", "add", "--detach", worktreeDir, targetSha], {
249
+ cwd,
250
+ env: gitEnv,
251
+ encoding: "utf8",
252
+ });
253
+ if (add.status !== 0) {
254
+ throw new CliError("submit_worktree_failed", `cannot create temporary merged worktree for scoped gate: ${(add.stderr || add.stdout).trim()}`);
255
+ }
256
+ const alreadyRebased = isAncestor(targetSha, unitHead, cwd) === true;
257
+ if (alreadyRebased) {
258
+ const co = spawnSync("git", ["-C", worktreeDir, "checkout", "--detach", unitHead], {
259
+ cwd: worktreeDir,
260
+ env: gitEnv,
261
+ encoding: "utf8",
262
+ });
263
+ if (co.status !== 0) {
264
+ throw new CliError("submit_worktree_failed", `cannot check out unit head ${unitHead.slice(0, 9)} in temporary gate worktree: ${(co.stderr || co.stdout).trim()}`);
265
+ }
266
+ }
267
+ else {
268
+ const merge = spawnSync("git", ["-C", worktreeDir, "merge", "--no-edit", "--no-ff", unitHead], {
269
+ cwd: worktreeDir,
270
+ env: gitEnv,
271
+ encoding: "utf8",
272
+ });
273
+ if (merge.status !== 0) {
274
+ spawnSync("git", ["-C", worktreeDir, "merge", "--abort"], { cwd: worktreeDir, env: gitEnv, encoding: "utf8" });
275
+ const detail = (merge.stderr || merge.stdout).trim().slice(0, 400);
276
+ throw new CliError("merge_conflict_with_target", `unit head ${unitHead.slice(0, 9)} does not merge cleanly onto current origin/${targetBranch} (${targetSha.slice(0, 9)}): ${detail}`, `Rebase or merge origin/${targetBranch} cleanly and resolve conflicts, then run b9s wu submit again`);
277
+ }
278
+ }
279
+ const mergedSha = fullSha("HEAD", worktreeDir);
280
+ if (!mergedSha)
281
+ throw new CliError("submit_worktree_failed", "cannot resolve merged HEAD commit SHA in temporary gate worktree");
282
+ const tree = spawnSync("git", ["-C", worktreeDir, "rev-parse", "HEAD^{tree}"], { cwd: worktreeDir, env: gitEnv, encoding: "utf8" });
283
+ const mergedTreeSha = tree.status === 0 && /^[0-9a-f]{40}$/i.test(tree.stdout.trim()) ? tree.stdout.trim().toLowerCase() : null;
284
+ return {
285
+ dir: worktreeDir,
286
+ targetSha,
287
+ unitHead,
288
+ mergedSha,
289
+ mergedTreeSha,
290
+ rebased: alreadyRebased,
291
+ cleanup,
292
+ };
293
+ }
294
+ catch (error) {
295
+ cleanup();
296
+ throw error;
297
+ }
298
+ }
299
+ export const defaultScopedGateRunner = (cmd, args, opts) => new Promise((resolve, reject) => {
300
+ const child = spawn(cmd, args, {
301
+ cwd: opts.cwd,
302
+ env: opts.env,
303
+ stdio: ["ignore", "pipe", "pipe"],
304
+ });
305
+ let output = "";
306
+ const handleChunk = (chunk) => {
307
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
308
+ output += text;
309
+ opts.onLine?.(text);
310
+ };
311
+ child.stdout.on("data", handleChunk);
312
+ child.stderr.on("data", handleChunk);
313
+ child.once("error", reject);
314
+ child.once("close", (code, signal) => {
315
+ resolve({ exitCode: code ?? (signal ? 1 : 0), output });
316
+ });
317
+ });
318
+ export function resolveLocalCustomGateCommand(gateCommand, unitNumber, mergedSha) {
319
+ const expanded = gateCommand.trim().replaceAll("{unit}", String(unitNumber)).replaceAll("{head}", mergedSha);
320
+ return expanded.replace(/^b9s\s+lock\s+run\s+complete-suite\b(?:\s+--\S+(?:\s+(?!--)\S+)?)*\s+--\s+/, "").trim();
321
+ }
322
+ export async function executeScopedGateForSubmit(opts) {
323
+ const env = opts.env ?? process.env;
324
+ const cwd = opts.cwd ?? process.cwd();
325
+ const plan = scopedGatePlan(opts.changedPaths, opts.merge);
326
+ if (!plan.required || plan.stages.length === 0)
327
+ return null;
328
+ let pgProbe = null;
329
+ if (plan.postgresRequiredReasons.length > 0) {
330
+ pgProbe = await (opts.deps?.probePostgres ?? probeLocalPostgres)(env);
331
+ if (!pgProbe.available) {
332
+ throw new CliError("missing_postgres", `cannot run required scoped gate stage(s) [${plan.stages.join(", ")}] on this machine: ${plan.postgresRequiredReasons.join("; ")}. Local PostgreSQL is unavailable at ${pgProbe.host}:${pgProbe.port}${pgProbe.reason ? ` (${pgProbe.reason})` : ""}`, "Start local PostgreSQL on 127.0.0.1:15432 or set PG_ADMIN_URL to a reachable local PostgreSQL instance, then rerun b9s wu submit");
333
+ }
334
+ }
335
+ const worktree = (opts.deps?.prepareWorktree ?? prepareMergedWorktreeForSubmit)(opts.targetBranch, opts.unitHead, cwd, env);
336
+ const startedAt = Date.now();
337
+ try {
338
+ const childEnv = {
339
+ ...withGitIdentityEnv(env),
340
+ GATE_REMOTE: "origin",
341
+ npm_config_prefer_offline: env.npm_config_prefer_offline ?? "true",
342
+ ...(pgProbe?.available && !env.PG_ADMIN_URL ? { PG_ADMIN_URL: pgProbe.adminUrl } : {}),
343
+ };
344
+ let cmd = "/bin/sh";
345
+ let args;
346
+ let commandSummary;
347
+ if (plan.mode === "gate_sh") {
348
+ if (!existsSync(join(worktree.dir, "scripts", "gate.sh"))) {
349
+ throw new CliError("scoped_gate_script_missing", `scripts/gate.sh is missing in merged commit ${worktree.mergedSha.slice(0, 9)}`, "Ensure scripts/gate.sh is present on the repository or adjust merge.gate_command");
350
+ }
351
+ args = ["scripts/gate.sh", worktree.mergedSha, ...plan.stages.flatMap((stage) => ["--stage", stage])];
352
+ commandSummary = `scripts/gate.sh ${worktree.mergedSha} ${plan.stages.map((s) => `--stage ${JSON.stringify(s)}`).join(" ")}`.slice(0, 500);
353
+ }
354
+ else {
355
+ const customCmd = resolveLocalCustomGateCommand(plan.customCommand ?? "", opts.unitNumber, worktree.mergedSha);
356
+ if (!customCmd) {
357
+ throw new CliError("scoped_gate_script_missing", "configured merge.gate_command resolved to an empty command");
358
+ }
359
+ args = ["-c", customCmd];
360
+ commandSummary = customCmd.slice(0, 500);
361
+ }
362
+ const runner = opts.deps?.runCommand ?? defaultScopedGateRunner;
363
+ const result = await runner(cmd, args, {
364
+ cwd: worktree.dir,
365
+ env: childEnv,
366
+ onLine: opts.deps?.onLog ?? ((chunk) => process.stderr.write(chunk)),
367
+ });
368
+ const durationMs = Math.max(0, Date.now() - startedAt);
369
+ if (result.exitCode !== 0) {
370
+ const failedStep = parseFailedGateStep(result.output, []);
371
+ const tail = result.output.trim().split(/\r?\n/).slice(-25).join("\n");
372
+ throw new CliError("scoped_gate_failed", `scoped submit gate failed at ${failedStep} (exit ${result.exitCode}) on merged head ${worktree.mergedSha.slice(0, 9)} (unit ${worktree.unitHead.slice(0, 9)} + origin/${opts.targetBranch} ${worktree.targetSha.slice(0, 9)})${tail ? `:\n${tail}` : ""}`, "Fix the failing test or build regression locally, commit, and run b9s wu submit again");
373
+ }
374
+ return {
375
+ unit_head: worktree.unitHead,
376
+ target_branch: opts.targetBranch,
377
+ target_sha: worktree.targetSha,
378
+ merged_sha: worktree.mergedSha,
379
+ merged_tree_sha: worktree.mergedTreeSha,
380
+ rebased: worktree.rebased,
381
+ machine: opts.machine,
382
+ stages: plan.stages,
383
+ changed_paths: [...opts.changedPaths],
384
+ exit_code: 0,
385
+ passed_at: new Date().toISOString(),
386
+ command: commandSummary,
387
+ duration_ms: durationMs,
388
+ };
389
+ }
390
+ finally {
391
+ worktree.cleanup();
392
+ }
393
+ }
package/dist/state.js CHANGED
@@ -64,6 +64,15 @@ export function updateState(agent, change, env = process.env) {
64
64
  return next;
65
65
  }, { busyCode: "state_busy" });
66
66
  }
67
+ /** Persist wake-command outcomes across watcher restarts for the next heartbeat. */
68
+ export function recordWakeAttempt(agent, outcome, at = new Date().toISOString(), env = process.env) {
69
+ return updateState(agent, (state) => {
70
+ const prior = state.wake_attempt ?? { consecutive_failures: 0, last_failure_exit_code: null, last_failure_message: null, last_failure_at: null, last_success_at: null };
71
+ return { ...state, wake_attempt: outcome.success
72
+ ? { ...prior, consecutive_failures: 0, last_success_at: at }
73
+ : { ...prior, consecutive_failures: prior.consecutive_failures + 1, last_failure_exit_code: outcome.exitCode, last_failure_message: outcome.message.slice(0, 300), last_failure_at: at } };
74
+ }, env);
75
+ }
67
76
  /**
68
77
  * Replaces the whole state file (first set-up, tests). Anything that changes a field of a state
69
78
  * another process may also be writing uses updateState instead: a copy read earlier and written
package/dist/usage.js CHANGED
@@ -1,7 +1,8 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { claudeTranscript, dshUsage } from "./harnesses.js";
1
+ import { existsSync } from "node:fs";
2
+ import { claudeTranscript, dshUsageFromRecordsDetailed } from "./harnesses.js";
3
3
  import { antigravityUsage } from "./antigravity.js";
4
4
  import { scanLinesBackward, TAIL_CHUNK_BYTES } from "./tail-lines.js";
5
+ import { JsonlRecordTooLargeError, readJsonlRecords } from "./jsonl.js";
5
6
  /**
6
7
  * How far back a usage window may be read. The watcher measures every completed turn, so this is read
7
8
  * once per turn rather than per pass, and a turn rarely writes more than a few MB; past the cap the
@@ -14,15 +15,10 @@ export function claudeSessionWithHookMetadata(sessionId, transcript, provider, r
14
15
  return { harness: "claude-code", transcript, session_id: sessionId, provider, ...(sameSession && remembered.compactions?.length ? { compactions: remembered.compactions } : {}) };
15
16
  }
16
17
  const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
17
- function lines(path) {
18
- return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
19
- try {
20
- return [JSON.parse(l)];
21
- }
22
- catch {
23
- return [];
24
- }
25
- });
18
+ function* lines(path) { yield* readJsonlRecords(path); }
19
+ function transcriptReadReason(error) {
20
+ const message = error instanceof Error ? error.message : String(error);
21
+ return error instanceof JsonlRecordTooLargeError ? message : `could not read session telemetry: ${message}`;
26
22
  }
27
23
  /** Earliest timestamp actually present in this session's supported metadata. */
28
24
  export function sessionStart(session) {
@@ -61,15 +57,19 @@ export function sessionContext(session, until) {
61
57
  : session.transcript;
62
58
  if (!transcript || !existsSync(transcript))
63
59
  return unknownContext(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
64
- const rows = lines(transcript);
65
60
  if (session.harness === "codex") {
66
61
  let latest;
67
- for (const row of rows) {
68
- const p = row.payload;
69
- const at = typeof row.timestamp === "string" ? row.timestamp : "";
70
- const tokens = p?.info?.last_token_usage?.total_tokens, window = p?.info?.model_context_window;
71
- if (row.type === "event_msg" && p?.type === "token_count" && at && Number.isFinite(epoch(at)) && epoch(at) <= epoch(until) && positiveInt(tokens) && positiveInt(window) && (!latest || epoch(at) > epoch(latest.at)))
72
- latest = { at, tokens, window };
62
+ try {
63
+ for (const row of lines(transcript)) {
64
+ const p = row.payload;
65
+ const at = typeof row.timestamp === "string" ? row.timestamp : "";
66
+ const tokens = p?.info?.last_token_usage?.total_tokens, window = p?.info?.model_context_window;
67
+ if (row.type === "event_msg" && p?.type === "token_count" && at && Number.isFinite(epoch(at)) && epoch(at) <= epoch(until) && positiveInt(tokens) && positiveInt(window) && (!latest || epoch(at) > epoch(latest.at)))
68
+ latest = { at, tokens, window };
69
+ }
70
+ }
71
+ catch (error) {
72
+ return unknownContext(transcriptReadReason(error));
73
73
  }
74
74
  if (!latest)
75
75
  return unknownContext("no Codex token_count with a model_context_window is available yet");
@@ -77,17 +77,22 @@ export function sessionContext(session, until) {
77
77
  }
78
78
  if (session.harness === "claude-code") {
79
79
  let latest;
80
- for (const row of rows) {
81
- const msg = row.message;
82
- const at = typeof row.timestamp === "string" ? row.timestamp : "";
83
- if (row.type !== "assistant" || !at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until) || !msg?.usage)
84
- continue;
85
- const model = msg.model;
86
- const window = claudeContextWindow(model);
87
- const usage = msg.usage;
88
- const tokens = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.output_tokens ?? 0);
89
- if (window && positiveInt(tokens) && (!latest || epoch(at) > epoch(latest.at)))
90
- latest = { at, tokens, window };
80
+ try {
81
+ for (const row of lines(transcript)) {
82
+ const msg = row.message;
83
+ const at = typeof row.timestamp === "string" ? row.timestamp : "";
84
+ if (row.type !== "assistant" || !at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until) || !msg?.usage)
85
+ continue;
86
+ const model = msg.model;
87
+ const window = claudeContextWindow(model);
88
+ const usage = msg.usage;
89
+ const tokens = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.output_tokens ?? 0);
90
+ if (window && positiveInt(tokens) && (!latest || epoch(at) > epoch(latest.at)))
91
+ latest = { at, tokens, window };
92
+ }
93
+ }
94
+ catch (error) {
95
+ return unknownContext(transcriptReadReason(error));
91
96
  }
92
97
  if (!latest)
93
98
  return unknownContext("no Claude assistant usage for a model with a confirmed context window is available yet");
@@ -95,16 +100,21 @@ export function sessionContext(session, until) {
95
100
  }
96
101
  if (session.harness === "antigravity") {
97
102
  let latest;
98
- for (const row of rows) {
99
- const at = typeof row.finished_at === "string" ? row.finished_at : "";
100
- if (!at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until))
101
- continue;
102
- const result = row.result;
103
- const u = result?.usage;
104
- const tokens = typeof u?.total_tokens === "number" ? u.total_tokens : u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.thinking_tokens ?? 0) + (u.cache_read_tokens ?? 0) : null;
105
- const window = row.model_context_window ?? row.context_window;
106
- if (tokens !== null && positiveInt(tokens) && (!latest || at > latest.at))
107
- latest = { at, tokens, ...(positiveInt(window) ? { window } : {}) };
103
+ try {
104
+ for (const row of lines(transcript)) {
105
+ const at = typeof row.finished_at === "string" ? row.finished_at : "";
106
+ if (!at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until))
107
+ continue;
108
+ const result = row.result;
109
+ const u = result?.usage;
110
+ const tokens = typeof u?.total_tokens === "number" ? u.total_tokens : u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.thinking_tokens ?? 0) + (u.cache_read_tokens ?? 0) : null;
111
+ const window = row.model_context_window ?? row.context_window;
112
+ if (tokens !== null && positiveInt(tokens) && (!latest || at > latest.at))
113
+ latest = { at, tokens, ...(positiveInt(window) ? { window } : {}) };
114
+ }
115
+ }
116
+ catch (error) {
117
+ return unknownContext(transcriptReadReason(error));
108
118
  }
109
119
  if (!latest?.window)
110
120
  return unknownContext(latest ? "Antigravity model context window has not been confirmed on a real run" : "no Antigravity per-turn usage record is available yet");
@@ -132,30 +142,41 @@ export function sessionCompactions(session, since, until) {
132
142
  : session.transcript;
133
143
  if (!transcript || !existsSync(transcript))
134
144
  return unknownCompactions(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
135
- const boundaries = [], hookCompactions = [];
145
+ let boundaryCount = 0;
146
+ const pairedHooks = new Set();
147
+ const hookCompactions = [];
136
148
  const sinceAt = epoch(since), untilAt = epoch(until);
137
149
  if (!Number.isFinite(sinceAt) || !Number.isFinite(untilAt))
138
150
  return unknownCompactions("the unit event time range is invalid");
139
- for (const row of lines(transcript)) {
140
- let at;
141
- if (session.harness === "codex" && row.type === "response_item" && row.payload?.type === "compaction")
142
- at = typeof row.timestamp === "string" ? row.timestamp : undefined;
143
- if (session.harness === "claude-code" && row.type === "system" && row.subtype === "compact_boundary")
144
- at = typeof row.timestamp === "string" ? row.timestamp : undefined;
145
- const eventAt = at ? epoch(at) : NaN;
146
- if (Number.isFinite(eventAt) && eventAt >= sinceAt && eventAt < untilAt)
147
- boundaries.push(eventAt);
148
- }
149
151
  if (session.harness === "claude-code")
150
152
  for (const at of session.compactions ?? [])
151
153
  if (Number.isFinite(at) && at >= sinceAt && at < untilAt)
152
154
  hookCompactions.push(at);
155
+ try {
156
+ for (const row of lines(transcript)) {
157
+ let at;
158
+ if (session.harness === "codex" && row.type === "response_item" && row.payload?.type === "compaction")
159
+ at = typeof row.timestamp === "string" ? row.timestamp : undefined;
160
+ if (session.harness === "claude-code" && row.type === "system" && row.subtype === "compact_boundary")
161
+ at = typeof row.timestamp === "string" ? row.timestamp : undefined;
162
+ const eventAt = at ? epoch(at) : NaN;
163
+ if (Number.isFinite(eventAt) && eventAt >= sinceAt && eventAt < untilAt) {
164
+ boundaryCount++;
165
+ hookCompactions.forEach((hookAt, index) => { if (Math.abs(eventAt - hookAt) <= 30_000)
166
+ pairedHooks.add(index); });
167
+ }
168
+ }
169
+ }
170
+ catch (error) {
171
+ return unknownCompactions(transcriptReadReason(error));
172
+ }
153
173
  if (session.harness !== "codex" && session.harness !== "claude-code")
154
174
  return unknownCompactions(`${session.harness} does not expose compaction events in a supported local session format`);
155
175
  // Claude's hook and transcript can report the same compaction. Deduplicate only across those
156
176
  // two sources so two real transcript boundaries close together are still counted separately.
157
- const unpairedHooks = hookCompactions.filter((hookAt) => !boundaries.some((boundaryAt) => Math.abs(boundaryAt - hookAt) <= 30_000));
158
- return { count: boundaries.length + unpairedHooks.length, reason: null };
177
+ // Hook metadata is known before scanning the transcript; pair it with transcript boundaries
178
+ // while streaming so memory use does not grow with the full session history.
179
+ return { count: boundaryCount + hookCompactions.filter((_hookAt, index) => !pairedHooks.has(index)).length, reason: null };
159
180
  }
160
181
  /**
161
182
  * Codex rollout: `event_msg` `token_count` events carry running totals, so the window's use is the
@@ -258,15 +279,26 @@ export function sessionUsage(session, since, until) {
258
279
  if (session.harness === "claude-code")
259
280
  return withProvider(claudeUsage(transcript, since, until));
260
281
  if (session.harness === "dsh") {
261
- const text = readFileSync(session.transcript, "utf8");
262
- if (!/"type"\s*:\s*"b9s_invocation_start"/.test(text))
282
+ let tokens, hasInvocationStart;
283
+ try {
284
+ ({ usage: tokens, hasInvocationStart } = dshUsageFromRecordsDetailed(lines(session.transcript), since, until));
285
+ }
286
+ catch (error) {
287
+ return none(session.harness, transcriptReadReason(error));
288
+ }
289
+ if (!hasInvocationStart)
263
290
  return none(session.harness, "DeepSeek Harness events have no local invocation timing, so usage cannot be attributed to this work-unit window");
264
- const tokens = dshUsage(text, since, until);
265
291
  const base = { harness: "dsh", source: "dsh-step-end-events", scope: "session", since, until, tokens: null };
266
292
  return tokens.total ? { ...base, tokens } : { ...base, reason: "no step_end usage events in the DeepSeek Harness turn log during this window" };
267
293
  }
268
294
  if (session.harness === "antigravity") {
269
- const tokens = antigravityUsage(session.transcript, since, until);
295
+ let tokens;
296
+ try {
297
+ tokens = antigravityUsage(session.transcript, since, until);
298
+ }
299
+ catch (error) {
300
+ return none(session.harness, transcriptReadReason(error));
301
+ }
270
302
  const base = { harness: "antigravity", source: "agy-json-turn-records", scope: "session", since, until, tokens };
271
303
  return tokens ? base : { ...base, reason: "no Antigravity usage records in the window" };
272
304
  }