@agentguard-run/burn 0.3.19 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.20 (2026-09-27)
4
+
5
+ - New `calendar`: tokens per day for every Claude Code and Codex session on this machine, sub-agents included, on one heatmap: a column per week, a row per weekday, five shades from Less to More. With no flag it starts at the oldest recorded day and fits the terminal (80 columns when piped); `calendar --weeks N` shows exactly N weeks, 1 to 53. `calendar json` prints every day and the totals and is never translated. `--lang es|pt` and your locale pick the language as they do for `why`.
6
+ - The calendar's summary gives the total tokens, the dollars at API prices ("not a bill"), the busiest day, the share of tokens sub-agents used and, when there were any, how many sub-agent launches AgentGuard held: refused by an enforced STOP, or held for your yes. A total of $1,000 or more (at API prices, not a bill) prints in whole dollars with thousands separators, for example "$28,252 to $28,254 at API prices, not a bill", and as one number when both ends round to the same dollar. A day is amber when sub-agents used more than half of its tokens and carries a red mark when AgentGuard held a launch; piped or without colour those days are the letters `s` and `H`. Nothing in the calendar compares you with anyone else.
7
+ - The calendar counts each response once, on the local day it was recorded, with the parser and prices `why` uses. A response stored in two files (a sub-agent's copy of its parent's reply, a project that moved, a forked session) counts once. Checked against `why` on 574 real sessions, every day matched except one session stored in two project directories, which the calendar counts once across both. A forked Codex session whose copied history has no verifiable boundary is left out, with a note.
8
+ - Claude Code deletes transcripts after 30 days by default, so each `calendar` run keeps a daily count per transcript in `calendar/daily.json` under the Burn home: tokens, sub-agent tokens and dollars per day, with no paths and no content, readable only by you. A transcript still on disk is always counted from the transcript, a deleted one's days come from the daily count, and no day is counted twice. `calendar/cache.json` lets a later run read again only the transcripts that changed. A very large transcript is read in 16 MB pieces, so it never has to fit in memory as one string.
9
+ - `why` now ends with the one action that matters most for the session, from the session's own numbers and Anthropic's published guidance (code.claude.com/docs/en/costs, /prompt-caching and /sub-agents). A cause stands out at the 0.3.16 thresholds (sub-agents at 20% of session tokens, full-prefix rewrites at 15% of the API list total) or, for two new causes, at 30% of session tokens: the conversation Claude reads again on every message, and the setup it reads before every message. The cause that is largest at API list price wins, or the largest in tokens when a model has no known price. The actions:
10
+ - Sub-agents that ran on the main conversation's model: "Next: 38 sub-agents ran on Opus 5.5. For searching and reading logs, a smaller model does the job: set CLAUDE_CODE_SUBAGENT_MODEL=haiku, or put model: haiku in the sub-agent's definition."
11
+ - Any other sub-agent use, reworded because a STOP now asks first: "Next: sub-agents used 48.9% of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/try". 0.3.19 said spawn limits refuse that launch. In interactive Claude Code the next launch past a limit waits for your yes; it is refused only where no prompt can show. Spanish and Portuguese say the same.
12
+ - Reloads after a pause longer than the cache lasts: how many, the longest pause, and "Run /compact before a break, so the reload after it is smaller." Reloads caused by switching models: how many, and "Pick your model when you start, or switch at a break, right after /compact." Any other reload cause: the 0.3.16 tip with its dollars and `rewrites`, unchanged.
13
+ - The conversation read again on every message: its median per message, and "/compact at a natural break, or /clear between unrelated tasks". This replaces the 0.3.16 history tip.
14
+ - The setup read before every message (CLAUDE.md, tools, MCP servers and your first message): its median per message, a short CLAUDE.md, and turning off MCP servers you are not using (/mcp).
15
+ No tip claims a saving, and no new tip prints a dollar figure. `quiet on` still hides the tip.
16
+ - `why` adds one measured line when the transcript records a `/compact`, an automatic compaction, a model switch or a `/clear`, for example "Measured change: after /compact on 2026-09-27 at 14:02 UTC, Claude read a median of 85K tokens per message, down from 660K in the 20 messages before." It compares the median tokens per message in up to 20 messages after the latest such event with as many before it, main conversation only; with fewer than 5 on either side it tries an earlier event. It is a measurement next to an event, never a saving and never a cause, and it prints whether tips are on or off.
17
+ - A STOP now shows what the session's finished sub-agents averaged. When an enforced STOP holds a sub-agent launch in Claude Code and at least three of the session's sub-agents have finished, the permission prompt gains one line: "The 15 sub-agents that finished in this session averaged 10.0M tokens each ($4.99 at API prices, not a bill). This one could differ." The box of a refused launch carries the same line. A sub-agent counts as finished when Claude Code records it as completed; failed, killed and stopped ones do not. The figures come from the finished sub-agents' own transcripts, added up while the hook reads them as it already did, so the hook never reads a transcript twice; on the author's machine its time stayed within run-to-run noise. A model with no known price leaves the dollars out. With fewer than three finished, the prompt and the box are as in 0.3.19. Codex, Cursor, the proxy and the middleware print their STOP text unchanged.
18
+ - `--version` and `-v` print the version and exit 0. They used to print the whole help and exit 64.
19
+ - `help`, `--help` and `-h` print the help and exit 0. An unknown command still prints it and exits 64.
20
+ - Piped output is no longer cut short. The CLI now exits only after stdout and stderr have flushed; on macOS a pipe could stop at 64 KB (`calendar --weeks 53 json` stopped mid-string, and a large `why json` could too).
21
+ - The calendar, the tips and the measured line print in Latin American Spanish and Brazilian Portuguese as `why` does, figures in en-US digits. The STOP line is English, as all STOP text is.
22
+ - What changes in output: in English, `why` is byte-identical to 0.3.19 except the tip line, wherever the chosen tip or its wording changed, and the measured line, wherever an event qualifies. `why json` gains `signals.reset` (`{kind, trigger, at}`) on the first response after a compaction or a recorded `/clear`, and `state.pendingReset` when a transcript ends on one; a session with neither prints the same json as 0.3.19. The help lists `calendar`. The STOP prompt and box change only as described above. `compare` and every other command print what they did in 0.3.19.
23
+ - Internals: `readInsightTranscript` and `readInsightSession` take an optional `{ chunkBytes }`. `whyTip` takes a `WhyTipInput` that `whyTipInput` builds from `sessionFigures`. New `calendarDollars`, `proofLine`, `modelLabel`, `shortTokens`, `finishedSubagents`, `subagentCostLine`, `CALENDAR_TEXT` and `DECISION_TEXT`; `askReason` and `renderStop` take an optional cost line. Recordings accept `calendar` frames. Tests: 489 (488 pass, 1 skipped), up from 443 in 0.3.19.
24
+
3
25
  ## 0.3.19 (2026-09-27)
4
26
 
5
27
  - Every command Burn prints now uses the short, unscoped name `npx agentguard-burn` (the `agentguard-burn` launcher on npm runs the latest Burn): the override line in the STOP box, the `why` tips in English, Spanish and Portuguese, and the `quiet` messages. The name has no "@", so X no longer turns a quoted command into a link to someone else's account. `why` output is otherwise byte-identical to 0.3.16 in English.
package/README.md CHANGED
@@ -14,6 +14,8 @@ agentguard-burn why
14
14
 
15
15
  The two init commands print hook configuration for review. Merge the relevant snippet into your host configuration. They do not write it. For Codex, review and trust the hook through `/hooks`. Upgrading an existing hook requires the new snippet: it matches every tool so pace can update on ordinary tool calls, while admission still gates spawns.
16
16
 
17
+ `agentguard-burn --version` (or `-v`) prints the installed version.
18
+
17
19
  For Claude Code, configure its `statusLine` command as `agentguard-burn statusline`. It receives the host JSON on stdin. Codex 0.154.0 has no external status command slot. Use `agentguard-burn statusline SESSION_ID` in a companion terminal and the native Codex limit indicators. See [host fields and setup](docs/USAGE_AND_PRICING.md#what-the-hosts-expose).
18
20
 
19
21
  ## Import a DisciplineBench run
@@ -200,9 +202,18 @@ A session argument can also be a transcript path. Without one, Burn uses the ses
200
202
 
201
203
  The table covers instruction stack + system, history re-sent, repeated file reads, subagent fan-out, tool output, conversation, full-prefix rewrites, output and unattributed usage. The fixed-prefix baseline is the first assistant response's measured context. It includes the initial user message, so the label is an operational baseline rather than a direct measurement of instruction files. A rewrite classified as prefix change resets that baseline and is counted in the footer; the new baseline can include history already present at that point.
202
204
 
203
- The report ends with at most one tip from the session's own numbers, first match wins: subagent fan-out at 20% or more of session tokens, full-prefix rewrites at 15% or more of the session's API list equivalent (skipped when a model is unpriced), history re-sent at 30% or more of session tokens. The tip quotes the share or dollars the table prints and names one next step. When nothing reaches its threshold there is no tip. `agentguard-burn quiet on` hides it, `quiet off` shows it again and `quiet` says which. `why json` never contains it.
205
+ The report ends with at most one tip: the one action that matters most for this session, from its own numbers. A cause stands out at these shares: sub-agents at 20% or more of session tokens, full-prefix rewrites at 15% or more of the session's API list equivalent (skipped when a model is unpriced), and the conversation Claude re-reads, or the setup it reads before every message, at 30% or more of session tokens. Among the causes that stand out, the largest at API list price wins (the largest in tokens when a model is unpriced), and the tip names one action from Anthropic's own guidance ([costs](https://code.claude.com/docs/en/costs), [prompt caching](https://code.claude.com/docs/en/prompt-caching), [sub-agents](https://code.claude.com/docs/en/sub-agents)):
206
+
207
+ - Sub-agents that ran on the main model: `38 sub-agents ran on Opus 5.5.` and a smaller model for searching and reading logs (`CLAUDE_CODE_SUBAGENT_MODEL=haiku`, or `model: haiku` in the sub-agent's definition). Otherwise the sub-agent share, and AgentGuard's free plugin, which asks you before the next sub-agent past your limit starts.
208
+ - Reloads after a pause outlasted the cache: how many, the longest pause, and `/compact` before a break. Reloads from switching models: how many, and switching at a break right after `/compact`. Any other reload cause: the dollars and `agentguard-burn rewrites`.
209
+ - The conversation re-read on every message: its median per message, and `/compact` at a natural break or `/clear` between unrelated tasks.
210
+ - The setup read before every message (CLAUDE.md, tools, MCP servers and the first message): its median per message, a short CLAUDE.md and turning off unused MCP servers (`/mcp`).
211
+
212
+ The setup and the re-read conversation split each call's cached reads at the size of the session's first call, so a rewrite that resets the table's baseline never turns re-read conversation into setup. Tips never claim a saving and print no dollar figure except the rewrite dollars the table prints. When nothing stands out there is no tip. `agentguard-burn quiet on` hides it, `quiet off` shows it again and `quiet` says which. `why json` never contains it.
204
213
 
205
- `why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language, and `--lang es`, `--lang pt` or `--lang en` picks one explicitly. The order is `--lang`, then `AGENTGUARD_LANG`, then `LC_ALL`, `LC_MESSAGES` and `LANG` (the first one set decides, as POSIX says, so `LC_ALL=C` means English), then the locale Node resolves. Every other language is English. Figures keep their en-US formatting in every language (`1,234,567`, `$1335.37`, `12.3%`), so a translated report matches screenshots digit for digit. Only `why` is translated: `why json` is the same in every language, and every other command stays English.
214
+ After a `/compact`, an automatic compaction, a model switch, or a `/clear` that the transcript records, `why` adds one measured line before the tip, for example `Measured change: after /compact on 2026-09-27 at 14:02 UTC, Claude read a median of 85K tokens per message, down from 660K in the 20 messages before.` It compares the median tokens per message of the main conversation in the N messages after the latest such event with the N before it: N is 20, fewer when the session or the next or previous event leaves fewer, and with fewer than 5 on either side that event says nothing. It states a measurement next to an event, never a saving or a cause, and prints whether or not tips are on.
215
+
216
+ `why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language, and `--lang es`, `--lang pt` or `--lang en` picks one explicitly. The order is `--lang`, then `AGENTGUARD_LANG`, then `LC_ALL`, `LC_MESSAGES` and `LANG` (the first one set decides, as POSIX says, so `LC_ALL=C` means English), then the locale Node resolves. Every other language is English. Figures keep their en-US formatting in every language (`1,234,567`, `$1335.37`, `12.3%`), so a translated report matches screenshots digit for digit. `why`, `compare` and `calendar` are translated. Their `json` output is the same in every language, and every other command stays English.
206
217
 
207
218
  Later cache reads up to the baseline go to instruction stack + system. Reads above it go to history re-sent. Fresh input plus cache creation is the measured arriving increment. Burn subtracts the previous response's output before assigning that increment to intervening tool results and user messages. Result byte sizes only split that measured total; bytes are never converted into tokens. A result for a previously read Read path goes to re-read files. Mixed user and tool intervals are marked shared and counted in the footer.
208
219
 
@@ -266,6 +277,47 @@ AgentGuard cannot tell whether these sessions did the same task. Compare runs of
266
277
 
267
278
  `compare` measures and does not rank models. `--lang es|pt` and your locale choose the language exactly as for `why`. `compare json` is never translated: both sessions with ids, paths, project, models and every metric, and each change as an unrounded fraction of A.
268
279
 
280
+ ## Tokens per day
281
+
282
+ ```sh
283
+ agentguard-burn calendar
284
+ agentguard-burn calendar --weeks 12
285
+ agentguard-burn calendar json
286
+ ```
287
+
288
+ Every Claude Code and Codex session on this machine on one heatmap, sub-agents included: a column per week, a row per weekday, darker for more tokens. Each response's tokens and API price come from the parser and prices `why` uses, counted on the local calendar day the response was recorded. A response recorded in two files (a sub-agent's copy of its parent's last reply, a project that moved, a forked session) counts once, merged the way `why` merges a session. A forked Codex session whose copied history has no verifiable boundary is left out and named in a note, as `why` reports it unavailable.
289
+
290
+ The summary gives the total tokens, the dollars at API prices (not a bill; from $1,000 in whole dollars, such as `$28,252 to $28,254 at API prices, not a bill`, and one number when both ends round to the same dollar), the busiest day, the share of tokens sub-agents used (every token of their responses) and, when there were any, how many sub-agent launches AgentGuard held: refused by an enforced STOP, or held for your yes, as the decisions ledger records them. A day is amber when sub-agents used more than half of its tokens, and carries a red mark when AgentGuard held a launch that day. The five shades run from Less to More: a day's level is the quarter of the shown days with tokens that it reaches, so the busiest day shown is always the darkest. Tokens on a model without a verified rate are counted but left out of the dollars, and a note names the model.
291
+
292
+ With no flag the calendar starts at the oldest recorded day, capped to the weeks that fit the terminal (80 columns when piped); `--weeks N` shows exactly N weeks, 1 to 53, ending with this week. A colour terminal draws coloured squares; piped, with `--no-color` or with `NO_COLOR` set, each day is a shade character (`· ░ ▒ ▓ █`) and the two kinds of marked day are the letters `s` and `H`. The fixture in `tests/fixtures/calendar-fixtures.ts` prints:
293
+
294
+ ```text
295
+ AgentGuard calendar: tokens per day, Aug 30 to Sep 26, 2026
296
+ 696,040 tokens · $7.29 at API prices, not a bill
297
+ busiest day: Sep 24 (511,040 tokens) · sub-agents used 7.3% of tokens
298
+ AgentGuard held 2 launches
299
+
300
+ Sep
301
+ Su · · ·
302
+ Mo · s ·
303
+ Tu ░ · · ·
304
+ We · ▒ H ·
305
+ Th · · · █
306
+ Fr · · · ·
307
+ Sa · · · ▒
308
+
309
+ Less · ░ ▒ ▓ █ More
310
+ Days marked s: sub-agents used more than half of that day's tokens.
311
+ Days marked H: AgentGuard held a launch that day.
312
+ From Claude Code and Codex sessions on this machine, sub-agents included.
313
+ Claude Code deletes sessions older than 30 days by default.
314
+ Burn keeps each day's count whenever you run this, so the calendar grows.
315
+ ```
316
+
317
+ Claude Code deletes transcripts after 30 days by default (`cleanupPeriodDays`), so each run keeps a daily count per transcript file in `calendar/daily.json` under the Burn home (`AGENTGUARD_HOME`, default `~/.agentguard`): tokens, sub-agent tokens and dollars per day, with no paths and no content, owner-only and written atomically. A transcript still on disk is always counted from the transcript; a deleted transcript's days come from the daily count; no file-day is counted from both. Run `calendar` at least once within Claude Code's retention period to keep every day. `calendar/cache.json` keeps each response's counts, keyed by the transcript's path digest, size and modification time, so a later run re-reads only the transcripts that changed; a new Burn version or a pricing override recounts everything once.
318
+
319
+ `calendar json` is never translated: every day of the span with its figures and level, the totals, the busiest day and where the figures came from. `--lang es|pt` and your locale choose the language exactly as for `why`. Nothing in the calendar compares you with anyone else.
320
+
269
321
  ## Two safety planes
270
322
 
271
323
  Structural limits use active time rather than the age of the session. The
@@ -398,9 +450,16 @@ prompt. The prompt names the one limit that fired, for example:
398
450
  ```
399
451
  AgentGuard: 15 sub-agents in the last 15 active minutes. Limit: 15.
400
452
  Session so far: 15 sub-agents, 154.0M tokens.
453
+ The 12 sub-agents that finished in this session averaged 10.0M tokens each ($4.99 at API prices, not a bill). This one could differ.
401
454
  Allow this one launch? If you say no, nothing starts.
402
455
  ```
403
456
 
457
+ The third line appears once at least three of the session's sub-agents have
458
+ finished: what they averaged, measured from their own transcripts as the hook
459
+ reads them anyway (never a second pass), and never a forecast. With fewer, the
460
+ prompt is the other three lines. The box of a refused launch carries the same
461
+ line.
462
+
404
463
  You answer with one keypress. Claude never sees that text, and auto mode
405
464
  cannot approve it silently (Claude Code 2.1.211 and later), so the answer is
406
465
  yours. Where no prompt can appear (print mode, `bypassPermissions`, `dontAsk`,
@@ -1,4 +1,10 @@
1
- export type CanvasColor = 'mint' | 'slate' | 'amber' | 'red' | 'white' | 'none';
1
+ /**
2
+ * Heat ramps for calendar cells: `shade0` is a day with no tokens; `teal1` to
3
+ * `teal4` and `amber1` to `amber4` are the four token levels, mixed from the
4
+ * canvas background toward mint and amber, so the top level is the brand colour.
5
+ */
6
+ export type CanvasHeatColor = 'shade0' | 'teal1' | 'teal2' | 'teal3' | 'teal4' | 'amber1' | 'amber2' | 'amber3' | 'amber4';
7
+ export type CanvasColor = 'mint' | 'slate' | 'amber' | 'red' | 'white' | 'none' | CanvasHeatColor;
2
8
  export type CanvasColorMode = 'truecolor' | '256' | 'none';
3
9
  export interface CanvasCell {
4
10
  char: string;
@@ -9,6 +9,15 @@ exports.CANVAS_PALETTE = {
9
9
  amber: { hex: '#F59E0B', rgb: [245, 158, 11], ansi256: 208 },
10
10
  red: { hex: '#EF4444', rgb: [239, 68, 68], ansi256: 203 },
11
11
  white: { hex: '#E2E8F0', rgb: [226, 232, 240], ansi256: 254 },
12
+ shade0: { hex: '#333E4B', rgb: [51, 62, 75], ansi256: 238 },
13
+ teal1: { hex: '#164E4E', rgb: [22, 78, 78], ansi256: 23 },
14
+ teal2: { hex: '#1C6F6D', rgb: [28, 111, 109], ansi256: 30 },
15
+ teal3: { hex: '#239692', rgb: [35, 150, 146], ansi256: 37 },
16
+ teal4: { hex: '#2ABCB4', rgb: [42, 188, 180], ansi256: 44 },
17
+ amber1: { hex: '#5D4213', rgb: [93, 66, 19], ansi256: 94 },
18
+ amber2: { hex: '#8C5F10', rgb: [140, 95, 16], ansi256: 136 },
19
+ amber3: { hex: '#C27F0E', rgb: [194, 127, 14], ansi256: 172 },
20
+ amber4: { hex: '#F59E0B', rgb: [245, 158, 11], ansi256: 214 },
12
21
  };
13
22
  const GLYPHS = {
14
23
  '0': ['█▀█', '█ █', '█▄█'], '1': [' ▀█', ' █', ' █'],
@@ -31,7 +40,7 @@ const BIG_GLYPHS = {
31
40
  '9': [' ### ', '# #', '# #', ' ####', ' #', ' #', ' ### '],
32
41
  '-': [' ', ' ', ' ', '#####', ' ', ' ', ' '],
33
42
  };
34
- const colors = new Set(['mint', 'slate', 'amber', 'red', 'white', 'none']);
43
+ const colors = new Set(['mint', 'slate', 'amber', 'red', 'white', 'none', 'shade0', 'teal1', 'teal2', 'teal3', 'teal4', 'amber1', 'amber2', 'amber3', 'amber4']);
35
44
  function dimension(value, fallback, limit) {
36
45
  return Math.max(1, Math.min(limit, Math.floor(typeof value === 'number' && Number.isFinite(value) ? value : fallback)));
37
46
  }
package/dist/src/cli.js CHANGED
@@ -141,6 +141,11 @@ async function main(argv) {
141
141
  };
142
142
  const has = (name) => rawRest.includes(name);
143
143
  switch (command) {
144
+ case '--version':
145
+ case '-v':
146
+ // The version of this install, from the package that ships it, and nothing else.
147
+ process.stdout.write(`${require('../../package.json').version}\n`);
148
+ return 0;
144
149
  case 'live': {
145
150
  const { runLivePanel } = await Promise.resolve().then(() => __importStar(require('./live-panel')));
146
151
  return runLivePanel(HOME, rawRest);
@@ -263,6 +268,48 @@ async function main(argv) {
263
268
  show({ kind: 'command', command, values: { ...report } }, json ? JSON.stringify(report, null, 2) + '\n' : renderCompare(report, language) + '\n', json);
264
269
  return 0;
265
270
  }
271
+ case 'calendar': {
272
+ // `--weeks N` (1 to 53, also --weeks=N), `json`, and `--lang` exactly as `why` takes it.
273
+ const args = [];
274
+ let lang, langGiven = false, weeksText, weeksGiven = false;
275
+ for (let i = 0; i < rest.length; i++) {
276
+ if (rest[i] === '--lang') {
277
+ langGiven = true;
278
+ lang = rest[++i];
279
+ }
280
+ else if (rest[i].startsWith('--lang=')) {
281
+ langGiven = true;
282
+ lang = rest[i].slice('--lang='.length);
283
+ }
284
+ else if (rest[i] === '--weeks') {
285
+ weeksGiven = true;
286
+ weeksText = rest[++i];
287
+ }
288
+ else if (rest[i].startsWith('--weeks=')) {
289
+ weeksGiven = true;
290
+ weeksText = rest[i].slice('--weeks='.length);
291
+ }
292
+ else
293
+ args.push(rest[i]);
294
+ }
295
+ const json = args.includes('json') || args.includes('--json');
296
+ const weeks = weeksGiven && /^\d{1,2}$/.test(weeksText ?? '') ? Number(weeksText) : undefined;
297
+ if ((langGiven && (0, i18n_1.whyLangOf)(lang) === null) || (weeksGiven && !(weeks >= 1 && weeks <= 53)) || args.some(value => value !== 'json' && value !== '--json')) {
298
+ process.stderr.write('Usage: agentguard-burn calendar [--weeks N] [json] [--lang en|es|pt]\n');
299
+ return 64;
300
+ }
301
+ const language = (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() });
302
+ const { calendarReport, collectCalendar } = await Promise.resolve().then(() => __importStar(require('./insights/calendar')));
303
+ const { renderCalendar } = await Promise.resolve().then(() => __importStar(require('./insights/calendar-render')));
304
+ // The span fits the terminal: its columns on a TTY, 80 when piped.
305
+ const columns = process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 ? process.stdout.columns : 80;
306
+ const data = collectCalendar({ home: HOME, rates: (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)) });
307
+ if (!data.saved)
308
+ process.stderr.write(i18n_1.CALENDAR_TEXT[language].saveFailed + '\n');
309
+ const report = calendarReport(data, { now: Date.now(), columns, ...(weeks ? { weeks } : {}) });
310
+ show({ kind: 'calendar', report, lang: language, columns }, json ? JSON.stringify(report, null, 2) + '\n' : renderCalendar(report, language, columns) + '\n', json);
311
+ return 0;
312
+ }
266
313
  case 'quiet': {
267
314
  const [state, ...extra] = rest;
268
315
  if (extra.length || (state !== undefined && state !== 'on' && state !== 'off')) {
@@ -526,7 +573,7 @@ async function main(argv) {
526
573
  return 0;
527
574
  }
528
575
  default:
529
- show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
576
+ show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
530
577
  ' ps [--json] local agent processes, held memory and workspace disk\n' +
531
578
  ' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
532
579
  ' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
@@ -540,6 +587,7 @@ async function main(argv) {
540
587
  ' why [session] token attribution and API list-price equivalents\n' +
541
588
  ' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
542
589
  ' compare [sessionA] [sessionB] two sessions side by side: tokens, cache, sub-agents, rewrites, list USD; json and --lang as for why\n' +
590
+ ' calendar [--weeks N] tokens per day, Claude Code and Codex together: sub-agent days, launches AgentGuard held, dollars at API prices; json and --lang as for why\n' +
543
591
  ' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
544
592
  ' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
545
593
  ' pace [session] ten-minute pace and next-hour projection\n' +
@@ -561,7 +609,7 @@ async function main(argv) {
561
609
  'Developer review commands (never installed as hooks):\n' +
562
610
  ' guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]\n' +
563
611
  ' deduplicate recorded shell text; --rank explicitly permits jsort provider requests\n');
564
- return command ? 64 : 0;
612
+ return !command || command === 'help' || command === '--help' || command === '-h' ? 0 : 64;
565
613
  }
566
614
  }
567
615
  async function run() {
@@ -607,7 +655,19 @@ async function run() {
607
655
  throw error;
608
656
  }
609
657
  }
610
- run().then((code) => process.exit(code), (error) => {
658
+ /**
659
+ * Exit once stdout and stderr have handed everything to the OS. A pipe is
660
+ * asynchronous on macOS, and exiting at once cut piped output at 64 KB
661
+ * (`calendar --weeks 53 json` stopped mid-string).
662
+ */
663
+ function exit(code) {
664
+ let pending = 2;
665
+ const done = () => { if (--pending === 0)
666
+ process.exit(code); };
667
+ process.stdout.write('', done);
668
+ process.stderr.write('', done);
669
+ }
670
+ run().then((code) => exit(code), (error) => {
611
671
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
612
- process.exit(4);
672
+ exit(4);
613
673
  });
@@ -6,6 +6,8 @@ import type { AuditReport, AuditRow } from './idle/types';
6
6
  import type { BurnReport } from './types';
7
7
  import { type StopHost } from './stop-text';
8
8
  import type { ReplaySummary } from './replay/simulate';
9
+ import type { CalendarReport } from './insights/calendar';
10
+ import type { WhyLang } from './insights/i18n';
9
11
  export type AuditFrameReport = Omit<AuditReport, 'processes' | 'rows'> & {
10
12
  rows: Array<Omit<AuditRow, 'processes'>>;
11
13
  };
@@ -35,6 +37,14 @@ export type BurnFrame = {
35
37
  command: string;
36
38
  values: Record<string, unknown>;
37
39
  page?: number;
40
+ }
41
+ /** A calendar is one block sized to its weeks, drawn whole and never paged; `columns` is the width its text wrapped at. */
42
+ | {
43
+ kind: 'calendar';
44
+ report: CalendarReport;
45
+ lang: WhyLang;
46
+ columns: number;
47
+ page?: number;
38
48
  };
39
49
  export interface FrameOptions {
40
50
  recorded?: boolean;
@@ -35,6 +35,11 @@ function valueRows(values, prefix = '', depth = 0) {
35
35
  });
36
36
  }
37
37
  function renderFrame(data, options = {}) {
38
+ if (data.kind === 'calendar') {
39
+ // Loaded only when a calendar is drawn, so hooks and other commands never load it.
40
+ const { drawCalendar } = require('./insights/calendar-render');
41
+ return drawCalendar(data.report, data.lang, data.columns, options.colour);
42
+ }
38
43
  if (data.kind === 'bench')
39
44
  return (0, bench_panel_1.renderBenchPanel)(data.snapshot, options);
40
45
  if (data.kind === 'live')
@@ -14,6 +14,12 @@
14
14
  import type { BurnEvent } from '../types';
15
15
  /** Component maxima for one provider response, never transcript contents. */
16
16
  export type UsageSnapshot = [input: number, output: number, cacheCreation: number, cacheRead: number];
17
+ /**
18
+ * Usage one child transcript added under one model, deduplicated exactly as the
19
+ * session totals are. Cache writes are split into their five-minute and one-hour
20
+ * parts when the record says; a write with no recorded lifetime is in neither.
21
+ */
22
+ export type ChildUsage = [input: number, output: number, cacheWrite: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number];
17
23
  export interface ReaderCursor {
18
24
  /** Byte just after the last complete newline we processed. */
19
25
  offset: number;
@@ -27,18 +33,37 @@ export interface ReaderCursor {
27
33
  usageByMessage?: Map<string, UsageSnapshot>;
28
34
  /** Child file cursors share usageByMessage with their parent. */
29
35
  children?: Map<string, ReaderCursor>;
36
+ /**
37
+ * On a child cursor read from its first byte: the usage that child added, by
38
+ * model id ('' when none is recorded). A child an older Burn had already read
39
+ * part of has none, and stays unmeasured rather than undercounted.
40
+ */
41
+ usage?: Map<string, ChildUsage>;
42
+ /** Sub-agent ids the transcripts record as completed; the parent's set, shared with its children. */
43
+ completed?: Set<string>;
30
44
  }
31
45
  export declare function newCursor(): ReaderCursor;
32
46
  interface RawLine {
47
+ type?: unknown;
33
48
  timestamp?: string;
34
49
  uuid?: string;
35
50
  parentUuid?: string;
36
51
  isSidechain?: boolean;
37
52
  message?: {
38
53
  id?: unknown;
39
- usage?: Record<string, number | undefined>;
54
+ model?: unknown;
55
+ usage?: Record<string, unknown>;
40
56
  content?: unknown;
41
57
  };
58
+ /** A queued message (queue-operation records). */
59
+ content?: unknown;
60
+ /** A queued command (attachment records). */
61
+ attachment?: {
62
+ type?: unknown;
63
+ prompt?: unknown;
64
+ };
65
+ /** A tool's recorded result; a synchronous sub-agent's carries its id and status. */
66
+ toolUseResult?: unknown;
42
67
  }
43
68
  /** Turn one parsed line into an event, or null if it carries nothing we track. */
44
69
  export declare function normaliseLine(raw: RawLine, cursor: ReaderCursor): BurnEvent | null;
@@ -37,6 +37,48 @@ function toMillis(value) {
37
37
  function nonNegative(value) {
38
38
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
39
39
  }
40
+ const MODEL_ID = /^[A-Za-z0-9_.:/-]{1,128}$/;
41
+ const AGENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
42
+ /**
43
+ * Add one response's newly observed usage to its child's running total. The
44
+ * five-minute and one-hour parts of a cache write follow the record's own split;
45
+ * a write without one keeps no lifetime and prices as a range.
46
+ */
47
+ function addChildUsage(usage, raw, [input, output, write, read]) {
48
+ const model = typeof raw.message?.model === 'string' && MODEL_ID.test(raw.message.model) ? raw.message.model : '';
49
+ const split = raw.message?.usage?.cache_creation;
50
+ const record = split && typeof split === 'object' ? split : {};
51
+ const fiveMinute = nonNegative(record.ephemeral_5m_input_tokens), oneHour = nonNegative(record.ephemeral_1h_input_tokens);
52
+ const hour = fiveMinute + oneHour > 0 ? Math.round(write * oneHour / (fiveMinute + oneHour)) : 0;
53
+ const five = fiveMinute + oneHour > 0 ? write - hour : 0;
54
+ const row = usage.get(model) ?? [0, 0, 0, 0, 0, 0];
55
+ usage.set(model, [row[0] + input, row[1] + output, row[2] + write, row[3] + read, row[4] + five, row[5] + hour]);
56
+ }
57
+ /**
58
+ * Note the sub-agents the host records as completed. Claude Code writes a
59
+ * synchronous sub-agent's result with status "completed", and announces the end
60
+ * of a background one with a <task-notification> in a queued message (a queue
61
+ * operation, a queued-command attachment, or the user message it becomes). Only
62
+ * the id of a completed sub-agent is kept; nothing else of the message is.
63
+ */
64
+ function observeCompleted(raw, completed) {
65
+ const result = raw.toolUseResult;
66
+ if (result && typeof result === 'object' && !Array.isArray(result)) {
67
+ const { status, agentId } = result;
68
+ if (status === 'completed' && typeof agentId === 'string' && AGENT_ID.test(agentId))
69
+ completed.add(agentId);
70
+ }
71
+ const text = raw.type === 'queue-operation' ? raw.content
72
+ : raw.type === 'user' ? raw.message?.content
73
+ : raw.type === 'attachment' && raw.attachment?.type === 'queued_command' ? raw.attachment.prompt : undefined;
74
+ if (typeof text !== 'string' || !text.startsWith('<task-notification>'))
75
+ return;
76
+ for (const [, body] of text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
77
+ const id = /<task-id>([A-Za-z0-9_-]{1,64})<\/task-id>/.exec(body)?.[1];
78
+ if (id && /<status>completed<\/status>/.test(body))
79
+ completed.add(id);
80
+ }
81
+ }
40
82
  /** Turn one parsed line into an event, or null if it carries nothing we track. */
41
83
  function normaliseLine(raw, cursor) {
42
84
  const at = toMillis(raw.timestamp);
@@ -47,6 +89,7 @@ function normaliseLine(raw, cursor) {
47
89
  nonNegative(usage.cache_creation_input_tokens), nonNegative(usage.cache_read_input_tokens)];
48
90
  let tokens = snapshot.reduce((sum, value) => sum + value, 0);
49
91
  let cacheRead = snapshot[3];
92
+ let added = snapshot;
50
93
  // Claude writes one row per content block, all carrying the same message.id.
51
94
  // Fork copies preserve that id too. Match the attribution parser's global
52
95
  // identity and per-category maxima, emitting only newly observed usage.
@@ -55,10 +98,13 @@ function normaliseLine(raw, cursor) {
55
98
  cursor.usageByMessage ??= new Map();
56
99
  const previous = cursor.usageByMessage.get(id) ?? [0, 0, 0, 0];
57
100
  const merged = snapshot.map((value, index) => Math.max(value, previous[index]));
58
- tokens = merged.reduce((sum, value, index) => sum + value - previous[index], 0);
59
- cacheRead = merged[3] - previous[3];
101
+ added = merged.map((value, index) => value - previous[index]);
102
+ tokens = added.reduce((sum, value) => sum + value, 0);
103
+ cacheRead = added[3];
60
104
  cursor.usageByMessage.set(id, merged);
61
105
  }
106
+ if (cursor.usage && tokens > 0)
107
+ addChildUsage(cursor.usage, raw, added);
62
108
  // Depth attribution: a line's depth is its parent's depth, plus one if the
63
109
  // host flagged it as a sidechain (subagent) line. Unknown parents are root.
64
110
  const parentDepth = raw.parentUuid ? cursor.depthByUuid.get(raw.parentUuid) ?? 0 : 0;
@@ -121,6 +167,8 @@ function readIncremental(path, cursor, options = {}) {
121
167
  if (size < cursor.offset) {
122
168
  cursor.offset = 0;
123
169
  cursor.depthByUuid.clear();
170
+ // Shared de-duplication would hide a re-read file's usage: it is no longer measured.
171
+ cursor.usage = undefined;
124
172
  }
125
173
  cursor.size = size;
126
174
  if (size === cursor.offset)
@@ -145,6 +193,8 @@ function readIncremental(path, cursor, options = {}) {
145
193
  if (lineBytes.length > 0 && lineBytes.length <= MAX_LINE) {
146
194
  try {
147
195
  const parsed = JSON.parse(lineBytes.toString('utf8'));
196
+ if (cursor.completed)
197
+ observeCompleted(parsed, cursor.completed);
148
198
  const event = normaliseLine(parsed, cursor);
149
199
  if (event)
150
200
  events.push(event);
@@ -186,6 +236,7 @@ function readIncremental(path, cursor, options = {}) {
186
236
  function readSessionIncremental(path, cursor, options = {}) {
187
237
  cursor.usageByMessage ??= new Map();
188
238
  cursor.children ??= new Map();
239
+ cursor.completed ??= new Set();
189
240
  const events = readIncremental(path, cursor, options);
190
241
  const directory = (0, node_path_1.join)(path.replace(/\.jsonl$/, ''), 'subagents');
191
242
  let names;
@@ -200,6 +251,11 @@ function readSessionIncremental(path, cursor, options = {}) {
200
251
  for (const name of names) {
201
252
  const child = cursor.children.get(name) ?? newCursor();
202
253
  child.usageByMessage = cursor.usageByMessage;
254
+ // A sub-agent's own sub-agents report their completion in its transcript.
255
+ child.completed = cursor.completed;
256
+ // Measured from its first byte, as it is read anyway: no second pass over any child.
257
+ if (!child.usage && child.offset === 0)
258
+ child.usage = new Map();
203
259
  cursor.children.set(name, child);
204
260
  for (const event of readIncremental((0, node_path_1.join)(directory, name), child, options)) {
205
261
  if (event.tokens > 0 || event.cacheRead > 0)
@@ -14,7 +14,7 @@
14
14
  * cannot fail closed if Claude Code times the hook out, so the hot path does
15
15
  * as little as possible.
16
16
  */
17
- import { type ReaderCursor, type UsageSnapshot } from '../history/claude-transcript';
17
+ import { type ChildUsage, type ReaderCursor, type UsageSnapshot } from '../history/claude-transcript';
18
18
  import type { BurnReport, Policy, SessionState } from '../types';
19
19
  export interface HookInput {
20
20
  hook_event_name?: string;
@@ -46,6 +46,10 @@ export interface PersistedReaderCursor {
46
46
  usageVersion?: 1;
47
47
  usageByMessage?: [string, UsageSnapshot][];
48
48
  children?: [string, PersistedReaderCursor][];
49
+ /** A child measured from its first byte: the usage it added, by model. */
50
+ usage?: [string, ChildUsage][];
51
+ /** The parent only: sub-agent ids the transcripts record as completed. */
52
+ completed?: string[];
49
53
  }
50
54
  export interface PersistedSession {
51
55
  cursor: PersistedReaderCursor;
@@ -42,6 +42,7 @@ const stop_text_1 = require("../stop-text");
42
42
  const node_os_1 = require("node:os");
43
43
  const live_1 = require("../insights/live");
44
44
  const hook_1 = require("../idle/hook");
45
+ const subagent_cost_1 = require("../subagent-cost");
45
46
  const SPAWN_TOOLS = new Set(['Agent', 'Task']);
46
47
  function sessionFile(home, sessionId) {
47
48
  return (0, node_path_1.join)(home, 'sessions', `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
@@ -55,15 +56,19 @@ function inflateHookSession(raw) {
55
56
  surfaceReaders: new Map(raw.state.surfaceReaders.map(([k, v]) => [k, new Set(v)])),
56
57
  };
57
58
  }
58
- function inflateCursor(raw, shared) {
59
+ function inflateCursor(raw, shared, completed) {
59
60
  const usageByMessage = shared ?? new Map(raw.usageByMessage ?? []);
60
- return { ...raw, depthByUuid: new Map(raw.depthByUuid), usageByMessage,
61
- children: new Map((raw.children ?? []).map(([name, child]) => [name, inflateCursor(child, usageByMessage)])) };
61
+ const done = completed ?? new Set(raw.completed ?? []);
62
+ return { offset: raw.offset, size: raw.size, malformedLines: raw.malformedLines, depthByUuid: new Map(raw.depthByUuid),
63
+ usageVersion: raw.usageVersion, usageByMessage, completed: done, ...(raw.usage ? { usage: new Map(raw.usage) } : {}),
64
+ children: new Map((raw.children ?? []).map(([name, child]) => [name, inflateCursor(child, usageByMessage, done)])) };
62
65
  }
63
66
  function persistCursor(cursor, child = false) {
64
67
  return { offset: cursor.offset, size: cursor.size, malformedLines: cursor.malformedLines, depthByUuid: [...cursor.depthByUuid],
65
68
  usageVersion: cursor.usageVersion,
66
69
  ...(!child ? { usageByMessage: [...(cursor.usageByMessage ?? [])] } : {}),
70
+ ...(!child && cursor.completed?.size ? { completed: [...cursor.completed] } : {}),
71
+ ...(child && cursor.usage ? { usage: [...cursor.usage] } : {}),
67
72
  ...(cursor.children?.size ? { children: [...cursor.children].map(([name, value]) => [name, persistCursor(value, true)]) } : {}) };
68
73
  }
69
74
  function loadSession(home, sessionId, firstEventAt) {
@@ -204,7 +209,6 @@ function handleSpawnPreToolUse(input, home, now) {
204
209
  const proposedDepth = input.agent_id ? 2 : 1;
205
210
  const { report, reservation, window } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, input.tool_use_id ?? `${input.session_id}:${now}`, now, { sessions: (0, account_1.readAccountSessions)(home, state, now), now });
206
211
  const shouldDeny = report.verdict === 'STOP' || !reservation.allowed;
207
- const reason = shouldDeny ? buildDenyReason(report, reservation) : '';
208
212
  // The audited override: only consulted when a block is about to happen.
209
213
  const override = shouldDeny && policy.mode === 'enforce' ? (0, override_1.consumeOverride)(home, now) : null;
210
214
  const blocked = policy.mode === 'enforce' && shouldDeny && !override;
@@ -244,12 +248,14 @@ function handleSpawnPreToolUse(input, home, now) {
244
248
  });
245
249
  if (shouldDeny && policy.mode === 'enforce') {
246
250
  if (!override) {
251
+ // The cost of one more sub-agent, at the decision: from the state just refreshed, never a transcript read.
252
+ const costLine = decisionCostLine(refreshed.cursor, home, policy);
247
253
  if (asked) {
248
254
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'asked', host: 'claude-code' });
249
- return ask((0, stop_text_1.askReason)(report));
255
+ return ask((0, stop_text_1.askReason)(report, costLine));
250
256
  }
251
257
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'blocked', host: 'claude-code' });
252
- return deny(reason);
258
+ return deny(buildDenyReason(report, costLine));
253
259
  }
254
260
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'overridden', host: 'claude-code' });
255
261
  return { continue: true, systemMessage: (0, stop_text_1.overriddenLine)(report, override) };
@@ -274,12 +280,33 @@ function handleSpawnPreToolUse(input, home, now) {
274
280
  return policy.mode === 'enforce' ? deny(reason) : { continue: true, suppressOutput: true };
275
281
  }
276
282
  }
277
- function buildDenyReason(report, _reservation) {
283
+ function buildDenyReason(report, costLine) {
278
284
  // Claude Code shows this reason to the user. A box reads as an alarm; a
279
285
  // sentence reads as a log line. Colour is off: the host decides rendering.
280
286
  // Claude trims leading whitespace before adding Error:. A zero-width word
281
287
  // joiner preserves the blank first line, keeping that prefix off the frame.
282
- return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code' });
288
+ return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code', costLine });
289
+ }
290
+ /**
291
+ * What this session's finished sub-agents averaged, in English like the rest of
292
+ * the STOP text, or null below three. Best effort: a pricing file that cannot be
293
+ * read costs the line its dollars, and nothing here can turn a prompt into a
294
+ * failed-closed refusal.
295
+ */
296
+ function decisionCostLine(cursor, home, policy) {
297
+ let rates;
298
+ try {
299
+ rates = (0, live_1.readPricing)(home, policy);
300
+ }
301
+ catch {
302
+ rates = null;
303
+ }
304
+ try {
305
+ return (0, subagent_cost_1.subagentCostLine)((0, subagent_cost_1.finishedSubagents)(cursor, rates ?? {}, rates !== null));
306
+ }
307
+ catch {
308
+ return null;
309
+ }
283
310
  }
284
311
  const ASK_MODES = new Set(['default', 'acceptEdits', 'auto', 'plan']);
285
312
  /**