@agentguard-run/burn 0.3.26 → 0.3.28

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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.28 (2026-10-03)
4
+
5
+ - `why --commits` gives no per-commit figure when other local sessions overlap the window in the same repository: the commits can't be split between sessions, so the line says so instead of printing a number that would credit this session with other sessions' commits.
6
+ - `why --commits` (opt-in) adds what a session's tokens bought, counted in commits that landed while it ran: `What it bought: 12 commits landed while this session ran (9 co-authored by Claude Code). 844,000,000 tokens per commit co-authored by Claude Code.` The line sits after the report's measurements and before the tip, so the report still ends with the tip. Without the flag `why` never runs git and never reads a repository, and its output, `why json` included, is what 0.3.27 prints.
7
+ - The window runs from the session's first record through its last record plus 10 minutes, a stored sub-agent's records included. A commit counts when its committer time falls inside, both edges included, once per hash, from every branch, tag, remote-tracking ref and worktree of the repository; a stash and git notes do not count. A Co-authored-by trailer with Claude's address (`noreply@anthropic.com`), or naming Claude with no other address, makes it co-authored by Claude Code; Codex's own trailer, `Co-authored-by: Codex <noreply@openai.com>`, which Codex adds when its commit attribution is on, makes it co-authored by Codex.
8
+ - The per-commit figure divides the session's tokens by the commits Claude Code or Codex co-authored (a commit naming both counts once), and its label names them (`by Claude Code`, `by Codex`, `by Claude Code or Codex`), so teammates' commits fetched into the repository never lower it. Only when no commit in the window names either agent does it divide by every landed commit, labeled `tokens per landed commit`.
9
+ - git stops following a branch at a commit dated before `--since`, so the log is asked from two days before the window and the exact window is applied by Burn: a commit with an out-of-order date no longer hides the commits under it.
10
+ - Other local sessions in the same repository whose windows overlap this one add `shared with N overlapping sessions`, since their commits can't be split between sessions.
11
+ - What it reads: the time and recorded working directory on the first and last records of the session's transcripts and of the other local sessions; from git, `rev-parse --show-toplevel --git-common-dir` and one `log` whose format is `%H`, `%ct` and the Co-authored-by trailers only. Counts only: no hash, email, message, file name or path is printed or kept, and nothing leaves the computer.
12
+ - Every git call shares a 2 second budget and is killed when it runs out. No repository, a missing git, a timeout, or a transcript that records no directory or time ends the line with that reason and never stops the report.
13
+ - `why json --commits` adds `commits: {status, landed, coAuthoredByClaudeCode, coAuthoredByCodex, coAuthored, overlappingSessions, tokensPerLandedCommit, tokensPerCoAuthoredCommit, perCommitBasis, graceMinutes}`; `perCommitBasis` (`coAuthored` or `landed`) names the figure the line prints.
14
+ - Spanish and Portuguese say the same, in the same tone: "844,000,000 tokens por commit con coautoría de Claude Code", "844,000,000 tokens por commit em coautoria com o Claude Code".
15
+ - `calendar` has no `--commits`: its daily counts keep no working directory or session times, by design, so a week's commits could not be counted again once Claude Code deletes a transcript.
16
+ - Tests: 560 (559 pass, 1 skipped), up from 537. The new ones build git repositories in temp directories with fixed commit dates and check the window edges, the grace, an out-of-order commit date, deduplication, the trailers, a team repository, attribution turned off, Claude Code and Codex together, overlapping sessions, a missing git, a hung git and that `why` without the flag starts no process at all.
17
+
18
+ ## 0.3.27 (2026-10-02)
19
+
20
+ - `why` and every other command that reads one session no longer stop on a session file over about 512 MB. A transcript over 256 MB is now read in 16 MB pieces cut at line ends, the way `calendar` reads every file, so no single string has to hold the whole file, and the report equals a whole-file read. One long-running Claude Code session had reached 568 MB, and `why` on it stopped with "Cannot create a string longer than 0x1fffffe8 characters"; it now reports in about 9 seconds. Files up to 256 MB are read exactly as before.
21
+ - Tests: 537 (536 pass, 1 skipped).
22
+
3
23
  ## 0.3.26 (2026-10-02)
4
24
 
5
25
  - Sub-agents that started, used tokens and ended without finishing now show up in `why`, `calendar` and the STOP line. A sub-agent counts only on terminal evidence: Claude Code recorded the status of its task notification as `failed`, `killed` or `stopped`, and never recorded it as `completed` or resumed (a SendMessage result that started it again). One launched in the background with no end recorded may still be running, so it never counts. A launch refused before it started (a hook, a permission rule, your no) has no transcript and used no tokens, so it is not counted either. Burn has no rule for a session being over, so it relies on these records alone. It knows whether a sub-agent finished, never whether its work was right, so every line says "ended without finishing", never "failed".
package/README.md CHANGED
@@ -238,6 +238,40 @@ Optional settings in your existing `burn-policy.json`:
238
238
 
239
239
  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).
240
240
 
241
+ ### What it bought: `why --commits`
242
+
243
+ ```sh
244
+ agentguard-burn why --commits
245
+ agentguard-burn why SESSION_ID --commits
246
+ agentguard-burn why SESSION_ID json --commits
247
+ ```
248
+
249
+ `why` shows where a session's tokens went; `--commits` adds what they bought, counted in commits that landed while the session ran. It is one line after the report's measurements and before the tip:
250
+
251
+ ```text
252
+ What it bought: 12 commits landed while this session ran (9 co-authored by Claude Code). 844,000,000 tokens per commit co-authored by Claude Code.
253
+ ```
254
+
255
+ It is off by default. Without `--commits`, `why` never runs git and never reads a repository, and its output, `why json` included, is unchanged.
256
+
257
+ With `--commits`, and only then, Burn reads:
258
+
259
+ - From the session's transcripts (the session and the sub-agents stored with it): the time on its first and last records and the working directory the host recorded there (Claude Code's `cwd`; Codex's `session_meta` and `turn_context`). No message content is kept.
260
+ - From your other local Claude Code and Codex transcripts: the same fields from their first and last records, to find sessions that ran at the same time in the same repository.
261
+ - From git, on this computer: `git -C <cwd> rev-parse --show-toplevel --git-common-dir` to find the repository (for this session, and for each other directory found running at the same time), then one `git log --exclude=refs/stash --exclude=refs/notes/* --all --since=@<start minus 2 days> --until=@<end> --format=%H%x00%ct%x00%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x01)`, which prints each commit's hash, committer time and Co-authored-by trailers and nothing else of it. Every git call shares 2 seconds; past that the call is killed.
262
+
263
+ All of it stays on this computer, and nothing is stored. The line and the json carry counts only, never a hash, an email, a commit message, a file name or a path. `why json --commits` adds `commits: {status, landed, coAuthoredByClaudeCode, coAuthoredByCodex, coAuthored, overlappingSessions, tokensPerLandedCommit, tokensPerCoAuthoredCommit, perCommitBasis, graceMinutes}`, with `status` one of `ok`, `no_repository`, `unrecorded`, `git_missing`, `git_timeout` or `git_error`.
264
+
265
+ How it counts:
266
+
267
+ - The window runs from the session's first record through its last record plus 10 minutes, so the commit that closes a session counts. A stored sub-agent's records widen it. A commit counts when its committer time falls inside, both edges included, and each hash counts once, whichever branches, tags, remote-tracking refs or worktrees hold it. git stops following a branch at a commit dated before the time it is asked from, so it is asked from two days before the window and Burn applies the exact window itself: a commit with an out-of-order date (a skewed clock) hides nothing under it unless it is dated more than two days before the window. A stash and git notes are not landed commits. A rebase or cherry-pick inside the window makes new commits, and they count, as does a teammate's commit fetched with its time inside the window. A session resumed days later has a window that spans the days in between.
268
+ - A commit is co-authored by Claude Code when a `Co-authored-by` trailer carries Claude's address (`noreply@anthropic.com`), or names Claude with no address or an anthropic.com one; a person named Claude with their own address is not. Codex appends `Co-authored-by: Codex <noreply@openai.com>` when its commit attribution is on, and those commits are co-authored by Codex. The session's own host is always named; the other only when it co-authored any.
269
+ - When other local sessions ran in the same repository during the window (in a worktree of it too), the line says `shared with N overlapping sessions`: those commits can't be split between sessions, so the line and the json then give no per-commit figure. A Claude Code sub-agent belongs to its session, as in the rest of `why`; a Codex sub-agent keeps its own rollout, which `why` reads as a session of its own, so it counts as one here.
270
+ - The per-commit figure is the token total the report's header prints, divided by the commits in the window that Claude Code or Codex co-authored (a commit naming both counts once), and its label names them: `tokens per commit co-authored by Claude Code`, `by Codex`, or `by Claude Code or Codex`. So a teammate's commits, fetched or local, count as landed but never lower it. Only when no commit in the window names either agent, as when commit attribution is off, does it divide by every landed commit, and the line then says `tokens per landed commit`. `why json` carries both, `tokensPerCoAuthoredCommit` (null when the agents co-authored none) and `tokensPerLandedCommit`, and `perCommitBasis` (`coAuthored` or `landed`) says which one the line prints.
271
+ - With no commit, the line says `What it bought: no commits landed while this session ran.` A directory that is no repository, a missing git, a git that does not answer within 2 seconds, or a transcript that records no directory or time ends the line with that reason; the rest of the report is unchanged and the exit code stays 0.
272
+
273
+ A landed commit is a count, not a judgment of the work in it. The line is in Spanish and Portuguese with the rest of `why`. `calendar` has no `--commits`: its daily counts keep no working directory and no session times, by design, so a week's commits could not be counted again once Claude Code deletes a transcript after 30 days.
274
+
241
275
  ## Compare two sessions
242
276
 
243
277
  ```sh
@@ -701,6 +735,7 @@ A provenance JSON beside the requested MP4 records the source recording's SHA256
701
735
  ## What it never does
702
736
 
703
737
  Runtime observation and enforcement do not persist or render prompts, responses, file contents or tool inputs. The explicit developer `guard-candidates` command copies shell text already present in a ledger into a private review; only its `--rank` option can send that text to the selected provider.
738
+ `why` runs git only with `--commits`, and then reads commit hashes, times and co-author trailers on this computer and prints counts alone.
704
739
  No telemetry. No provider-quota guesses. Account forecasts use only observed host percentages, never an invented allowance or cache weighting.
705
740
 
706
741
  ### Local live panel
package/dist/src/cli.js CHANGED
@@ -212,8 +212,9 @@ async function main(argv) {
212
212
  }
213
213
  case 'why': {
214
214
  // `--lang en|es|pt` (or --lang=es) picks the report's language and is never a session selector.
215
+ // `--commits` adds the commits that landed while the session ran. It is the only way `why` runs git.
215
216
  const args = [];
216
- let lang, langGiven = false;
217
+ let lang, langGiven = false, withCommits = false;
217
218
  for (let i = 0; i < rest.length; i++) {
218
219
  if (rest[i] === '--lang') {
219
220
  langGiven = true;
@@ -223,6 +224,8 @@ async function main(argv) {
223
224
  langGiven = true;
224
225
  lang = rest[i].slice('--lang='.length);
225
226
  }
227
+ else if (rest[i] === '--commits')
228
+ withCommits = true;
226
229
  else
227
230
  args.push(rest[i]);
228
231
  }
@@ -233,7 +236,11 @@ async function main(argv) {
233
236
  const location = (0, sessions_1.selectInsightTranscript)(args.find(value => value !== 'json'));
234
237
  const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId });
235
238
  const json = args.includes('json');
236
- 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);
239
+ // The commits reader is loaded only with the flag, so a plain `why` never reaches it.
240
+ const commits = withCommits ? await (await Promise.resolve().then(() => __importStar(require('./insights/commits')))).sessionCommits({ path: location.path }) : undefined;
241
+ const commitsValue = commits ? (0, render_2.commitsJson)(commits, transcript.state.forkHistoryBoundaryUnknown ? null : (0, render_2.sessionFigures)(transcript).attribution.totalTokens) : undefined;
242
+ 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)))), ...(commitsValue ? { commits: commitsValue } : {}) } }, json ? JSON.stringify(commitsValue ? { ...transcript, commits: commitsValue } : transcript, null, 2) + '\n'
243
+ : (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() }), ...(commits ? { commits } : {}) }) + '\n', json);
237
244
  return 0;
238
245
  }
239
246
  case 'compare': {
@@ -622,6 +629,7 @@ async function main(argv) {
622
629
  ' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
623
630
  ' why [session] token attribution and API list-price equivalents\n' +
624
631
  ' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
632
+ ' --commits count the commits that landed in its git repository while it ran (runs git on this computer; off by default)\n' +
625
633
  ' compare [sessionA] [sessionB] two sessions side by side: tokens, cache, sub-agents, rewrites, list USD; json and --lang as for why\n' +
626
634
  ' 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' +
627
635
  ' card [--weeks N] [--out file.png] the calendar\'s totals as one 1200x675 image to share (default 4 weeks); written locally, nothing uploaded\n' +
@@ -0,0 +1,84 @@
1
+ import { COMMIT_GRACE_MS, GIT_BUDGET_MS, type SessionCommits } from './types';
2
+ export { COMMIT_GRACE_MS, GIT_BUDGET_MS };
3
+ /** Each commit's hash, committer time and Co-authored-by trailer values, one commit per line: nothing else of a commit. */
4
+ export declare const COMMIT_LOG_FORMAT = "%H%x00%ct%x00%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x01)";
5
+ /** The repository a working directory belongs to: its top level, and the directory its worktrees share. */
6
+ export declare const repositoryArguments: (cwd: string) => string[];
7
+ /**
8
+ * git stops following a branch at the first commit dated before `--since`, so a
9
+ * commit whose date is out of order (a skewed clock, a date set by hand) would
10
+ * hide every commit under it. git is asked from this much earlier, and the exact
11
+ * window is applied in parseCommitLog: only a commit dated more than two days
12
+ * before the window, on top of commits inside it, can still hide them.
13
+ */
14
+ export declare const LOG_SLACK_SECONDS: number;
15
+ /**
16
+ * Commits reachable from any ref (branches, tags, remote-tracking refs, HEAD)
17
+ * whose committer time is from LOG_SLACK_SECONDS before `since` through
18
+ * `until`, in whole seconds; parseCommitLog keeps the exact window. A stash and
19
+ * notes are left out: neither is a commit that landed. Signature checks stay
20
+ * off, so no signing program runs.
21
+ */
22
+ export declare function commitLogArguments(root: string, sinceSeconds: number, untilSeconds: number): string[];
23
+ /** When one transcript file ran, and where. */
24
+ export interface TranscriptSpan {
25
+ /** The first record's time; null when the start of the file records none. */
26
+ first: number | null;
27
+ /** The last record's time, or the file's modification time when the end of the file records none. */
28
+ last: number | null;
29
+ /** The first working directory the file records. */
30
+ cwd: string | null;
31
+ }
32
+ /** The first record with a time and the first with a working directory, from the start of the file; the last record with a time, from its end. */
33
+ export declare function transcriptSpan(path: string): TranscriptSpan | null;
34
+ /** A session's own transcript files, as `why` reads them: the session, then each child stored in its `subagents` folder. */
35
+ export declare function sessionFiles(path: string): string[];
36
+ /** The session's window, first record to last record (the grace is added by the caller), and its first recorded working directory. */
37
+ export declare function sessionSpan(files: string[]): {
38
+ start: number;
39
+ end: number;
40
+ cwd: string | null;
41
+ } | null;
42
+ /**
43
+ * Which agent a Co-authored-by value names: Claude Code when it carries
44
+ * Claude's address (noreply@anthropic.com), or names Claude with no address or
45
+ * an anthropic.com one; Codex when it names Codex with no address or an
46
+ * openai.com one (Codex appends `Co-authored-by: Codex <noreply@openai.com>`
47
+ * when its commit attribution is on). A person who happens to be called Claude,
48
+ * with their own address, is not an agent.
49
+ */
50
+ export declare function coAuthorAgent(value: string): 'claude' | 'codex' | null;
51
+ /**
52
+ * The commits `git log` printed with COMMIT_LOG_FORMAT whose committer time is
53
+ * in [since, until] seconds, each hash counted once, and how many name each
54
+ * agent as co-author. Null when this git printed the trailer placeholder back
55
+ * (it predates trailer options), so no count can be trusted.
56
+ */
57
+ export declare function parseCommitLog(stdout: string, sinceSeconds: number, untilSeconds: number): {
58
+ landed: number;
59
+ claudeCode: number;
60
+ codex: number;
61
+ coAuthored: number;
62
+ } | null;
63
+ export interface SessionCommitsOptions {
64
+ /** The session's transcript, as `why` selected it. */
65
+ path: string;
66
+ /** Where the other local sessions are found: Claude Code's projects and Codex's sessions under the home directory by default. */
67
+ roots?: {
68
+ claude: string;
69
+ codex: string;
70
+ };
71
+ /** The environment git runs with, PATH included; this process's by default. */
72
+ env?: NodeJS.ProcessEnv;
73
+ /** Tests only: the git budget, GIT_BUDGET_MS by default. */
74
+ budgetMs?: number;
75
+ }
76
+ /**
77
+ * The commits that landed in the session's repository while it ran: committer
78
+ * time from the session's first record through its last record plus
79
+ * COMMIT_GRACE_MS. The repository is the one holding the first working
80
+ * directory the session records. A missing git, a timeout, a directory that is
81
+ * no repository or a transcript that records no directory or time is a status,
82
+ * never an exception.
83
+ */
84
+ export declare function sessionCommits(options: SessionCommitsOptions): Promise<SessionCommits>;
@@ -0,0 +1,379 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOG_SLACK_SECONDS = exports.repositoryArguments = exports.COMMIT_LOG_FORMAT = exports.GIT_BUDGET_MS = exports.COMMIT_GRACE_MS = void 0;
4
+ exports.commitLogArguments = commitLogArguments;
5
+ exports.transcriptSpan = transcriptSpan;
6
+ exports.sessionFiles = sessionFiles;
7
+ exports.sessionSpan = sessionSpan;
8
+ exports.coAuthorAgent = coAuthorAgent;
9
+ exports.parseCommitLog = parseCommitLog;
10
+ exports.sessionCommits = sessionCommits;
11
+ /**
12
+ * `why --commits`: what a session's tokens bought, counted in commits that
13
+ * landed while it ran. Opt-in: the CLI loads this module only when the flag is
14
+ * given, so without it `why` never runs git and never reads a repository.
15
+ *
16
+ * From transcripts it takes only each record's time and the working directory
17
+ * the host recorded (Claude Code writes `cwd` on its records, Codex on its
18
+ * session_meta and turn_context payloads), from the first and last records of
19
+ * the session's own files and of the other local sessions, to find the ones that
20
+ * overlap it in the same repository. No message content is kept. From git it
21
+ * reads only each commit's hash, committer time and Co-authored-by trailers, and
22
+ * keeps counts: no hash, email, message, file name or path leaves this module,
23
+ * and nothing leaves the computer.
24
+ */
25
+ const node_child_process_1 = require("node:child_process");
26
+ const node_fs_1 = require("node:fs");
27
+ const node_path_1 = require("node:path");
28
+ const sessions_1 = require("./sessions");
29
+ const types_1 = require("./types");
30
+ Object.defineProperty(exports, "COMMIT_GRACE_MS", { enumerable: true, get: function () { return types_1.COMMIT_GRACE_MS; } });
31
+ Object.defineProperty(exports, "GIT_BUDGET_MS", { enumerable: true, get: function () { return types_1.GIT_BUDGET_MS; } });
32
+ /** Each commit's hash, committer time and Co-authored-by trailer values, one commit per line: nothing else of a commit. */
33
+ exports.COMMIT_LOG_FORMAT = '%H%x00%ct%x00%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x01)';
34
+ /** The repository a working directory belongs to: its top level, and the directory its worktrees share. */
35
+ const repositoryArguments = (cwd) => ['-C', cwd, 'rev-parse', '--show-toplevel', '--git-common-dir'];
36
+ exports.repositoryArguments = repositoryArguments;
37
+ /**
38
+ * git stops following a branch at the first commit dated before `--since`, so a
39
+ * commit whose date is out of order (a skewed clock, a date set by hand) would
40
+ * hide every commit under it. git is asked from this much earlier, and the exact
41
+ * window is applied in parseCommitLog: only a commit dated more than two days
42
+ * before the window, on top of commits inside it, can still hide them.
43
+ */
44
+ exports.LOG_SLACK_SECONDS = 2 * 24 * 60 * 60;
45
+ /**
46
+ * Commits reachable from any ref (branches, tags, remote-tracking refs, HEAD)
47
+ * whose committer time is from LOG_SLACK_SECONDS before `since` through
48
+ * `until`, in whole seconds; parseCommitLog keeps the exact window. A stash and
49
+ * notes are left out: neither is a commit that landed. Signature checks stay
50
+ * off, so no signing program runs.
51
+ */
52
+ function commitLogArguments(root, sinceSeconds, untilSeconds) {
53
+ return ['-C', root, '-c', 'core.fsmonitor=false', '-c', 'log.showSignature=false', 'log', '--exclude=refs/stash', '--exclude=refs/notes/*', '--all',
54
+ `--since=@${sinceSeconds - exports.LOG_SLACK_SECONDS}`, `--until=@${untilSeconds}`, `--format=${exports.COMMIT_LOG_FORMAT}`];
55
+ }
56
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
57
+ /** A record time as the usage parser reads it: an ISO string, or epoch seconds or milliseconds. */
58
+ function millis(value) {
59
+ if (typeof value === 'string') {
60
+ const parsed = Date.parse(value);
61
+ return Number.isFinite(parsed) ? parsed : undefined;
62
+ }
63
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0)
64
+ return value < 100_000_000_000 ? value * 1000 : value;
65
+ return undefined;
66
+ }
67
+ /** One record's time and recorded working directory. Nothing else of the record is kept. */
68
+ function recordFacts(line) {
69
+ if (!line.trim())
70
+ return null;
71
+ let value;
72
+ try {
73
+ value = JSON.parse(line);
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ const record = object(value), payload = object(record.payload);
79
+ const at = millis(record.timestamp ?? record.created_at ?? payload.timestamp);
80
+ const cwd = typeof record.cwd === 'string' ? record.cwd : record.type === 'session_meta' || record.type === 'turn_context' ? payload.cwd : undefined;
81
+ return { ...(at !== undefined ? { at } : {}), ...(typeof cwd === 'string' && cwd.length > 0 ? { cwd } : {}) };
82
+ }
83
+ /** A transcript is read from its start or its end, first this much and then at most the larger amount, so a long session is never read whole. */
84
+ const SCAN_BYTES = [256 * 1024, 16 * 1024 * 1024];
85
+ /** The complete lines among the first or last `bytes` of a file; the line the cut splits is dropped. */
86
+ function edgeLines(fd, size, bytes, fromEnd) {
87
+ const length = Math.min(size, bytes), position = fromEnd ? size - length : 0, buffer = Buffer.alloc(length);
88
+ let read = 0;
89
+ while (read < length) {
90
+ const got = (0, node_fs_1.readSync)(fd, buffer, read, length - read, position + read);
91
+ if (!got)
92
+ break;
93
+ read += got;
94
+ }
95
+ const lines = buffer.subarray(0, read).toString('utf8').split('\n');
96
+ if (length < size) {
97
+ if (fromEnd)
98
+ lines.shift();
99
+ else
100
+ lines.pop();
101
+ }
102
+ return lines;
103
+ }
104
+ /** The first record with a time and the first with a working directory, from the start of the file; the last record with a time, from its end. */
105
+ function transcriptSpan(path) {
106
+ let fd;
107
+ try {
108
+ fd = (0, node_fs_1.openSync)(path, 'r');
109
+ const info = (0, node_fs_1.fstatSync)(fd), size = info.size;
110
+ let first = null, cwd = null, last = null;
111
+ for (const bytes of SCAN_BYTES) {
112
+ for (const line of edgeLines(fd, size, bytes, false)) {
113
+ const facts = recordFacts(line);
114
+ if (!facts)
115
+ continue;
116
+ if (first === null && facts.at !== undefined)
117
+ first = facts.at;
118
+ if (cwd === null && facts.cwd !== undefined)
119
+ cwd = facts.cwd;
120
+ if (first !== null && cwd !== null)
121
+ break;
122
+ }
123
+ if ((first !== null && cwd !== null) || bytes >= size)
124
+ break;
125
+ }
126
+ for (const bytes of SCAN_BYTES) {
127
+ const lines = edgeLines(fd, size, bytes, true);
128
+ for (let i = lines.length - 1; i >= 0 && last === null; i--)
129
+ last = recordFacts(lines[i])?.at ?? null;
130
+ if (last !== null || bytes >= size)
131
+ break;
132
+ }
133
+ return { first, last: first === null ? last : last ?? info.mtimeMs, cwd };
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ finally {
139
+ if (fd !== undefined)
140
+ (0, node_fs_1.closeSync)(fd);
141
+ }
142
+ }
143
+ /** A session's own transcript files, as `why` reads them: the session, then each child stored in its `subagents` folder. */
144
+ function sessionFiles(path) {
145
+ const files = [path], children = (0, node_path_1.join)(path.replace(/\.jsonl$/, ''), 'subagents');
146
+ try {
147
+ for (const name of (0, node_fs_1.readdirSync)(children).filter(name => name.endsWith('.jsonl')).sort())
148
+ files.push((0, node_path_1.join)(children, name));
149
+ }
150
+ catch { /* no sub-agents stored */ }
151
+ return files;
152
+ }
153
+ /** The session's window, first record to last record (the grace is added by the caller), and its first recorded working directory. */
154
+ function sessionSpan(files) {
155
+ let start = Infinity, end = -Infinity, cwd = null;
156
+ for (const file of files) {
157
+ const span = transcriptSpan(file);
158
+ if (!span)
159
+ continue;
160
+ cwd ??= span.cwd;
161
+ if (span.first === null)
162
+ continue;
163
+ start = Math.min(start, span.first);
164
+ end = Math.max(end, span.first, span.last ?? span.first);
165
+ }
166
+ return Number.isFinite(start) ? { start, end, cwd } : null;
167
+ }
168
+ const STATUS = { missing: 'git_missing', timeout: 'git_timeout', failed: 'git_error' };
169
+ /** Variables that point git at another repository, as a git hook or a script can leave them; the session's own directory decides instead. */
170
+ const REPOSITORY_VARIABLES = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_PREFIX'];
171
+ /** A long session in a busy repository is thousands of commits at about 100 bytes each. */
172
+ const MAX_LOG_BYTES = 64 * 1024 * 1024;
173
+ function gitEnvironment(env) {
174
+ const result = { ...env };
175
+ for (const key of REPOSITORY_VARIABLES)
176
+ delete result[key];
177
+ // English messages to tell "not a repository" apart; no lock taken, no prompt, and no object fetched from a remote.
178
+ return { ...result, LC_ALL: 'C', GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', GIT_NO_LAZY_FETCH: '1' };
179
+ }
180
+ /**
181
+ * One git call: answered as a timeout the moment its share of the budget runs
182
+ * out, and killed with SIGKILL then. The kill is sent here, not through an abort
183
+ * signal: execFile hands an abort signal to spawn without its killSignal, so an
184
+ * abort would only send SIGTERM.
185
+ */
186
+ function runGit(args, env, timeoutMs) {
187
+ return new Promise(settle => {
188
+ if (!(timeoutMs > 0)) {
189
+ settle({ kind: 'timeout' });
190
+ return;
191
+ }
192
+ let done = false, child;
193
+ const finish = (result) => { if (done)
194
+ return; done = true; clearTimeout(timer); settle(result); };
195
+ const timer = setTimeout(() => { finish({ kind: 'timeout' }); child?.kill('SIGKILL'); }, timeoutMs);
196
+ try {
197
+ child = (0, node_child_process_1.execFile)('git', args, { env: gitEnvironment(env), maxBuffer: MAX_LOG_BYTES, encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {
198
+ if (!error)
199
+ finish({ kind: 'ok', stdout });
200
+ else if (error.code === 'ENOENT')
201
+ finish({ kind: 'missing' });
202
+ else
203
+ finish({ kind: 'failed', stderr: String(stderr ?? '') });
204
+ });
205
+ }
206
+ catch {
207
+ finish({ kind: 'missing' });
208
+ }
209
+ });
210
+ }
211
+ /** Wall time spent waiting on git, shared by every call of one report. */
212
+ class GitBudget {
213
+ limitMs;
214
+ spent = 0;
215
+ constructor(limitMs) {
216
+ this.limitMs = limitMs;
217
+ }
218
+ async run(work) {
219
+ const started = Date.now();
220
+ try {
221
+ return await work(this.limitMs - this.spent);
222
+ }
223
+ finally {
224
+ this.spent += Date.now() - started;
225
+ }
226
+ }
227
+ }
228
+ const realPath = (path) => { try {
229
+ return (0, node_fs_1.realpathSync)(path);
230
+ }
231
+ catch {
232
+ return (0, node_path_1.resolve)(path);
233
+ } };
234
+ const isDirectory = (path) => { try {
235
+ return (0, node_fs_1.statSync)(path).isDirectory();
236
+ }
237
+ catch {
238
+ return false;
239
+ } };
240
+ /** `rev-parse` printed the top level and the shared git directory, the second relative to `cwd` when git prints it that way. */
241
+ function parseRepository(cwd, stdout) {
242
+ const [root, common] = stdout.split('\n').map(line => line.trim());
243
+ return root && common ? { root, common: realPath((0, node_path_1.resolve)(cwd, common)) } : null;
244
+ }
245
+ const NOT_A_REPOSITORY = /not a git repository|must be run in a work tree/i;
246
+ async function repositoryOf(cwd, env, budget) {
247
+ if (!isDirectory(cwd))
248
+ return { kind: 'none' };
249
+ const result = await budget.run(timeout => runGit((0, exports.repositoryArguments)(cwd), env, timeout));
250
+ if (result.kind === 'failed' && NOT_A_REPOSITORY.test(result.stderr))
251
+ return { kind: 'none' };
252
+ if (result.kind !== 'ok')
253
+ return result;
254
+ const repository = parseRepository(cwd, result.stdout);
255
+ return repository ? { kind: 'repository', repository } : { kind: 'failed', stderr: '' };
256
+ }
257
+ /**
258
+ * Which agent a Co-authored-by value names: Claude Code when it carries
259
+ * Claude's address (noreply@anthropic.com), or names Claude with no address or
260
+ * an anthropic.com one; Codex when it names Codex with no address or an
261
+ * openai.com one (Codex appends `Co-authored-by: Codex <noreply@openai.com>`
262
+ * when its commit attribution is on). A person who happens to be called Claude,
263
+ * with their own address, is not an agent.
264
+ */
265
+ function coAuthorAgent(value) {
266
+ const [, rawName = '', rawEmail = ''] = /^([^<]*)(?:<([^>]*)>)?/.exec(value.trim()) ?? [];
267
+ const name = rawName.trim(), email = (rawEmail.trim() || (name.includes('@') ? name : '')).toLowerCase();
268
+ if (email === 'noreply@anthropic.com')
269
+ return 'claude';
270
+ if (/^claude\b/i.test(name) && (!email || email.endsWith('@anthropic.com')))
271
+ return 'claude';
272
+ if (/^codex\b/i.test(name) && (!email || email.endsWith('@openai.com')))
273
+ return 'codex';
274
+ return null;
275
+ }
276
+ /**
277
+ * The commits `git log` printed with COMMIT_LOG_FORMAT whose committer time is
278
+ * in [since, until] seconds, each hash counted once, and how many name each
279
+ * agent as co-author. Null when this git printed the trailer placeholder back
280
+ * (it predates trailer options), so no count can be trusted.
281
+ */
282
+ function parseCommitLog(stdout, sinceSeconds, untilSeconds) {
283
+ const seen = new Set();
284
+ let claudeCode = 0, codex = 0, coAuthored = 0;
285
+ for (const line of stdout.split('\n')) {
286
+ const [hash, time, trailers = ''] = line.split('\0');
287
+ if (trailers.startsWith('%('))
288
+ return null;
289
+ if (!hash || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(hash) || !time || !/^\d+$/.test(time))
290
+ continue;
291
+ const at = Number(time);
292
+ if (at < sinceSeconds || at > untilSeconds || seen.has(hash))
293
+ continue;
294
+ seen.add(hash);
295
+ const agents = new Set(trailers.split('\x01').map(coAuthorAgent));
296
+ if (agents.has('claude'))
297
+ claudeCode++;
298
+ if (agents.has('codex'))
299
+ codex++;
300
+ if (agents.has('claude') || agents.has('codex'))
301
+ coAuthored++;
302
+ }
303
+ return { landed: seen.size, claudeCode, codex, coAuthored };
304
+ }
305
+ const counts = (status) => ({ status, landed: 0, claudeCode: 0, codex: 0, coAuthored: 0, overlappingSessions: 0 });
306
+ /**
307
+ * The commits that landed in the session's repository while it ran: committer
308
+ * time from the session's first record through its last record plus
309
+ * COMMIT_GRACE_MS. The repository is the one holding the first working
310
+ * directory the session records. A missing git, a timeout, a directory that is
311
+ * no repository or a transcript that records no directory or time is a status,
312
+ * never an exception.
313
+ */
314
+ async function sessionCommits(options) {
315
+ const env = options.env ?? process.env, budget = new GitBudget(options.budgetMs ?? types_1.GIT_BUDGET_MS);
316
+ const own = sessionFiles(options.path), span = sessionSpan(own);
317
+ if (!span || span.cwd === null)
318
+ return counts('unrecorded');
319
+ const found = await repositoryOf(span.cwd, env, budget);
320
+ if (found.kind === 'none')
321
+ return counts('no_repository');
322
+ if (found.kind !== 'repository')
323
+ return counts(STATUS[found.kind]);
324
+ const [since, until] = windowSeconds(span.start, span.end);
325
+ const log = await budget.run(timeout => runGit(commitLogArguments(found.repository.root, since, until), env, timeout));
326
+ if (log.kind !== 'ok')
327
+ return counts(STATUS[log.kind]);
328
+ const landed = parseCommitLog(log.stdout, since, until);
329
+ if (!landed)
330
+ return counts('git_error');
331
+ if (landed.landed === 0)
332
+ return { status: 'ok', ...landed, overlappingSessions: 0 };
333
+ const overlapping = await overlappingSessions({ own, since, until, cwd: span.cwd, repository: found.repository,
334
+ roots: options.roots ?? (0, sessions_1.transcriptRoots)(), env, budget });
335
+ return typeof overlapping === 'number' ? { status: 'ok', ...landed, overlappingSessions: overlapping } : counts(overlapping);
336
+ }
337
+ /** A window in the whole seconds commits are counted in: first record through last record plus the grace. */
338
+ const windowSeconds = (first, last) => [Math.floor(first / 1000), Math.floor((last + types_1.COMMIT_GRACE_MS) / 1000)];
339
+ /**
340
+ * Other local sessions whose windows overlap this one, in the whole seconds both
341
+ * count commits in, in the same repository (a worktree of it counts, since it
342
+ * shares its commits). A session's stored sub-agents belong to it, as `why`
343
+ * reads them, so they are never counted on their own. A session in the same
344
+ * recorded directory needs no git call; any other directory is asked once.
345
+ */
346
+ async function overlappingSessions(input) {
347
+ const own = new Set(input.own.map(realPath));
348
+ const byDirectory = new Map();
349
+ for (const location of (0, sessions_1.discoverInsightTranscripts)(input.roots)) {
350
+ if (location.host === 'claude' && ((0, sessions_1.isSubagentTranscript)(location) || (0, sessions_1.isSessionSidecar)(location)))
351
+ continue;
352
+ // A file last written before the window opened cannot reach into it.
353
+ if (windowSeconds(location.modifiedAt, location.modifiedAt)[1] < input.since || own.has(realPath(location.path)))
354
+ continue;
355
+ const span = transcriptSpan(location.path);
356
+ if (!span || span.first === null || span.cwd === null)
357
+ continue;
358
+ const [since, until] = windowSeconds(span.first, Math.max(span.first, span.last ?? span.first));
359
+ if (since > input.until || until < input.since)
360
+ continue;
361
+ byDirectory.set(span.cwd, (byDirectory.get(span.cwd) ?? 0) + 1);
362
+ }
363
+ let shared = byDirectory.get(input.cwd) ?? 0;
364
+ byDirectory.delete(input.cwd);
365
+ const directories = [...byDirectory.keys()].filter(isDirectory);
366
+ if (!directories.length)
367
+ return shared;
368
+ const results = await input.budget.run(timeout => Promise.all(directories.map(directory => runGit((0, exports.repositoryArguments)(directory), input.env, timeout))));
369
+ for (const [i, result] of results.entries()) {
370
+ if (result.kind === 'missing' || result.kind === 'timeout')
371
+ return STATUS[result.kind];
372
+ if (result.kind !== 'ok')
373
+ continue;
374
+ const repository = parseRepository(directories[i], result.stdout);
375
+ if (repository && repository.common === input.repository.common)
376
+ shared += byDirectory.get(directories[i]);
377
+ }
378
+ return shared;
379
+ }
@@ -9,7 +9,7 @@
9
9
  * Detection is pure: the CLI passes in the flag, the environment and the Intl
10
10
  * locale, and each renderer receives the chosen language as an argument.
11
11
  */
12
- import type { CompareMetric, InsightBucket, InsightObservations } from './types';
12
+ import { type CompareMetric, type InsightBucket, type InsightHost, type InsightObservations, type SessionCommits } from './types';
13
13
  export type WhyLang = 'en' | 'es' | 'pt';
14
14
  /**
15
15
  * The language of a flag value or locale: the part before '_', '-', '.' or '@',
@@ -91,6 +91,17 @@ export interface WhyText {
91
91
  time: string;
92
92
  }, after: string, before: string, messages: number, direction: 'down' | 'up' | 'same') => string;
93
93
  hide: string;
94
+ /**
95
+ * The `why --commits` line: the commits that landed in the session's repository
96
+ * while it ran, how many name Claude Code or Codex as co-author (the session's
97
+ * own host always, the other only above zero), the other local sessions that
98
+ * share them, and this session's tokens per commit (null when its usage is
99
+ * unavailable). That figure divides by the commits the agents co-authored, named
100
+ * in its label, and by every landed commit only when they co-authored none. Or
101
+ * why nothing was counted. A count of commits, never a claim about what they
102
+ * are worth.
103
+ */
104
+ bought: (commits: SessionCommits, host: InsightHost, perCommit: string | null) => string;
94
105
  }
95
106
  /** What `why` measures a change around. `model` is a display name (Sonnet 5). */
96
107
  export type ProofEvent = {
@@ -3,6 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = void 0;
4
4
  exports.whyLangOf = whyLangOf;
5
5
  exports.detectWhyLang = detectWhyLang;
6
+ /**
7
+ * Languages of the plain `why`, `compare` and `calendar` reports: English, Latin
8
+ * American Spanish and Brazilian Portuguese. Only words change. Numbers keep their
9
+ * en-US formatting (1,234,567, $1335.37, 12.3%) so figures match screenshots and
10
+ * the site, and session ids, model ids, commands, URLs and product names print as
11
+ * they are. `why json`, `compare json` and `calendar json` are machine formats,
12
+ * never translated.
13
+ *
14
+ * Detection is pure: the CLI passes in the flag, the environment and the Intl
15
+ * locale, and each renderer receives the chosen language as an argument.
16
+ */
17
+ const types_1 = require("./types");
6
18
  /**
7
19
  * The language of a flag value or locale: the part before '_', '-', '.' or '@',
8
20
  * in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
@@ -28,6 +40,15 @@ function detectWhyLang(sources = {}) {
28
40
  return whyLangOf(value) ?? 'en';
29
41
  return whyLangOf(sources.intlLocale) ?? 'en';
30
42
  }
43
+ /** The co-author counts in the `why --commits` line: the session's own host first, the other agent only when it co-authored any. */
44
+ function coAuthors(commits, host, words, first, other) {
45
+ const [own, ownCount, rest, restCount] = host === 'codex'
46
+ ? [words.codex, commits.codex, words.claude, commits.claudeCode]
47
+ : [words.claude, commits.claudeCode, words.codex, commits.codex];
48
+ return `${first(ownCount, own)}${restCount > 0 ? `, ${other(restCount, rest)}` : ''}`;
49
+ }
50
+ /** The agents the per-commit figure's commits name: Claude Code, Codex, or both, always in that order. */
51
+ const coAuthorNames = (commits, claude, codex, or) => commits.claudeCode > 0 && commits.codex > 0 ? `${claude} ${or} ${codex}` : commits.codex > 0 ? codex : claude;
31
52
  /** Spanish and Portuguese nouns agree with their count: 1 is singular, 0 and everything else plural. */
32
53
  const plural = (n, one, other) => `${n} ${n === 1 ? one : other}`;
33
54
  const times = (n) => n === 1 ? 'once' : `${n} times`;
@@ -82,6 +103,25 @@ const en = {
82
103
  return `Measured change: after ${what} on ${when.date} at ${when.time} UTC, Claude read a median of ${after} tokens per message, ${change}.`;
83
104
  },
84
105
  hide: 'Hide tips like this: npx agentguard-burn quiet on',
106
+ bought: (commits, host, perCommit) => {
107
+ const what = 'What it bought: ';
108
+ switch (commits.status) {
109
+ case 'ok': {
110
+ if (!commits.landed)
111
+ return `${what}no commits landed while this session ran.`;
112
+ const agents = coAuthors(commits, host, { claude: 'Claude Code', codex: 'Codex' }, (n, agent) => `${n} co-authored by ${agent}`, (n, agent) => `${n} by ${agent}`);
113
+ const sessions = commits.overlappingSessions;
114
+ const shared = sessions ? `, shared with ${sessions} overlapping ${sessions === 1 ? 'session' : 'sessions'}, so the commits can't be split between sessions` : '';
115
+ const per = commits.coAuthored > 0 ? `commit co-authored by ${coAuthorNames(commits, 'Claude Code', 'Codex', 'or')}` : 'landed commit';
116
+ return `${what}${commits.landed} ${commits.landed === 1 ? 'commit' : 'commits'} landed while this session ran (${agents})${shared}.${perCommit === null || sessions ? '' : ` ${perCommit} tokens per ${per}.`}`;
117
+ }
118
+ case 'no_repository': return `${what}no git repository for this session.`;
119
+ case 'unrecorded': return `${what}this transcript does not record where or when the session ran, so no commits were read.`;
120
+ case 'git_missing': return `${what}git was not found on this computer, so no commits were read.`;
121
+ case 'git_timeout': return `${what}git did not answer within ${types_1.GIT_BUDGET_MS / 1000} seconds, so no commits were read.`;
122
+ case 'git_error': return `${what}git could not read this session's repository, so no commits were read.`;
123
+ }
124
+ },
85
125
  };
86
126
  /** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
87
127
  const es = {
@@ -133,6 +173,25 @@ const es = {
133
173
  return `Cambio medido: después ${what} el ${when.date} a las ${when.time} UTC, Claude leyó una mediana de ${after} tokens por mensaje, ${change}.`;
134
174
  },
135
175
  hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
176
+ bought: (commits, host, perCommit) => {
177
+ const what = 'Lo que compró: ';
178
+ switch (commits.status) {
179
+ case 'ok': {
180
+ if (!commits.landed)
181
+ return `${what}no se registró ningún commit mientras corría esta sesión.`;
182
+ const agents = coAuthors(commits, host, { claude: 'Claude Code', codex: 'Codex' }, (n, agent) => `${n} con coautoría de ${agent}`, (n, agent) => `${n} de ${agent}`);
183
+ const one = commits.landed === 1, sessions = commits.overlappingSessions;
184
+ const shared = sessions ? `, ${one ? 'compartido' : 'compartidos'} con ${plural(sessions, 'sesión superpuesta', 'sesiones superpuestas')}, así que los commits no se pueden repartir entre sesiones` : '';
185
+ const per = commits.coAuthored > 0 ? `con coautoría de ${coAuthorNames(commits, 'Claude Code', 'Codex', 'o')}` : 'registrado';
186
+ return `${what}${one ? 'se registró 1 commit' : `se registraron ${commits.landed} commits`} mientras corría esta sesión (${agents})${shared}.${perCommit === null || sessions ? '' : ` ${perCommit} tokens por commit ${per}.`}`;
187
+ }
188
+ case 'no_repository': return `${what}esta sesión no tiene un repositorio git.`;
189
+ case 'unrecorded': return `${what}esta transcripción no registra dónde ni cuándo corrió la sesión, así que no se leyó ningún commit.`;
190
+ case 'git_missing': return `${what}no se encontró git en esta computadora, así que no se leyó ningún commit.`;
191
+ case 'git_timeout': return `${what}git no respondió en ${types_1.GIT_BUDGET_MS / 1000} segundos, así que no se leyó ningún commit.`;
192
+ case 'git_error': return `${what}git no pudo leer el repositorio de esta sesión, así que no se leyó ningún commit.`;
193
+ }
194
+ },
136
195
  };
137
196
  /** Brazilian Portuguese: você forms. */
138
197
  const pt = {
@@ -184,6 +243,25 @@ const pt = {
184
243
  return `Mudança medida: depois ${what} em ${when.date} às ${when.time} UTC, o Claude leu uma mediana de ${after} tokens por mensagem, ${change}.`;
185
244
  },
186
245
  hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
246
+ bought: (commits, host, perCommit) => {
247
+ const what = 'O que comprou: ';
248
+ switch (commits.status) {
249
+ case 'ok': {
250
+ if (!commits.landed)
251
+ return `${what}nenhum commit foi registrado enquanto esta sessão rodava.`;
252
+ const agents = coAuthors(commits, host, { claude: 'o Claude Code', codex: 'o Codex' }, (n, agent) => `${n} em coautoria com ${agent}`, (n, agent) => `${n} com ${agent}`);
253
+ const one = commits.landed === 1, sessions = commits.overlappingSessions;
254
+ const shared = sessions ? `, ${one ? 'compartilhado' : 'compartilhados'} com ${plural(sessions, 'sessão sobreposta', 'sessões sobrepostas')}, então os commits não podem ser divididos entre as sessões` : '';
255
+ const per = commits.coAuthored > 0 ? `em coautoria com ${coAuthorNames(commits, 'o Claude Code', 'o Codex', 'ou')}` : 'registrado';
256
+ return `${what}${one ? 'foi registrado 1 commit' : `foram registrados ${commits.landed} commits`} enquanto esta sessão rodava (${agents})${shared}.${perCommit === null || sessions ? '' : ` ${perCommit} tokens por commit ${per}.`}`;
257
+ }
258
+ case 'no_repository': return `${what}esta sessão não tem um repositório git.`;
259
+ case 'unrecorded': return `${what}esta transcrição não registra onde nem quando a sessão rodou, então nenhum commit foi lido.`;
260
+ case 'git_missing': return `${what}o git não foi encontrado neste computador, então nenhum commit foi lido.`;
261
+ case 'git_timeout': return `${what}o git não respondeu em ${types_1.GIT_BUDGET_MS / 1000} segundos, então nenhum commit foi lido.`;
262
+ case 'git_error': return `${what}o git não conseguiu ler o repositório desta sessão, então nenhum commit foi lido.`;
263
+ }
264
+ },
187
265
  };
188
266
  exports.WHY_TEXT = { en, es, pt };
189
267
  exports.DECISION_TEXT = {
@@ -1,5 +1,5 @@
1
1
  import { type DollarRange, type PricingTable, type TurnPrice } from './pricing';
2
- import { type AttributionSummary, type InsightBucket, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
2
+ import { type AttributionSummary, type CommitsStatus, type InsightBucket, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence, type SessionCommits } from './types';
3
3
  import { type WhyLang } from './i18n';
4
4
  export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
5
5
  export declare function totalTokens(turn: InsightTurn): number;
@@ -131,10 +131,44 @@ export declare const PROOF_MINIMUM = 5;
131
131
  * the event caused it.
132
132
  */
133
133
  export declare function proofLine(turns: InsightTurn[], lang?: WhyLang): string | null;
134
- /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
134
+ /** The session's tokens over every commit that landed while it ran, teammates' included; null when none landed or the session's usage is unavailable. */
135
+ export declare function tokensPerLandedCommit(totalTokens: number | null, commits: SessionCommits): number | null;
136
+ /** The session's tokens over the commits Claude Code or Codex co-authored, each once; null when the agents co-authored none or usage is unavailable. */
137
+ export declare function tokensPerCoAuthoredCommit(totalTokens: number | null, commits: SessionCommits): number | null;
138
+ /**
139
+ * The commits the line's per-commit figure divides by: the ones Claude Code or
140
+ * Codex co-authored when there are any, so a teammate's commits fetched into the
141
+ * repository never lower it; every landed commit only when no commit names
142
+ * either agent. Null when nothing landed or nothing was counted.
143
+ */
144
+ export declare function perCommitBasis(commits: SessionCommits): 'coAuthored' | 'landed' | null;
145
+ /** The figure the line prints, on perCommitBasis. */
146
+ export declare function tokensPerCommit(totalTokens: number | null, commits: SessionCommits): number | null;
147
+ /** The `commits` object `why json --commits` adds: counts only, null where nothing was counted. */
148
+ export interface CommitsJson {
149
+ status: CommitsStatus;
150
+ landed: number | null;
151
+ coAuthoredByClaudeCode: number | null;
152
+ coAuthoredByCodex: number | null;
153
+ /** Commits co-authored by either agent, each once: what tokensPerCoAuthoredCommit divides by. */
154
+ coAuthored: number | null;
155
+ overlappingSessions: number | null;
156
+ tokensPerLandedCommit: number | null;
157
+ tokensPerCoAuthoredCommit: number | null;
158
+ /** Which of the two the line prints. */
159
+ perCommitBasis: 'coAuthored' | 'landed' | null;
160
+ graceMinutes: number;
161
+ }
162
+ export declare function commitsJson(commits: SessionCommits, totalTokens: number | null): CommitsJson;
163
+ /**
164
+ * `lang` changes words only: every figure, id, command and URL prints as it does
165
+ * in English, and `why json` never passes through here. `commits`, given only by
166
+ * `why --commits`, adds its line after the measurements and before the tip.
167
+ */
135
168
  export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable, options?: {
136
169
  tips?: boolean;
137
170
  lang?: WhyLang;
171
+ commits?: SessionCommits;
138
172
  }): string;
139
173
  export interface RewriteRow extends RewriteEvidence {
140
174
  sessionId: string;
@@ -11,6 +11,11 @@ exports.whyTipInput = whyTipInput;
11
11
  exports.whyTipLine = whyTipLine;
12
12
  exports.unfinishedSubagents = unfinishedSubagents;
13
13
  exports.proofLine = proofLine;
14
+ exports.tokensPerLandedCommit = tokensPerLandedCommit;
15
+ exports.tokensPerCoAuthoredCommit = tokensPerCoAuthoredCommit;
16
+ exports.perCommitBasis = perCommitBasis;
17
+ exports.tokensPerCommit = tokensPerCommit;
18
+ exports.commitsJson = commitsJson;
14
19
  exports.renderWhy = renderWhy;
15
20
  exports.rewriteReport = rewriteReport;
16
21
  exports.rewriteReportJson = rewriteReportJson;
@@ -285,7 +290,40 @@ function proofLine(turns, lang = 'en') {
285
290
  }
286
291
  return null;
287
292
  }
288
- /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
293
+ /** The session's tokens over every commit that landed while it ran, teammates' included; null when none landed or the session's usage is unavailable. */
294
+ function tokensPerLandedCommit(totalTokens, commits) {
295
+ return commits.status === 'ok' && commits.overlappingSessions === 0 && commits.landed > 0 && totalTokens !== null ? Math.round(totalTokens / commits.landed) : null;
296
+ }
297
+ /** The session's tokens over the commits Claude Code or Codex co-authored, each once; null when the agents co-authored none or usage is unavailable. */
298
+ function tokensPerCoAuthoredCommit(totalTokens, commits) {
299
+ return commits.status === 'ok' && commits.overlappingSessions === 0 && commits.coAuthored > 0 && totalTokens !== null ? Math.round(totalTokens / commits.coAuthored) : null;
300
+ }
301
+ /**
302
+ * The commits the line's per-commit figure divides by: the ones Claude Code or
303
+ * Codex co-authored when there are any, so a teammate's commits fetched into the
304
+ * repository never lower it; every landed commit only when no commit names
305
+ * either agent. Null when nothing landed or nothing was counted.
306
+ */
307
+ function perCommitBasis(commits) {
308
+ return commits.status !== 'ok' || commits.landed === 0 || commits.overlappingSessions > 0 ? null : commits.coAuthored > 0 ? 'coAuthored' : 'landed';
309
+ }
310
+ /** The figure the line prints, on perCommitBasis. */
311
+ function tokensPerCommit(totalTokens, commits) {
312
+ const basis = perCommitBasis(commits);
313
+ return basis === 'coAuthored' ? tokensPerCoAuthoredCommit(totalTokens, commits) : basis === 'landed' ? tokensPerLandedCommit(totalTokens, commits) : null;
314
+ }
315
+ function commitsJson(commits, totalTokens) {
316
+ const ok = commits.status === 'ok';
317
+ return { status: commits.status, landed: ok ? commits.landed : null, coAuthoredByClaudeCode: ok ? commits.claudeCode : null, coAuthoredByCodex: ok ? commits.codex : null,
318
+ coAuthored: ok ? commits.coAuthored : null, overlappingSessions: ok ? commits.overlappingSessions : null,
319
+ tokensPerLandedCommit: tokensPerLandedCommit(totalTokens, commits), tokensPerCoAuthoredCommit: tokensPerCoAuthoredCommit(totalTokens, commits),
320
+ perCommitBasis: perCommitBasis(commits), graceMinutes: types_1.COMMIT_GRACE_MS / 60_000 };
321
+ }
322
+ /**
323
+ * `lang` changes words only: every figure, id, command and URL prints as it does
324
+ * in English, and `why json` never passes through here. `commits`, given only by
325
+ * `why --commits`, adds its line after the measurements and before the tip.
326
+ */
289
327
  function renderWhy(transcript, rates = {}, options = {}) {
290
328
  const lang = options.lang ?? 'en', text = i18n_1.WHY_TEXT[lang];
291
329
  const money = (value) => (0, live_1.dollars)(value, text);
@@ -294,6 +332,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
294
332
  `AgentGuard why: ${transcript.sessionId}`,
295
333
  text.forkUnavailable,
296
334
  table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
335
+ ...(options.commits ? ['', text.bought(options.commits, transcript.host, null)] : []),
297
336
  ].join('\n');
298
337
  const figures = sessionFigures(transcript, rates);
299
338
  const { turns, attribution, prices, totals, totalUsd } = figures;
@@ -312,6 +351,8 @@ function renderWhy(transcript, rates = {}, options = {}) {
312
351
  // Measurements, not tips: they print whether or not tips are on.
313
352
  const proof = proofLine(turns, lang);
314
353
  const unfinished = unfinishedSubagents(transcript, figures);
354
+ const perCommit = options.commits ? tokensPerCommit(attribution.totalTokens, options.commits) : null;
355
+ const bought = options.commits ? text.bought(options.commits, transcript.host, perCommit === null ? null : (0, exports.count)(perCommit)) : null;
315
356
  return [
316
357
  `AgentGuard why: ${transcript.sessionId}`,
317
358
  text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
@@ -329,6 +370,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
329
370
  ...(mixedWriteAllocation ? [text.mixedRanges] : []),
330
371
  text.diagnostics(transcript.diagnostics.duplicateUsageRecords, transcript.diagnostics.malformedLines),
331
372
  ...(proof ? ['', proof] : []),
373
+ ...(bought ? ['', bought] : []),
332
374
  ...(tip ? ['', tip, text.hide] : []),
333
375
  ].join('\n');
334
376
  }
@@ -14,10 +14,20 @@ export interface InsightReadOptions {
14
14
  * parsed with the parser state the previous piece returned, so no single string
15
15
  * holds the whole file (V8 cannot hold a string past about 512 MB). The turns,
16
16
  * observations and summed diagnostics equal a whole-file parse. Unset reads the
17
- * whole file at once, as `why` does.
17
+ * whole file at once, as `why` does, unless the file is over
18
+ * WHOLE_FILE_MAX_BYTES: then it is read in pieces all the same.
18
19
  */
19
20
  chunkBytes?: number;
21
+ /** Tests only: the size above which a read with no chunkBytes still goes in pieces. */
22
+ wholeFileMaxBytes?: number;
20
23
  }
24
+ /**
25
+ * Above this size a whole-file read could pass V8's string limit, so the file is
26
+ * read in pieces even when no chunk size was asked for. Such a session is rare
27
+ * but real: one long-running Claude Code session reached 568 MB, and `why` on
28
+ * it stopped with "Cannot create a string longer than 0x1fffffe8 characters".
29
+ */
30
+ export declare const WHOLE_FILE_MAX_BYTES: number;
21
31
  export declare function readInsightTranscript(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
22
32
  /** Read one Claude session plus its explicitly stored child transcripts. */
23
33
  export declare function readInsightSession(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.providerResponseIdentity = void 0;
3
+ exports.WHOLE_FILE_MAX_BYTES = exports.providerResponseIdentity = void 0;
4
4
  exports.parseInsightTranscript = parseInsightTranscript;
5
5
  exports.readInsightTranscript = readInsightTranscript;
6
6
  exports.readInsightSession = readInsightSession;
@@ -528,11 +528,23 @@ function parseInsightTranscript(text, options = {}) {
528
528
  return { host: state.host, sessionId: state.sessionId, turns: Object.values(state.seen), updatedTurns: [...updated.values()], diagnostics, state,
529
529
  observations: observations(state.observedCalls ?? {}), acceptedQuotaLineNumbers };
530
530
  }
531
+ /**
532
+ * Above this size a whole-file read could pass V8's string limit, so the file is
533
+ * read in pieces even when no chunk size was asked for. Such a session is rare
534
+ * but real: one long-running Claude Code session reached 568 MB, and `why` on
535
+ * it stopped with "Cannot create a string longer than 0x1fffffe8 characters".
536
+ */
537
+ exports.WHOLE_FILE_MAX_BYTES = 256 * 1024 * 1024;
538
+ const LARGE_FILE_CHUNK_BYTES = 16 * 1024 * 1024;
531
539
  const DIAGNOSTIC_KEYS = ['lines', 'malformedLines', 'duplicateUsageRecords', 'unsupportedUsageRecords', 'inheritedUsageRecords'];
532
540
  function parseFile(filename, options, read) {
533
- const limit = read.chunkBytes;
534
- if (!limit || !(limit > 0))
535
- return parseInsightTranscript((0, node_fs_1.readFileSync)(filename, 'utf8'), options);
541
+ let limit = read.chunkBytes;
542
+ if (!limit || !(limit > 0)) {
543
+ const max = read.wholeFileMaxBytes ?? exports.WHOLE_FILE_MAX_BYTES;
544
+ if ((0, node_fs_1.statSync)(filename).size <= max)
545
+ return parseInsightTranscript((0, node_fs_1.readFileSync)(filename, 'utf8'), options);
546
+ limit = Math.min(LARGE_FILE_CHUNK_BYTES, max);
547
+ }
536
548
  const fd = (0, node_fs_1.openSync)(filename, 'r');
537
549
  try {
538
550
  if ((0, node_fs_1.fstatSync)(fd).size <= limit)
@@ -178,6 +178,29 @@ export interface InsightParseOptions {
178
178
  state?: InsightParserState;
179
179
  spawnedSession?: boolean;
180
180
  }
181
+ /** A commit up to ten minutes after the session's last record still counts: the commit that closes a session often lands just after its last reply. */
182
+ export declare const COMMIT_GRACE_MS: number;
183
+ /** Every git call for one `why --commits` report shares this budget. Past it the call is killed and the line says git did not answer. */
184
+ export declare const GIT_BUDGET_MS = 2000;
185
+ /** `ok`, or why nothing was counted: no repository at the recorded directory, no directory or time recorded, no git, no answer in time, or a git error. */
186
+ export type CommitsStatus = 'ok' | 'no_repository' | 'unrecorded' | 'git_missing' | 'git_timeout' | 'git_error';
187
+ /**
188
+ * What `why --commits` counted for one session (src/insights/commits.ts): the
189
+ * commits whose committer time falls in the session's window, each counted once
190
+ * by hash; how many of them a Co-authored-by trailer credits to Claude Code and
191
+ * to Codex; and the other local sessions whose windows overlap it in the same
192
+ * repository. Counts only, never a hash, email, message or path. Every count is
193
+ * 0 unless `status` is `ok`.
194
+ */
195
+ export interface SessionCommits {
196
+ status: CommitsStatus;
197
+ landed: number;
198
+ claudeCode: number;
199
+ codex: number;
200
+ /** Commits co-authored by Claude Code or Codex, each counted once: a commit naming both counts once here and once in each count above. */
201
+ coAuthored: number;
202
+ overlappingSessions: number;
203
+ }
181
204
  /** Precedence order when several signals are present; `unknown` is the Codex residual, never prefix change by default. */
182
205
  export type RewriteCause = 'model_switch' | 'version_upgrade' | 'compaction' | 'first_spawned_turn' | 'idle_ttl_expired' | 'image_pruning' | 'prefix_change' | 'unknown_ttl' | 'unknown';
183
206
  export declare const REWRITE_CAUSES: RewriteCause[];
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.COMPARE_METRICS = exports.REWRITE_CAUSES = exports.INSIGHT_BUCKETS = void 0;
3
+ exports.COMPARE_METRICS = exports.REWRITE_CAUSES = exports.GIT_BUDGET_MS = exports.COMMIT_GRACE_MS = exports.INSIGHT_BUCKETS = void 0;
4
4
  exports.INSIGHT_BUCKETS = ['instruction_stack', 'history_resent', 'reread_files', 'subagent_fanout', 'tool_output', 'conversation', 'full_prefix_rewrites', 'output', 'unattributed'];
5
+ /** A commit up to ten minutes after the session's last record still counts: the commit that closes a session often lands just after its last reply. */
6
+ exports.COMMIT_GRACE_MS = 10 * 60_000;
7
+ /** Every git call for one `why --commits` report shares this budget. Past it the call is killed and the line says git did not answer. */
8
+ exports.GIT_BUDGET_MS = 2_000;
5
9
  exports.REWRITE_CAUSES = ['model_switch', 'version_upgrade', 'compaction', 'first_spawned_turn', 'idle_ttl_expired', 'image_pruning', 'prefix_change', 'unknown_ttl', 'unknown'];
6
10
  /** The rows `compare` prints for each session, in table order. */
7
11
  exports.COMPARE_METRICS = ['assistantResponses', 'inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'freshInputTokens', 'cacheShare', 'outputTokens', 'subagentsLaunched', 'fullPrefixRewrites', 'usd'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.3.26",
3
+ "version": "0.3.28",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://agentguard.run/burn",