@agentguard-run/burn 0.3.1 → 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 (76) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +83 -8
  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.d.ts +1 -0
  8. package/dist/src/cli.js +65 -2
  9. package/dist/src/frames.d.ts +4 -0
  10. package/dist/src/frames.js +3 -0
  11. package/dist/src/gateway.js +5 -3
  12. package/dist/src/guard-candidates-ranker.d.ts +27 -0
  13. package/dist/src/guard-candidates-ranker.js +134 -0
  14. package/dist/src/guard-candidates.d.ts +34 -0
  15. package/dist/src/guard-candidates.js +226 -0
  16. package/dist/src/hook/pre-tool-use.js +2 -1
  17. package/dist/src/ledger-panel.d.ts +40 -0
  18. package/dist/src/ledger-panel.js +174 -0
  19. package/dist/src/live-panel.d.ts +12 -0
  20. package/dist/src/live-panel.js +27 -107
  21. package/dist/src/record-ledger.d.ts +30 -0
  22. package/dist/src/record-ledger.js +165 -0
  23. package/dist/src/recording.js +8 -2
  24. package/dist/src/state/spawn-window.d.ts +13 -1
  25. package/dist/src/state/spawn-window.js +18 -3
  26. package/docs/LIVE_PANEL_2026_09.md +52 -28
  27. package/docs/assets/burn-bench-fixture.evidence.json +18 -0
  28. package/docs/assets/burn-bench-fixture.gif +0 -0
  29. package/docs/assets/burn-bench-fixture.mp4 +0 -0
  30. package/docs/assets/burn-bench-fixture.mp4.provenance.json +70 -0
  31. package/docs/assets/burn-bench-fixture.png +0 -0
  32. package/docs/assets/burn-bench-fixture.recording.jsonl +8 -0
  33. package/docs/assets/burn-real-stop-sep20-stop-1920.png +0 -0
  34. package/docs/assets/burn-real-stop-sep20-stop-390.png +0 -0
  35. package/docs/assets/burn-real-stop-sep20.evidence.json +67 -0
  36. package/docs/assets/burn-real-stop-sep20.gif +0 -0
  37. package/docs/assets/burn-real-stop-sep20.jsonl +39 -0
  38. package/docs/assets/burn-real-stop-sep20.mp4 +0 -0
  39. package/docs/assets/{burn-live-sep19.mp4.provenance.json → burn-real-stop-sep20.mp4.provenance.json} +45 -81
  40. package/docs/assets/burn-real-stop-sep20.policy.json +47 -0
  41. package/docs/assets/burn-real-stop-sep20.receipts.ndjson +18 -0
  42. package/docs/burn-render.md +12 -2
  43. package/fixtures/bench-panel-104x35.txt +35 -0
  44. package/fixtures/bench-panel-80x24.txt +24 -0
  45. package/fixtures/bench-run/burn-postrun.json +1 -0
  46. package/fixtures/bench-run/fixture-note.txt +1 -0
  47. package/fixtures/bench-run/grader.json +1 -0
  48. package/fixtures/bench-run/ledger.ndjson +8 -0
  49. package/fixtures/bench-run/manifest.json +1 -0
  50. package/fixtures/bench-run/measurement-key.json +1 -0
  51. package/fixtures/bench-run/patch.diff +0 -0
  52. package/fixtures/bench-run/policy.json +1 -0
  53. package/fixtures/bench-run/pricing.json +1 -0
  54. package/fixtures/bench-run/run.json +1 -0
  55. package/fixtures/bench-run/sensitivity-policy.json +1 -0
  56. package/fixtures/guard-candidates-ledger.ndjson +11 -0
  57. package/fixtures/live-sep20-stop-104x35.txt +35 -0
  58. package/package.json +7 -4
  59. package/vendor/disciplinebench/LICENSE +202 -0
  60. package/vendor/disciplinebench/PROVENANCE.json +17 -0
  61. package/vendor/disciplinebench/harness/reducer.cjs +168 -0
  62. package/vendor/disciplinebench/harness/schema.cjs +14 -0
  63. package/vendor/disciplinebench/harness/util.cjs +23 -0
  64. package/vendor/disciplinebench/harness/verify.cjs +111 -0
  65. package/vendor/disciplinebench/schemas/aggregate.json +51 -0
  66. package/vendor/disciplinebench/schemas/event.json +62 -0
  67. package/vendor/disciplinebench/schemas/grader.json +38 -0
  68. package/vendor/disciplinebench/schemas/run.json +197 -0
  69. package/docs/assets/burn-live-sep19-stop-1920.png +0 -0
  70. package/docs/assets/burn-live-sep19-stop-390.png +0 -0
  71. package/docs/assets/burn-live-sep19.evidence.json +0 -288
  72. package/docs/assets/burn-live-sep19.gif +0 -0
  73. package/docs/assets/burn-live-sep19.jsonl +0 -45
  74. package/docs/assets/burn-live-sep19.mp4 +0 -0
  75. package/docs/assets/burn-live-sep19.observations.jsonl +0 -45
  76. package/docs/assets/burn-live-sep19.receipt.json +0 -38
package/dist/src/cli.js CHANGED
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * ps local agent processes, held memory and orphan workspace disk
7
7
  * reap interactively SIGTERM selected safe processes, never delete
8
+ * record reconstruct a session recording from its ledger decisions
8
9
  * replay what enforcement would have stopped, on your history
9
10
  * calibrate fit thresholds to your own usage, write shadow policy
10
11
  * status mode, shadow decisions, eligibility, every host's sessions
@@ -130,6 +131,28 @@ async function main(argv) {
130
131
  const { runLivePanel } = await Promise.resolve().then(() => __importStar(require('./live-panel')));
131
132
  return runLivePanel(HOME, rawRest);
132
133
  }
134
+ case 'record': {
135
+ const { recordLedger, recordLedgerArguments } = await Promise.resolve().then(() => __importStar(require('./record-ledger')));
136
+ const result = recordLedger(HOME, recordLedgerArguments(rest));
137
+ show({ kind: 'command', command, values: { ...result } }, `Recording: ${result.output}\nSession: ${result.session}\nRange: ${result.from} to ${result.to}\n${result.frameCount} frames from ${result.decisionCount} ledger decisions.\n`
138
+ + (result.clippedStopHold ? 'The requested end clips the final STOP hold. No decision timestamps were extended.\n' : ''));
139
+ return 0;
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
+ }
133
156
  case 'ps':
134
157
  case 'reap':
135
158
  return (0, cli_1.runIdleCommand)(command, rawRest, HOME);
@@ -198,6 +221,29 @@ async function main(argv) {
198
221
  return 0;
199
222
  }
200
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
+ }
201
247
  const policy = (0, pre_tool_use_1.loadPolicy)(HOME);
202
248
  const paths = rest.filter((a) => a.endsWith('.jsonl'));
203
249
  const targets = paths.length ? paths : (0, simulate_1.discoverTranscripts)();
@@ -374,9 +420,10 @@ async function main(argv) {
374
420
  return 0;
375
421
  }
376
422
  default:
377
- show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'render', 'blocks', 'why', 'rewrites', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|render|blocks|why|rewrites|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
423
+ show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'why', 'rewrites', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|why|rewrites|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
378
424
  ' ps [--json] local agent processes, held memory and workspace disk\n' +
379
425
  ' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] local recorded-run export\n' +
426
+ ' record --session <id> [--from <iso>] [--to <iso>] --out <run.jsonl> reconstruct local ledger frames\n' +
380
427
  ' live [--session ID] [--once] [--replay run.jsonl] local instrument panel\n' +
381
428
  ' --record <file.jsonl> append structured frames for any command; --no-color keeps plain output\n' +
382
429
  ' reap numbered interactive SIGTERM, never delete or force-kill\n' +
@@ -387,6 +434,8 @@ async function main(argv) {
387
434
  ' statusline [session] one-line local status; accepts Claude status JSON\n' +
388
435
  ' pricing verified model rates and local overrides\n' +
389
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' +
390
439
  ' calibrate fit thresholds to your history (writes shadow policy)\n' +
391
440
  ' status mode, shadow observations, eligibility, hook health, every host\n' +
392
441
  ' init [claude|cursor|codex] [--write] print the hook snippet, or merge it into the config (with a backup)\n' +
@@ -395,12 +444,26 @@ async function main(argv) {
395
444
  ' resume --once --reason "..." let the next STOP through, once, on any host\n' +
396
445
  ' resume --reason "..." let STOPs through for 15 minutes; --clear ends it\n' +
397
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' +
398
- ' 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');
399
451
  return command ? 64 : 0;
400
452
  }
401
453
  }
402
454
  async function run() {
403
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
+ }
462
+ if (parsed.args[0] === 'record' && parsed.file) {
463
+ const { recordLedgerArguments, validateCompanionRecording } = await Promise.resolve().then(() => __importStar(require('./record-ledger')));
464
+ const options = recordLedgerArguments(parsed.args.slice(1).filter(arg => arg !== '--no-color'));
465
+ validateCompanionRecording(HOME, options.out, parsed.file);
466
+ }
404
467
  (0, recording_1.configureRecording)(parsed.file);
405
468
  try {
406
469
  const code = await main(parsed.args);
@@ -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') {
@@ -219,13 +219,13 @@ class Gateway {
219
219
  }
220
220
  const live = new Map(meta.liveSpawns);
221
221
  const proposedDepth = event.proposedDepth ?? (event.issuerId !== undefined && live.has(event.issuerId) ? live.get(event.issuerId) + 1 : 1);
222
- const { report, reservation } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, event.spawnId, event.at, { sessions: (0, account_1.readAccountSessions)(this.home, state, event.at), now: event.at });
222
+ const { report, reservation, window } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, event.spawnId, event.at, { sessions: (0, account_1.readAccountSessions)(this.home, state, event.at), now: event.at }, meta.capabilities);
223
223
  const wouldBlock = report.verdict === 'STOP' || !reservation.allowed;
224
224
  const verdict = wouldBlock ? 'STOP' : report.verdict;
225
225
  // Session-scope STOPs need a session we trust. Fan-out is session scope.
226
226
  const due = wouldBlock && policy.mode === 'enforce' && event.attribution === 'high';
227
227
  const override = due ? (0, override_1.consumeOverride)(this.home, event.at) : null;
228
- const decision = this.finish({ action: 'spawn', host: event.host, sessionId: event.sessionId, at: event.at, proposedDepth, verdict, wouldBlock, blocked: due && !override, override, report, effectiveSpawns: reservation.effectiveSpawns, compute: null }, policy, meta, state);
228
+ const decision = this.finish({ action: 'spawn', host: event.host, sessionId: event.sessionId, at: event.at, proposedDepth, verdict, wouldBlock, blocked: due && !override, override, report, effectiveSpawns: reservation.effectiveSpawns, compute: null, window }, policy, meta, state);
229
229
  this.save(meta, state);
230
230
  return decision;
231
231
  });
@@ -272,7 +272,8 @@ class Gateway {
272
272
  const due = wouldBlock && policy.mode === 'enforce' && (event.attribution === 'high' || machineStop);
273
273
  const override = due ? (0, override_1.consumeOverride)(this.home, event.at) : null;
274
274
  const blocked = due && !override;
275
- const decision = this.finish({ action: 'model_call', host: event.host, sessionId: event.sessionId, at: event.at, proposedDepth: null, verdict: report.verdict, wouldBlock, blocked, override, report, effectiveSpawns: state.spawnCount, compute }, policy, meta, state);
275
+ const decision = this.finish({ action: 'model_call', host: event.host, sessionId: event.sessionId, at: event.at, proposedDepth: null, verdict: report.verdict, wouldBlock, blocked, override, report, effectiveSpawns: state.spawnCount, compute,
276
+ window: (0, spawn_window_1.decisionWindow)(state, policy.thresholds, false, meta.capabilities) }, policy, meta, state);
276
277
  if (blocked) {
277
278
  // A denied call neither occupies the machine nor spends tokens.
278
279
  tx.finishCall(event.callId, windowMs(policy), event.at);
@@ -379,6 +380,7 @@ class Gateway {
379
380
  findings: d.report.findings.map((f) => ({ detector: f.detector, verdict: f.verdict, observed: f.observed, threshold: f.threshold })),
380
381
  effectiveSpawns: d.effectiveSpawns,
381
382
  totals: d.report.totals,
383
+ window: d.window,
382
384
  compute: d.compute,
383
385
  coverage: meta.capabilities,
384
386
  })}\n`, { mode: 0o600 });
@@ -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
+ }
@@ -189,7 +189,7 @@ function handleSpawnPreToolUse(input, home, now) {
189
189
  // Depth of the proposed child: the issuing agent's depth plus one. A hook
190
190
  // fired inside a subagent carries agent_id; treat that as depth 1 issuer.
191
191
  const proposedDepth = input.agent_id ? 2 : 1;
192
- const { report, reservation } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, input.tool_use_id ?? `${input.session_id}:${now}`, now, { sessions: (0, account_1.readAccountSessions)(home, state, now), now });
192
+ const { report, reservation, window } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, input.tool_use_id ?? `${input.session_id}:${now}`, now, { sessions: (0, account_1.readAccountSessions)(home, state, now), now });
193
193
  const shouldDeny = report.verdict === 'STOP' || !reservation.allowed;
194
194
  const reason = shouldDeny ? buildDenyReason(report, reservation) : '';
195
195
  // The audited override: only consulted when a block is about to happen.
@@ -223,6 +223,7 @@ function handleSpawnPreToolUse(input, home, now) {
223
223
  findings: report.findings.map((f) => ({ detector: f.detector, verdict: f.verdict, observed: f.observed, threshold: f.threshold })),
224
224
  effectiveSpawns: reservation.effectiveSpawns,
225
225
  totals: report.totals,
226
+ window,
226
227
  });
227
228
  if (shouldDeny && policy.mode === 'enforce') {
228
229
  if (!override) {