benignswarm 0.12.95 → 0.12.97

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,218 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join, resolve } from "node:path";
6
+ export const TEMPLATE_FAMILIES = ["node-web", "python", "rust", "eda", "mobile-linux", "hardware-bound"];
7
+ const fail = (message) => { throw new Error(message); };
8
+ const record = (v) => !!v && typeof v === "object" && !Array.isArray(v);
9
+ function exactKeys(value, keys, where) {
10
+ for (const key of Object.keys(value))
11
+ if (!keys.includes(key))
12
+ fail(`${where}: unexpected field ${key}`);
13
+ }
14
+ function command(cwd, executable, args) {
15
+ const result = spawnSync(executable, args, { cwd, encoding: "utf8" });
16
+ if (result.error)
17
+ fail(`${executable}: ${result.error.message}`);
18
+ if (result.status !== 0)
19
+ fail(`${executable} failed: ${(result.stderr || result.stdout).trim()}`);
20
+ return result.stdout.trim();
21
+ }
22
+ function validateEntry(templatesDir, family, version) {
23
+ const dir = join(templatesDir, family, version);
24
+ if (lstatSync(dir).isSymbolicLink())
25
+ fail(`${dir}: symbolic links are not allowed`);
26
+ const file = join(dir, "template.json");
27
+ let parsed;
28
+ try {
29
+ parsed = JSON.parse(readFileSync(file, "utf8"));
30
+ }
31
+ catch (e) {
32
+ return fail(`${file}: ${e.message}`);
33
+ }
34
+ if (!record(parsed))
35
+ return fail(`${file}: expected an object`);
36
+ const value = parsed;
37
+ const m = value;
38
+ exactKeys(value, ["schemaVersion", "family", "version", "kind", "description", "platform", "container", "base", "machineLabels", "tools", "probes", "defaultTest", "devcontainer"], file);
39
+ if (m.schemaVersion !== 1 || m.family !== family || m.version !== version || !/^\d+\.\d+\.\d+$/.test(m.version))
40
+ fail(`${file}: schemaVersion, family, or semantic version does not match its catalog path`);
41
+ if (m.kind !== "container" && m.kind !== "host")
42
+ fail(`${file}: kind must be container or host`);
43
+ if (typeof m.description !== "string" || !m.description.trim())
44
+ fail(`${file}: description is required`);
45
+ if (m.platform !== "linux/amd64" && m.platform !== "linux/arm64" && m.platform !== "host")
46
+ fail(`${file}: unsupported platform ${m.platform}`);
47
+ if (!Array.isArray(m.tools) || m.tools.some(t => !record(t) || typeof t.name !== "string" || !t.name || typeof t.version !== "string" || !t.version))
48
+ fail(`${file}: tools need name and version`);
49
+ for (const tool of m.tools)
50
+ exactKeys(tool, ["name", "version"], `${file} tools`);
51
+ if (new Set(m.tools.map(tool => tool.name)).size !== m.tools.length)
52
+ fail(`${file}: tool names must be unique`);
53
+ if (m.tools.some(tool => !/^(?:v)?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(tool.version)))
54
+ fail(`${file}: tool versions must be exact semantic versions`);
55
+ if (!Array.isArray(m.probes) || !m.probes.length || m.probes.some(p => !record(p) || !/^[a-z0-9][a-z0-9-]*$/.test(String(p.name)) || !/^[a-z0-9][a-z0-9._-]*$/.test(String(p.capability)) || typeof p.command !== "string" || !p.command.trim()))
56
+ fail(`${file}: probes need a name, capability and command`);
57
+ for (const probe of m.probes)
58
+ exactKeys(probe, ["name", "capability", "command"], `${file} probes`);
59
+ if (!record(m.defaultTest) || typeof m.defaultTest.command !== "string" || !m.defaultTest.command.trim() || typeof m.defaultTest.setupRequired !== "boolean")
60
+ fail(`${file}: defaultTest needs command and setupRequired`);
61
+ exactKeys(m.defaultTest, ["command", "setupRequired"], `${file} defaultTest`);
62
+ if (!existsSync(join(dir, "README.md")))
63
+ fail(`${dir}: README.md is required`);
64
+ if (m.kind === "container") {
65
+ if (m.platform === "host" || "container" in value)
66
+ fail(`${file}: container entries need a Linux platform and cannot set container`);
67
+ if (!record(m.base) || typeof m.base.image !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9./_-]*:[^@\s]+$/.test(m.base.image) || typeof m.base.digest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(m.base.digest))
68
+ return fail(`${file}: container base must include an image tag and sha256 digest`);
69
+ const base = m.base;
70
+ exactKeys(base, ["image", "digest"], `${file} base`);
71
+ if (/:latest$/i.test(base.image))
72
+ fail(`${file}: floating latest base tags are forbidden even with a digest`);
73
+ const toolVersion = (name) => m.tools.find(tool => tool.name === name)?.version;
74
+ const nodeVersion = toolVersion("Node.js");
75
+ const pythonVersion = toolVersion("Python");
76
+ const rustVersion = toolVersion("rustc");
77
+ const kicadVersion = toolVersion("KiCad");
78
+ if ((m.family === "node-web" || m.family === "mobile-linux") && (!nodeVersion || !base.image.startsWith(`node:${nodeVersion}-`)))
79
+ fail(`${file}: Node.js version must match the pinned base image`);
80
+ if (m.family === "python" && (!pythonVersion || !base.image.startsWith(`python:${pythonVersion}-`)))
81
+ fail(`${file}: Python version must match the pinned base image`);
82
+ if (m.family === "rust" && (!rustVersion || !base.image.startsWith(`rust:${rustVersion}-`)))
83
+ fail(`${file}: rustc version must match the pinned base image`);
84
+ if (m.family === "rust" && toolVersion("Cargo") !== rustVersion)
85
+ fail(`${file}: Cargo version must match rustc and the pinned base image`);
86
+ if (m.family === "eda" && (!kicadVersion || base.image !== `kicad/kicad:${kicadVersion}`))
87
+ fail(`${file}: KiCad version must match the pinned base image`);
88
+ if (m.devcontainer !== "devcontainer.json" || !existsSync(join(dir, "devcontainer.json")))
89
+ fail(`${file}: devcontainer.json is required`);
90
+ if ("machineLabels" in value)
91
+ fail(`${file}: container entries cannot declare machineLabels`);
92
+ const expected = `${base.image}@${base.digest}`;
93
+ const dockerfile = readFileSync(join(dir, "Dockerfile"), "utf8");
94
+ const bases = [...dockerfile.matchAll(/^FROM\s+(\S+)/gim)].map(match => match[1]);
95
+ if (!bases.length || bases.some(image => image !== expected))
96
+ fail(`${dir}/Dockerfile: every FROM must be exactly ${expected}`);
97
+ if (bases.some(image => /:latest@sha256:/i.test(image)))
98
+ fail(`${dir}/Dockerfile: floating latest base tags are forbidden even with a digest`);
99
+ const npmVersion = toolVersion("npm");
100
+ const uvVersion = toolVersion("uv");
101
+ if (npmVersion && !dockerfile.includes(`npm@${npmVersion}`))
102
+ fail(`${file}: npm version must match the pinned install command in Dockerfile`);
103
+ if (uvVersion && !dockerfile.includes(`uv==${uvVersion}`))
104
+ fail(`${file}: uv version must match the pinned install command in Dockerfile`);
105
+ const dc = JSON.parse(readFileSync(join(dir, "devcontainer.json"), "utf8"));
106
+ if (!record(dc.build) || dc.build.dockerfile !== "Dockerfile")
107
+ fail(`${dir}/devcontainer.json: build.dockerfile must be Dockerfile`);
108
+ if (dc.features !== undefined) {
109
+ if (!record(dc.features))
110
+ return fail(`${dir}/devcontainer.json: features must be an object`);
111
+ const features = dc.features;
112
+ for (const feature of Object.keys(features)) {
113
+ if (!/(?:@sha256:[a-f0-9]{64}|:\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.test(feature))
114
+ fail(`${dir}/devcontainer.json: feature ${feature} must use an immutable version or sha256 digest`);
115
+ }
116
+ }
117
+ const files = readdirSync(dir).sort().join(",");
118
+ if (files !== "Dockerfile,README.md,devcontainer.json,template.json")
119
+ fail(`${dir}: container entries must contain only Dockerfile, README.md, devcontainer.json, and template.json`);
120
+ }
121
+ else {
122
+ if (m.platform !== "host" || m.container !== "none")
123
+ fail(`${file}: host entries need platform=host and container=none`);
124
+ if ("base" in value || "devcontainer" in value)
125
+ fail(`${file}: host entries cannot declare a base or devcontainer`);
126
+ if (!Array.isArray(m.machineLabels) || !m.machineLabels.length || m.machineLabels.some(v => typeof v !== "string" || !v) || new Set(m.machineLabels).size !== m.machineLabels.length)
127
+ fail(`${file}: host entries need unique machineLabels`);
128
+ const files = readdirSync(dir).sort().join(",");
129
+ if (files !== "README.md,template.json")
130
+ fail(`${dir}: host entries must contain only README.md and template.json`);
131
+ }
132
+ for (const name of readdirSync(dir))
133
+ if (lstatSync(join(dir, name)).isSymbolicLink())
134
+ fail(`${dir}/${name}: symbolic links are not allowed`);
135
+ return m;
136
+ }
137
+ export function validateTemplateCatalog(root) {
138
+ const templatesDir = join(resolve(root), "templates");
139
+ if (lstatSync(templatesDir).isSymbolicLink())
140
+ fail(`${templatesDir}: symbolic links are not allowed`);
141
+ const schemaFile = join(templatesDir, "catalog.schema.json");
142
+ const schema = JSON.parse(readFileSync(schemaFile, "utf8"));
143
+ if (schema.$schema !== "https://json-schema.org/draft/2020-12/schema" || !record(schema.properties) || !("schemaVersion" in schema.properties))
144
+ fail(`${schemaFile}: version 1 JSON Schema contract missing`);
145
+ const expectedFiles = [...TEMPLATE_FAMILIES, "catalog.json", "catalog.schema.json"].sort().join(",");
146
+ if (readdirSync(templatesDir).sort().join(",") !== expectedFiles)
147
+ fail(`${templatesDir}: unexpected catalog files; only the index, schema, and six family directories are allowed`);
148
+ for (const name of readdirSync(templatesDir))
149
+ if (lstatSync(join(templatesDir, name)).isSymbolicLink())
150
+ fail(`${templatesDir}/${name}: symbolic links are not allowed`);
151
+ const indexFile = join(templatesDir, "catalog.json");
152
+ const index = JSON.parse(readFileSync(indexFile, "utf8"));
153
+ if (Object.keys(index).some(key => !["schemaVersion", "release", "families"].includes(key)))
154
+ fail(`${indexFile}: unexpected catalog index field`);
155
+ if (index.schemaVersion !== 1 || typeof index.release !== "string" || !/^\d+\.\d+\.\d+$/.test(index.release))
156
+ return fail(`${indexFile}: schemaVersion 1 and a semantic release are required`);
157
+ if (!Array.isArray(index.families) || [...index.families].sort().join(",") !== [...TEMPLATE_FAMILIES].sort().join(","))
158
+ fail(`${indexFile}: families must list each supported family exactly once`);
159
+ const entries = [];
160
+ for (const family of TEMPLATE_FAMILIES) {
161
+ const familyDir = join(templatesDir, family);
162
+ if (lstatSync(familyDir).isSymbolicLink())
163
+ fail(`${familyDir}: symbolic links are not allowed`);
164
+ const versions = readdirSync(familyDir).sort();
165
+ if (!versions.length)
166
+ fail(`${familyDir}: at least one version is required`);
167
+ for (const version of versions)
168
+ entries.push(validateEntry(templatesDir, family, version));
169
+ }
170
+ return { release: index.release, entries };
171
+ }
172
+ export function packTemplateCatalog(root, outputDir, signingKey) {
173
+ const repo = resolve(root);
174
+ const keyPath = resolve(signingKey);
175
+ if (!existsSync(keyPath))
176
+ fail(`signing key not found: ${keyPath}`);
177
+ if (command(repo, "git", ["status", "--porcelain"]))
178
+ fail("refusing to package a dirty source revision; commit all changes and remove untracked files first");
179
+ const { release } = validateTemplateCatalog(repo);
180
+ const sourceRevision = command(repo, "git", ["rev-parse", "HEAD"]);
181
+ const out = resolve(outputDir);
182
+ mkdirSync(out, { recursive: true });
183
+ const archive = join(out, `environment-templates-${release}.tar.gz`);
184
+ const signature = `${archive}.sig`;
185
+ if (existsSync(archive) || existsSync(signature))
186
+ fail(`release already exists; refusing to overwrite ${basename(archive)}`);
187
+ const staging = mkdtempSync(join(tmpdir(), "b9s-template-release-"));
188
+ const stage = join(staging, "release");
189
+ mkdirSync(stage);
190
+ try {
191
+ const committedTar = join(staging, "committed-templates.tar");
192
+ const snapshot = spawnSync("git", ["archive", "--format=tar", sourceRevision, "templates"], { cwd: repo });
193
+ if (snapshot.error)
194
+ fail(`git archive: ${snapshot.error.message}`);
195
+ if (snapshot.status !== 0)
196
+ fail(`git archive failed: ${String(snapshot.stderr ?? "").trim()}`);
197
+ writeFileSync(committedTar, snapshot.stdout, { flag: "wx" });
198
+ command(repo, "tar", ["-xf", committedTar, "-C", stage]);
199
+ writeFileSync(join(stage, "CATALOG-RELEASE.json"), `${JSON.stringify({ schemaVersion: 1, release, sourceRevision }, null, 2)}\n`, { flag: "wx" });
200
+ const tempArchive = join(staging, "release.tar.gz");
201
+ const tempSignature = join(staging, "release.tar.gz.sig");
202
+ command(repo, "tar", ["-czf", tempArchive, "-C", stage, "templates", "CATALOG-RELEASE.json"]);
203
+ command(repo, "openssl", ["dgst", "-sha256", "-sign", keyPath, "-out", tempSignature, tempArchive]);
204
+ const sha256 = createHash("sha256").update(readFileSync(tempArchive)).digest("hex");
205
+ copyFileSync(tempArchive, archive, constants.COPYFILE_EXCL);
206
+ try {
207
+ copyFileSync(tempSignature, signature, constants.COPYFILE_EXCL);
208
+ }
209
+ catch (error) {
210
+ rmSync(archive, { force: true });
211
+ throw error;
212
+ }
213
+ return { archive, signature, sha256, sourceRevision };
214
+ }
215
+ finally {
216
+ rmSync(staging, { recursive: true, force: true });
217
+ }
218
+ }
@@ -0,0 +1,17 @@
1
+ const BYTES_PER_WORKER = 2 * 1024 ** 3;
2
+ const DEFAULT_WORKER_CAP = 8;
3
+ export function calculateVitestMaxWorkers(input, override) {
4
+ if (override !== undefined && override !== "") {
5
+ const parsed = Number(override);
6
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
7
+ throw new Error("BSCHAT_TEST_MAX_WORKERS must be a positive integer");
8
+ }
9
+ return parsed;
10
+ }
11
+ const availableCores = Number.isFinite(input.availableCores) ? Math.max(1, Math.floor(input.availableCores)) : 1;
12
+ const load = Number.isFinite(input.loadAverage) ? Math.max(0, input.loadAverage) : 0;
13
+ const idleCores = Math.max(1, availableCores - Math.ceil(load));
14
+ const freeMemory = Number.isFinite(input.freeMemoryBytes) ? Math.max(0, input.freeMemoryBytes) : 0;
15
+ const memoryWorkers = Math.max(1, Math.floor(freeMemory / BYTES_PER_WORKER));
16
+ return Math.max(1, Math.min(idleCores, memoryWorkers, DEFAULT_WORKER_CAP));
17
+ }
package/dist/turn.js CHANGED
@@ -1,5 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
+ export const DEFAULT_TURN_COALESCE_SECONDS = 180;
4
+ export const MAX_TURN_COALESCE_SECONDS = 3600;
5
+ /** Whether direct pending work is still inside its per-session coalescing window. */
6
+ export function shouldDeferTurn(input) {
7
+ return input.pending && input.seconds > 0 && !input.operator && !input.urgent && input.now < input.firstPendingAt + input.seconds * 1000;
8
+ }
3
9
  /** Where a Codex session stands, from its rollout: `task_started` opens a turn, `task_complete` or `turn_aborted` closes it. */
4
10
  export function codexTurnPhase(rolloutText) {
5
11
  let open = null;
package/dist/usage.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { claudeTranscript, dshUsage } from "./harnesses.js";
3
3
  import { antigravityUsage } from "./antigravity.js";
4
+ /** Keep hook-only Claude compaction metadata only when it belongs to the exact session selected. */
5
+ export function claudeSessionWithHookMetadata(sessionId, transcript, provider, remembered) {
6
+ const sameSession = remembered?.harness === "claude-code" && remembered.session_id === sessionId;
7
+ return { harness: "claude-code", transcript, session_id: sessionId, provider, ...(sameSession && remembered.compactions?.length ? { compactions: remembered.compactions } : {}) };
8
+ }
4
9
  const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
5
10
  function lines(path) {
6
11
  return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
@@ -12,6 +17,118 @@ function lines(path) {
12
17
  }
13
18
  });
14
19
  }
20
+ const unknownContext = (reason) => ({ pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason });
21
+ const unknownCompactions = (reason) => ({ count: null, reason });
22
+ const positiveInt = (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
23
+ const pct = (tokens, window) => Math.max(0, Math.min(100, tokens / window * 100));
24
+ const epoch = (at) => Date.parse(at);
25
+ /** Current fill is a point-in-time snapshot, not cumulative unit usage. Content is never inspected. */
26
+ export function sessionContext(session, until) {
27
+ if (!session)
28
+ return unknownContext("no harness session is available on this machine");
29
+ if (!(["codex", "claude-code", "antigravity"].includes(session.harness)))
30
+ return unknownContext(session.harness === "dsh" ? "DeepSeek Harness does not expose a confirmed context window in its local session records" : `${session.harness} does not expose context fill in a supported local session format`);
31
+ const transcript = session.harness === "claude-code" && session.session_id
32
+ ? (session.transcript && existsSync(session.transcript) ? session.transcript : claudeTranscript(session.session_id) ?? session.transcript)
33
+ : session.transcript;
34
+ if (!transcript || !existsSync(transcript))
35
+ return unknownContext(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
36
+ const rows = lines(transcript);
37
+ if (session.harness === "codex") {
38
+ let latest;
39
+ for (const row of rows) {
40
+ const p = row.payload;
41
+ const at = typeof row.timestamp === "string" ? row.timestamp : "";
42
+ const tokens = p?.info?.last_token_usage?.total_tokens, window = p?.info?.model_context_window;
43
+ 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)))
44
+ latest = { at, tokens, window };
45
+ }
46
+ if (!latest)
47
+ return unknownContext("no Codex token_count with a model_context_window is available yet");
48
+ return { pct: pct(latest.tokens, latest.window), tokens: latest.tokens, window: latest.window, source: "codex-rollout", measured_at: latest.at, reason: null };
49
+ }
50
+ if (session.harness === "claude-code") {
51
+ let latest;
52
+ for (const row of rows) {
53
+ const msg = row.message;
54
+ const at = typeof row.timestamp === "string" ? row.timestamp : "";
55
+ if (row.type !== "assistant" || !at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until) || !msg?.usage)
56
+ continue;
57
+ const model = msg.model;
58
+ const window = claudeContextWindow(model);
59
+ const usage = msg.usage;
60
+ const tokens = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.output_tokens ?? 0);
61
+ if (window && positiveInt(tokens) && (!latest || epoch(at) > epoch(latest.at)))
62
+ latest = { at, tokens, window };
63
+ }
64
+ if (!latest)
65
+ return unknownContext("no Claude assistant usage for a model with a confirmed context window is available yet");
66
+ return { pct: pct(latest.tokens, latest.window), tokens: latest.tokens, window: latest.window, source: "claude-transcript", measured_at: latest.at, reason: null };
67
+ }
68
+ if (session.harness === "antigravity") {
69
+ let latest;
70
+ for (const row of rows) {
71
+ const at = typeof row.finished_at === "string" ? row.finished_at : "";
72
+ if (!at || !Number.isFinite(epoch(at)) || epoch(at) > epoch(until))
73
+ continue;
74
+ const result = row.result;
75
+ const u = result?.usage;
76
+ 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;
77
+ const window = row.model_context_window ?? row.context_window;
78
+ if (tokens !== null && positiveInt(tokens) && (!latest || at > latest.at))
79
+ latest = { at, tokens, ...(positiveInt(window) ? { window } : {}) };
80
+ }
81
+ if (!latest?.window)
82
+ return unknownContext(latest ? "Antigravity model context window has not been confirmed on a real run" : "no Antigravity per-turn usage record is available yet");
83
+ return { pct: pct(latest.tokens, latest.window), tokens: latest.tokens, window: latest.window, source: "agy-json-turn-records", measured_at: latest.at, reason: null };
84
+ }
85
+ return unknownContext(session.harness === "dsh" ? "DeepSeek Harness does not expose a confirmed context window in its local session records" : `${session.harness} does not expose context fill in a supported local session format`);
86
+ }
87
+ function claudeContextWindow(model) {
88
+ if (!model)
89
+ return null;
90
+ if (/^claude-(?:fable|opus|sonnet)-(?:5|4-6|4-7|4-8)(?:-|$)/.test(model))
91
+ return 1_000_000;
92
+ if (/^claude-(?:opus|sonnet|haiku)-(?:4|3)(?:-|$)/.test(model))
93
+ return 200_000;
94
+ return null;
95
+ }
96
+ /** Compaction deltas are derived from event metadata; the payload/content of messages is ignored. */
97
+ export function sessionCompactions(session, since, until) {
98
+ if (!session)
99
+ return unknownCompactions("no harness session is available on this machine");
100
+ if (session.harness !== "codex" && session.harness !== "claude-code")
101
+ return unknownCompactions(`${session.harness} does not expose compaction events in a supported local session format`);
102
+ const transcript = session.harness === "claude-code" && session.session_id
103
+ ? (session.transcript && existsSync(session.transcript) ? session.transcript : claudeTranscript(session.session_id) ?? session.transcript)
104
+ : session.transcript;
105
+ if (!transcript || !existsSync(transcript))
106
+ return unknownCompactions(`the session file ${transcript || session.session_id || "(unknown)"} is gone`);
107
+ const boundaries = [], hookCompactions = [];
108
+ const sinceAt = epoch(since), untilAt = epoch(until);
109
+ if (!Number.isFinite(sinceAt) || !Number.isFinite(untilAt))
110
+ return unknownCompactions("the unit event time range is invalid");
111
+ for (const row of lines(transcript)) {
112
+ let at;
113
+ if (session.harness === "codex" && row.type === "response_item" && row.payload?.type === "compaction")
114
+ at = typeof row.timestamp === "string" ? row.timestamp : undefined;
115
+ if (session.harness === "claude-code" && row.type === "system" && row.subtype === "compact_boundary")
116
+ at = typeof row.timestamp === "string" ? row.timestamp : undefined;
117
+ const eventAt = at ? epoch(at) : NaN;
118
+ if (Number.isFinite(eventAt) && eventAt >= sinceAt && eventAt < untilAt)
119
+ boundaries.push(eventAt);
120
+ }
121
+ if (session.harness === "claude-code")
122
+ for (const at of session.compactions ?? [])
123
+ if (Number.isFinite(at) && at >= sinceAt && at < untilAt)
124
+ hookCompactions.push(at);
125
+ if (session.harness !== "codex" && session.harness !== "claude-code")
126
+ return unknownCompactions(`${session.harness} does not expose compaction events in a supported local session format`);
127
+ // Claude's hook and transcript can report the same compaction. Deduplicate only across those
128
+ // two sources so two real transcript boundaries close together are still counted separately.
129
+ const unpairedHooks = hookCompactions.filter((hookAt) => !boundaries.some((boundaryAt) => Math.abs(boundaryAt - hookAt) <= 30_000));
130
+ return { count: boundaries.length + unpairedHooks.length, reason: null };
131
+ }
15
132
  /**
16
133
  * Codex rollout: `event_msg` `token_count` events carry running totals, so the window's use is the
17
134
  * last total at or before `until` minus the last total before `since` (zero when the session began
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.95";
1
+ export const CLI_VERSION = "0.12.97";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.95",
3
+ "version": "0.12.97",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {