benignswarm 0.12.110 → 0.12.111

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.
@@ -1626,7 +1626,7 @@ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
1626
1626
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
1627
1627
  const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
1628
1628
  if (!thread || !ph || "missing" in ph)
1629
- return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
1629
+ return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
1630
1630
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
1631
1631
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
1632
1632
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
@@ -7,6 +7,7 @@ import { spawnSync } from "node:child_process";
7
7
  import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
8
8
  import { table } from "../output.js";
9
9
  import { collectPruneProtection } from "../prune-protection.js";
10
+ import { sweepClosedHarnessServers } from "../harness-server-sweep.js";
10
11
  const CLOSED = ["done", "abandoned", "superseded"];
11
12
  const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
12
13
  const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
@@ -53,6 +54,7 @@ export async function unitWorktrees(creds, project, options = {}) {
53
54
  clearTimeout(timer);
54
55
  }
55
56
  const closed = new Map();
57
+ const closedCheckouts = [];
56
58
  const active = { paths: new Map(), branches: new Map() };
57
59
  for (const u of all.units) {
58
60
  const label = `WU #${u.number} (${u.status})`;
@@ -66,12 +68,19 @@ export async function unitWorktrees(creds, project, options = {}) {
66
68
  if (!u.worktree || !existsSync(u.worktree))
67
69
  continue;
68
70
  closed.set(realpathSync(u.worktree), `WU #${u.number} ${u.status}`);
71
+ if (typeof u.closed_at === "string" && Number.isSafeInteger(u.number))
72
+ closedCheckouts.push({ path: realpathSync(u.worktree), number: u.number, closedAt: u.closed_at, branch: typeof u.branch === "string" ? u.branch : null });
69
73
  }
70
- return { closed, active };
74
+ return { closed, active, closedCheckouts };
71
75
  }
72
76
  export async function pruneProjectWorktrees(creds, project, cwd, protection, log) {
73
77
  const before = await scanProject(creds, project, { cwd });
74
78
  const units = await unitWorktrees(creds, project);
79
+ const linked = scanWorktrees(cwd);
80
+ if (!linked)
81
+ throw new Error("could not verify linked worktrees for harness process sweep");
82
+ const linkedBranches = new Map(linked.worktrees.map(worktree => [realpathSync(worktree.path), worktree.branch]));
83
+ await sweepClosedHarnessServers(units.closedCheckouts.filter(unit => unit.branch !== null && linkedBranches.get(unit.path) === unit.branch), units.active, protection, log);
75
84
  const report = pruneReport(cwd, units.closed, units.active, undefined, protection);
76
85
  const dirtyClosed = [...new Set(report.kept.flatMap((item) => {
77
86
  const number = item.dirtyClosed ? /WU #(\d+)/.exec(item.dirtyClosed)?.[1] : undefined;
@@ -0,0 +1,78 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { isAbsolute, relative, sep } from "node:path";
3
+ import { scanWorktreeProcesses } from "./machine-processes.js";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ function within(root, path) {
6
+ const rel = relative(root, path);
7
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
8
+ }
9
+ /** Stop only identified test servers in a verified closed and otherwise unused checkout. */
10
+ export async function sweepClosedHarnessServers(checkouts, active, protection, log, deps = {}) {
11
+ const now = deps.now ?? Date.now();
12
+ const scan = deps.scan ?? ((path) => scanWorktreeProcesses(path, { project_roots: [path], foreign_roots: [] }));
13
+ const signal = deps.signal ?? ((pid, signal) => { process.kill(pid, signal); });
14
+ const alive = deps.alive ?? ((pid) => {
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ }
19
+ catch (error) {
20
+ if (error.code === "ESRCH")
21
+ return false;
22
+ throw error;
23
+ }
24
+ });
25
+ const pause = deps.pause ?? delay;
26
+ const attempts = deps.attempts ?? 10;
27
+ for (const unit of checkouts) {
28
+ const closed = Date.parse(unit.closedAt);
29
+ if (!Number.isFinite(closed) || now - closed < 30 * 60_000)
30
+ continue;
31
+ try {
32
+ const root = realpathSync(unit.path);
33
+ if (active.branches.has(unit.branch ?? "") || [...active.paths.keys()].some(path => within(root, path) || within(path, root)))
34
+ continue;
35
+ if (protection.inUse.some(use => {
36
+ const path = realpathSync(use.path);
37
+ return within(root, path) || within(path, root);
38
+ }))
39
+ continue;
40
+ const processes = scan(root);
41
+ for (const candidate of processes) {
42
+ if (!/(?:^|[\s/])(?:wrangler(?:\.js)?\s+dev|vite(?:\.js)?(?:\s|$)|workerd(?:\s|$))/.test(candidate.command))
43
+ continue;
44
+ const identity = () => {
45
+ const current = scan(root).find(p => p.pid === candidate.pid);
46
+ if (current)
47
+ return current.started_at === candidate.started_at && current.command === candidate.command && current.cwd === candidate.cwd ? "same" : "changed";
48
+ return alive(candidate.pid) ? "unknown" : "gone";
49
+ };
50
+ let state = identity();
51
+ if (state !== "same") {
52
+ log(`closed unit #${unit.number}: process ${candidate.pid} ${state} before signal; not stopped`);
53
+ continue;
54
+ }
55
+ signal(candidate.pid, "SIGTERM");
56
+ for (let i = 0; i < attempts && state === "same"; i++) {
57
+ await pause(100);
58
+ state = identity();
59
+ }
60
+ if (state === "same") {
61
+ // The last complete scan establishes the identity immediately before escalation.
62
+ signal(candidate.pid, "SIGKILL");
63
+ for (let i = 0; i < attempts && state === "same"; i++) {
64
+ await pause(100);
65
+ state = identity();
66
+ }
67
+ }
68
+ if (state === "gone")
69
+ log(`closed unit #${unit.number}: stopped pid ${candidate.pid}, age ${candidate.elapsed_seconds}s, command ${candidate.command}`);
70
+ else
71
+ log(`closed unit #${unit.number}: pid ${candidate.pid} exit not verified (${state}), age ${candidate.elapsed_seconds}s, command ${candidate.command}`);
72
+ }
73
+ }
74
+ catch (error) {
75
+ log(`closed unit #${unit.number}: harness process sweep could not inspect safely; no further processes stopped: ${error.message}`);
76
+ }
77
+ }
78
+ }
package/dist/harnesses.js CHANGED
@@ -6,7 +6,8 @@ import { CliError } from "./errors.js";
6
6
  import { configRoot } from "./config.js";
7
7
  import { readState, writeState } from "./state.js";
8
8
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
- import { codexTurnPhase, usageLimitUntil } from "./turn.js";
9
+ import { readTurnPhase, usageLimitUntil } from "./turn.js";
10
+ import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
10
11
  import { antigravityProbe } from "./antigravity.js";
11
12
  /**
12
13
  * Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
@@ -331,12 +332,15 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
331
332
  };
332
333
  }
333
334
  function codexProbe(thread) {
334
- const read = () => { const r = codexRollout(thread); return r ? codexTurnPhase(readFileSync(r, "utf8")) : null; };
335
+ const read = () => { const r = codexRollout(thread); return r ? readTurnPhase(r) : null; };
335
336
  return {
336
337
  label: "Codex",
337
338
  what: `thread ${thread}`,
338
339
  phase() {
339
340
  const ph = read();
341
+ // A reader that hit its cap without deciding never reports idle: start nothing, report unknown.
342
+ if (ph?.unknown)
343
+ return { missing: `${ph.unknown}; cannot tell whether a turn is running, so starting none`, unknown: true };
340
344
  if (ph)
341
345
  return { ...ph, lastErrorAt: ph.lastEventAt };
342
346
  return {
@@ -351,17 +355,24 @@ function codexProbe(thread) {
351
355
  const path = codexRollout(thread);
352
356
  if (!path)
353
357
  return "";
354
- const messages = readFileSync(path, "utf8").split("\n").flatMap((line) => {
358
+ // The last 800 characters of assistant text: read from the end until that much is collected (WU #474).
359
+ const messages = [];
360
+ let collected = 0;
361
+ scanLinesBackward(path, (line) => {
362
+ let event;
355
363
  try {
356
- const event = JSON.parse(line);
357
- if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
358
- return [];
359
- const content = event.payload.message.content;
360
- return typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
364
+ event = JSON.parse(line);
361
365
  }
362
366
  catch {
363
- return [];
367
+ return false;
364
368
  }
369
+ if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
370
+ return false;
371
+ const content = event.payload.message.content;
372
+ const parts = typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
373
+ messages.unshift(...parts);
374
+ collected += parts.reduce((n, t) => n + t.length + 1, 0);
375
+ return collected >= 800;
365
376
  });
366
377
  return messages.join("\n").slice(-800);
367
378
  },
@@ -409,6 +420,37 @@ export function claudeTranscriptTimes(text) {
409
420
  }
410
421
  return { lastEventAt, promptAt };
411
422
  }
423
+ /**
424
+ * claudeTranscriptTimes for a transcript file, read from the end to the latest user prompt (WU #474).
425
+ * `capped` is set when the prompt was not found within the read cap: the prompt time is then unknown.
426
+ */
427
+ export function claudeTranscriptTimesFromFile(path, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
428
+ let lastEventAt = null;
429
+ let promptAt = null;
430
+ const scan = scanLinesBackward(path, (line) => {
431
+ let j;
432
+ try {
433
+ j = JSON.parse(line);
434
+ }
435
+ catch {
436
+ return false;
437
+ } // a line still being written
438
+ if (!j.timestamp)
439
+ return false;
440
+ if (lastEventAt === null)
441
+ lastEventAt = j.timestamp;
442
+ if (j.type === "user" && typeof j.message?.content === "string") {
443
+ promptAt = j.timestamp;
444
+ return true;
445
+ }
446
+ return false;
447
+ }, chunkBytes, maxBytes);
448
+ return scan.capped ? { lastEventAt, promptAt, capped: true } : { lastEventAt, promptAt };
449
+ }
450
+ const claudeTimesCache = new FileFactsCache();
451
+ function readClaudeTranscriptTimes(path) {
452
+ return claudeTimesCache.get(path, (p) => claudeTranscriptTimesFromFile(p));
453
+ }
412
454
  /**
413
455
  * The error a `claude -p --output-format json` run ended with, or null when it succeeded. Output
414
456
  * that is not the result object (a missing session prints plain text) is returned as the error.
@@ -484,15 +526,18 @@ function claudeProbe(session, ref) {
484
526
  const tr = claudeTranscript(session);
485
527
  if (!tr)
486
528
  return { missing: `no transcript for Claude Code session ${session} under ${join(claudeHome(), "projects")}; cannot tell whether a turn is running, so starting none` };
487
- const times = claudeTranscriptTimes(readFileSync(tr, "utf8"));
529
+ const times = readClaudeTranscriptTimes(tr);
488
530
  // Claude Code writes no turn-ended marker, so a running turn is a process holding the session.
489
531
  const running = sessionProcesses(session).length > 0;
532
+ // No process and no prompt within the read cap: the bounded read can't place the latest turn, so it never reports idle.
533
+ if (!running && times.capped)
534
+ return { missing: `no user prompt within the last ${Math.round(TAIL_MAX_BYTES / 1048576)} MB of ${tr}; cannot tell where the latest turn stands, so starting none`, unknown: true };
490
535
  const res = lastResult();
491
536
  return { running, startedAt: times.promptAt, lastEventAt: times.lastEventAt, lastError: running ? null : res?.error ?? null, lastErrorAt: res?.at ?? null };
492
537
  },
493
538
  startedSince(ms) {
494
539
  const tr = claudeTranscript(session);
495
- const p = tr ? claudeTranscriptTimes(readFileSync(tr, "utf8")).promptAt : null;
540
+ const p = tr ? readClaudeTranscriptTimes(tr).promptAt : null;
496
541
  return !!p && Date.parse(p) >= ms - 5_000;
497
542
  },
498
543
  turnError: () => lastResult()?.error ?? null,
@@ -0,0 +1,90 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
2
+ /**
3
+ * Reading append-only session logs (Codex rollouts, Claude Code transcripts) from the end. The daemon
4
+ * and the watchers need only the newest facts in these files, yet they grow for the life of a thread
5
+ * (120-150 MB per Codex rollout on aws1, 2026-11-17), and reading them whole every pass churned
6
+ * gigabytes per machine (WU #474).
7
+ */
8
+ export const TAIL_CHUNK_BYTES = 256 * 1024;
9
+ /** How far back a per-pass reader may look (WU #474 scope: a hard cap). Past it the answer is "unknown", never "idle". */
10
+ export const TAIL_MAX_BYTES = 8 * 1024 * 1024;
11
+ /** Counts scans and bytes read, so tests can prove an unchanged file is not read again and a scan stops at its cap. */
12
+ export const tailReadStats = { scans: 0, bytes: 0 };
13
+ /**
14
+ * Calls `visit` with each complete line of the file from the last to the first, until it returns true
15
+ * (stop), the file's start is reached, or `maxBytes` have been read (then `capped` is true and the
16
+ * piece of a line cut by the cap is never visited). Lines split on the newline byte, which never occurs
17
+ * inside a multi-byte UTF-8 sequence, so decoding each line separately is exact. A final line without a
18
+ * newline is still visited (a writer may be mid-line; callers skip what doesn't parse, as the full reads
19
+ * did). A single line longer than the cap is never assembled: memory stays within the cap.
20
+ */
21
+ export function scanLinesBackward(path, visit, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
22
+ const fd = openSync(path, "r");
23
+ tailReadStats.scans++;
24
+ let bytesRead = 0;
25
+ try {
26
+ let pos = fstatSync(fd).size;
27
+ let carry = Buffer.alloc(0);
28
+ while (pos > 0) {
29
+ if (bytesRead >= maxBytes)
30
+ return { bytesRead, capped: true };
31
+ const start = Math.max(0, pos - Math.min(chunkBytes, maxBytes - bytesRead));
32
+ const chunk = Buffer.alloc(pos - start);
33
+ let got = 0;
34
+ while (got < chunk.length) {
35
+ const n = readSync(fd, chunk, got, chunk.length - got, start + got);
36
+ if (n === 0)
37
+ break;
38
+ got += n;
39
+ }
40
+ bytesRead += got;
41
+ tailReadStats.bytes += got;
42
+ const data = carry.length ? Buffer.concat([chunk.subarray(0, got), carry]) : chunk.subarray(0, got);
43
+ let end = data.length;
44
+ // Walk newline positions from the end; the piece before the first newline may continue in the previous chunk.
45
+ for (let i = data.length - 1; i >= 0; i--) {
46
+ if (data[i] !== 0x0a)
47
+ continue;
48
+ if (end > i + 1 && visit(data.subarray(i + 1, end).toString("utf8")))
49
+ return { bytesRead, capped: false };
50
+ end = i;
51
+ }
52
+ carry = Buffer.from(data.subarray(0, end));
53
+ pos = start;
54
+ }
55
+ if (carry.length && visit(carry.toString("utf8")))
56
+ return { bytesRead, capped: false };
57
+ return { bytesRead, capped: false };
58
+ }
59
+ finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+ /** Results computed from a file, reused while the file's identity (device, inode), size and mtime are unchanged. */
64
+ export class FileFactsCache {
65
+ max;
66
+ entries = new Map();
67
+ constructor(max = 256) {
68
+ this.max = max;
69
+ }
70
+ get(path, compute) {
71
+ const fd = openSync(path, "r");
72
+ let key;
73
+ try {
74
+ const s = fstatSync(fd, { bigint: true });
75
+ key = `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}`;
76
+ }
77
+ finally {
78
+ closeSync(fd);
79
+ }
80
+ const hit = this.entries.get(path);
81
+ if (hit && hit.key === key)
82
+ return hit.value;
83
+ const value = compute(path);
84
+ this.entries.delete(path);
85
+ this.entries.set(path, { key, value });
86
+ if (this.entries.size > this.max)
87
+ this.entries.delete(this.entries.keys().next().value);
88
+ return value;
89
+ }
90
+ }
package/dist/turn.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { readFileSync } from "node:fs";
2
+ import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "./tail-lines.js";
3
3
  export const DEFAULT_TURN_COALESCE_SECONDS = 180;
4
4
  export const MAX_TURN_COALESCE_SECONDS = 3600;
5
5
  /** Whether direct pending work is still inside its per-session coalescing window. */
@@ -53,8 +53,57 @@ export function usageLimitUntil(error) {
53
53
  const t = Date.parse(`${m[1]}, ${m[2]} ${m[3]}`);
54
54
  return Number.isNaN(t) ? null : t;
55
55
  }
56
+ /**
57
+ * codexTurnPhase for a rollout file, reading it from the end: the latest timestamp, then back to the
58
+ * latest task_started, noting the latest close (task_complete / turn_aborted) on the way. That is the
59
+ * same answer the whole-file read gives, but it reads only back to the start of the current turn, and an
60
+ * unchanged file is not read again (WU #474).
61
+ */
62
+ export function codexTurnPhaseFromFile(rollout, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
63
+ let lastEventAt = null;
64
+ let closed = false;
65
+ let closeError = null;
66
+ let startedAt = null;
67
+ let started = false;
68
+ const scan = scanLinesBackward(rollout, (line) => {
69
+ let j;
70
+ try {
71
+ j = JSON.parse(line);
72
+ }
73
+ catch {
74
+ return false;
75
+ } // a line still being written
76
+ if (lastEventAt === null && j.timestamp)
77
+ lastEventAt = j.timestamp;
78
+ // Past the latest task_started only the newest timestamp is still wanted (that line may have had none).
79
+ if (started)
80
+ return lastEventAt !== null;
81
+ if (j.type !== "event_msg")
82
+ return false;
83
+ const t = j.payload?.type;
84
+ if ((t === "task_complete" || t === "turn_aborted") && !closed) {
85
+ closed = true;
86
+ closeError = j.payload?.error?.message ?? null;
87
+ return false;
88
+ }
89
+ if (t === "task_started") {
90
+ started = true;
91
+ startedAt = j.timestamp ?? null;
92
+ return lastEventAt !== null;
93
+ }
94
+ return false;
95
+ }, chunkBytes, maxBytes);
96
+ if (!started && !closed && scan.capped) {
97
+ return { running: false, startedAt: null, lastEventAt, lastError: null, unknown: `neither the start nor the end of the latest turn is within the last ${Math.round(maxBytes / 1048576)} MB of ${rollout}` };
98
+ }
99
+ if (!started)
100
+ return { running: false, startedAt: null, lastEventAt, lastError: closed ? closeError : null };
101
+ return { running: !closed && startedAt !== null, startedAt, lastEventAt, lastError: closed ? closeError : null };
102
+ }
103
+ const turnPhaseCache = new FileFactsCache();
104
+ /** The turn phase of a rollout file; an unchanged file (same inode, size and mtime) is answered from memory. */
56
105
  export function readTurnPhase(rollout) {
57
- return codexTurnPhase(readFileSync(rollout, "utf8"));
106
+ return turnPhaseCache.get(rollout, (path) => codexTurnPhaseFromFile(path));
58
107
  }
59
108
  /**
60
109
  * Starts the turn command in its own process group, so a watcher restart (an upgrade reloads every
package/dist/usage.js CHANGED
@@ -1,6 +1,13 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { claudeTranscript, dshUsage } from "./harnesses.js";
3
3
  import { antigravityUsage } from "./antigravity.js";
4
+ import { scanLinesBackward, TAIL_CHUNK_BYTES } from "./tail-lines.js";
5
+ /**
6
+ * How far back a usage window may be read. The watcher measures every completed turn, so this is read
7
+ * once per turn rather than per pass, and a turn rarely writes more than a few MB; past the cap the
8
+ * result is "unavailable" with the reason, never a partial count (WU #474).
9
+ */
10
+ export const USAGE_MAX_BYTES = 32 * 1024 * 1024;
4
11
  /** Keep hook-only Claude compaction metadata only when it belongs to the exact session selected. */
5
12
  export function claudeSessionWithHookMetadata(sessionId, transcript, provider, remembered) {
6
13
  const sameSession = remembered?.harness === "claude-code" && remembered.session_id === sessionId;
@@ -155,23 +162,34 @@ export function sessionCompactions(session, since, until) {
155
162
  * last total at or before `until` minus the last total before `since` (zero when the session began
156
163
  * inside the window).
157
164
  */
158
- export function codexUsage(path, since, until) {
165
+ export function codexUsage(path, since, until, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = USAGE_MAX_BYTES) {
159
166
  let before = null, end = null;
160
167
  let plan = null;
161
- for (const j of lines(path)) {
168
+ // From the end: the first match met going back is the last one in file order, which is what the whole-file read kept.
169
+ const scan = scanLinesBackward(path, (line) => {
170
+ let j;
171
+ try {
172
+ j = JSON.parse(line);
173
+ }
174
+ catch {
175
+ return false;
176
+ }
162
177
  const p = j.payload;
163
178
  const at = typeof j.timestamp === "string" ? j.timestamp : null;
164
179
  if (j.type !== "event_msg" || p?.type !== "token_count" || !at)
165
- continue;
180
+ return false;
166
181
  const total = p.info?.total_token_usage;
167
- if (total && at < since)
182
+ if (total && at < since && !before)
168
183
  before = total;
169
- if (total && at <= until)
184
+ if (total && at <= until && !end)
170
185
  end = total;
171
- if (at <= until && p.rate_limits?.primary && typeof p.rate_limits.primary.used_percent === "number")
186
+ if (at <= until && !plan && p.rate_limits?.primary && typeof p.rate_limits.primary.used_percent === "number")
172
187
  plan = { used_percent: p.rate_limits.primary.used_percent, window_minutes: p.rate_limits.primary.window_minutes ?? null };
173
- }
188
+ return before !== null && plan !== null;
189
+ }, chunkBytes, maxBytes);
174
190
  const base = { harness: "codex", source: "codex-rollout", scope: "session", since, until, tokens: null, plan };
191
+ if (scan.capped && !before)
192
+ return { ...base, reason: `the window's start is beyond the last ${Math.round(maxBytes / 1048576)} MB of the session file; not counted` };
175
193
  if (!end)
176
194
  return { ...base, reason: "no token counts in the session up to now" };
177
195
  const d = (k) => (end[k] ?? 0) - (before?.[k] ?? 0);
@@ -179,20 +197,38 @@ export function codexUsage(path, since, until) {
179
197
  t.total = t.input + t.output;
180
198
  return { ...base, tokens: t };
181
199
  }
200
+ /** Claude transcripts are appended in time order; entries this far before the window's start end the backward read. */
201
+ const CLAUDE_ORDER_SLACK_MS = 5 * 60_000;
182
202
  /**
183
203
  * Claude Code transcript: assistant entries carry `message.usage`. One message is written once per
184
204
  * content block with the same id, so each message id counts once (its last entry).
185
205
  */
186
- export function claudeUsage(path, since, until) {
206
+ export function claudeUsage(path, since, until, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = USAGE_MAX_BYTES) {
187
207
  const byMessage = new Map();
188
- for (const j of lines(path)) {
208
+ const stopBefore = new Date(Date.parse(since) - CLAUDE_ORDER_SLACK_MS).toISOString();
209
+ // From the end; the first entry met per message id is its last in file order, the one the whole-file read kept.
210
+ const scan = scanLinesBackward(path, (line) => {
211
+ let j;
212
+ try {
213
+ j = JSON.parse(line);
214
+ }
215
+ catch {
216
+ return false;
217
+ }
189
218
  const m = j.message;
190
219
  const at = typeof j.timestamp === "string" ? j.timestamp : null;
220
+ if (at && at < stopBefore)
221
+ return true;
191
222
  if (j.type !== "assistant" || !m?.usage || !at || at < since || at > until)
192
- continue;
193
- byMessage.set(m.id ?? `${at}`, m.usage);
194
- }
223
+ return false;
224
+ const key = m.id ?? `${at}`;
225
+ if (!byMessage.has(key))
226
+ byMessage.set(key, m.usage);
227
+ return false;
228
+ }, chunkBytes, maxBytes);
195
229
  const base = { harness: "claude-code", source: "claude-transcript", scope: "session", since, until, tokens: null };
230
+ if (scan.capped)
231
+ return { ...base, reason: `the window's start is beyond the last ${Math.round(maxBytes / 1048576)} MB of the transcript; not counted` };
196
232
  if (!byMessage.size)
197
233
  return { ...base, reason: "no assistant messages in the window" };
198
234
  const t = zero();
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.110";
1
+ export const CLI_VERSION = "0.12.111";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.110",
3
+ "version": "0.12.111",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {