@agentguard-run/burn 0.3.2 → 0.3.3

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 (45) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +58 -2
  3. package/dist/src/bench-import.d.ts +74 -0
  4. package/dist/src/bench-import.js +232 -0
  5. package/dist/src/bench-panel.d.ts +42 -0
  6. package/dist/src/bench-panel.js +119 -0
  7. package/dist/src/cli.js +50 -1
  8. package/dist/src/frames.d.ts +4 -0
  9. package/dist/src/frames.js +3 -0
  10. package/dist/src/guard-candidates-ranker.d.ts +27 -0
  11. package/dist/src/guard-candidates-ranker.js +134 -0
  12. package/dist/src/guard-candidates.d.ts +34 -0
  13. package/dist/src/guard-candidates.js +226 -0
  14. package/dist/src/recording.js +4 -1
  15. package/docs/assets/burn-bench-fixture.evidence.json +18 -0
  16. package/docs/assets/burn-bench-fixture.gif +0 -0
  17. package/docs/assets/burn-bench-fixture.mp4 +0 -0
  18. package/docs/assets/burn-bench-fixture.mp4.provenance.json +70 -0
  19. package/docs/assets/burn-bench-fixture.png +0 -0
  20. package/docs/assets/burn-bench-fixture.recording.jsonl +8 -0
  21. package/fixtures/bench-panel-104x35.txt +35 -0
  22. package/fixtures/bench-panel-80x24.txt +24 -0
  23. package/fixtures/bench-run/burn-postrun.json +1 -0
  24. package/fixtures/bench-run/fixture-note.txt +1 -0
  25. package/fixtures/bench-run/grader.json +1 -0
  26. package/fixtures/bench-run/ledger.ndjson +8 -0
  27. package/fixtures/bench-run/manifest.json +1 -0
  28. package/fixtures/bench-run/measurement-key.json +1 -0
  29. package/fixtures/bench-run/patch.diff +0 -0
  30. package/fixtures/bench-run/policy.json +1 -0
  31. package/fixtures/bench-run/pricing.json +1 -0
  32. package/fixtures/bench-run/run.json +1 -0
  33. package/fixtures/bench-run/sensitivity-policy.json +1 -0
  34. package/fixtures/guard-candidates-ledger.ndjson +11 -0
  35. package/package.json +7 -4
  36. package/vendor/disciplinebench/LICENSE +202 -0
  37. package/vendor/disciplinebench/PROVENANCE.json +17 -0
  38. package/vendor/disciplinebench/harness/reducer.cjs +168 -0
  39. package/vendor/disciplinebench/harness/schema.cjs +14 -0
  40. package/vendor/disciplinebench/harness/util.cjs +23 -0
  41. package/vendor/disciplinebench/harness/verify.cjs +111 -0
  42. package/vendor/disciplinebench/schemas/aggregate.json +51 -0
  43. package/vendor/disciplinebench/schemas/event.json +62 -0
  44. package/vendor/disciplinebench/schemas/grader.json +38 -0
  45. package/vendor/disciplinebench/schemas/run.json +197 -0
package/dist/src/cli.js CHANGED
@@ -138,6 +138,21 @@ async function main(argv) {
138
138
  + (result.clippedStopHold ? 'The requested end clips the final STOP hold. No decision timestamps were extended.\n' : ''));
139
139
  return 0;
140
140
  }
141
+ case 'import-bench': {
142
+ const source = rest[0];
143
+ if (!source || source.startsWith('--') || (has('--out') && (!flag('--out') || flag('--out').startsWith('--'))))
144
+ throw new Error('Usage: agentguard-burn import-bench <run-dir> [--out <directory>] [--publisher-key-id <id>]');
145
+ if (has('--publisher-key-id') && (!flag('--publisher-key-id') || flag('--publisher-key-id').startsWith('--')))
146
+ throw new Error('Use --publisher-key-id <trusted-key-id>.');
147
+ const { importBench } = await Promise.resolve().then(() => __importStar(require('./bench-import')));
148
+ const result = await importBench(source, { out: flag('--out'), expectedPublisherKeyId: flag('--publisher-key-id') });
149
+ show({ kind: 'command', command, values: { ...result } }, `Verified DisciplineBench run: ${result.run.run_id}${result.run.fixture ? ' (fixture)' : ''}\n`
150
+ + `Publisher: ${result.verification.publisher_key_id} | Measurement: ${result.verification.measurement_key_id}\n`
151
+ + (result.verification.publisher_pinned ? 'Publisher key: pinned\n' : 'Embedded keys prove integrity, not external identity. Use --publisher-key-id to pin a trusted publisher.\n')
152
+ + `Replay input: ${result.replayPath}\nRound pricing: ${result.pricingPath}\nRecording: ${result.recordingPath}\n`
153
+ + 'Replay requires --pricing <round-pricing-path>. The recording uses the same signed snapshot.\n');
154
+ return 0;
155
+ }
141
156
  case 'ps':
142
157
  case 'reap':
143
158
  return (0, cli_1.runIdleCommand)(command, rawRest, HOME);
@@ -206,6 +221,29 @@ async function main(argv) {
206
221
  return 0;
207
222
  }
208
223
  case 'replay': {
224
+ // A bench import is a verified projection, not a native transcript. Never send it
225
+ // through the hypothetical-cost replay or this machine's pricing overrides.
226
+ if (rest[0]?.endsWith('.json') || has('--pricing')) {
227
+ const source = rest[0], pricing = flag('--pricing');
228
+ if (!source || source.startsWith('--') || !pricing || pricing.startsWith('--'))
229
+ throw new Error('DisciplineBench replay requires replay.json --pricing <snapshot.json>.');
230
+ if (has('--publisher-key-id') && (!flag('--publisher-key-id') || flag('--publisher-key-id').startsWith('--')))
231
+ throw new Error('Use --publisher-key-id <trusted-key-id>.');
232
+ const { replayBench, renderBenchReplay } = await Promise.resolve().then(() => __importStar(require('./bench-import')));
233
+ const result = await replayBench(source, pricing, { expectedPublisherKeyId: flag('--publisher-key-id') });
234
+ for (const frame of result.frames)
235
+ (0, recording_1.recordFrame)(frame.data, frame.at, frame.viewport);
236
+ if (has('--json'))
237
+ process.stdout.write(JSON.stringify({ run: result.run, verification: result.verification, pricing_sha256: result.pricing_sha256 }, null, 2) + '\n');
238
+ else if (process.stdout.isTTY && !noColor && process.env.NO_COLOR === undefined) {
239
+ const { renderFrame } = await Promise.resolve().then(() => __importStar(require('./frames')));
240
+ const last = result.frames.at(-1);
241
+ process.stdout.write(renderFrame(last.data, { recorded: true, at: last.at }).render() + '\n');
242
+ }
243
+ else
244
+ process.stdout.write(renderBenchReplay(result));
245
+ return 0;
246
+ }
209
247
  const policy = (0, pre_tool_use_1.loadPolicy)(HOME);
210
248
  const paths = rest.filter((a) => a.endsWith('.jsonl'));
211
249
  const targets = paths.length ? paths : (0, simulate_1.discoverTranscripts)();
@@ -396,6 +434,8 @@ async function main(argv) {
396
434
  ' statusline [session] one-line local status; accepts Claude status JSON\n' +
397
435
  ' pricing verified model rates and local overrides\n' +
398
436
  ' replay [files...] [--json] [--top N] [--min-tokens N]\n' +
437
+ ' import-bench <run-dir> [--out <directory>] [--publisher-key-id ID] verify and convert a signed bundle\n' +
438
+ ' replay <replay.json> --pricing <snapshot.json> [--json] pinned DisciplineBench replay\n' +
399
439
  ' calibrate fit thresholds to your history (writes shadow policy)\n' +
400
440
  ' status mode, shadow observations, eligibility, hook health, every host\n' +
401
441
  ' init [claude|cursor|codex] [--write] print the hook snippet, or merge it into the config (with a backup)\n' +
@@ -404,12 +444,21 @@ async function main(argv) {
404
444
  ' resume --once --reason "..." let the next STOP through, once, on any host\n' +
405
445
  ' resume --reason "..." let STOPs through for 15 minutes; --clear ends it\n' +
406
446
  ' proxy --upstream http://127.0.0.1:11434 --host ollama|vllm|lm-studio|openai-compatible [--listen 127.0.0.1:18080] [--session ID]\n' +
407
- ' conformance replay the storm and the grind through every adapter shape\n');
447
+ ' conformance replay the storm and the grind through every adapter shape\n' +
448
+ 'Developer review commands (never installed as hooks):\n' +
449
+ ' guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]\n' +
450
+ ' deduplicate recorded shell text; --rank explicitly permits jsort provider requests\n');
408
451
  return command ? 64 : 0;
409
452
  }
410
453
  }
411
454
  async function run() {
412
455
  const parsed = (0, recording_1.recordingArguments)(process.argv.slice(2));
456
+ if (parsed.args[0] === 'guard-candidates') {
457
+ if (parsed.file)
458
+ throw new Error('guard-candidates creates review files only. --record is not supported.');
459
+ const { runGuardCandidates } = await Promise.resolve().then(() => __importStar(require('./guard-candidates')));
460
+ return runGuardCandidates(HOME, parsed.args.slice(1));
461
+ }
413
462
  if (parsed.args[0] === 'record' && parsed.file) {
414
463
  const { recordLedgerArguments, validateCompanionRecording } = await Promise.resolve().then(() => __importStar(require('./record-ledger')));
415
464
  const options = recordLedgerArguments(parsed.args.slice(1).filter(arg => arg !== '--no-color'));
@@ -1,5 +1,6 @@
1
1
  /** Recorded frames carry observations, not ANSI, screen text or process arguments. */
2
2
  import { Canvas } from './canvas';
3
+ import { type BenchPanelSnapshot } from './bench-panel';
3
4
  import { type LivePanelSnapshot } from './live-panel';
4
5
  import type { AuditReport, AuditRow } from './idle/types';
5
6
  import type { BurnReport } from './types';
@@ -8,6 +9,9 @@ export type AuditFrameReport = Omit<AuditReport, 'processes' | 'rows'> & {
8
9
  rows: Array<Omit<AuditRow, 'processes'>>;
9
10
  };
10
11
  export type BurnFrame = {
12
+ kind: 'bench';
13
+ snapshot: BenchPanelSnapshot;
14
+ } | {
11
15
  kind: 'live';
12
16
  snapshot: LivePanelSnapshot;
13
17
  } | {
@@ -5,6 +5,7 @@ exports.framePageCount = framePageCount;
5
5
  exports.renderFrame = renderFrame;
6
6
  /** Recorded frames carry observations, not ANSI, screen text or process arguments. */
7
7
  const canvas_1 = require("./canvas");
8
+ const bench_panel_1 = require("./bench-panel");
8
9
  const live_panel_1 = require("./live-panel");
9
10
  function auditFrame(command, report) {
10
11
  const { processes: ignored, rows, ...metadata } = report;
@@ -33,6 +34,8 @@ function valueRows(values, prefix = '', depth = 0) {
33
34
  });
34
35
  }
35
36
  function renderFrame(data, options = {}) {
37
+ if (data.kind === 'bench')
38
+ return (0, bench_panel_1.renderBenchPanel)(data.snapshot, options);
36
39
  if (data.kind === 'live')
37
40
  return (0, live_panel_1.renderLivePanel)(data.snapshot, options);
38
41
  if (data.kind === 'report' && data.report.verdict === 'STOP') {
@@ -0,0 +1,27 @@
1
+ import type { ReviewOutput } from './guard-candidates';
2
+ export interface RankProvider {
3
+ name: 'typesafe' | 'openrouter';
4
+ url: string;
5
+ model: string;
6
+ key: string;
7
+ }
8
+ export interface RankRequest {
9
+ commands: string[];
10
+ criterion: string;
11
+ provider: RankProvider;
12
+ }
13
+ export interface RankedCommand {
14
+ command: string;
15
+ score: number;
16
+ standardError: number | null;
17
+ comparisons: number;
18
+ }
19
+ export declare function rankProvider(env: NodeJS.ProcessEnv): RankProvider | null;
20
+ /** Require one finite result for every exact input. Never accept partial or invented rows. */
21
+ export declare function parseRankedCommands(text: string, commands: string[]): RankedCommand[];
22
+ export declare function rankWithJsort(request: RankRequest, output: ReviewOutput, runtime?: {
23
+ executable?: string;
24
+ prefixArgs?: string[];
25
+ fetch?: typeof fetch;
26
+ env?: NodeJS.ProcessEnv;
27
+ }): Promise<RankedCommand[]>;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rankProvider = rankProvider;
4
+ exports.parseRankedCommands = parseRankedCommands;
5
+ exports.rankWithJsort = rankWithJsort;
6
+ /** Optional jsort CLI adapter. All provider requests pass the printed-body gate. */
7
+ const node_child_process_1 = require("node:child_process");
8
+ const node_crypto_1 = require("node:crypto");
9
+ const node_http_1 = require("node:http");
10
+ function rankProvider(env) {
11
+ const typesafe = env.TYPESAFE_API_KEY?.trim(), openrouter = env.OPENROUTER_API_KEY?.trim();
12
+ if (typesafe)
13
+ return { name: 'typesafe', url: 'https://api.typesafe.ai/v1/systemone', model: 'jev-latest', key: typesafe };
14
+ if (openrouter)
15
+ return { name: 'openrouter', url: 'https://openrouter.ai/api/alpha/decisions', model: '~typesafe/jev-latest', key: openrouter };
16
+ return null;
17
+ }
18
+ /** Require one finite result for every exact input. Never accept partial or invented rows. */
19
+ function parseRankedCommands(text, commands) {
20
+ const remaining = new Set(commands), ranked = [];
21
+ for (const line of text.split('\n').filter(line => line.trim())) {
22
+ const row = JSON.parse(line);
23
+ if (!row || typeof row.command !== 'string' || !remaining.delete(row.command)
24
+ || typeof row.jsort_score !== 'number' || !Number.isFinite(row.jsort_score)
25
+ || !(row.jsort_se === null || typeof row.jsort_se === 'number' && Number.isFinite(row.jsort_se) && row.jsort_se >= 0)
26
+ || !Number.isSafeInteger(row.jsort_n) || row.jsort_n < 1 || row.jsort_partial === true)
27
+ throw new Error('Invalid or incomplete jsort result.');
28
+ ranked.push({ command: row.command, score: row.jsort_score, standardError: row.jsort_se, comparisons: row.jsort_n });
29
+ }
30
+ if (remaining.size)
31
+ throw new Error('Missing jsort results.');
32
+ return ranked.sort((a, b) => b.score - a.score);
33
+ }
34
+ async function rankWithJsort(request, output, runtime = {}) {
35
+ const { provider, commands, criterion } = request;
36
+ const allowed = new Set(commands), secret = (0, node_crypto_1.randomUUID)(), controllers = new Set();
37
+ const question = { type: 'noul', instructions: `Text A ranks higher than text B on this criterion: "${criterion}"` };
38
+ const input = commands.map(command => JSON.stringify({ command })).join('\n') + '\n';
39
+ // Either HTTPX JSON encoding is valid: literal UTF-8 or six-byte escapes per
40
+ // UTF-16 code unit, for both commands in a comparison. Never truncate input.
41
+ const maxBody = commands.reduce((maximum, command) => Math.max(maximum, command.length * 12 + 4096), 65536);
42
+ let failed = false;
43
+ const server = (0, node_http_1.createServer)(async (req, res) => {
44
+ const fail = (status) => { failed = true; res.writeHead(status).end('{}'); };
45
+ if (req.method !== 'POST' || req.url !== '/' || req.headers.authorization !== `Bearer ${secret}`) {
46
+ fail(403);
47
+ return;
48
+ }
49
+ const chunks = [];
50
+ let bytes = 0;
51
+ const controller = new AbortController();
52
+ controllers.add(controller);
53
+ const timeout = setTimeout(() => controller.abort(), 20000);
54
+ try {
55
+ for await (const chunk of req) {
56
+ bytes += Buffer.byteLength(chunk);
57
+ if (bytes > maxBody) {
58
+ fail(413);
59
+ return;
60
+ }
61
+ chunks.push(Buffer.from(chunk));
62
+ }
63
+ const body = Buffer.concat(chunks), text = body.toString('utf8');
64
+ if (!Buffer.from(text, 'utf8').equals(body)) {
65
+ fail(400);
66
+ return;
67
+ }
68
+ const parsed = JSON.parse(text);
69
+ const keys = (value) => value && typeof value === 'object' ? Object.keys(value).sort().join(',') : '';
70
+ if (keys(parsed) !== 'model,questions,state' || parsed.model !== provider.model || keys(parsed.state) !== 'A,B'
71
+ || !allowed.has(parsed.state.A) || !allowed.has(parsed.state.B) || keys(parsed.questions) !== 'q'
72
+ || keys(parsed.questions.q) !== 'instructions,type' || parsed.questions.q.type !== question.type
73
+ || parsed.questions.q.instructions !== question.instructions) {
74
+ fail(400);
75
+ return;
76
+ }
77
+ // Write and flush the exact body bytes before starting the external request.
78
+ // No headers containing either the provider key or local token are printed.
79
+ await output(`Sending JSON to ${provider.url}:\n${body.toString('utf8')}\n`);
80
+ if (controller.signal.aborted)
81
+ throw new Error('Request timed out before forwarding.');
82
+ const response = await (runtime.fetch ?? fetch)(provider.url, { method: 'POST', body,
83
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${provider.key}`, 'X-Title': 'AgentGuard Burn guard-candidates' },
84
+ signal: controller.signal, redirect: 'error' });
85
+ const responseBody = await response.text();
86
+ res.writeHead(response.status, { 'Content-Type': 'application/json' }).end(responseBody);
87
+ }
88
+ catch {
89
+ fail(502);
90
+ }
91
+ finally {
92
+ clearTimeout(timeout);
93
+ controllers.delete(controller);
94
+ }
95
+ });
96
+ server.requestTimeout = 25000;
97
+ const parentEnv = runtime.env ?? process.env;
98
+ try {
99
+ await new Promise((resolve, reject) => {
100
+ server.once('error', reject);
101
+ server.listen(0, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
102
+ });
103
+ const address = server.address();
104
+ if (!address || typeof address === 'string')
105
+ throw new Error('Local preview gate unavailable.');
106
+ // Do not inherit gateway overrides, model overrides, provider keys, proxies,
107
+ // Python startup code or other credentials. jsort receives only a local token.
108
+ const env = {};
109
+ for (const key of ['PATH', 'HOME', 'USERPROFILE', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL']) {
110
+ if (parentEnv[key] !== undefined)
111
+ env[key] = parentEnv[key];
112
+ }
113
+ Object.assign(env, { JEV_URL: `http://127.0.0.1:${address.port}/`, PYTHONIOENCODING: 'utf-8', PYTHONDONTWRITEBYTECODE: '1',
114
+ [provider.name === 'typesafe' ? 'TYPESAFE_API_KEY' : 'OPENROUTER_API_KEY']: secret });
115
+ const maxChars = commands.reduce((maximum, command) => Math.max(maximum, command.length), 1);
116
+ const args = [...runtime.prefixArgs ?? [], '--jsonl', '--field', 'command', '-o', '--no-cache', '--no-stats',
117
+ '--api', provider.name, '--model', provider.model, '--max-chars', String(maxChars), '--budget', '1', '--timeout', '15', '-j', '8', criterion];
118
+ const stdout = await new Promise((resolve, reject) => {
119
+ const child = (0, node_child_process_1.execFile)(runtime.executable ?? 'jsort', args, { env, encoding: 'utf8', shell: false, windowsHide: true,
120
+ timeout: 300000, maxBuffer: Math.max(1024 * 1024, Buffer.byteLength(input) * 2 + commands.length * 512) }, (error, stdout) => error ? reject(new Error('jsort did not complete.')) : resolve(stdout));
121
+ child.stdin?.on('error', () => { });
122
+ child.stdin?.end(input);
123
+ });
124
+ if (failed)
125
+ throw new Error('A request did not pass the preview gate.');
126
+ return parseRankedCommands(stdout, commands);
127
+ }
128
+ finally {
129
+ for (const controller of controllers)
130
+ controller.abort();
131
+ server.closeAllConnections();
132
+ await new Promise(resolve => server.close(() => resolve()));
133
+ }
134
+ }
@@ -0,0 +1,34 @@
1
+ import { type RankRequest, type RankedCommand } from './guard-candidates-ranker';
2
+ export declare const GUARD_CRITERION = "how likely is this command to destroy data, leak a secret, escalate privilege, or change infrastructure";
3
+ export interface CandidateOptions {
4
+ ledgers: string[];
5
+ out?: string;
6
+ rank: boolean;
7
+ }
8
+ export interface CandidateReview {
9
+ schema: 'agentguard.guard-candidates.review.v1';
10
+ generatedAt: string;
11
+ sources: string[];
12
+ records: number;
13
+ shellRecordsWithoutText: number;
14
+ malformed: Array<{
15
+ source: string;
16
+ line: number;
17
+ }>;
18
+ raw: Array<{
19
+ command: string;
20
+ occurrences: number;
21
+ }>;
22
+ }
23
+ export type ReviewOutput = (text: string) => Promise<void>;
24
+ export type CandidateRanker = (request: RankRequest, output: ReviewOutput) => Promise<RankedCommand[]>;
25
+ export declare function candidateArguments(args: string[]): CandidateOptions;
26
+ /** Only named ledger files, not transcripts, shell history or arbitrary JSON. */
27
+ export declare function discoverCandidateLedgers(home: string, env: NodeJS.ProcessEnv): string[];
28
+ /** Read all records up to each file's opening size, including its last complete line. */
29
+ export declare function collectCandidates(files: string[]): Promise<CandidateReview>;
30
+ export declare function runGuardCandidates(home: string, args: string[], dependencies?: {
31
+ env?: NodeJS.ProcessEnv;
32
+ output?: ReviewOutput;
33
+ ranker?: CandidateRanker;
34
+ }): Promise<number>;
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GUARD_CRITERION = void 0;
4
+ exports.candidateArguments = candidateArguments;
5
+ exports.discoverCandidateLedgers = discoverCandidateLedgers;
6
+ exports.collectCandidates = collectCandidates;
7
+ exports.runGuardCandidates = runGuardCandidates;
8
+ /** Developer review only. Never imported by a hook or an enforcement path. */
9
+ const node_fs_1 = require("node:fs");
10
+ const node_path_1 = require("node:path");
11
+ const node_readline_1 = require("node:readline");
12
+ const node_crypto_1 = require("node:crypto");
13
+ const guard_candidates_ranker_1 = require("./guard-candidates-ranker");
14
+ exports.GUARD_CRITERION = 'how likely is this command to destroy data, leak a secret, escalate privilege, or change infrastructure';
15
+ const USAGE = 'Usage: agentguard-burn guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]';
16
+ const SHELL = /(?:^|[._])(?:bash|powershell|shell|exec_command|run_command|execute_command|run_shell_command|shell_command)$/i;
17
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
18
+ function candidateArguments(args) {
19
+ const result = { ledgers: [], rank: false };
20
+ for (let index = 0; index < args.length; index++) {
21
+ const flag = args[index];
22
+ if (flag === '--no-color')
23
+ continue;
24
+ if (flag === '--rank' && !result.rank) {
25
+ result.rank = true;
26
+ continue;
27
+ }
28
+ if (flag !== '--ledger' && flag !== '--out')
29
+ throw new Error(USAGE);
30
+ const value = args[++index];
31
+ if (!value || value.startsWith('--') || /[\x00-\x1f\x7f]/.test(value))
32
+ throw new Error(USAGE);
33
+ if (flag === '--ledger')
34
+ result.ledgers.push(value);
35
+ else if (result.out)
36
+ throw new Error(USAGE);
37
+ else
38
+ result.out = value;
39
+ }
40
+ if (result.out && !result.out.endsWith('.review.json'))
41
+ throw new Error('Use --out <name.review.json>. Only review files can be created.');
42
+ return result;
43
+ }
44
+ /** Only named ledger files, not transcripts, shell history or arbitrary JSON. */
45
+ function discoverCandidateLedgers(home, env) {
46
+ const found = [];
47
+ const visited = new Set();
48
+ const walk = (directory) => {
49
+ let physical;
50
+ try {
51
+ physical = (0, node_fs_1.realpathSync)(directory);
52
+ }
53
+ catch (error) {
54
+ if (error.code === 'ENOENT')
55
+ return;
56
+ throw error;
57
+ }
58
+ if (visited.has(physical))
59
+ return;
60
+ visited.add(physical);
61
+ for (const entry of (0, node_fs_1.readdirSync)(physical, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
62
+ const file = (0, node_path_1.join)(physical, entry.name);
63
+ if (entry.isDirectory())
64
+ walk(file);
65
+ else if (entry.isFile() && /^(?:decisions|receipts|ledger)(?:[.-].*)?\.(?:ndjson|jsonl)(?:\.[0-9TZ_.:-]+)?$/.test(entry.name))
66
+ found.push(file);
67
+ // Do not follow nested links outside a local state root.
68
+ }
69
+ };
70
+ for (const root of [home, env.PLUGIN_DATA, env.CLAUDE_PLUGIN_DATA])
71
+ if (root)
72
+ walk(root);
73
+ return [...new Set(found)].sort();
74
+ }
75
+ /** Recognized tool records only: response text and incidental command fields are not input. */
76
+ function shellCommands(value) {
77
+ const row = object(value), decision = object(row.decision);
78
+ const records = [row, decision, object(row.plugin), object(decision.plugin)];
79
+ if (row.type === 'tool_request')
80
+ records.push(object(row.data));
81
+ const commands = new Set();
82
+ let shell = false;
83
+ for (const record of records) {
84
+ const tool = object(record.tool);
85
+ const name = record.tool_name ?? record.toolName ?? (typeof record.tool === 'string' ? record.tool : tool.name)
86
+ ?? (record.type === 'function_call' ? record.name : undefined);
87
+ if (typeof name !== 'string' || !SHELL.test(name))
88
+ continue;
89
+ shell = true;
90
+ const inputs = [record, record.tool_input, record.toolInput, record.input, record.arguments, record.args, tool.input, tool.arguments];
91
+ for (let input of inputs) {
92
+ if (typeof input === 'string') {
93
+ // Codex function arguments are JSON. A recorded toolInput string can
94
+ // instead be the entire shell program, including embedded newlines.
95
+ if (input.trimStart().startsWith('{')) {
96
+ try {
97
+ input = JSON.parse(input);
98
+ }
99
+ catch { /* Keep the recorded string. */ }
100
+ }
101
+ if (typeof input === 'string') {
102
+ if (input.trim())
103
+ commands.add(input);
104
+ continue;
105
+ }
106
+ }
107
+ const fields = object(input);
108
+ for (const field of ['command', 'cmd', 'script']) {
109
+ const values = Array.isArray(fields[field]) ? fields[field] : [fields[field]];
110
+ for (const command of values)
111
+ if (typeof command === 'string' && command.trim())
112
+ commands.add(command);
113
+ }
114
+ }
115
+ }
116
+ return { shell, commands: [...commands] };
117
+ }
118
+ /** Read all records up to each file's opening size, including its last complete line. */
119
+ async function collectCandidates(files) {
120
+ const sources = [...new Set(files.map(file => (0, node_fs_1.realpathSync)(file)))].sort();
121
+ const review = { schema: 'agentguard.guard-candidates.review.v1', generatedAt: new Date().toISOString(),
122
+ sources, records: 0, shellRecordsWithoutText: 0, malformed: [], raw: [] };
123
+ const counts = new Map();
124
+ for (const source of sources) {
125
+ const stat = (0, node_fs_1.statSync)(source);
126
+ if (!stat.isFile())
127
+ throw new Error('A ledger must be a regular local file.');
128
+ if (!stat.size)
129
+ continue;
130
+ const stream = (0, node_fs_1.createReadStream)(source, { start: 0, end: stat.size - 1, encoding: 'utf8' });
131
+ const lines = (0, node_readline_1.createInterface)({ input: stream, crlfDelay: Infinity });
132
+ let lineNumber = 0;
133
+ try {
134
+ for await (const line of lines) {
135
+ lineNumber++;
136
+ const text = lineNumber === 1 ? line.replace(/^\uFEFF/, '') : line;
137
+ if (!text.trim())
138
+ continue;
139
+ let row;
140
+ try {
141
+ row = JSON.parse(text);
142
+ }
143
+ catch {
144
+ review.malformed.push({ source, line: lineNumber });
145
+ continue;
146
+ }
147
+ if (!row || typeof row !== 'object' || Array.isArray(row)) {
148
+ review.malformed.push({ source, line: lineNumber });
149
+ continue;
150
+ }
151
+ review.records++;
152
+ const extracted = shellCommands(row);
153
+ if (extracted.shell && !extracted.commands.length)
154
+ review.shellRecordsWithoutText++;
155
+ for (const command of extracted.commands)
156
+ counts.set(command, (counts.get(command) ?? 0) + 1);
157
+ }
158
+ }
159
+ finally {
160
+ lines.close();
161
+ stream.destroy();
162
+ }
163
+ }
164
+ review.raw = [...counts].map(([command, occurrences]) => ({ command, occurrences }));
165
+ return review;
166
+ }
167
+ function requireFresh(file) {
168
+ // lstat catches dangling links too. Creation below also uses exclusive open.
169
+ try {
170
+ (0, node_fs_1.lstatSync)(file);
171
+ }
172
+ catch (error) {
173
+ if (error.code === 'ENOENT')
174
+ return;
175
+ throw error;
176
+ }
177
+ throw new Error('Review output already exists. Choose a new --out <name.review.json>.');
178
+ }
179
+ const writeReview = (file, value) => (0, node_fs_1.writeFileSync)(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
180
+ const print = text => new Promise((resolve, reject) => process.stdout.write(text, error => error ? reject(error) : resolve()));
181
+ async function runGuardCandidates(home, args, dependencies = {}) {
182
+ const options = candidateArguments(args), env = dependencies.env ?? process.env, output = dependencies.output ?? print;
183
+ const file = (0, node_path_1.resolve)(options.out ?? `guard-candidates-${Date.now()}-${(0, node_crypto_1.randomUUID)().slice(0, 8)}.review.json`);
184
+ const rankedFile = file.replace(/\.review\.json$/, '.ranked.review.json');
185
+ requireFresh(file);
186
+ if (options.rank)
187
+ requireFresh(rankedFile);
188
+ const review = await collectCandidates(options.ledgers.length ? options.ledgers : discoverCandidateLedgers(home, env));
189
+ writeReview(file, review);
190
+ await output(`Raw review: ${file}\n${review.raw.length} unique commands from ${review.records} ledger records.\n`
191
+ + `${review.shellRecordsWithoutText} shell records have no command text; ${review.malformed.length} malformed rows.\n`);
192
+ if (!options.rank) {
193
+ await output('Local review only. Use --rank to request external ranking.\n');
194
+ return 0;
195
+ }
196
+ const provider = (0, guard_candidates_ranker_1.rankProvider)(env);
197
+ if (!provider) {
198
+ await output('Ranking skipped: set TYPESAFE_API_KEY or OPENROUTER_API_KEY in the environment. Nothing sent.\n');
199
+ return 0;
200
+ }
201
+ if (review.malformed.length) {
202
+ await output('Ranking skipped: repair malformed ledger rows first. Raw review retained; nothing sent.\n');
203
+ return 4;
204
+ }
205
+ if (review.raw.length < 2) {
206
+ await output('Ranking skipped: at least two unique commands are needed. Nothing sent.\n');
207
+ return 0;
208
+ }
209
+ const request = { commands: review.raw.map(row => row.command), criterion: exports.GUARD_CRITERION, provider };
210
+ // JSON escaping preserves newlines and terminal control characters literally.
211
+ await output(`External ranking requested: ${provider.name} at ${provider.url}\n`
212
+ + `Criterion: ${JSON.stringify(exports.GUARD_CRITERION)}\nCommand texts to send, without truncation (JSON):\n${JSON.stringify(request.commands, null, 2)}\n`
213
+ + 'Every outgoing JSON request body will be printed before forwarding. The API key is used only as an authentication header.\n');
214
+ try {
215
+ const ranked = await (dependencies.ranker ?? guard_candidates_ranker_1.rankWithJsort)(request, output);
216
+ writeReview(rankedFile, { schema: 'agentguard.guard-candidates.ranked-review.v1', generatedAt: new Date().toISOString(), rawReview: file,
217
+ criterion: exports.GUARD_CRITERION, provider: provider.name, endpoint: provider.url, model: provider.model,
218
+ scoreMeaning: 'Relative jsort Bradley-Terry scores in logit units, not calibrated probabilities or enforcement rules.', ranked });
219
+ await output(`Ranked review: ${rankedFile}\nReview only. No policy or rule was changed.\n`);
220
+ return 0;
221
+ }
222
+ catch {
223
+ await output('Ranking failed. Raw review retained; no ranked review written. Install jsort 0.1.3 (jev-sort) and check the provider or budget before retrying.\n');
224
+ return 4;
225
+ }
226
+ }
@@ -9,6 +9,7 @@ exports.recordingArguments = recordingArguments;
9
9
  /** Explicit, local-only frame recording. Never capture rendered output. */
10
10
  const node_fs_1 = require("node:fs");
11
11
  const node_path_1 = require("node:path");
12
+ const bench_panel_1 = require("./bench-panel");
12
13
  let destination;
13
14
  let frames = 0;
14
15
  function configureRecording(file) { destination = file; frames = 0; }
@@ -42,12 +43,14 @@ function readRecording(file) {
42
43
  catch {
43
44
  throw new Error(`Invalid recording JSON at line ${index + 1}.`);
44
45
  }
45
- if (row?.version !== 1 || typeof row.at !== 'string' || !Number.isFinite(Date.parse(row.at)) || !row.data || !['audit', 'report', 'replay', 'command', 'live'].includes(row.data.kind))
46
+ if (row?.version !== 1 || typeof row.at !== 'string' || !Number.isFinite(Date.parse(row.at)) || !row.data || !['audit', 'report', 'replay', 'command', 'live', 'bench'].includes(row.data.kind))
46
47
  throw new Error(`Invalid frame at line ${index + 1}.`);
47
48
  if (row.viewport && (!Number.isInteger(row.viewport.width) || row.viewport.width < 1 || row.viewport.width > 104 || !Number.isInteger(row.viewport.height) || row.viewport.height < 1 || row.viewport.height > 35))
48
49
  throw new Error(`Invalid viewport at line ${index + 1}.`);
49
50
  if (result.length && Date.parse(row.at) < Date.parse(result.at(-1).at))
50
51
  throw new Error(`Recording timestamps go backwards at line ${index + 1}.`);
52
+ if (row.data.kind === 'bench' && (!(0, bench_panel_1.validateBenchPanelSnapshot)(row.data.snapshot) || row.at !== row.data.snapshot.observed_at))
53
+ throw new Error(`Invalid bench frame at line ${index + 1}.`);
51
54
  if (row.data.kind === 'live') {
52
55
  const snapshot = row.data.snapshot;
53
56
  const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
@@ -0,0 +1,18 @@
1
+ {
2
+ "fixture": true,
3
+ "source_bundle": "fixtures/bench-run",
4
+ "run_id": "fixture-burn-bench-import",
5
+ "ledger_sha256": "6749e56f9b76af4a9554b3aa32f2669999882615672ff0f141c68e0aaa17dcda",
6
+ "publisher_key_id": "90cb3800322d802e",
7
+ "measurement_key_id": "a028716f476411d4",
8
+ "frame_index": 5,
9
+ "frame_at": "2026-10-01T00:00:10.000Z",
10
+ "list_price_exposure_usd": 0.0155,
11
+ "files": {
12
+ "burn-bench-fixture.png": "4bf899ba804874df039fcdda75d2c4cd91ba4d4a2167aa4b76451e0eaead7048",
13
+ "burn-bench-fixture.mp4": "9d432af5a0b9066294fd9857e6e8889f7b4ad9fc0fa60d0590f18b8f79377558",
14
+ "burn-bench-fixture.gif": "dee81e725bcc3c289aa869c4b9711e3e8690c98a8f922ff26f5dcdbbd9cd6560",
15
+ "burn-bench-fixture.mp4.provenance.json": "e7e8319d1e37426ec9bd0fa77de013ecff38eda77df59d9a735de895bd1377ef",
16
+ "burn-bench-fixture.recording.jsonl": "3f6f5726bedabc69b947a2d90592119419762dd5e3036283d1e2eb50841cd0fa"
17
+ }
18
+ }