@agentguard-run/burn 0.3.18 → 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.
Files changed (35) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +105 -5
  3. package/dist/src/canvas.d.ts +7 -1
  4. package/dist/src/canvas.js +10 -1
  5. package/dist/src/cli.js +101 -7
  6. package/dist/src/frames.d.ts +10 -0
  7. package/dist/src/frames.js +5 -0
  8. package/dist/src/history/claude-transcript.d.ts +26 -1
  9. package/dist/src/history/claude-transcript.js +58 -2
  10. package/dist/src/hook/pre-tool-use.d.ts +6 -2
  11. package/dist/src/hook/pre-tool-use.js +35 -8
  12. package/dist/src/insights/calendar-render.d.ts +48 -0
  13. package/dist/src/insights/calendar-render.js +196 -0
  14. package/dist/src/insights/calendar.d.ts +138 -0
  15. package/dist/src/insights/calendar.js +431 -0
  16. package/dist/src/insights/compare.d.ts +104 -0
  17. package/dist/src/insights/compare.js +210 -0
  18. package/dist/src/insights/i18n.d.ts +134 -8
  19. package/dist/src/insights/i18n.js +200 -13
  20. package/dist/src/insights/render.d.ts +93 -13
  21. package/dist/src/insights/render.js +212 -28
  22. package/dist/src/insights/sessions.d.ts +25 -0
  23. package/dist/src/insights/sessions.js +72 -5
  24. package/dist/src/insights/transcript.d.ts +13 -2
  25. package/dist/src/insights/transcript.js +61 -6
  26. package/dist/src/insights/types.d.ts +17 -0
  27. package/dist/src/insights/types.js +3 -1
  28. package/dist/src/recording.js +5 -1
  29. package/dist/src/replay/render.d.ts +2 -0
  30. package/dist/src/replay/render.js +4 -0
  31. package/dist/src/stop-text.d.ts +16 -5
  32. package/dist/src/stop-text.js +28 -6
  33. package/dist/src/subagent-cost.d.ts +38 -0
  34. package/dist/src/subagent-cost.js +65 -0
  35. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
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
+
25
+ ## 0.3.19 (2026-09-27)
26
+
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.
28
+ - `enforce` now says what enforcement does: "In an interactive Claude Code session the next STOP asks you first; where nobody can answer, it refuses the launch."
29
+ - `why` with no session no longer picks a file Claude Code keeps inside a session's own directory, such as `<session>/skill-injections.jsonl`, when that file is the newest on disk.
30
+ - New `compare [sessionA] [sessionB] [json] [--lang en|es|pt]`: two sessions side by side from local transcripts, so the same task run once on each model reads as one table. Rows: assistant responses; input tokens, split into cache reads, cache writes and fresh input; the cache share (cache reads divided by all input); output tokens; sub-agents launched; full-prefix rewrites; the API list-price equivalent. Each is exactly the figure `why` prints for that session, child transcripts included, and the table says "Totals include sub-agents." The Change column is B against A: a signed percentage for counts and dollars, and a difference in percentage points for the cache share (for example "+2.6 pp", never a percentage of a percentage; `change.cacheShare` in json is that difference), only where both values are numbers and A is not zero as printed; a dollar range compares midpoints, and an unpriced model prints `unpriced` with no change. Every report ends with "Dollar figures are API list-price equivalents, not a bill." and "AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task."
31
+ - Picking: two sessions compare those two in the order given; one pairs it with the newest other top-level session in its project; none takes the two newest top-level sessions in the project of the newest one. Ids, id suffixes and transcript paths resolve as they do for `why`. Sub-agent transcripts and other files Claude Code keeps beside a session (such as `skill-injections.jsonl`) are never picked. A Codex rollout's project is the working directory it recorded, and a spawned sub-agent rollout is skipped. Unless both are named, A is the session that started first. The session variables `why` falls back on are not read. Fewer than two sessions exits 1 with one line on stderr saying so and how to pass two ids.
32
+ - Both sessions are named above the table: the short id (the last part of the session id, accepted back as an id suffix), the time of the first recorded response in UTC, the dominant model by output tokens (every model with at least 5% of output tokens, with its share, when there are several) and the project path (the working directory the transcript recorded, read from its first records only).
33
+ - The table fits 80 columns in English. Spanish and Portuguese follow `why`: every line through `src/insights/i18n.ts`, figures in en-US digits, AgentGuard untranslated, the same language precedence and the same exit-64 usage line for a bad `--lang`. `compare json` is never translated and carries both sessions (ids, paths, project, models, every metric) and each change as an unrounded fraction of A. The report prints its plain table on a terminal, through the same presentation path as the other reports.
34
+ - What changes in output: only the new command, and the help, which lists it in its synopsis and on one new line. `why`, `why json` and every other command are byte-identical to 0.3.17. Internally, `why`'s header figures now come from an exported `sessionFigures`, which `compare` reads as well; `render.ts` exports its `table`, `count` and `share` helpers, and `sessions.ts` gains `transcriptRoots` (the same default roots) and `transcriptOrigin` (the recorded working directory and the parser's sub-agent verdict, from at most the first megabyte of a transcript).
35
+
3
36
  ## 0.3.18 (2026-09-27)
4
37
 
5
38
  - An enforced STOP in an interactive Claude Code session (Manual, accept edits, auto or plan mode) now holds the launch behind Claude Code's own permission prompt instead of refusing it: three lines naming the one limit that fired, then "Allow this one launch? If you say no, nothing starts." Claude Code shows that text to the person and not to Claude, and since Claude Code 2.1.211 auto mode cannot approve it silently. Print mode, `bypassPermissions`, `dontAsk`, Codex and Cursor still refuse outright. `"stopStyle": "deny"` in `burn-policy.json` keeps the outright refusal everywhere. The decisions ledger records `asked: true` and the permission mode; the signed receipt adds the reason `decision:ask`.
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.
213
+
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.
204
215
 
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.
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
 
@@ -225,6 +236,88 @@ Optional settings in your existing `burn-policy.json`:
225
236
 
226
237
  Merge these fields into the existing policy. All existing thresholds and modes remain supported. Prices are exact-model API list equivalents, not a subscription bill. Unknown models show tokens only. Every rate has a source and verification date. A local override file and full pricing table are documented in [Usage and pricing](docs/USAGE_AND_PRICING.md).
227
238
 
239
+ ## Compare two sessions
240
+
241
+ ```sh
242
+ agentguard-burn compare
243
+ agentguard-burn compare SESSION_ID
244
+ agentguard-burn compare SESSION_A SESSION_B
245
+ agentguard-burn compare SESSION_A SESSION_B json
246
+ ```
247
+
248
+ Run the same task once on each model, then put the two sessions side by side. With no session, `compare` takes the two most recent top-level sessions in the project of the newest one; with one, that session and the newest other top-level session in its project; with two, those two in the order given. Sessions resolve as they do for `why` (id, id suffix or transcript path). Sub-agent transcripts and other files Claude Code keeps beside a session are never picked. A Codex rollout's project is the working directory it recorded, and a spawned sub-agent rollout is skipped. Unless you name both, A is the session that started first. Fewer than two sessions exits 1 with one line saying how to pass two ids.
249
+
250
+ Both sessions are named first: the short id (the last part of the session id, which `compare` and `why` accept back), the time of the first recorded response in UTC, the model with the most output tokens (every model with at least 5% of output tokens, with its share, when there are several) and the project path. Each figure is the one `why` prints for that session, child transcripts included. Change is B against A, only where both values are numbers and A is not zero as printed; a dollar range compares midpoints, and an unpriced model prints `unpriced` with no change. The fixture in `tests/fixtures/compare-fixtures.ts` renders as:
251
+
252
+ ```text
253
+ AgentGuard compare: B against A
254
+ A aaaaaaaaaaaa started 2026-09-25 10:01 UTC
255
+ Output by model: claude-opus-5-5 92.3%, claude-haiku-4-5-20251001 7.7%
256
+ Project: /synthetic/project
257
+ B bbbbbbbbbbbb started 2026-09-25 11:01 UTC
258
+ Model: claude-sonnet-5
259
+ Project: /synthetic/project
260
+
261
+ Metric A B Change
262
+ Assistant responses 4 3 -25.0%
263
+ Input tokens 599,600 543,000 -9.4%
264
+ read from cache 200,000 360,000 +80.0%
265
+ cache writes 396,000 180,500 -54.4%
266
+ fresh input 3,600 2,500 -30.6%
267
+ Cache share 33.4% 66.3% +98.8%
268
+ Output tokens 6,500 4,000 -38.5%
269
+ Sub-agents launched 1 0 -100.0%
270
+ Full-prefix rewrites 2 1 -50.0%
271
+ List USD $2.13 $0.57 -73.3%
272
+ Totals include sub-agents.
273
+
274
+ Dollar figures are API list-price equivalents, not a bill.
275
+ AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task.
276
+ ```
277
+
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.
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
+
228
321
  ## Two safety planes
229
322
 
230
323
  Structural limits use active time rather than the age of the session. The
@@ -357,9 +450,16 @@ prompt. The prompt names the one limit that fired, for example:
357
450
  ```
358
451
  AgentGuard: 15 sub-agents in the last 15 active minutes. Limit: 15.
359
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.
360
454
  Allow this one launch? If you say no, nothing starts.
361
455
  ```
362
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
+
363
463
  You answer with one keypress. Claude never sees that text, and auto mode
364
464
  cannot approve it silently (Claude Code 2.1.211 and later), so the answer is
365
465
  yours. Where no prompt can appear (print mode, `bypassPermissions`, `dontAsk`,
@@ -368,9 +468,9 @@ ends with the override to run. In Claude Code, type it with `!` in front so it
368
468
  runs in your own shell:
369
469
 
370
470
  ```
371
- ! npx @agentguard-run/burn resume --once --reason "these 60 agents are the plan" # the next STOP passes, once, on any host
372
- ! npx @agentguard-run/burn resume --reason "load test" # every STOP passes for 15 minutes
373
- ! npx @agentguard-run/burn resume --clear
471
+ ! npx agentguard-burn resume --once --reason "these 60 agents are the plan" # the next STOP passes, once, on any host
472
+ ! npx agentguard-burn resume --reason "load test" # every STOP passes for 15 minutes
473
+ ! npx agentguard-burn resume --clear
374
474
  ```
375
475
 
376
476
  Only the person can override. A `!` command never passes through a hook, so
@@ -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);
@@ -230,6 +235,81 @@ async function main(argv) {
230
235
  show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))) } }, json ? JSON.stringify(transcript, null, 2) + '\n' : (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) }) + '\n', json);
231
236
  return 0;
232
237
  }
238
+ case 'compare': {
239
+ // Up to two session selectors, `json`, and `--lang` exactly as `why` takes it.
240
+ const args = [];
241
+ let lang, langGiven = false;
242
+ for (let i = 0; i < rest.length; i++) {
243
+ if (rest[i] === '--lang') {
244
+ langGiven = true;
245
+ lang = rest[++i];
246
+ }
247
+ else if (rest[i].startsWith('--lang=')) {
248
+ langGiven = true;
249
+ lang = rest[i].slice('--lang='.length);
250
+ }
251
+ else
252
+ args.push(rest[i]);
253
+ }
254
+ const json = args.includes('json') || args.includes('--json');
255
+ const selectors = args.filter(value => value !== 'json' && value !== '--json');
256
+ if ((langGiven && (0, i18n_1.whyLangOf)(lang) === null) || selectors.length > 2 || selectors.some(value => !value.trim() || value.startsWith('--'))) {
257
+ process.stderr.write('Usage: agentguard-burn compare [sessionA] [sessionB] [json] [--lang en|es|pt]\n');
258
+ return 64;
259
+ }
260
+ const language = (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() });
261
+ const { comparePicked, pickCompareSessions, renderCompare } = await Promise.resolve().then(() => __importStar(require('./insights/compare')));
262
+ const pick = pickCompareSessions(selectors);
263
+ if (!pick.ok) {
264
+ process.stderr.write(i18n_1.COMPARE_TEXT[language].fewerThanTwo(pick.found, pick.project) + '\n');
265
+ return 1;
266
+ }
267
+ const report = comparePicked(pick, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)));
268
+ show({ kind: 'command', command, values: { ...report } }, json ? JSON.stringify(report, null, 2) + '\n' : renderCompare(report, language) + '\n', json);
269
+ return 0;
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
+ }
233
313
  case 'quiet': {
234
314
  const [state, ...extra] = rest;
235
315
  if (extra.length || (state !== undefined && state !== 'on' && state !== 'off')) {
@@ -240,8 +320,8 @@ async function main(argv) {
240
320
  (0, upgrade_moments_1.setQuiet)(HOME, state === 'on');
241
321
  const quiet = quietOn();
242
322
  show({ kind: 'command', command, values: { tips: quiet ? 'off' : 'on', quiet: quiet ? 'on' : 'off', file: (0, upgrade_moments_1.quietFile)(HOME) } }, quiet
243
- ? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx @agentguard-run/burn quiet off\n'
244
- : 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx @agentguard-run/burn quiet on\n');
323
+ ? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx agentguard-burn quiet off\n'
324
+ : 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx agentguard-burn quiet on\n');
245
325
  return 0;
246
326
  }
247
327
  case 'rewrites':
@@ -465,7 +545,7 @@ async function main(argv) {
465
545
  return 2;
466
546
  }
467
547
  savePolicy({ ...policy, mode: 'enforce' });
468
- show({ kind: 'command', command, values: { mode: 'enforce' } }, 'Enforcement ON. The next STOP will block the spawn.\n');
548
+ show({ kind: 'command', command, values: { mode: 'enforce' } }, 'Enforcement ON. In an interactive Claude Code session the next STOP asks you first; where nobody can answer, it refuses the launch.\n');
469
549
  return 0;
470
550
  }
471
551
  case 'shadow': {
@@ -493,7 +573,7 @@ async function main(argv) {
493
573
  return 0;
494
574
  }
495
575
  default:
496
- show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', '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|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' +
497
577
  ' ps [--json] local agent processes, held memory and workspace disk\n' +
498
578
  ' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
499
579
  ' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
@@ -506,6 +586,8 @@ async function main(argv) {
506
586
  ' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
507
587
  ' why [session] token attribution and API list-price equivalents\n' +
508
588
  ' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
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' +
509
591
  ' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
510
592
  ' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
511
593
  ' pace [session] ten-minute pace and next-hour projection\n' +
@@ -527,7 +609,7 @@ async function main(argv) {
527
609
  'Developer review commands (never installed as hooks):\n' +
528
610
  ' guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]\n' +
529
611
  ' deduplicate recorded shell text; --rank explicitly permits jsort provider requests\n');
530
- return command ? 64 : 0;
612
+ return !command || command === 'help' || command === '--help' || command === '-h' ? 0 : 64;
531
613
  }
532
614
  }
533
615
  async function run() {
@@ -573,7 +655,19 @@ async function run() {
573
655
  throw error;
574
656
  }
575
657
  }
576
- 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) => {
577
671
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
578
- process.exit(4);
672
+ exit(4);
579
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)