@agentguard-run/burn 0.3.27 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +48 -0
  3. package/dist/src/adapters/codex.d.ts +4 -2
  4. package/dist/src/adapters/codex.js +55 -9
  5. package/dist/src/cli.js +43 -5
  6. package/dist/src/history/claude-transcript.d.ts +0 -13
  7. package/dist/src/history/claude-transcript.js +11 -10
  8. package/dist/src/hook/pre-tool-use.d.ts +0 -16
  9. package/dist/src/hook/pre-tool-use.js +15 -10
  10. package/dist/src/index.d.ts +4 -1
  11. package/dist/src/index.js +18 -1
  12. package/dist/src/insights/commits.d.ts +84 -0
  13. package/dist/src/insights/commits.js +379 -0
  14. package/dist/src/insights/i18n.d.ts +12 -1
  15. package/dist/src/insights/i18n.js +78 -0
  16. package/dist/src/insights/launch-evidence.d.ts +25 -0
  17. package/dist/src/insights/launch-evidence.js +54 -0
  18. package/dist/src/insights/price-shadow.js +2 -1
  19. package/dist/src/insights/render.d.ts +36 -2
  20. package/dist/src/insights/render.js +43 -1
  21. package/dist/src/insights/tally.d.ts +45 -0
  22. package/dist/src/insights/tally.js +266 -0
  23. package/dist/src/insights/transcript.js +9 -1
  24. package/dist/src/insights/tree.d.ts +36 -0
  25. package/dist/src/insights/tree.js +285 -0
  26. package/dist/src/insights/types.d.ts +25 -0
  27. package/dist/src/insights/types.js +5 -1
  28. package/dist/src/receipt.d.ts +10 -0
  29. package/dist/src/receipt.js +53 -2
  30. package/dist/src/tool-names.d.ts +6 -0
  31. package/dist/src/tool-names.js +10 -0
  32. package/dist/src/upgrade-moments.js +2 -1
  33. package/docs/OCT5_VERIFICATION.md +118 -0
  34. package/docs/TREE_AND_TALLY.md +70 -0
  35. package/docs/launch-tree-local-oct5.txt +7 -0
  36. package/docs/oct5-followup/REPORT.md +105 -0
  37. package/docs/oct5-followup/checks.json +20 -0
  38. package/docs/oct5-followup/free-plugin-fixture-output.txt +12 -0
  39. package/docs/oct5-followup/tally-after.json +5 -0
  40. package/docs/oct5-followup/tally-after.txt +1 -0
  41. package/docs/oct5-followup/tree-after.json +40 -0
  42. package/docs/oct5-followup/tree-after.txt +7 -0
  43. package/docs/oct5-followup/tree-before.txt +7 -0
  44. package/docs/oct5-followup/verify-free-receipts.cjs +81 -0
  45. package/docs/session-tally-local-oct5.txt +1 -0
  46. package/package.json +7 -3
@@ -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 = {
@@ -0,0 +1,25 @@
1
+ import type { InsightParserState } from './types';
2
+ type Row = Record<string, any>;
3
+ export interface LaunchEvidence {
4
+ nodes: Record<string, {
5
+ activityAt?: number[];
6
+ name?: string;
7
+ model?: string;
8
+ depth?: number;
9
+ }>;
10
+ calls: Record<string, {
11
+ parent: string;
12
+ name?: string;
13
+ model?: string;
14
+ }>;
15
+ edges: Array<{
16
+ child: string;
17
+ parent: string;
18
+ source: string;
19
+ }>;
20
+ owners: Record<string, string>;
21
+ current?: string;
22
+ }
23
+ /** Called only for reports that explicitly request lineage collection. */
24
+ export declare function observeLaunchRecord(raw: Row, state: InsightParserState, at?: number): void;
25
+ export {};