@agentguard-run/burn 0.5.1 → 0.6.0

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,414 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compactReplay = compactReplay;
4
+ exports.collectCompactReplay = collectCompactReplay;
5
+ exports.renderCompactReplay = renderCompactReplay;
6
+ const node_fs_1 = require("node:fs");
7
+ const node_readline_1 = require("node:readline");
8
+ const node_path_1 = require("node:path");
9
+ const node_os_1 = require("node:os");
10
+ const version_1 = require("../version");
11
+ const live_1 = require("./live");
12
+ const pricing_1 = require("./pricing");
13
+ const transcript_1 = require("./transcript");
14
+ const compact_settings_1 = require("./compact-settings");
15
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
16
+ const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
17
+ const DAY = 86_400_000;
18
+ const WINDOWS = [600_000, 400_000, 300_000, 200_000];
19
+ /** Claude JSONL files only, including subagents. Symlinks and sidecars are skipped. */
20
+ function transcriptFiles(root) {
21
+ const files = [];
22
+ const walk = (directory, depth) => {
23
+ if (depth > 8)
24
+ return;
25
+ let entries;
26
+ try {
27
+ entries = (0, node_fs_1.readdirSync)(directory, { withFileTypes: true });
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ for (const entry of entries) {
33
+ const path = (0, node_path_1.join)(directory, entry.name);
34
+ if (entry.isDirectory())
35
+ walk(path, depth + 1);
36
+ else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name !== 'skill-injections.jsonl')
37
+ files.push(path);
38
+ }
39
+ };
40
+ walk(root, 0);
41
+ // A parent's provider response owns a copy inherited by its child.
42
+ return files.sort((a, b) => Number((0, node_path_1.dirname)(a).endsWith('subagents')) - Number((0, node_path_1.dirname)(b).endsWith('subagents')) || a.localeCompare(b));
43
+ }
44
+ const timestamp = (value) => {
45
+ const at = typeof value === 'string' ? Date.parse(value) : NaN;
46
+ return Number.isFinite(at) ? at : null;
47
+ };
48
+ /** Retains usage and boundaries only; messages and tool inputs never enter the report. */
49
+ async function readSession(file, from, to, diagnostics, firstObserved) {
50
+ const turns = new Map();
51
+ const invalid = new Set();
52
+ let boundary, clear = false, gap = false, cwd;
53
+ const stream = (0, node_fs_1.createReadStream)(file, { encoding: 'utf8' });
54
+ const lines = (0, node_readline_1.createInterface)({ input: stream, crlfDelay: Infinity });
55
+ let lineNumber = 0;
56
+ try {
57
+ for await (const line of lines) {
58
+ lineNumber++;
59
+ if (!line.trim())
60
+ continue;
61
+ let raw;
62
+ try {
63
+ raw = object(JSON.parse(line));
64
+ }
65
+ catch {
66
+ diagnostics.malformedLines++;
67
+ gap = true;
68
+ continue;
69
+ }
70
+ const at = timestamp(raw.timestamp);
71
+ const message = object(raw.message);
72
+ const nativeId = message.id ?? raw.uuid;
73
+ const id = (0, transcript_1.providerResponseIdentity)('claude', nativeId ?? [file, lineNumber]);
74
+ // Fork copies may rewrite timestamps. Remember original response dates
75
+ // before filtering, without keeping any out-of-range message or usage.
76
+ if (raw.type === 'assistant' && nativeId !== undefined && at !== null)
77
+ firstObserved.set(id, Math.min(firstObserved.get(id) ?? at, at));
78
+ if (at !== null && (at < from || at > to))
79
+ continue;
80
+ if (raw.type === 'system' && raw.subtype === 'compact_boundary') {
81
+ const metadata = object(raw.compactMetadata);
82
+ if (boundary)
83
+ gap = true;
84
+ boundary = { pre: count(metadata.preTokens) ? metadata.preTokens : null,
85
+ trigger: metadata.trigger === 'auto' || metadata.trigger === 'manual' ? metadata.trigger : 'unknown', at };
86
+ if (at === null)
87
+ diagnostics.missingTimestamps++;
88
+ continue;
89
+ }
90
+ if (raw.type === 'user') {
91
+ const content = message.content;
92
+ const text = typeof content === 'string' ? content : Array.isArray(content) ? content.map(item => object(item).text).filter(item => typeof item === 'string').join('\n') : '';
93
+ if (text.includes('<command-name>/clear</command-name>'))
94
+ clear = true;
95
+ continue;
96
+ }
97
+ if (raw.type !== 'assistant' || message.model === '<synthetic>')
98
+ continue;
99
+ if (at === null) {
100
+ diagnostics.missingTimestamps++;
101
+ gap = true;
102
+ continue;
103
+ }
104
+ if (!cwd && typeof raw.cwd === 'string')
105
+ cwd = raw.cwd;
106
+ const usage = object(message.usage);
107
+ // A missing category is unknown, not zero. Streaming snapshots are allowed
108
+ // to complete later, but an unresolved response makes its replay incomplete.
109
+ if (!['input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens', 'output_tokens'].every(key => count(usage[key]))) {
110
+ if (!turns.has(id))
111
+ invalid.add(id);
112
+ continue;
113
+ }
114
+ invalid.delete(id);
115
+ const input = usage.input_tokens, read = usage.cache_read_input_tokens;
116
+ const write = usage.cache_creation_input_tokens, output = usage.output_tokens;
117
+ if (!Number.isSafeInteger(input + read + write + output)) {
118
+ invalid.add(id);
119
+ continue;
120
+ }
121
+ if (input + read + write + output === 0)
122
+ continue;
123
+ const split = object(usage.cache_creation);
124
+ const five = split.ephemeral_5m_input_tokens, hour = split.ephemeral_1h_input_tokens;
125
+ const knownSplit = count(five) && count(hour) && five + hour === write;
126
+ const ttl = usage.cache_ttl_seconds ?? raw.cache_ttl_seconds ?? message.cache_ttl_seconds;
127
+ const turn = {
128
+ id, sessionId: (0, node_path_1.basename)(file, '.jsonl'), host: 'claude', at,
129
+ ...(typeof message.model === 'string' && /^[\w.:[\]/-]{1,128}$/.test(message.model) ? { model: message.model } : {}),
130
+ inputTokens: input, cacheReadTokens: read, cacheWriteTokens: write, outputTokens: output, contextTokens: input + read + write,
131
+ ...(knownSplit ? { cacheWrite5mTokens: five, cacheWrite1hTokens: hour } : {}),
132
+ ...(ttl === 300 || ttl === 3600 ? { cacheTtlSeconds: ttl } : {}),
133
+ signals: { afterCompaction: Boolean(boundary), firstSpawnedTurn: false }, explicitAttribution: [], uncertainties: [],
134
+ };
135
+ const previous = turns.get(id);
136
+ if (previous) {
137
+ diagnostics.duplicateResponses++;
138
+ previous.usage = (0, transcript_1.deduplicateTurns)([previous.usage, turn])[0];
139
+ }
140
+ else {
141
+ turns.set(id, { usage: turn, ...(boundary ? { boundary } : {}), ...(clear ? { clear } : {}), ...(gap ? { gap } : {}) });
142
+ boundary = undefined;
143
+ clear = false;
144
+ gap = false;
145
+ }
146
+ }
147
+ }
148
+ finally {
149
+ lines.close();
150
+ stream.destroy();
151
+ }
152
+ return { turns: [...turns.values()], cwd, incomplete: invalid.size + (gap ? 1 : 0) + (boundary ? 1 : 0) };
153
+ }
154
+ const totalTokens = (turn) => turn.contextTokens + turn.outputTokens;
155
+ const plus = (a, b) => a && b ? { min: a.min + b.min, max: a.max + b.max } : null;
156
+ const zero = () => ({ min: 0, max: 0 });
157
+ const median = (values) => {
158
+ const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
159
+ return sorted.length % 2 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
160
+ };
161
+ const sampleKey = (session, model) => `${session.subagent ? 'child' : 'main'}:${model ?? 'unknown'}`;
162
+ const measuredReset = (frame) => Boolean(frame.boundary && frame.boundary.pre !== null
163
+ && frame.usage.contextTokens > 0 && frame.usage.contextTokens < frame.boundary.pre);
164
+ /** Keep fresh input, then cache writes, then reads when a shorter context fits.
165
+ * A new reset writes the new cache prefix. TTL uncertainty stays a price range. */
166
+ function resized(turn, context, reset) {
167
+ const inputTokens = Math.min(turn.inputTokens, context);
168
+ const cacheWriteTokens = reset ? context - inputTokens : Math.min(turn.cacheWriteTokens, context - inputTokens);
169
+ const cacheReadTokens = context - inputTokens - cacheWriteTokens;
170
+ const result = { ...turn, contextTokens: context, inputTokens, cacheWriteTokens, cacheReadTokens };
171
+ delete result.cacheWrite5mTokens;
172
+ delete result.cacheWrite1hTokens;
173
+ if (turn.cacheWriteTokens > 0 && turn.cacheWrite5mTokens !== undefined && turn.cacheWrite1hTokens !== undefined) {
174
+ result.cacheWrite5mTokens = Math.round(cacheWriteTokens * turn.cacheWrite5mTokens / turn.cacheWriteTokens);
175
+ result.cacheWrite1hTokens = cacheWriteTokens - result.cacheWrite5mTokens;
176
+ }
177
+ return result;
178
+ }
179
+ function simulate(session, window, pool, rates) {
180
+ const result = { tokens: 0, usd: zero(), compactions: 0, unavailable: [] };
181
+ if (session.incomplete || session.turns.some(turn => turn.gap))
182
+ result.unavailable.push('Missing or malformed usage interrupts a session.');
183
+ const local = new Map();
184
+ for (const frame of session.turns)
185
+ if (measuredReset(frame)) {
186
+ const key = sampleKey(session, frame.usage.model);
187
+ local.set(key, [...local.get(key) ?? [], frame.usage.contextTokens]);
188
+ }
189
+ const recordedCompactions = session.turns.filter(frame => frame.boundary).length;
190
+ const events = [];
191
+ let context = 0, previous;
192
+ const maxima = new Map();
193
+ for (const frame of session.turns)
194
+ maxima.set(frame.usage.model ?? 'unknown', Math.max(maxima.get(frame.usage.model ?? 'unknown') ?? 0, frame.usage.contextTokens, frame.boundary?.pre ?? 0));
195
+ const actualByModel = new Map();
196
+ for (const frame of session.turns) {
197
+ const turn = frame.usage, boundary = frame.boundary;
198
+ let actual = actualByModel.get(turn.model ?? 'unknown');
199
+ if (!actual) {
200
+ actual = (0, compact_settings_1.resolveCompactWindow)(turn.model, session.settings, maxima.get(turn.model ?? 'unknown'));
201
+ actualByModel.set(turn.model ?? 'unknown', actual);
202
+ }
203
+ const threshold = window === null ? actual.tokens : Math.min(window, actual.modelContextTokens);
204
+ let reset = false;
205
+ if (frame.clear || boundary?.trigger === 'manual') {
206
+ // The setting cannot remove the person's explicit reset.
207
+ context = turn.contextTokens;
208
+ if (boundary) {
209
+ result.compactions++;
210
+ reset = true;
211
+ }
212
+ }
213
+ else {
214
+ if (boundary && boundary.pre === null)
215
+ result.unavailable.push('A compaction has no recorded preTokens measurement.');
216
+ const observed = boundary?.pre ?? turn.contextTokens;
217
+ context = previous ? Math.max(0, context + observed - previous.contextTokens) : observed;
218
+ if (actual.enabled && context >= threshold) {
219
+ const key = sampleKey(session, turn.model), samples = local.get(key) ?? pool.get(key);
220
+ if (!samples?.length)
221
+ result.unavailable.push('No measured post-compaction size for a window crossing.');
222
+ else {
223
+ const post = median(samples);
224
+ if (post >= threshold)
225
+ result.unavailable.push('Measured post-compaction context does not fit this window.');
226
+ else {
227
+ events.push({ turn, pre: context, post });
228
+ context = post;
229
+ result.compactions++;
230
+ reset = true;
231
+ }
232
+ }
233
+ }
234
+ }
235
+ const usage = resized(turn, context, reset);
236
+ result.tokens += totalTokens(usage);
237
+ result.usd = plus(result.usd, (0, pricing_1.priceTurn)(usage, rates).usd);
238
+ previous = turn;
239
+ }
240
+ // Recorded usage does not reliably identify the summary API requests. Credit
241
+ // none when fewer occur. For extra ones, charge a full uncached read plus the
242
+ // measured post-reset context as summary output: a conservative estimate,
243
+ // deliberately not a claim that summary output is recorded in the transcript.
244
+ const extra = Math.max(0, result.compactions - recordedCompactions);
245
+ for (const event of extra ? events.slice(-extra) : []) {
246
+ const summary = { ...event.turn, contextTokens: event.pre, inputTokens: event.pre,
247
+ cacheReadTokens: 0, cacheWriteTokens: 0, cacheWrite5mTokens: 0, cacheWrite1hTokens: 0, outputTokens: event.post };
248
+ result.tokens += totalTokens(summary);
249
+ result.usd = plus(result.usd, (0, pricing_1.priceTurn)(summary, rates).usd);
250
+ }
251
+ return result;
252
+ }
253
+ /** Pure numerical replay. No observed reset is forced into the automatic backtest. */
254
+ function compactReplay(sessions, options) {
255
+ const { days, now } = options, rates = options.rates ?? {};
256
+ const diagnostics = options.diagnostics ?? { unreadableFiles: 0, incompleteResponses: 0, duplicateResponses: 0, missingTimestamps: 0, malformedLines: 0 };
257
+ const pool = new Map(), settings = new Map();
258
+ let recordedTokens = 0, recordedUsd = zero(), recordedCompactions = 0, responses = 0;
259
+ for (const session of sessions) {
260
+ const maxima = new Map();
261
+ for (const frame of session.turns)
262
+ maxima.set(frame.usage.model ?? 'unknown', Math.max(maxima.get(frame.usage.model ?? 'unknown') ?? 0, frame.usage.contextTokens, frame.boundary?.pre ?? 0));
263
+ const models = new Set();
264
+ for (const frame of session.turns) {
265
+ const turn = frame.usage;
266
+ recordedTokens += totalTokens(turn);
267
+ recordedUsd = plus(recordedUsd, (0, pricing_1.priceTurn)(turn, rates).usd);
268
+ responses++;
269
+ if (!models.has(turn.model ?? 'unknown')) {
270
+ const actual = { ...(0, compact_settings_1.resolveCompactWindow)(turn.model, session.settings, maxima.get(turn.model ?? 'unknown')), model: turn.model ?? 'unknown' };
271
+ settings.set(JSON.stringify(actual), actual);
272
+ models.add(turn.model ?? 'unknown');
273
+ }
274
+ if (frame.boundary) {
275
+ recordedCompactions++;
276
+ const key = sampleKey(session, turn.model);
277
+ if (measuredReset(frame))
278
+ pool.set(key, [...pool.get(key) ?? [], turn.contextTokens]);
279
+ }
280
+ }
281
+ }
282
+ const values = [...settings.values()], actualWindows = [...new Set(values.map(value => value.tokens))];
283
+ const baselineWindow = actualWindows.length === 1 ? actualWindows[0] : null;
284
+ const windowLabel = (window) => window === 1_000_000 ? '1M' : `${window / 1000}K`;
285
+ const targets = [null, ...WINDOWS.filter(window => window !== baselineWindow)];
286
+ const windows = targets.map(window => {
287
+ let tokens = 0, usd = zero(), compactions = 0;
288
+ const unavailable = new Set();
289
+ for (const session of sessions) {
290
+ const result = simulate(session, window, pool, rates);
291
+ tokens += result.tokens;
292
+ usd = plus(usd, result.usd);
293
+ compactions += result.compactions;
294
+ result.unavailable.forEach(reason => unavailable.add(reason));
295
+ }
296
+ if (!responses)
297
+ unavailable.add('No complete Claude Code usage in this date range.');
298
+ return { window: window ?? baselineWindow, label: window === null ? `${baselineWindow ? windowLabel(baselineWindow) : 'Mixed'} current` : windowLabel(window), current: window === null,
299
+ tokens: unavailable.size ? null : tokens, usd: unavailable.size ? null : usd, compactions: unavailable.size ? null : compactions,
300
+ extraCompactions: null, tokensSaved: null, usdSaved: null, tokenChangePercent: null, usdChangePercent: null, unavailable: [...unavailable] };
301
+ });
302
+ const baseline = windows[0];
303
+ for (const row of windows) {
304
+ if (row.tokens !== null && baseline.tokens !== null) {
305
+ row.tokensSaved = baseline.tokens - row.tokens;
306
+ row.tokenChangePercent = baseline.tokens ? (row.tokens - baseline.tokens) / baseline.tokens * 100 : 0;
307
+ }
308
+ if (row.compactions !== null && baseline.compactions !== null)
309
+ row.extraCompactions = row.compactions - baseline.compactions;
310
+ if (row.usd && baseline.usd) {
311
+ row.usdSaved = row.current ? zero() : { min: baseline.usd.min - row.usd.max, max: baseline.usd.max - row.usd.min };
312
+ const base = (baseline.usd.min + baseline.usd.max) / 2, next = (row.usd.min + row.usd.max) / 2;
313
+ row.usdChangePercent = base ? (next - base) / base * 100 : null;
314
+ }
315
+ }
316
+ const errorTokens = baseline.tokens === null ? null : baseline.tokens - recordedTokens;
317
+ const errorPercent = errorTokens === null || !recordedTokens ? null : Math.abs(errorTokens) / recordedTokens * 100;
318
+ const complete = !diagnostics.unreadableFiles && !diagnostics.incompleteResponses && !diagnostics.missingTimestamps && !diagnostics.malformedLines && baseline.tokens !== null;
319
+ const unreliable = errorPercent !== null && errorPercent > 10;
320
+ const warnings = [...new Set(sessions.flatMap(session => session.settings.warnings))];
321
+ const candidates = windows.filter(row => !row.current && row.window !== null
322
+ && row.window >= compact_settings_1.MIN_COMPACT_WINDOW && row.window <= compact_settings_1.MAX_COMPACT_WINDOW
323
+ && values.every(value => value.commandCanApply && row.window < value.tokens)
324
+ && row.extraCompactions !== null && row.extraCompactions < 2 * recordedCompactions
325
+ && (row.tokensSaved ?? 0) > 0 && (row.usdSaved?.min ?? 0) > 0);
326
+ // Choose the smallest qualifying window, with a strict limit on extra resets.
327
+ candidates.sort((a, b) => a.window - b.window);
328
+ const pick = !unreliable && complete && !warnings.length ? candidates[0] : undefined;
329
+ const suggestion = pick ? { window: pick.window, command: `/autocompact ${pick.window / 1000}k` } : null;
330
+ const band = errorPercent === null ? 'unavailable' : `${errorPercent.toFixed(1)}%`;
331
+ const caveat = `Caveat: backtest error band ${band} against recorded tokens at the current window${unreliable ? '; replay is unreliable for this machine' : ''}${!complete ? '; incomplete evidence, no recommendation' : ''}. This is measured replay error, not a statistical confidence interval; task quality and future output can change.`;
332
+ const notes = [
333
+ 'Savings compare each simulation with the current-window replay. Tokens include input, cache reads, cache writes and output.',
334
+ `The suggestion is the smallest tested window within 100K to 1M with positive savings and extra compactions strictly below twice the recorded current count (${recordedCompactions}). The full table lets you choose.`,
335
+ 'Post-compaction sizes use the median measured next-request context, first in that transcript, otherwise from the same model and main or sub-agent role in this date range.',
336
+ 'Extra summaries conservatively cost a full uncached context read plus the measured reset size as output. Fewer summaries receive no credit. New resets rewrite the cache; ordinary output stays fixed.',
337
+ 'Current saved settings are applied to this history. Past launch flags, remote managed policy, host safety buffers and changes to settings during a session are not reconstructed. Partial sessions start at their first recorded context in the date range.',
338
+ ...(values.some(value => value.assumed) ? ['The tuned default is not recorded as a setting; the model window is assumed for rows without an explicit value.'] : []),
339
+ ...(values.some(value => !value.commandCanApply) ? ['Automatic compaction is disabled or an override prevents the saved slash command from applying; no apply command is suggested.'] : []),
340
+ ...warnings,
341
+ ...[...new Set(windows.flatMap(row => row.unavailable))],
342
+ ];
343
+ return { version: version_1.BURN_VERSION, days, from: new Date(now - days * DAY).toISOString(), to: new Date(now).toISOString(), basis: 'API list equivalent',
344
+ sessions: sessions.filter(session => !session.subagent).length, subagentTranscripts: sessions.filter(session => session.subagent).length,
345
+ responses, measuredCompactions: [...pool.values()].reduce((sum, sizes) => sum + sizes.length, 0),
346
+ recorded: { tokens: recordedTokens, usd: recordedUsd, compactions: recordedCompactions }, settings: values, windows,
347
+ backtest: { replayTokens: baseline.tokens, recordedTokens, errorTokens, errorPercent, unreliable, complete }, suggestion, diagnostics, caveat, notes, settingSource: compact_settings_1.COMPACT_SETTING_SOURCE };
348
+ }
349
+ async function collectCompactReplay(options = {}) {
350
+ const days = options.days ?? 7, now = options.now ?? Date.now();
351
+ if (!Number.isSafeInteger(days) || days < 1 || days > 3650)
352
+ throw new Error('Days must be a whole number from 1 to 3650.');
353
+ if (!Number.isFinite(now) || now - days * DAY < 0)
354
+ throw new Error('Invalid replay date range.');
355
+ const env = options.env ?? process.env;
356
+ const configDir = options.configDir ?? (env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude'));
357
+ const diagnostics = { unreadableFiles: 0, incompleteResponses: 0, duplicateResponses: 0, missingTimestamps: 0, malformedLines: 0 };
358
+ const sessions = [], ownership = new Map();
359
+ const firstObserved = new Map();
360
+ const settingsCache = new Map();
361
+ for (const file of transcriptFiles((0, node_path_1.join)(configDir, 'projects'))) {
362
+ let parsed;
363
+ try {
364
+ parsed = await readSession(file, now - days * DAY, now, diagnostics, firstObserved);
365
+ }
366
+ catch {
367
+ diagnostics.unreadableFiles++;
368
+ continue;
369
+ }
370
+ diagnostics.incompleteResponses += parsed.incomplete;
371
+ const turns = parsed.turns.filter(frame => {
372
+ const previous = ownership.get(frame.usage.id);
373
+ if (!previous) {
374
+ ownership.set(frame.usage.id, frame);
375
+ return true;
376
+ }
377
+ previous.usage = (0, transcript_1.deduplicateTurns)([previous.usage, frame.usage])[0];
378
+ diagnostics.duplicateResponses++;
379
+ return false;
380
+ });
381
+ if (!turns.length && !parsed.incomplete)
382
+ continue;
383
+ const cwd = parsed.cwd ?? options.cwd ?? process.cwd();
384
+ let settings = options.settings ?? settingsCache.get(cwd);
385
+ if (!settings) {
386
+ settings = (0, compact_settings_1.readCompactSettings)({ configDir, cwd, env });
387
+ settingsCache.set(cwd, settings);
388
+ }
389
+ sessions.push({ id: (0, node_path_1.basename)(file, '.jsonl'), subagent: (0, node_path_1.dirname)(file).endsWith('subagents') || (0, node_path_1.basename)(file).startsWith('agent-'), turns, settings, incomplete: parsed.incomplete });
390
+ }
391
+ for (const session of sessions)
392
+ session.turns = session.turns.filter(frame => (firstObserved.get(frame.usage.id) ?? now) >= now - days * DAY)
393
+ .sort((a, b) => a.usage.at - b.usage.at);
394
+ return compactReplay(sessions.filter(session => session.turns.length || session.incomplete), { days, now, rates: options.rates, diagnostics });
395
+ }
396
+ function renderCompactReplay(report) {
397
+ const n = (value) => value === null ? 'unavailable' : value.toLocaleString('en-US');
398
+ const percent = (value) => value === null ? 'n/a' : `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
399
+ const rows = report.windows.map(row => [row.label, n(row.tokensSaved), (0, live_1.dollars)(row.usdSaved), n(row.extraCompactions), percent(row.tokenChangePercent)]);
400
+ const header = ['Window', 'Tokens saved', 'USD saved', 'Extra compactions', 'Token change'];
401
+ const widths = header.map((label, index) => Math.max(label.length, ...rows.map(row => row[index].length)));
402
+ const table = [header, ...rows].map(row => row.map((cell, index) => cell.padEnd(widths[index])).join(' ').trimEnd()).join('\n');
403
+ return [
404
+ `Burn ${version_1.BURN_VERSION} | AgentGuard compact-replay: last ${report.days} days`,
405
+ `${report.sessions} session${report.sessions === 1 ? '' : 's'}, ${report.subagentTranscripts} sub-agent transcripts, ${report.responses} responses; ${report.measuredCompactions} measured compactions.`,
406
+ `Recorded: ${n(report.recorded.tokens)} tokens, ${(0, live_1.dollars)(report.recorded.usd)} API list equivalent. All dollars below are API list equivalent, not a bill.`,
407
+ '', table, report.caveat,
408
+ `Backtest: ${n(report.backtest.replayTokens)} replay tokens versus ${n(report.backtest.recordedTokens)} recorded; difference ${n(report.backtest.errorTokens)} tokens.`,
409
+ ...report.settings.map(value => `Current ${value.model}: ${n(value.tokens)} tokens (${value.source}${value.assumed ? ', assumed' : ''}).`),
410
+ '', ...report.notes,
411
+ report.suggestion ? `To try the suggested window, type this in Claude Code for each model you want to change: ${report.suggestion.command}`
412
+ : 'No smaller window is supported by this replay. Check your current window in Claude Code: /autocompact',
413
+ ].join('\n');
414
+ }
@@ -0,0 +1,30 @@
1
+ export declare const COMPACT_SETTING_SOURCE = "https://code.claude.com/docs/en/model-config#set-the-auto-compact-window";
2
+ export declare const MIN_COMPACT_WINDOW = 100000;
3
+ export declare const MAX_COMPACT_WINDOW = 1000000;
4
+ type RecordValue = Record<string, unknown>;
5
+ export interface CompactScope {
6
+ name: string;
7
+ value: RecordValue;
8
+ }
9
+ export interface CompactSettings {
10
+ scopes: CompactScope[];
11
+ env: NodeJS.ProcessEnv;
12
+ warnings: string[];
13
+ }
14
+ export interface CompactWindow {
15
+ tokens: number;
16
+ modelContextTokens: number;
17
+ source: string;
18
+ assumed: boolean;
19
+ enabled: boolean;
20
+ commandCanApply: boolean;
21
+ }
22
+ /** Reads settings only. Never runs Claude Code, a credential helper, or a shell. */
23
+ export declare function readCompactSettings(options?: {
24
+ configDir?: string;
25
+ cwd?: string;
26
+ env?: NodeJS.ProcessEnv;
27
+ managedFile?: string | null;
28
+ }): CompactSettings;
29
+ export declare function resolveCompactWindow(model: string | undefined, settings: CompactSettings, observedMaximum?: number): CompactWindow;
30
+ export {};
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_COMPACT_WINDOW = exports.MIN_COMPACT_WINDOW = exports.COMPACT_SETTING_SOURCE = void 0;
4
+ exports.readCompactSettings = readCompactSettings;
5
+ exports.resolveCompactWindow = resolveCompactWindow;
6
+ const node_fs_1 = require("node:fs");
7
+ const node_os_1 = require("node:os");
8
+ const node_path_1 = require("node:path");
9
+ // Verified against Claude Code's own documentation on 2026-10-09:
10
+ // https://code.claude.com/docs/en/model-config#set-the-auto-compact-window
11
+ // https://code.claude.com/docs/en/settings-reference#modelsettings
12
+ // https://code.claude.com/docs/en/settings-reference#autocompactwindow
13
+ exports.COMPACT_SETTING_SOURCE = 'https://code.claude.com/docs/en/model-config#set-the-auto-compact-window';
14
+ exports.MIN_COMPACT_WINDOW = 100_000;
15
+ exports.MAX_COMPACT_WINDOW = 1_000_000;
16
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
17
+ /** Reads settings only. Never runs Claude Code, a credential helper, or a shell. */
18
+ function readCompactSettings(options = {}) {
19
+ const env = options.env ?? process.env;
20
+ const configDir = options.configDir ?? (env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude'));
21
+ const cwd = options.cwd ?? process.cwd();
22
+ const managedFile = options.managedFile === undefined
23
+ ? process.platform === 'darwin' ? '/Library/Application Support/ClaudeCode/managed-settings.json'
24
+ : process.platform === 'win32' ? (0, node_path_1.join)(env.ProgramFiles ?? 'C:\\Program Files', 'ClaudeCode', 'managed-settings.json')
25
+ : '/etc/claude-code/managed-settings.json'
26
+ : options.managedFile;
27
+ const scopes = [], warnings = [];
28
+ const files = [
29
+ ['user', (0, node_path_1.join)(configDir, 'settings.json')],
30
+ ['project', (0, node_path_1.join)(cwd, '.claude', 'settings.json')],
31
+ ['local', (0, node_path_1.join)(cwd, '.claude', 'settings.local.json')],
32
+ ...(managedFile ? [['managed', managedFile]] : []),
33
+ ];
34
+ for (const [name, file] of files) {
35
+ try {
36
+ const raw = JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
37
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
38
+ throw new Error('invalid');
39
+ scopes.push({ name, value: object(raw) });
40
+ }
41
+ catch (error) {
42
+ if (error.code !== 'ENOENT')
43
+ warnings.push(`Could not read ${name} compaction settings.`);
44
+ }
45
+ }
46
+ return { scopes, env, warnings };
47
+ }
48
+ /** Canonical names, dated IDs and provider spellings use the same saved row. */
49
+ function canonicalModel(model) {
50
+ return model.match(/claude-(?:opus|sonnet|haiku|fable)-\d+(?:-\d{1,2})?(?=$|[^0-9]|\[)/i)?.[0].toLowerCase() ?? model;
51
+ }
52
+ function maximumContext(model, settings, observedMaximum) {
53
+ if (on(settings.env.CLAUDE_CODE_DISABLE_1M_CONTEXT))
54
+ return 200_000;
55
+ const canonical = canonicalModel(model);
56
+ if (/^claude-(?:fable-|(?:opus|sonnet)-5|haiku-5-5)/.test(canonical) || /^claude-opus-4-[789]$/.test(canonical))
57
+ return exports.MAX_COMPACT_WINDOW;
58
+ // An extended-context session's recorded model can omit the display suffix.
59
+ const selected = settings.scopes.map(scope => scope.value.model).filter(value => typeof value === 'string').at(-1);
60
+ if (model.includes('[1m]') || (typeof selected === 'string' && selected.includes('[1m]')) || observedMaximum > 200_000)
61
+ return exports.MAX_COMPACT_WINDOW;
62
+ if (/^claude-(?:opus|sonnet)-4-6$/.test(canonical) || /^claude-haiku-4-5$/.test(canonical))
63
+ return 200_000;
64
+ return exports.MAX_COMPACT_WINDOW;
65
+ }
66
+ function resolveCompactWindow(model, settings, observedMaximum = 0) {
67
+ // Settings env blocks replace inherited variables in ordinary local sessions.
68
+ // https://code.claude.com/docs/en/env-vars#precedence
69
+ const environment = { ...settings.env };
70
+ for (const scope of settings.scopes)
71
+ for (const [key, value] of Object.entries(object(scope.value.env))) {
72
+ if (typeof value === 'string')
73
+ environment[key] = value;
74
+ }
75
+ const maximum = maximumContext(model ?? '', { ...settings, env: environment }, observedMaximum);
76
+ let tokens = maximum, source = 'model default (assumed)', assumed = true, enabled = true, commandCanApply = true;
77
+ const canonical = canonicalModel(model ?? '');
78
+ for (const scope of settings.scopes) {
79
+ if (typeof scope.value.autoCompactEnabled === 'boolean')
80
+ enabled = scope.value.autoCompactEnabled;
81
+ const models = object(scope.value.modelSettings);
82
+ const row = object(models[model ?? ''] ?? models[canonical]);
83
+ const value = row.autoCompactWindow ?? scope.value.autoCompactWindow;
84
+ if (value === undefined)
85
+ continue;
86
+ const perModel = row.autoCompactWindow !== undefined;
87
+ if (value === 'auto' && perModel) {
88
+ tokens = maximum;
89
+ assumed = true;
90
+ }
91
+ else if (typeof value === 'number' && Number.isInteger(value) && value >= exports.MIN_COMPACT_WINDOW && value <= exports.MAX_COMPACT_WINDOW) {
92
+ tokens = Math.min(value, maximum);
93
+ assumed = false;
94
+ }
95
+ else {
96
+ settings.warnings.push(`Invalid ${scope.name} autoCompactWindow; actual window is unknown.`);
97
+ continue;
98
+ }
99
+ source = `${scope.name} ${perModel ? 'modelSettings' : 'autoCompactWindow'}`;
100
+ commandCanApply = scope.name === 'user';
101
+ }
102
+ const env = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
103
+ if (env !== undefined && env !== '') {
104
+ // Claude Code parses an integer and clamps it. In particular, 500k is 500,
105
+ // then clamps to 100K; it does not mean 500,000 in this environment variable.
106
+ const parsed = Number.parseInt(env, 10);
107
+ if (Number.isFinite(parsed)) {
108
+ tokens = Math.min(maximum, Math.max(exports.MIN_COMPACT_WINDOW, Math.min(exports.MAX_COMPACT_WINDOW, parsed)));
109
+ source = 'CLAUDE_CODE_AUTO_COMPACT_WINDOW';
110
+ assumed = false;
111
+ commandCanApply = false;
112
+ }
113
+ else
114
+ settings.warnings.push('Invalid compaction environment override; actual window is unknown.');
115
+ }
116
+ if (on(environment.DISABLE_AUTO_COMPACT) || on(environment.DISABLE_COMPACT))
117
+ enabled = false;
118
+ if (environment.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE)
119
+ settings.warnings.push('A percentage override can move the actual trigger earlier than the replay window.');
120
+ return { tokens, modelContextTokens: maximum, source, assumed, enabled, commandCanApply: commandCanApply && enabled };
121
+ }
122
+ const on = (value) => /^(1|true|yes|on)$/i.test(value ?? '');
@@ -12,6 +12,7 @@
12
12
  import { type CompareMetric, type InsightBucket, type InsightHost, type InsightObservations, type SessionCommits } from './types';
13
13
  export type WhyLang = 'en' | 'es' | 'pt';
14
14
  export { STATUS_TEXT } from './status-text';
15
+ export { SIMPLE_TEXT } from './simple-text';
15
16
  /**
16
17
  * The language of a flag value or locale: the part before '_', '-', '.' or '@',
17
18
  * in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
@@ -229,3 +230,21 @@ export interface CalendarText {
229
230
  };
230
231
  }
231
232
  export declare const CALENDAR_TEXT: Readonly<Record<WhyLang, CalendarText>>;
233
+ export interface WeekText {
234
+ labels: Record<import('./week').WeekTopCause, string>;
235
+ fixes: Record<import('./week').WeekTopCause, string>;
236
+ title: (start: string, end: string) => string;
237
+ summary: (tokens: string, usd: string | null) => string;
238
+ spent: (usd: string) => string;
239
+ shares: (useful: string, waste: string, unattributed: string, priced: boolean) => string;
240
+ row: (label: string, share: string, usd: string | null, tokens: string) => string;
241
+ wrongModel: (tokens: string, delta: string) => string;
242
+ next: (label: string, fix: string) => string;
243
+ noCause: string;
244
+ tokenBasis: string;
245
+ privacy: string;
246
+ incomplete: string;
247
+ excluded: (forks: string, undated: string) => string;
248
+ saveFailed: string;
249
+ }
250
+ export declare const WEEK_TEXT: Readonly<Record<WhyLang, WeekText>>;