@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,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.observeLaunchRecord = observeLaunchRecord;
4
+ const tool_names_1 = require("../tool-names");
5
+ const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
6
+ const id = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}$/.test(v) ? v : undefined;
7
+ // Only host metadata labels are retained. Never retain an Agent prompt or description.
8
+ const label = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9 _./:-]{0,63}$/.test(v) ? v : undefined;
9
+ /** Called only for reports that explicitly request lineage collection. */
10
+ function observeLaunchRecord(raw, state, at) {
11
+ const e = state.launchEvidence;
12
+ const payload = record(raw.payload), result = record(raw.toolUseResult);
13
+ const anonymousSidechain = raw.isSidechain === true && !id(raw.agentId) && !state.sessionId.startsWith('agent-');
14
+ const owner = id(raw.agentId) ?? (anonymousSidechain ? 'unidentified-sidechain:' + state.sessionId : state.lineage?.sessionId ?? state.sessionId.replace(/^agent-/, ''));
15
+ e.current = owner;
16
+ const node = e.nodes[owner] ??= {};
17
+ if (at !== undefined)
18
+ (node.activityAt ??= []).push(at);
19
+ node.name ??= anonymousSidechain ? 'sidechain identity not recorded' : label(raw.agentName ?? raw.agentType ?? payload.agent_nickname ?? payload.agent_role);
20
+ const parent = id(raw.parentAgentId) ?? state.lineage?.parentSessionId;
21
+ if (parent && parent !== owner)
22
+ e.edges.push({ child: owner, parent, source: 'parent metadata' });
23
+ const blocks = Array.isArray(raw.message?.content) ? [...raw.message.content] : [];
24
+ if (raw.type === 'response_item')
25
+ blocks.push(payload);
26
+ for (const value of blocks) {
27
+ const block = record(value);
28
+ const callId = id(block.id ?? block.call_id ?? block.tool_use_id);
29
+ if (['tool_use', 'function_call', 'custom_tool_call'].includes(block.type) && (0, tool_names_1.isLaunchTool)(block.name) && callId) {
30
+ let input = record(block.input);
31
+ if (typeof block.arguments === 'string') {
32
+ try {
33
+ input = record(JSON.parse(block.arguments));
34
+ }
35
+ catch { }
36
+ }
37
+ e.calls[callId] = { parent: owner, name: label(input.name ?? input.subagent_type ?? input.agent_type), model: label(input.model) };
38
+ }
39
+ if (['tool_result', 'function_call_output', 'custom_tool_call_output'].includes(block.type) && callId) {
40
+ let output = result;
41
+ if (typeof block.output === 'string') {
42
+ try {
43
+ output = record(JSON.parse(block.output));
44
+ }
45
+ catch { }
46
+ }
47
+ const child = id(output.agentId ?? output.agent_id), launch = e.calls[callId];
48
+ if (child && launch && block.is_error !== true && output.status !== 'failed') {
49
+ e.edges.push({ child, parent: launch.parent, source: 'launch tool result' });
50
+ e.nodes[child] = { ...e.nodes[child], ...(launch.name ? { name: launch.name } : {}), ...(launch.model ? { model: launch.model } : {}) };
51
+ }
52
+ }
53
+ }
54
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PRICE_LABEL = void 0;
4
4
  exports.priceShadowReport = priceShadowReport;
5
5
  exports.renderPriceShadow = renderPriceShadow;
6
+ const tool_names_1 = require("../tool-names");
6
7
  const node_fs_1 = require("node:fs");
7
8
  const node_path_1 = require("node:path");
8
9
  const receipt_1 = require("../receipt");
@@ -43,7 +44,7 @@ function collectSpawns(row, calls) {
43
44
  const name = (0, history_1.identifier)(block.name), id = (0, history_1.identifier)(block.id ?? block.call_id ?? block.tool_use_id);
44
45
  if (!id)
45
46
  continue;
46
- if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name && /^(?:(?:functions\.)?(?:Agent|Task|spawn_agent))$/.test(name)) {
47
+ if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name && (0, tool_names_1.isLaunchTool)(name)) {
47
48
  if (!calls.has(id))
48
49
  calls.set(id, { at });
49
50
  }
@@ -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
  }
@@ -0,0 +1,45 @@
1
+ import { type SignedDecisionLogEntry } from '@agentguard-run/spend';
2
+ export interface TallyCounts {
3
+ launches: number;
4
+ allowed: number;
5
+ asked: number;
6
+ saidYes: number;
7
+ stopped: number;
8
+ shadow: number;
9
+ unrecorded: number;
10
+ unresolvedAsked: number;
11
+ }
12
+ export type SessionTally = {
13
+ status: 'verified';
14
+ session: string;
15
+ host: string;
16
+ counts: TallyCounts;
17
+ tokens: number | null;
18
+ date: string;
19
+ lineage?: Array<Record<string, unknown>>;
20
+ } | {
21
+ status: 'missing' | 'verification_failed';
22
+ session: string;
23
+ reason: string;
24
+ };
25
+ type Entry = SignedDecisionLogEntry & {
26
+ publicKeyHex?: string;
27
+ };
28
+ /** Verify the whole physical chain before selecting any session or counting. */
29
+ export declare function verifyTallyLedger(entries: Entry[], publicKeyHex: string): Promise<boolean>;
30
+ /** Only verified, complete local ledgers can supply receipt lineage to tree. */
31
+ export declare function sessionLaunchReceipts(session: string, options?: {
32
+ home?: string;
33
+ data?: string;
34
+ }): Promise<Entry[]>;
35
+ export declare function tallyEntries(entries: Entry[], publicKeyHex: string, session: string): Promise<SessionTally>;
36
+ export declare function pluginLedgerDirectories(home?: string): string[];
37
+ export declare function readLedgerTallies(data: string): Promise<SessionTally[]>;
38
+ /** Completion-day increments, so a resumed session's cumulative totals upload once. */
39
+ export declare function readLedgerDailyTallies(data: string): Promise<SessionTally[]>;
40
+ export declare function sessionTally(session: string, options?: {
41
+ home?: string;
42
+ data?: string;
43
+ }): Promise<SessionTally>;
44
+ export declare function renderSessionTally(tally: SessionTally): string;
45
+ export {};
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyTallyLedger = verifyTallyLedger;
4
+ exports.sessionLaunchReceipts = sessionLaunchReceipts;
5
+ exports.tallyEntries = tallyEntries;
6
+ exports.pluginLedgerDirectories = pluginLedgerDirectories;
7
+ exports.readLedgerTallies = readLedgerTallies;
8
+ exports.readLedgerDailyTallies = readLedgerDailyTallies;
9
+ exports.sessionTally = sessionTally;
10
+ exports.renderSessionTally = renderSessionTally;
11
+ const tool_names_1 = require("../tool-names");
12
+ const node_fs_1 = require("node:fs");
13
+ const node_os_1 = require("node:os");
14
+ const node_path_1 = require("node:path");
15
+ const spend_1 = require("@agentguard-run/spend");
16
+ const spawn = tool_names_1.LAUNCH_TOOLS;
17
+ const missing = (session, reason = 'Signed session receipts are missing.') => ({ status: 'missing', session, reason });
18
+ const failed = (session) => ({ status: 'verification_failed', session, reason: 'Receipt signature or hash chain verification failed.' });
19
+ const meta = (entry) => entry.decision?.plugin ?? {};
20
+ /** Verify the whole physical chain before selecting any session or counting. */
21
+ async function verifyTallyLedger(entries, publicKeyHex) {
22
+ if (!/^[a-f0-9]{64}$/i.test(publicKeyHex))
23
+ return false;
24
+ try {
25
+ if (entries.some(e => e.publicKeyHex && e.publicKeyHex.toLowerCase() !== publicKeyHex.toLowerCase()))
26
+ return false;
27
+ return (await (0, spend_1.verifyChain)(entries, Buffer.from(publicKeyHex, 'hex'))).ok;
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ function countedSession(entries, session) {
34
+ const own = entries.filter(e => meta(e).sessionId === session);
35
+ const endings = own.filter(e => meta(e).event === 'session_receipt');
36
+ const ending = endings.at(-1);
37
+ if (!ending)
38
+ return missing(session);
39
+ if (own.at(-1) !== ending)
40
+ return missing(session, 'Signed receipts for the resumed session are incomplete.');
41
+ const calls = new Map(), outcomes = new Map();
42
+ for (const e of own) {
43
+ const m = meta(e);
44
+ if (!spawn.has(m.toolName) || typeof m.toolUseId !== 'string')
45
+ continue;
46
+ if (m.gate === 'receipt' && m.event === 'outcome') {
47
+ outcomes.set(m.toolUseId, [...(outcomes.get(m.toolUseId) ?? []), e]);
48
+ continue;
49
+ }
50
+ if (m.gate !== 'burn' || !['decision', 'fail_open', 'fail_closed'].includes(m.event))
51
+ continue;
52
+ calls.set(m.toolUseId, e);
53
+ }
54
+ const c = { launches: calls.size, allowed: 0, asked: 0, saidYes: 0, stopped: 0, shadow: 0, unrecorded: 0, unresolvedAsked: 0 };
55
+ for (const [id, e] of calls) {
56
+ const m = meta(e), d = e.decision;
57
+ if ([m.reasonCode, m.policyReasonCode].includes('burn_external_hook'))
58
+ return missing(session, 'Launch receipts belong to an external hook and are incomplete here.');
59
+ if (m.event === 'fail_open')
60
+ c.unrecorded++;
61
+ else if (m.asked === true || typeof m.approvalRuleId === 'string') {
62
+ if (m.host === 'codex')
63
+ return missing(session, 'This receipt labels a Codex launch as asked; its outcome cannot be tallied.');
64
+ c.asked++;
65
+ if (outcomes.get(id)?.some(o => o.sequence > e.sequence && o.decision.originalDecisionId === d.decisionId))
66
+ c.saidYes++;
67
+ }
68
+ else if (m.event === 'fail_closed' || d.action === 'block')
69
+ c.stopped++;
70
+ else if (d.action === 'allow' || d.action === 'downgrade')
71
+ c.allowed++;
72
+ else if (d.action === 'shadow')
73
+ c.shadow++;
74
+ else
75
+ return missing(session, 'A launch verdict is not supported by this reader.');
76
+ }
77
+ c.unresolvedAsked = c.asked - c.saidYes;
78
+ const receipt = meta(ending).receipt;
79
+ if (!receipt || receipt.version !== 1)
80
+ return missing(session, 'The signed session summary is missing or unsupported.');
81
+ // A signed summary with launches but no matching decisions is not a zero.
82
+ if (receipt?.subagents?.started > c.allowed + c.saidYes + c.shadow + c.unrecorded)
83
+ return missing(session, 'Signed launch receipts are incomplete for this session.');
84
+ if (!/^\d{4}-\d{2}-\d{2}T/.test(ending.decision.timestamp) || !Number.isFinite(Date.parse(ending.decision.timestamp)))
85
+ return failed(session);
86
+ return { status: 'verified', session, host: meta(ending).host ?? meta(calls.values().next().value ?? ending).host ?? 'unknown', counts: c,
87
+ tokens: Number.isSafeInteger(receipt?.tokens) && receipt.tokens >= 0 ? receipt.tokens : null,
88
+ date: new Date(ending.decision.timestamp).toISOString().slice(0, 10),
89
+ lineage: [...calls.values()].filter(e => meta(e).launch || meta(e).agent_id).map(e => {
90
+ const m = meta(e);
91
+ return { toolUseId: m.toolUseId, agent_id: m.agent_id ?? m.launch?.callerId ?? null,
92
+ agent_type: m.agent_type ?? m.launch?.callerType ?? null, depth: m.depth ?? null, launchDepth: m.launch?.depth ?? null };
93
+ }) };
94
+ }
95
+ /** Only verified, complete local ledgers can supply receipt lineage to tree. */
96
+ async function sessionLaunchReceipts(session, options = {}) {
97
+ const result = [];
98
+ for (const data of options.data ? [options.data] : pluginLedgerDirectories(options.home)) {
99
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson')))
100
+ continue;
101
+ const tallies = await readLedgerTallies(data);
102
+ if (tallies.some(t => t.status === 'verification_failed'))
103
+ throw new Error('Receipt signature or hash chain verification failed.');
104
+ if (!tallies.some(t => t.session === session && t.status === 'verified'))
105
+ continue;
106
+ const entries = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson'), 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
107
+ if (!await verifyTallyLedger(entries, (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim()))
108
+ throw new Error('Receipt signature or hash chain verification failed.');
109
+ result.push(...entries.filter(e => meta(e).sessionId === session));
110
+ }
111
+ return result;
112
+ }
113
+ async function tallyEntries(entries, publicKeyHex, session) {
114
+ if (!entries.length)
115
+ return missing(session);
116
+ if (!await verifyTallyLedger(entries, publicKeyHex))
117
+ return failed(session);
118
+ return countedSession(entries, session);
119
+ }
120
+ function pluginLedgerDirectories(home = process.env.AGENTGUARD_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard')) {
121
+ const dirs = new Set([process.env.PLUGIN_DATA || process.env.CLAUDE_PLUGIN_DATA || (0, node_path_1.join)(home, 'codex-plugin')]);
122
+ const registry = (0, node_path_1.join)(home, 'plugin-ledgers');
123
+ let files;
124
+ try {
125
+ files = (0, node_fs_1.readdirSync)(registry);
126
+ }
127
+ catch {
128
+ return [...dirs];
129
+ }
130
+ for (const file of files) {
131
+ if (!file.endsWith('.json'))
132
+ continue;
133
+ const entry = (0, node_path_1.join)(registry, file);
134
+ try {
135
+ const text = (0, node_fs_1.readFileSync)(entry, 'utf8'), row = JSON.parse(text);
136
+ if (typeof row?.data !== 'string' || !row.data.trim())
137
+ continue;
138
+ const data = (0, node_path_1.resolve)(row.data);
139
+ let missing = false;
140
+ try {
141
+ missing = !(0, node_fs_1.statSync)(data).isDirectory();
142
+ }
143
+ catch (error) {
144
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
145
+ continue;
146
+ missing = true;
147
+ }
148
+ if (!missing) {
149
+ dirs.add(data);
150
+ continue;
151
+ }
152
+ // Prune only the stale pointer, never its target. A concurrently replaced
153
+ // entry is retained. Unreadable or malformed neighbors do not stop discovery.
154
+ if ((0, node_fs_1.readFileSync)(entry, 'utf8') === text)
155
+ (0, node_fs_1.unlinkSync)(entry);
156
+ }
157
+ catch { /* One inaccessible entry must not hide healthy ledgers. */ }
158
+ }
159
+ return [...dirs];
160
+ }
161
+ async function readLedgerTallies(data) {
162
+ let entries, key;
163
+ try {
164
+ const ledgerPath = (0, node_path_1.join)(data, 'ledger', 'decisions.ndjson');
165
+ const text = (0, node_fs_1.readFileSync)(ledgerPath, 'utf8');
166
+ entries = text.split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
167
+ key = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim();
168
+ if (!await verifyTallyLedger(entries, key))
169
+ return [failed('unknown')];
170
+ // An intact prefix is not complete when the worker's durable head records
171
+ // later rows. Read this existing checkpoint without changing the ledger.
172
+ if ((0, node_fs_1.existsSync)(ledgerPath + '.durable-head.json')) {
173
+ const head = JSON.parse((0, node_fs_1.readFileSync)(ledgerPath + '.durable-head.json', 'utf8'));
174
+ const end = head?.sequence;
175
+ if (head?.version !== 1 || !Number.isSafeInteger(end) || end < -1 || end >= entries.length
176
+ || head.signerFingerprint !== (0, spend_1.computeSignerFingerprint)(Buffer.from(key, 'hex'))
177
+ || head.entryHash !== (end < 0 ? spend_1.GENESIS_PREVIOUS_HASH : entries[end]?.entryHash))
178
+ return [failed('unknown')];
179
+ const bytes = Buffer.from(text), prefix = bytes.subarray(0, head.byteLength);
180
+ if (!Number.isSafeInteger(head.byteLength) || head.byteLength < 0 || head.byteLength > bytes.length
181
+ || (head.byteLength > 0 && bytes[head.byteLength - 1] !== 10)
182
+ || prefix.toString('utf8').split('\n').filter(l => l.trim()).length !== end + 1)
183
+ return [failed('unknown')];
184
+ }
185
+ for (const file of ['fail-open-pending.ndjson', 'fail-open-pending.ndjson.recovering', 'session-receipts-pending.ndjson', 'ledger/unrecorded.ndjson', 'ledger/decisions.ndjson.sync-error.json']) {
186
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(data, file)) && (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, file), 'utf8').trim())
187
+ return [missing('unknown', 'Some decisions have no signed receipt yet.')];
188
+ }
189
+ if (entries.some(e => meta(e).integrity?.truncatedBytes > 0))
190
+ return [missing('unknown', 'The ledger records lost receipt data; a complete tally is unavailable.')];
191
+ }
192
+ catch (e) {
193
+ return e.code === 'ENOENT' ? [missing('unknown')] : [failed('unknown')];
194
+ }
195
+ return [...new Set(entries.filter(e => meta(e).event === 'session_receipt' || (meta(e).gate === 'burn' && spawn.has(meta(e).toolName))).map(e => meta(e).sessionId).filter((s) => typeof s === 'string'))].map(s => countedSession(entries, s));
196
+ }
197
+ /** Completion-day increments, so a resumed session's cumulative totals upload once. */
198
+ async function readLedgerDailyTallies(data) {
199
+ const complete = await readLedgerTallies(data);
200
+ if (complete.some(t => t.status !== 'verified'))
201
+ return complete;
202
+ const entries = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson'), 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
203
+ if (!await verifyTallyLedger(entries, (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim()))
204
+ return [failed('unknown')];
205
+ const result = [];
206
+ for (const session of new Set(entries.filter(e => meta(e).event === 'session_receipt').map(e => meta(e).sessionId))) {
207
+ if (countedSession(entries, session).status !== 'verified')
208
+ return [missing(session)];
209
+ const days = new Map();
210
+ let priorId;
211
+ for (let index = 0; index < entries.length; index++) {
212
+ const entry = entries[index];
213
+ if (meta(entry).sessionId !== session || meta(entry).event !== 'session_receipt')
214
+ continue;
215
+ if (meta(entry).previousReceiptId && meta(entry).previousReceiptId !== priorId)
216
+ return [missing(session, 'Resumed receipt linkage is incomplete.')];
217
+ priorId = entry.decision.decisionId;
218
+ const tally = countedSession(entries.slice(0, index + 1), session);
219
+ if (tally.status !== 'verified')
220
+ return [tally];
221
+ days.set(tally.date, tally);
222
+ }
223
+ let previous;
224
+ for (const tally of days.values()) {
225
+ const counts = Object.fromEntries(Object.entries(tally.counts).map(([key, value]) => [key, value - (previous?.counts[key] ?? 0)]));
226
+ const tokens = tally.tokens === null || previous?.tokens === null ? null : tally.tokens - (previous?.tokens ?? 0);
227
+ if (Object.values(counts).some(n => n < 0) || (tokens !== null && tokens < 0))
228
+ return [missing(session, 'A resumed session revised an earlier day. Daily counts are unavailable.')];
229
+ result.push({ ...tally, counts, tokens });
230
+ previous = tally;
231
+ }
232
+ }
233
+ return result;
234
+ }
235
+ async function sessionTally(session, options = {}) {
236
+ const results = [];
237
+ for (const data of options.data ? [options.data] : pluginLedgerDirectories(options.home)) {
238
+ if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson')))
239
+ continue;
240
+ const rows = await readLedgerTallies(data);
241
+ if (rows.some(r => r.status === 'verification_failed'))
242
+ return failed(session);
243
+ if (rows.some(r => r.session === 'unknown' && r.status === 'missing'))
244
+ return missing(session, 'Signed receipts or their public verification key are incomplete.');
245
+ results.push(...rows.filter(r => r.session === session));
246
+ }
247
+ if (results.length > 1)
248
+ return missing(session, 'This session spans multiple receipt ledgers; a complete tally is unavailable.');
249
+ return results[0] ?? missing(session);
250
+ }
251
+ function renderSessionTally(tally) {
252
+ if (tally.status !== 'verified')
253
+ return tally.reason;
254
+ const c = tally.counts;
255
+ const parts = [`${c.launches} launches`, `${c.allowed} allowed`];
256
+ if (tally.host !== 'codex' || c.asked)
257
+ parts.push(`${c.asked} asked`, `${c.saidYes} you approved`);
258
+ parts.push(`${c.stopped} refused`);
259
+ if (c.unresolvedAsked)
260
+ parts.push(`${c.unresolvedAsked} approval outcome not recorded`);
261
+ if (c.shadow)
262
+ parts.push(`${c.shadow} shadow`);
263
+ if (c.unrecorded)
264
+ parts.push(`${c.unrecorded} fail open`);
265
+ return parts.join(' · ');
266
+ }
@@ -5,10 +5,12 @@ exports.parseInsightTranscript = parseInsightTranscript;
5
5
  exports.readInsightTranscript = readInsightTranscript;
6
6
  exports.readInsightSession = readInsightSession;
7
7
  exports.deduplicateTurns = deduplicateTurns;
8
+ const tool_names_1 = require("../tool-names");
8
9
  const node_crypto_1 = require("node:crypto");
9
10
  const node_fs_1 = require("node:fs");
10
11
  const node_path_1 = require("node:path");
11
12
  const subagent_signals_1 = require("../history/subagent-signals");
13
+ const launch_evidence_1 = require("./launch-evidence");
12
14
  const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
13
15
  const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
14
16
  const hasCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
@@ -91,7 +93,7 @@ function observeTools(raw, state) {
91
93
  continue;
92
94
  const name = typeof block.name === 'string' ? block.name : '';
93
95
  const isRead = /^(?:(?:functions\.)?Read|(?:functions\.)?read_file)$/.test(name);
94
- const isSpawn = /^(?:(?:functions\.)?(?:Agent|Task|spawn_agent))$/.test(name);
96
+ const isSpawn = (0, tool_names_1.isLaunchTool)(name);
95
97
  if (!isRead && !isSpawn)
96
98
  continue;
97
99
  const id = digest(['tool', toolId]);
@@ -298,6 +300,8 @@ function observations(calls) {
298
300
  */
299
301
  function parseInsightTranscript(text, options = {}) {
300
302
  const state = options.state ?? emptyState(options);
303
+ if (options.collectLaunchTree)
304
+ state.launchEvidence ??= { nodes: Object.create(null), calls: Object.create(null), edges: [], owners: Object.create(null) };
301
305
  state.intervalStateVersion = 1;
302
306
  const diagnostics = { lines: 0, malformedLines: 0, duplicateUsageRecords: 0, unsupportedUsageRecords: 0, inheritedUsageRecords: 0 };
303
307
  const updated = new Map();
@@ -368,6 +372,8 @@ function parseInsightTranscript(text, options = {}) {
368
372
  diagnostics.inheritedUsageRecords++;
369
373
  continue;
370
374
  }
375
+ if (state.launchEvidence)
376
+ (0, launch_evidence_1.observeLaunchRecord)(raw, state, at);
371
377
  observeTools(raw, state);
372
378
  observeInputEvents(raw, state);
373
379
  observeImageBlocks(raw, state);
@@ -524,6 +530,8 @@ function parseInsightTranscript(text, options = {}) {
524
530
  }
525
531
  state.seen[id] = turn;
526
532
  updated.set(id, turn);
533
+ if (state.launchEvidence?.current)
534
+ state.launchEvidence.owners[id] = state.launchEvidence.current;
527
535
  }
528
536
  return { host: state.host, sessionId: state.sessionId, turns: Object.values(state.seen), updatedTurns: [...updated.values()], diagnostics, state,
529
537
  observations: observations(state.observedCalls ?? {}), acceptedQuotaLineNumbers };
@@ -0,0 +1,36 @@
1
+ import { type TranscriptLocation } from './sessions';
2
+ import type { InsightTranscript } from './types';
3
+ import type { LaunchEvidence } from './launch-evidence';
4
+ export interface LaunchNode {
5
+ id: string;
6
+ parent: string | null;
7
+ parentEvidence: string | null;
8
+ name: string;
9
+ models: string[];
10
+ ownTokens: number | null;
11
+ subtreeTokens: number | null;
12
+ tokenShare: number | null;
13
+ /** Active time, with each gap between recorded timestamps capped as in Burn. */
14
+ durationMs: number | null;
15
+ /** Elapsed time between the first and last recorded timestamps, including idle gaps. */
16
+ spanMs: number | null;
17
+ endedWithoutFinishing: boolean;
18
+ children: LaunchNode[];
19
+ depth?: number;
20
+ }
21
+ export interface LaunchTree {
22
+ session: string;
23
+ totalTokens: number | null;
24
+ root: LaunchNode;
25
+ unlinked: LaunchNode[];
26
+ notes: string[];
27
+ }
28
+ /** Edges require recorded parent metadata or a matched launch and result. */
29
+ export declare function buildLaunchTree(transcripts: InsightTranscript[], receipts?: LaunchEvidence): LaunchTree;
30
+ export declare function readLaunchTree(location: TranscriptLocation, locations?: TranscriptLocation[], receipts?: LaunchEvidence): LaunchTree;
31
+ export declare function readLaunchTreeWithReceipts(location: TranscriptLocation, options?: {
32
+ home?: string;
33
+ data?: string;
34
+ locations?: TranscriptLocation[];
35
+ }): Promise<LaunchTree>;
36
+ export declare function renderLaunchTree(tree: LaunchTree, short?: boolean): string;