@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.
- package/CHANGELOG.md +30 -0
- package/README.md +48 -0
- package/dist/src/adapters/codex.d.ts +4 -2
- package/dist/src/adapters/codex.js +55 -9
- package/dist/src/cli.js +43 -5
- package/dist/src/history/claude-transcript.d.ts +0 -13
- package/dist/src/history/claude-transcript.js +11 -10
- package/dist/src/hook/pre-tool-use.d.ts +0 -16
- package/dist/src/hook/pre-tool-use.js +15 -10
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +18 -1
- package/dist/src/insights/commits.d.ts +84 -0
- package/dist/src/insights/commits.js +379 -0
- package/dist/src/insights/i18n.d.ts +12 -1
- package/dist/src/insights/i18n.js +78 -0
- package/dist/src/insights/launch-evidence.d.ts +25 -0
- package/dist/src/insights/launch-evidence.js +54 -0
- package/dist/src/insights/price-shadow.js +2 -1
- package/dist/src/insights/render.d.ts +36 -2
- package/dist/src/insights/render.js +43 -1
- package/dist/src/insights/tally.d.ts +45 -0
- package/dist/src/insights/tally.js +266 -0
- package/dist/src/insights/transcript.js +9 -1
- package/dist/src/insights/tree.d.ts +36 -0
- package/dist/src/insights/tree.js +285 -0
- package/dist/src/insights/types.d.ts +25 -0
- package/dist/src/insights/types.js +5 -1
- package/dist/src/receipt.d.ts +10 -0
- package/dist/src/receipt.js +53 -2
- package/dist/src/tool-names.d.ts +6 -0
- package/dist/src/tool-names.js +10 -0
- package/dist/src/upgrade-moments.js +2 -1
- package/docs/OCT5_VERIFICATION.md +118 -0
- package/docs/TREE_AND_TALLY.md +70 -0
- package/docs/launch-tree-local-oct5.txt +7 -0
- package/docs/oct5-followup/REPORT.md +105 -0
- package/docs/oct5-followup/checks.json +20 -0
- package/docs/oct5-followup/free-plugin-fixture-output.txt +12 -0
- package/docs/oct5-followup/tally-after.json +5 -0
- package/docs/oct5-followup/tally-after.txt +1 -0
- package/docs/oct5-followup/tree-after.json +40 -0
- package/docs/oct5-followup/tree-after.txt +7 -0
- package/docs/oct5-followup/tree-before.txt +7 -0
- package/docs/oct5-followup/verify-free-receipts.cjs +81 -0
- package/docs/session-tally-local-oct5.txt +1 -0
- package/package.json +7 -3
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildLaunchTree = buildLaunchTree;
|
|
4
|
+
exports.readLaunchTree = readLaunchTree;
|
|
5
|
+
exports.readLaunchTreeWithReceipts = readLaunchTreeWithReceipts;
|
|
6
|
+
exports.renderLaunchTree = renderLaunchTree;
|
|
7
|
+
const node_fs_1 = require("node:fs");
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
const defaults_1 = require("../defaults");
|
|
10
|
+
const subagent_signals_1 = require("../history/subagent-signals");
|
|
11
|
+
const sessions_1 = require("./sessions");
|
|
12
|
+
const transcript_1 = require("./transcript");
|
|
13
|
+
const tally_1 = require("./tally");
|
|
14
|
+
const tokens = (t) => t.inputTokens + t.outputTokens + t.cacheReadTokens + t.cacheWriteTokens;
|
|
15
|
+
const sourceId = (t) => t.state.lineage?.sessionId ?? t.sessionId.replace(/^agent-/, '');
|
|
16
|
+
/** Edges require recorded parent metadata or a matched launch and result. */
|
|
17
|
+
function buildLaunchTree(transcripts, receipts) {
|
|
18
|
+
if (!transcripts.length)
|
|
19
|
+
throw new Error('No session transcript recorded.');
|
|
20
|
+
const rootId = sourceId(transcripts[0]);
|
|
21
|
+
const nodes = new Map(), times = new Map();
|
|
22
|
+
const incomplete = new Set(), owners = new Map();
|
|
23
|
+
const candidates = new Map();
|
|
24
|
+
const signals = { completed: new Set(), ended: new Set(), resumed: new Set() };
|
|
25
|
+
const notes = new Set();
|
|
26
|
+
const get = (id) => {
|
|
27
|
+
if (!nodes.has(id))
|
|
28
|
+
nodes.set(id, { id, parent: null, parentEvidence: null, name: id === rootId ? 'main session' : 'agent', models: [], ownTokens: null, subtreeTokens: null, tokenShare: null, durationMs: null, spanMs: null, endedWithoutFinishing: false, children: [] });
|
|
29
|
+
return nodes.get(id);
|
|
30
|
+
};
|
|
31
|
+
for (const t of transcripts) {
|
|
32
|
+
const sid = sourceId(t), node = get(sid);
|
|
33
|
+
const original = t.state.launchEvidence;
|
|
34
|
+
const mergedNodes = { ...original?.nodes };
|
|
35
|
+
if (t === transcripts[0])
|
|
36
|
+
for (const [id, value] of Object.entries(receipts?.nodes ?? {}))
|
|
37
|
+
mergedNodes[id] = { ...mergedNodes[id], ...value };
|
|
38
|
+
const e = t === transcripts[0] && receipts ? { ...original, nodes: mergedNodes,
|
|
39
|
+
edges: [...(original?.edges ?? []), ...receipts.edges], owners: original?.owners ?? {}, calls: original?.calls ?? {} } : original;
|
|
40
|
+
if (t.state.forkHistoryBoundaryUnknown || t.diagnostics.malformedLines) {
|
|
41
|
+
incomplete.add(sid);
|
|
42
|
+
for (const id of Object.keys(e?.nodes ?? {}))
|
|
43
|
+
incomplete.add(id);
|
|
44
|
+
notes.add('Some token usage is unavailable because transcript ownership or records are incomplete.');
|
|
45
|
+
}
|
|
46
|
+
for (const [id, meta] of Object.entries(e?.nodes ?? {})) {
|
|
47
|
+
const n = get(id);
|
|
48
|
+
if (meta.name)
|
|
49
|
+
n.name = meta.name;
|
|
50
|
+
if (meta.depth !== undefined)
|
|
51
|
+
n.depth = meta.depth;
|
|
52
|
+
if (meta.model && !n.models.includes(meta.model))
|
|
53
|
+
n.models.push(meta.model);
|
|
54
|
+
const activity = times.get(id) ?? new Set();
|
|
55
|
+
for (const at of meta.activityAt ?? [])
|
|
56
|
+
activity.add(at);
|
|
57
|
+
times.set(id, activity);
|
|
58
|
+
}
|
|
59
|
+
const edges = [...(e?.edges ?? [])];
|
|
60
|
+
if (t.state.lineage?.parentSessionId)
|
|
61
|
+
edges.push({ child: sid, parent: t.state.lineage.parentSessionId, source: 'parent metadata' });
|
|
62
|
+
for (const edge of edges) {
|
|
63
|
+
get(edge.child);
|
|
64
|
+
const parents = candidates.get(edge.child) ?? new Map();
|
|
65
|
+
parents.set(edge.parent, edge.source);
|
|
66
|
+
candidates.set(edge.child, parents);
|
|
67
|
+
}
|
|
68
|
+
for (const signal of ['completed', 'ended', 'resumed'])
|
|
69
|
+
for (const id of Object.keys(t.state.subagentSignals?.[signal] ?? {}))
|
|
70
|
+
signals[signal].add(id);
|
|
71
|
+
for (const turn of t.turns) {
|
|
72
|
+
const prior = owners.get(turn.id);
|
|
73
|
+
if (!prior || (turn.at !== undefined && (prior.at === undefined || turn.at < prior.at)))
|
|
74
|
+
owners.set(turn.id, { at: turn.at, id: e?.owners[turn.id] ?? sid });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Attribute a provider response once, using the same deduplication as why.
|
|
78
|
+
for (const turn of (0, transcript_1.deduplicateTurns)(transcripts.flatMap(t => t.turns))) {
|
|
79
|
+
const id = owners.get(turn.id).id, node = get(id);
|
|
80
|
+
if (!incomplete.has(id))
|
|
81
|
+
node.ownTokens = (node.ownTokens ?? 0) + tokens(turn);
|
|
82
|
+
if (turn.model && !node.models.includes(turn.model))
|
|
83
|
+
node.models.push(turn.model);
|
|
84
|
+
}
|
|
85
|
+
for (const node of nodes.values()) {
|
|
86
|
+
const parents = candidates.get(node.id);
|
|
87
|
+
if (node.id !== rootId && parents?.size === 1) {
|
|
88
|
+
const [parent, evidence] = [...parents][0];
|
|
89
|
+
if (nodes.has(parent) && parent !== node.id) {
|
|
90
|
+
node.parent = parent;
|
|
91
|
+
node.parentEvidence = evidence;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (parents && parents.size > 1)
|
|
95
|
+
notes.add('Conflicting parent records are shown under parent not recorded.');
|
|
96
|
+
node.endedWithoutFinishing = (0, subagent_signals_1.endedWithoutFinishing)(node.id, signals);
|
|
97
|
+
const ts = [...(times.get(node.id) ?? [])].sort((a, b) => a - b);
|
|
98
|
+
if (ts.length) {
|
|
99
|
+
node.spanMs = ts[ts.length - 1] - ts[0];
|
|
100
|
+
node.durationMs = 0;
|
|
101
|
+
for (let i = 1; i < ts.length; i++)
|
|
102
|
+
node.durationMs += Math.min(ts[i] - ts[i - 1], defaults_1.ACTIVE_GAP_CAP_MS);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// Break every edge involved in a cycle. Never choose a guessed parent.
|
|
106
|
+
for (const node of nodes.values()) {
|
|
107
|
+
const seen = new Set([node.id]);
|
|
108
|
+
let current = node;
|
|
109
|
+
while (current.parent) {
|
|
110
|
+
if (seen.has(current.parent)) {
|
|
111
|
+
for (const id of seen) {
|
|
112
|
+
get(id).parent = null;
|
|
113
|
+
get(id).parentEvidence = null;
|
|
114
|
+
}
|
|
115
|
+
notes.add('Cyclic parent records are shown under parent not recorded.');
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
seen.add(current.parent);
|
|
119
|
+
current = get(current.parent);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const unlinked = [];
|
|
123
|
+
for (const node of nodes.values()) {
|
|
124
|
+
if (node.parent)
|
|
125
|
+
get(node.parent).children.push(node);
|
|
126
|
+
else if (node.id !== rootId)
|
|
127
|
+
unlinked.push(node);
|
|
128
|
+
}
|
|
129
|
+
const total = [...nodes.values()].some(n => n.ownTokens === null) ? null : [...nodes.values()].reduce((sum, n) => sum + n.ownTokens, 0);
|
|
130
|
+
const sum = (n) => {
|
|
131
|
+
const child = n.children.map(sum);
|
|
132
|
+
n.subtreeTokens = n.ownTokens === null || child.includes(null) ? null : n.ownTokens + child.reduce((s, v) => s + v, 0);
|
|
133
|
+
n.tokenShare = total === null || total === 0 || n.ownTokens === null ? null : n.ownTokens / total;
|
|
134
|
+
n.children.sort((a, b) => a.id.localeCompare(b.id));
|
|
135
|
+
return n.subtreeTokens;
|
|
136
|
+
};
|
|
137
|
+
const root = get(rootId);
|
|
138
|
+
sum(root);
|
|
139
|
+
unlinked.forEach(sum);
|
|
140
|
+
if ([...nodes.values()].some(n => n.ownTokens === null))
|
|
141
|
+
notes.add('Missing usage is unknown, including children without a recorded transcript.');
|
|
142
|
+
return { session: rootId, totalTokens: total, root, unlinked, notes: [...notes] };
|
|
143
|
+
}
|
|
144
|
+
// Codex records identity and the parent in its first session_meta row. Inspect
|
|
145
|
+
// that bounded header before opening the full history of a related child.
|
|
146
|
+
function codexHeader(location) {
|
|
147
|
+
let fd;
|
|
148
|
+
try {
|
|
149
|
+
fd = (0, node_fs_1.openSync)(location.path, 'r');
|
|
150
|
+
const buffer = Buffer.alloc(1024 * 1024), length = (0, node_fs_1.readSync)(fd, buffer, 0, buffer.length, 0);
|
|
151
|
+
const first = buffer.subarray(0, length).toString('utf8').split('\n').find(line => line.trim());
|
|
152
|
+
if (!first)
|
|
153
|
+
return null;
|
|
154
|
+
const row = JSON.parse(first);
|
|
155
|
+
if (row.type !== 'session_meta')
|
|
156
|
+
return null;
|
|
157
|
+
const p = row.payload, parent = p?.parent_thread_id ?? p?.source?.subagent?.thread_spawn?.parent_thread_id;
|
|
158
|
+
return typeof p?.id === 'string' ? { id: p.id, ...(typeof parent === 'string' ? { parent } : {}) } : null;
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
if (fd !== undefined)
|
|
165
|
+
(0, node_fs_1.closeSync)(fd);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function readLaunchTree(location, locations, receipts) {
|
|
169
|
+
const load = (item) => (0, transcript_1.readInsightTranscript)(item.path, { host: item.host, sessionId: item.sessionId, collectLaunchTree: true });
|
|
170
|
+
const root = load(location), list = [root];
|
|
171
|
+
if (location.host === 'claude') {
|
|
172
|
+
const directory = (0, node_path_1.join)(location.path.replace(/\.jsonl$/, ''), 'subagents');
|
|
173
|
+
try {
|
|
174
|
+
for (const name of (0, node_fs_1.readdirSync)(directory).filter(n => /^agent-.+\.jsonl$/.test(n)).sort())
|
|
175
|
+
list.push(load({ path: (0, node_path_1.join)(directory, name), sessionId: (0, node_path_1.basename)(name, '.jsonl'), host: 'claude', modifiedAt: 0 }));
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
if (e.code !== 'ENOENT')
|
|
179
|
+
throw e;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
const all = (locations ?? (0, sessions_1.discoverInsightTranscripts)()).filter(l => l.host === 'codex' && l.path !== location.path).map(location => ({ location, header: codexHeader(location) }));
|
|
184
|
+
const ids = new Set([sourceId(root)]);
|
|
185
|
+
const loaded = new Set([location.path]);
|
|
186
|
+
const recordedChildren = new Set(Object.keys(root.state.launchEvidence?.nodes ?? {}));
|
|
187
|
+
for (let changed = true; changed;) {
|
|
188
|
+
changed = false;
|
|
189
|
+
for (const { location: item, header } of all)
|
|
190
|
+
if (!loaded.has(item.path) && header && ((header.parent && ids.has(header.parent)) || recordedChildren.has(header.id))) {
|
|
191
|
+
const t = load(item);
|
|
192
|
+
loaded.add(item.path);
|
|
193
|
+
ids.add(sourceId(t));
|
|
194
|
+
list.push(t);
|
|
195
|
+
changed = true;
|
|
196
|
+
for (const child of Object.keys(t.state.launchEvidence?.nodes ?? {}))
|
|
197
|
+
recordedChildren.add(child);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return buildLaunchTree(list, receipts);
|
|
202
|
+
}
|
|
203
|
+
async function readLaunchTreeWithReceipts(location, options = {}) {
|
|
204
|
+
const evidence = { nodes: {}, calls: {}, edges: [], owners: {} };
|
|
205
|
+
const session = (location.host === 'codex' ? codexHeader(location)?.id : location.sessionId) ?? location.sessionId;
|
|
206
|
+
const id = (v) => typeof v === 'string' && /^[A-Za-z0-9_.:@/-]{1,256}$/.test(v) ? v : null;
|
|
207
|
+
const caller = (v) => v === 'main' ? session : id(v);
|
|
208
|
+
for (const row of await (0, tally_1.sessionLaunchReceipts)(session, options)) {
|
|
209
|
+
const m = row.decision.plugin, who = caller(m.agent_id ?? m.launch?.callerId);
|
|
210
|
+
if (who) {
|
|
211
|
+
const old = evidence.nodes[who] ??= {};
|
|
212
|
+
const name = id(m.agent_type ?? m.launch?.callerType);
|
|
213
|
+
if (name)
|
|
214
|
+
old.name = name;
|
|
215
|
+
if (Number.isSafeInteger(m.depth) && m.depth >= 0)
|
|
216
|
+
old.depth = m.depth;
|
|
217
|
+
const parent = caller(m.parent_agent_id ?? m.launch?.parentAgentId);
|
|
218
|
+
if (parent)
|
|
219
|
+
evidence.edges.push({ child: who, parent, source: 'signed caller metadata' });
|
|
220
|
+
}
|
|
221
|
+
const child = id(m.spawned_agent_id);
|
|
222
|
+
if (child && who && m.event === 'outcome' && m.success !== false) {
|
|
223
|
+
evidence.nodes[child] ??= {};
|
|
224
|
+
const name = id(m.launch?.agentType);
|
|
225
|
+
if (name)
|
|
226
|
+
evidence.nodes[child].name = name;
|
|
227
|
+
if (Number.isSafeInteger(m.launch?.depth))
|
|
228
|
+
evidence.nodes[child].depth = m.launch.depth;
|
|
229
|
+
evidence.edges.push({ child, parent: who, source: 'signed launch outcome' });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return readLaunchTree(location, options.locations, evidence);
|
|
233
|
+
}
|
|
234
|
+
const compact = (n) => n === null ? '?' : n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n);
|
|
235
|
+
function humanDuration(ms, days = false) {
|
|
236
|
+
const minutes = Math.floor(ms / 60000), hours = Math.floor(minutes / 60);
|
|
237
|
+
if (ms > 0 && minutes === 0)
|
|
238
|
+
return '<1m';
|
|
239
|
+
if (days && hours >= 24)
|
|
240
|
+
return `${Math.floor(hours / 24)}d ${hours % 24}h`;
|
|
241
|
+
return hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
|
|
242
|
+
}
|
|
243
|
+
function renderLaunchTree(tree, short = false) {
|
|
244
|
+
const lines = ['Launch tree', 'Own / subtree tokens | share of session tokens | active time'];
|
|
245
|
+
const cut = (v, size) => [...v].length > size ? [...v].slice(0, size - 1).join('') + '…' : v;
|
|
246
|
+
let shown = 0;
|
|
247
|
+
const print = (n, depth) => {
|
|
248
|
+
if (short && shown >= 5)
|
|
249
|
+
return;
|
|
250
|
+
shown++;
|
|
251
|
+
const indent = ' '.repeat(Math.min(depth, 8));
|
|
252
|
+
lines.push(cut(`${indent}${depth > 8 ? 'depth ' + depth + ': ' : ''}${n.name} [${n.id.slice(0, 12)}] ${n.models.join(', ') || 'model not recorded'}`, 80));
|
|
253
|
+
const active = n.durationMs === null ? '?' : humanDuration(n.durationMs);
|
|
254
|
+
const span = n.spanMs !== null && n.spanMs !== n.durationMs ? ` · span ${humanDuration(n.spanMs, true)}` : '';
|
|
255
|
+
lines.push(cut(`${indent} ${compact(n.ownTokens)} / ${compact(n.subtreeTokens)} | ${n.tokenShare === null ? '?' : (100 * n.tokenShare).toFixed(1) + '%'} | active ${active}${span}`, 80));
|
|
256
|
+
if (n.endedWithoutFinishing)
|
|
257
|
+
lines.push(`${indent} ended without finishing`);
|
|
258
|
+
let visible = 0;
|
|
259
|
+
for (const child of n.children.slice(0, short ? 5 : 6)) {
|
|
260
|
+
if (short && shown >= 5)
|
|
261
|
+
break;
|
|
262
|
+
print(child, depth + 1);
|
|
263
|
+
visible++;
|
|
264
|
+
}
|
|
265
|
+
if (n.children.length > visible)
|
|
266
|
+
lines.push(`${indent} + ${n.children.length - visible} more like this`);
|
|
267
|
+
};
|
|
268
|
+
print(tree.root, 0);
|
|
269
|
+
if (tree.unlinked.length) {
|
|
270
|
+
lines.push('parent not recorded');
|
|
271
|
+
let visible = 0;
|
|
272
|
+
for (const node of tree.unlinked.slice(0, short ? 5 : 6)) {
|
|
273
|
+
if (short && shown >= 5)
|
|
274
|
+
break;
|
|
275
|
+
print(node, 1);
|
|
276
|
+
visible++;
|
|
277
|
+
}
|
|
278
|
+
if (tree.unlinked.length > visible)
|
|
279
|
+
lines.push(` + ${tree.unlinked.length - visible} more like this`);
|
|
280
|
+
}
|
|
281
|
+
lines.push(`Session tokens: ${compact(tree.totalTokens)}. Shares use each node's own tokens.`);
|
|
282
|
+
for (const note of tree.notes)
|
|
283
|
+
lines.push(cut(note, 80));
|
|
284
|
+
return lines.join('\n');
|
|
285
|
+
}
|
|
@@ -77,6 +77,7 @@ export interface InsightDiagnostics {
|
|
|
77
77
|
inheritedUsageRecords?: number;
|
|
78
78
|
}
|
|
79
79
|
export interface InsightParserState {
|
|
80
|
+
launchEvidence?: import('./launch-evidence').LaunchEvidence;
|
|
80
81
|
host: InsightHost;
|
|
81
82
|
sessionId: string;
|
|
82
83
|
model?: string;
|
|
@@ -177,6 +178,30 @@ export interface InsightParseOptions {
|
|
|
177
178
|
sessionId?: string;
|
|
178
179
|
state?: InsightParserState;
|
|
179
180
|
spawnedSession?: boolean;
|
|
181
|
+
collectLaunchTree?: boolean;
|
|
182
|
+
}
|
|
183
|
+
/** 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. */
|
|
184
|
+
export declare const COMMIT_GRACE_MS: number;
|
|
185
|
+
/** 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. */
|
|
186
|
+
export declare const GIT_BUDGET_MS = 2000;
|
|
187
|
+
/** `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. */
|
|
188
|
+
export type CommitsStatus = 'ok' | 'no_repository' | 'unrecorded' | 'git_missing' | 'git_timeout' | 'git_error';
|
|
189
|
+
/**
|
|
190
|
+
* What `why --commits` counted for one session (src/insights/commits.ts): the
|
|
191
|
+
* commits whose committer time falls in the session's window, each counted once
|
|
192
|
+
* by hash; how many of them a Co-authored-by trailer credits to Claude Code and
|
|
193
|
+
* to Codex; and the other local sessions whose windows overlap it in the same
|
|
194
|
+
* repository. Counts only, never a hash, email, message or path. Every count is
|
|
195
|
+
* 0 unless `status` is `ok`.
|
|
196
|
+
*/
|
|
197
|
+
export interface SessionCommits {
|
|
198
|
+
status: CommitsStatus;
|
|
199
|
+
landed: number;
|
|
200
|
+
claudeCode: number;
|
|
201
|
+
codex: number;
|
|
202
|
+
/** Commits co-authored by Claude Code or Codex, each counted once: a commit naming both counts once here and once in each count above. */
|
|
203
|
+
coAuthored: number;
|
|
204
|
+
overlappingSessions: number;
|
|
180
205
|
}
|
|
181
206
|
/** Precedence order when several signals are present; `unknown` is the Codex residual, never prefix change by default. */
|
|
182
207
|
export type RewriteCause = 'model_switch' | 'version_upgrade' | 'compaction' | 'first_spawned_turn' | 'idle_ttl_expired' | 'image_pruning' | 'prefix_change' | 'unknown_ttl' | 'unknown';
|
|
@@ -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/dist/src/receipt.d.ts
CHANGED
|
@@ -22,6 +22,11 @@ export interface ReceiptPayload {
|
|
|
22
22
|
/** sha256 of the session id: correlatable, not reversible. */
|
|
23
23
|
sessionDigest: string;
|
|
24
24
|
action: 'spawn' | 'model_call';
|
|
25
|
+
/** Exact host call identity, needed when another local plugin records outcomes. */
|
|
26
|
+
toolUseId?: string;
|
|
27
|
+
agent_id?: string | null;
|
|
28
|
+
agent_type?: string | null;
|
|
29
|
+
depth?: number | null;
|
|
25
30
|
policy: {
|
|
26
31
|
mode: 'shadow' | 'enforce';
|
|
27
32
|
digest: string;
|
|
@@ -59,3 +64,8 @@ export declare class ReceiptSigner {
|
|
|
59
64
|
}
|
|
60
65
|
export declare function verifyReceipt(receipt: SignedReceipt): boolean;
|
|
61
66
|
export declare function receiptDigest(receipt: SignedReceipt): string;
|
|
67
|
+
/** A standalone Claude hook owns admission; the plugin owns the host outcome.
|
|
68
|
+
* Verify its complete session chain and persisted head before correlating a
|
|
69
|
+
* call. Missing or old schemas yield no verdict, never an inferred allow.
|
|
70
|
+
*/
|
|
71
|
+
export declare function readSpawnAdmission(home: string, sessionId: string, toolUseId: string): SignedReceipt | null;
|
package/dist/src/receipt.js
CHANGED
|
@@ -19,6 +19,7 @@ exports.canonical = canonical;
|
|
|
19
19
|
exports.sha256 = sha256;
|
|
20
20
|
exports.verifyReceipt = verifyReceipt;
|
|
21
21
|
exports.receiptDigest = receiptDigest;
|
|
22
|
+
exports.readSpawnAdmission = readSpawnAdmission;
|
|
22
23
|
const node_crypto_1 = require("node:crypto");
|
|
23
24
|
const node_fs_1 = require("node:fs");
|
|
24
25
|
const node_path_1 = require("node:path");
|
|
@@ -49,8 +50,31 @@ class ReceiptSigner {
|
|
|
49
50
|
}
|
|
50
51
|
static loadOrCreate(home) {
|
|
51
52
|
const file = (0, node_path_1.join)(home, 'receipt-signing-key.pem');
|
|
53
|
+
const publish = () => {
|
|
54
|
+
const signer = new ReceiptSigner((0, node_fs_1.readFileSync)(file, 'utf8'));
|
|
55
|
+
// Readers pin this local public key instead of trusting a key supplied
|
|
56
|
+
// by a receipt. No private key is needed to ingest a standalone verdict.
|
|
57
|
+
const publicFile = (0, node_path_1.join)(home, 'receipt-public-key.base64');
|
|
58
|
+
if (!(0, node_fs_1.existsSync)(publicFile)) {
|
|
59
|
+
const temporary = `${publicFile}.${process.pid}.tmp`;
|
|
60
|
+
(0, node_fs_1.writeFileSync)(temporary, signer.publicKey + '\n', { mode: 0o600 });
|
|
61
|
+
try {
|
|
62
|
+
(0, node_fs_1.linkSync)(temporary, publicFile);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error.code !== 'EEXIST')
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
(0, node_fs_1.rmSync)(temporary, { force: true });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if ((0, node_fs_1.readFileSync)(publicFile, 'utf8').trim() !== signer.publicKey)
|
|
73
|
+
throw new Error('Burn receipt public key does not match its signer.');
|
|
74
|
+
return signer;
|
|
75
|
+
};
|
|
52
76
|
if ((0, node_fs_1.existsSync)(file))
|
|
53
|
-
return
|
|
77
|
+
return publish();
|
|
54
78
|
(0, node_fs_1.mkdirSync)(home, { recursive: true, mode: 0o700 });
|
|
55
79
|
// Sixty hook processes on a fresh home all arrive here at once. Exactly
|
|
56
80
|
// one key must win: write to a private temp name, then link it into
|
|
@@ -70,7 +94,7 @@ class ReceiptSigner {
|
|
|
70
94
|
finally {
|
|
71
95
|
(0, node_fs_1.rmSync)(tmp, { force: true });
|
|
72
96
|
}
|
|
73
|
-
return
|
|
97
|
+
return publish();
|
|
74
98
|
}
|
|
75
99
|
sign(payload) {
|
|
76
100
|
const bytes = Buffer.from(canonical(payload));
|
|
@@ -96,3 +120,30 @@ function verifyReceipt(receipt) {
|
|
|
96
120
|
function receiptDigest(receipt) {
|
|
97
121
|
return sha256(canonical(receipt));
|
|
98
122
|
}
|
|
123
|
+
/** A standalone Claude hook owns admission; the plugin owns the host outcome.
|
|
124
|
+
* Verify its complete session chain and persisted head before correlating a
|
|
125
|
+
* call. Missing or old schemas yield no verdict, never an inferred allow.
|
|
126
|
+
*/
|
|
127
|
+
function readSpawnAdmission(home, sessionId, toolUseId) {
|
|
128
|
+
if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'receipts.ndjson')) || !(0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'receipt-public-key.base64')))
|
|
129
|
+
return null;
|
|
130
|
+
const key = (0, node_fs_1.readFileSync)((0, node_path_1.join)(home, 'receipt-public-key.base64'), 'utf8').trim();
|
|
131
|
+
const rows = (0, node_fs_1.readFileSync)((0, node_path_1.join)(home, 'receipts.ndjson'), 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
132
|
+
const digest = sha256(sessionId);
|
|
133
|
+
let previous = null, match = null;
|
|
134
|
+
for (const row of rows) {
|
|
135
|
+
if (row.payload?.sessionDigest !== digest)
|
|
136
|
+
continue;
|
|
137
|
+
if (row.payload.previous !== previous || row.publicKey !== key || !verifyReceipt(row))
|
|
138
|
+
throw new Error('External Burn signature or chain verification failed.');
|
|
139
|
+
previous = receiptDigest(row);
|
|
140
|
+
if (row.payload.host === 'claude-code' && row.payload.action === 'spawn' && row.payload.toolUseId === toolUseId)
|
|
141
|
+
match = row;
|
|
142
|
+
}
|
|
143
|
+
if (!previous)
|
|
144
|
+
return null;
|
|
145
|
+
const state = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(home, 'sessions', sessionId.replace(/[^a-zA-Z0-9_-]/g, '_') + '.json'), 'utf8'));
|
|
146
|
+
if (state.lastReceipt !== previous)
|
|
147
|
+
throw new Error('External Burn receipt head is incomplete.');
|
|
148
|
+
return match;
|
|
149
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Host tool names observed in hooks and transcripts. No substring matching. */
|
|
2
|
+
export declare function isLaunchTool(value: unknown): boolean;
|
|
3
|
+
/** Shared Set-shaped interface for existing admission and reporting callers. */
|
|
4
|
+
export declare const LAUNCH_TOOLS: Readonly<{
|
|
5
|
+
has: typeof isLaunchTool;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LAUNCH_TOOLS = void 0;
|
|
4
|
+
exports.isLaunchTool = isLaunchTool;
|
|
5
|
+
/** Host tool names observed in hooks and transcripts. No substring matching. */
|
|
6
|
+
function isLaunchTool(value) {
|
|
7
|
+
return typeof value === 'string' && /^(?:functions\.)?(?:Agent|Task|spawn_agent|collaborationspawn_agent|collaboration\.spawn_agent)$/.test(value);
|
|
8
|
+
}
|
|
9
|
+
/** Shared Set-shaped interface for existing admission and reporting callers. */
|
|
10
|
+
exports.LAUNCH_TOOLS = Object.freeze({ has: isLaunchTool });
|
|
@@ -5,6 +5,7 @@ exports.setQuiet = setQuiet;
|
|
|
5
5
|
exports.pluginDirectories = pluginDirectories;
|
|
6
6
|
exports.monthlySummary = monthlySummary;
|
|
7
7
|
exports.renderMonthlySummary = renderMonthlySummary;
|
|
8
|
+
const tool_names_1 = require("./tool-names");
|
|
8
9
|
/** Local month-to-date counts and a dismissible Team invitation. No network. */
|
|
9
10
|
const node_fs_1 = require("node:fs");
|
|
10
11
|
const node_path_1 = require("node:path");
|
|
@@ -119,7 +120,7 @@ function monthlySummary(home, now = Date.now(), env = process.env) {
|
|
|
119
120
|
const at = typeof decision.timestamp === 'string' ? Date.parse(decision.timestamp) : NaN;
|
|
120
121
|
if (!(at >= since && at <= now) || meta.event !== 'decision' || decision.action !== 'block' || decision.enforcementMode !== 'enforce' || meta.approvalNeeded === true || typeof decision.decisionId !== 'string')
|
|
121
122
|
continue;
|
|
122
|
-
if (meta.gate === 'burn' &&
|
|
123
|
+
if (meta.gate === 'burn' && (0, tool_names_1.isLaunchTool)(meta.toolName))
|
|
123
124
|
spawns.add(typeof meta.burnReceiptId === 'string' ? 'burn:' + meta.burnReceiptId : 'plugin:' + decision.decisionId);
|
|
124
125
|
if (meta.gate === 'spend' && /(?:^|[._])(?:bash|powershell|shell|exec_command|run_command|execute_command|run_shell_command|shell_command)$/i.test(String(meta.toolName)))
|
|
125
126
|
commands.add(decision.decisionId);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# October 5 feature verification
|
|
2
|
+
|
|
3
|
+
Branches: `burn/launch-tree-tally-oct5` in the monorepo and `site/team-view-oct5` in the site repository. Fresh worktrees started from fetched `origin/main`. The site was rebased onto `540211a` before its final checks. All commits are signed as MerchantGuardOps. Nothing was pushed, published, deployed or sent to a person. Production keys and environment variables were not changed.
|
|
4
|
+
|
|
5
|
+
## Feature 1: real local launch tree
|
|
6
|
+
|
|
7
|
+
Actual command: `node dist/src/cli.js tree /Users/soccer/.claude/projects/-Users-soccer/321cfac5-66b0-4e36-ada5-01dcf3f0ba17.jsonl`.
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
Launch tree
|
|
11
|
+
Own / subtree tokens | share of session tokens | recorded duration
|
|
12
|
+
main session [321cfac5-66b] claude-fable-5-1, claude-opus-5-5
|
|
13
|
+
661.8M / 668.1M | 99.0% | 1292819s
|
|
14
|
+
general-purpose [a20b05bb4d19] claude-opus-5-5
|
|
15
|
+
6.4M / 6.4M | 1.0% | 631s
|
|
16
|
+
Session tokens: 668.1M. Shares use each node's own tokens.
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The exact JSON total is 668,141,484 tokens. The same short tree appeared in `why`. JSON output was also exercised. Duration includes elapsed gaps in the real transcript. A larger real session exercised the collapsed fan-out and the `parent not recorded` group. Tests cover depth three, missing and conflicting parents, cyclic records, provider deduplication, anonymous sidechains, missing child usage, Codex child discovery and wide or short displays.
|
|
20
|
+
|
|
21
|
+
## Feature 2: actual tally output
|
|
22
|
+
|
|
23
|
+
The same real session's `tally` output was:
|
|
24
|
+
|
|
25
|
+
```text
|
|
26
|
+
Signed session receipts are missing.
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
UNVERIFIED: a numeric tally for that real session. Its signed plugin receipts were not available. No transcript-derived replacement was invented.
|
|
30
|
+
|
|
31
|
+
A freshly signed synthetic ledger passed through the actual Burn CLI, unscoped wrapper, plugin tip and Team sync module. Both CLI names printed:
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
4 launches · 1 allowed · 2 asked · 1 you approved · 1 refused · 1 approval outcome not recorded
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The cached tip was:
|
|
38
|
+
|
|
39
|
+
```text
|
|
40
|
+
AgentGuard tip from your last session: 4 launches · 1 allowed · 2 asked · 1 you approved · 1 refused · 1 approval outcome not recorded
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Changing a signed decision after signing caused exit status 1 and prevented upload:
|
|
44
|
+
|
|
45
|
+
```text
|
|
46
|
+
Receipt signature or hash chain verification failed.
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Signature tests also reject removed middle rows, reordered or duplicated rows, a missing final summary, and a removed tail that disagrees with the worker's durable checkpoint. Approvals are a subset of asks. Refused means policy refusal; missing human answers remain unrecorded.
|
|
50
|
+
|
|
51
|
+
Installed Claude Code 2.1.289 displayed this SessionStart probe in its terminal:
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
SessionStart:startup says: AgentGuard tally display probe: 4 launches · 3 allowed · 1 refused
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Installed native Codex 0.160.0 displayed the SessionStart probe after the first prompt, before a separate UserPromptSubmit hook stopped the turn:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
↳ Hook · AgentGuard tally display probe: 4 launches · 3 allowed · 1 refused
|
|
61
|
+
• Hook stopped
|
|
62
|
+
└ Local probe stopped before model execution.
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Codex `exec` text and JSON modes did not display the message. The JSON probe recorded zero model tokens. The default PATH Codex launcher had a missing optional x64 package; verification used the installed native arm64 binary. Local terminal captures are under `/private/tmp/agentguard-host-probe/` in `claude-tui.txt`, `codex-sessionstart-tui.txt`, `codex-output.txt` and `codex-text.txt`.
|
|
66
|
+
|
|
67
|
+
## Feature 5: actual Team fixture output
|
|
68
|
+
|
|
69
|
+
The local page used the real dashboard authentication, license validation, signature verification, existing Redis store and API routes with synthetic licenses and data. Rendered totals were:
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
3 seats shared counts
|
|
73
|
+
Launches 84
|
|
74
|
+
Asks 11
|
|
75
|
+
Approvals 8
|
|
76
|
+
Refusals 6
|
|
77
|
+
Tokens 18,600,000
|
|
78
|
+
3 approval outcomes were not recorded.
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The full receipt-to-dashboard fixture uploaded one additional machine with 4 launches and 1,234 tokens. Sharing off made no upload; sharing on with valid Team access uploaded one signed aggregate; a tampered receipt prevented the next upload. Unknown payload fields, invalid signatures or arithmetic, foreign accounts, unregistered or revoked seats, expired or Solo licenses, concurrent duplicates and key replacement were tested.
|
|
82
|
+
|
|
83
|
+
| Viewport | scrollWidth | Console errors | Main action |
|
|
84
|
+
| --- | --- | --- | --- |
|
|
85
|
+
| 390 x 844 | 390 | 0 | Refresh counts passed |
|
|
86
|
+
| 1280 x 800 | 1280 | 0 | Refresh counts passed |
|
|
87
|
+
|
|
88
|
+
Screenshots are in the site worktree at `docs/team-view-oct5/team-390x844.png` and `docs/team-view-oct5/team-1280x800.png`. `verification.json` records the rendered text, viewport results and actual auth and dashboard requests. `receipts-verification.json` records the cross-repository signed-receipt fixture. Both screenshots were visually inspected.
|
|
89
|
+
|
|
90
|
+
## Checks
|
|
91
|
+
|
|
92
|
+
Final runs used native Node 22.17.1. Burn's inherited session-selector variables were cleared for its tests. Its dependencies were installed for arm64 so the existing canvas tests could load their native binding. No existing test or deadline was edited.
|
|
93
|
+
|
|
94
|
+
| Check | Passed | Skipped | Failed |
|
|
95
|
+
| --- | --- | --- | --- |
|
|
96
|
+
| Burn npm test | 576 | 1 | 0 |
|
|
97
|
+
| Plugin npm test | 541 | 4 | 0 |
|
|
98
|
+
| Site npm test after rebase | 2,218 | 1 | 0 |
|
|
99
|
+
| Tree and tally focused tests | 17 | 0 | 0 |
|
|
100
|
+
|
|
101
|
+
The plugin compatibility build generated 84 files and its check passed. Every new plugin file is listed in `scripts/sync-public.sh`, with compat paths generated from that list. Existing copy checks passed. Site `generate:geo` ran after the page commit; `check:geo` passed after the sitemap commit. The unscoped wrapper is unchanged and has no npm test script; its real argument forwarding was verified against the new local Burn CLI.
|
|
102
|
+
|
|
103
|
+
Repeat the site verification with `node scripts/verify-team-receipts.cjs /path/to/monorepo-worktree` and `DASHBOARD_PREVIEW_BROWSER_CHANNEL=chrome node scripts/verify-team-counts.cjs`. The latter needs local Redis and Chrome. These scripts use local fixtures and block external fixture requests.
|
|
104
|
+
|
|
105
|
+
## Integration needed from the plugin owner
|
|
106
|
+
|
|
107
|
+
1. Call `syncDailyCounts` from the detached worker's daily scheduling path after license and receipt completion. The module is implemented and manually callable; it is not scheduled by this branch. Keep the local opt-in and feature flag checks in force and keep uploads outside PreToolUse.
|
|
108
|
+
2. Coordinate one daily aggregation owner and receipt key per machine when Claude Code and Codex use separate plugin data directories. The new module reads its supplied data directory. Separate installations must not race to upload partial daily totals or different keys for the same seat. Server records are immutable and signer conflicts are rejected.
|
|
109
|
+
3. Update the plugin dependency and lockfile to the Burn release containing `sessionTally`, `readLedgerTallies` and `renderSessionTally`. The fixture uses the actual local build; the currently published dependency lacks these APIs.
|
|
110
|
+
4. Preserve the signed governing launch verdict, host, tool-call ID, ask metadata, linked outcome and final session receipt in the new admission path. If actual human refusals become available, record them explicitly; absent outcomes must stay unknown.
|
|
111
|
+
5. Emit a fresh final receipt after a resumed session and retain signed token totals for complete sessions. Current receipt lifecycle limitations produce an unavailable tally rather than a partial number. A signed per-day segment would be needed for exact calendar-day token allocation; this feature explicitly groups by session completion day.
|
|
112
|
+
6. For unattended Codex `exec`, expose a verified tally through a supported result surface or direct the operator to `agentguard-burn tally`. Its SessionStart message is not visible in that mode.
|
|
113
|
+
|
|
114
|
+
UNVERIFIED: the other agent's admission changes, automatic worker scheduling, multiple-installation aggregation and production upload or deployment. They were outside this branch's permitted plugin edits or explicitly parked by the user. The modules, local transport, authentication and rendered page were verified as described above.
|
|
115
|
+
|
|
116
|
+
Proposed coordinated release: Burn 0.4.0, unscoped wrapper 0.4.0 with a matching Burn dependency, and plugin 0.4.0 with the other agent's changes. The private site needs no npm version change. Versions were not bumped and packages were not published.
|
|
117
|
+
|
|
118
|
+
Parked for JP: production flags, production keys, deployment and npm publication. No main push or person-to-person message was attempted.
|