@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.
- package/CHANGELOG.md +15 -0
- package/README.md +83 -8
- package/dist/src/bench-import.d.ts +74 -0
- package/dist/src/bench-import.js +232 -0
- package/dist/src/bench-panel.d.ts +42 -0
- package/dist/src/bench-panel.js +119 -0
- package/dist/src/cli.d.ts +1 -0
- package/dist/src/cli.js +65 -2
- package/dist/src/frames.d.ts +4 -0
- package/dist/src/frames.js +3 -0
- package/dist/src/gateway.js +5 -3
- package/dist/src/guard-candidates-ranker.d.ts +27 -0
- package/dist/src/guard-candidates-ranker.js +134 -0
- package/dist/src/guard-candidates.d.ts +34 -0
- package/dist/src/guard-candidates.js +226 -0
- package/dist/src/hook/pre-tool-use.js +2 -1
- package/dist/src/ledger-panel.d.ts +40 -0
- package/dist/src/ledger-panel.js +174 -0
- package/dist/src/live-panel.d.ts +12 -0
- package/dist/src/live-panel.js +27 -107
- package/dist/src/record-ledger.d.ts +30 -0
- package/dist/src/record-ledger.js +165 -0
- package/dist/src/recording.js +8 -2
- package/dist/src/state/spawn-window.d.ts +13 -1
- package/dist/src/state/spawn-window.js +18 -3
- package/docs/LIVE_PANEL_2026_09.md +52 -28
- package/docs/assets/burn-bench-fixture.evidence.json +18 -0
- package/docs/assets/burn-bench-fixture.gif +0 -0
- package/docs/assets/burn-bench-fixture.mp4 +0 -0
- package/docs/assets/burn-bench-fixture.mp4.provenance.json +70 -0
- package/docs/assets/burn-bench-fixture.png +0 -0
- package/docs/assets/burn-bench-fixture.recording.jsonl +8 -0
- package/docs/assets/burn-real-stop-sep20-stop-1920.png +0 -0
- package/docs/assets/burn-real-stop-sep20-stop-390.png +0 -0
- package/docs/assets/burn-real-stop-sep20.evidence.json +67 -0
- package/docs/assets/burn-real-stop-sep20.gif +0 -0
- package/docs/assets/burn-real-stop-sep20.jsonl +39 -0
- package/docs/assets/burn-real-stop-sep20.mp4 +0 -0
- package/docs/assets/{burn-live-sep19.mp4.provenance.json → burn-real-stop-sep20.mp4.provenance.json} +45 -81
- package/docs/assets/burn-real-stop-sep20.policy.json +47 -0
- package/docs/assets/burn-real-stop-sep20.receipts.ndjson +18 -0
- package/docs/burn-render.md +12 -2
- package/fixtures/bench-panel-104x35.txt +35 -0
- package/fixtures/bench-panel-80x24.txt +24 -0
- package/fixtures/bench-run/burn-postrun.json +1 -0
- package/fixtures/bench-run/fixture-note.txt +1 -0
- package/fixtures/bench-run/grader.json +1 -0
- package/fixtures/bench-run/ledger.ndjson +8 -0
- package/fixtures/bench-run/manifest.json +1 -0
- package/fixtures/bench-run/measurement-key.json +1 -0
- package/fixtures/bench-run/patch.diff +0 -0
- package/fixtures/bench-run/policy.json +1 -0
- package/fixtures/bench-run/pricing.json +1 -0
- package/fixtures/bench-run/run.json +1 -0
- package/fixtures/bench-run/sensitivity-policy.json +1 -0
- package/fixtures/guard-candidates-ledger.ndjson +11 -0
- package/fixtures/live-sep20-stop-104x35.txt +35 -0
- package/package.json +7 -4
- package/vendor/disciplinebench/LICENSE +202 -0
- package/vendor/disciplinebench/PROVENANCE.json +17 -0
- package/vendor/disciplinebench/harness/reducer.cjs +168 -0
- package/vendor/disciplinebench/harness/schema.cjs +14 -0
- package/vendor/disciplinebench/harness/util.cjs +23 -0
- package/vendor/disciplinebench/harness/verify.cjs +111 -0
- package/vendor/disciplinebench/schemas/aggregate.json +51 -0
- package/vendor/disciplinebench/schemas/event.json +62 -0
- package/vendor/disciplinebench/schemas/grader.json +38 -0
- package/vendor/disciplinebench/schemas/run.json +197 -0
- package/docs/assets/burn-live-sep19-stop-1920.png +0 -0
- package/docs/assets/burn-live-sep19-stop-390.png +0 -0
- package/docs/assets/burn-live-sep19.evidence.json +0 -288
- package/docs/assets/burn-live-sep19.gif +0 -0
- package/docs/assets/burn-live-sep19.jsonl +0 -45
- package/docs/assets/burn-live-sep19.mp4 +0 -0
- package/docs/assets/burn-live-sep19.observations.jsonl +0 -45
- package/docs/assets/burn-live-sep19.receipt.json +0 -38
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { LivePanelSnapshot, PanelDecision } from './live-panel';
|
|
2
|
+
import type { Verdict } from './types';
|
|
3
|
+
export interface LedgerWindow {
|
|
4
|
+
activeMinutes: number | null;
|
|
5
|
+
windowActiveMinutes: number | null;
|
|
6
|
+
spawns: number | null;
|
|
7
|
+
tokens: number | null;
|
|
8
|
+
spawnCeiling: number | null;
|
|
9
|
+
replayShare: number | null;
|
|
10
|
+
}
|
|
11
|
+
export interface LedgerSession {
|
|
12
|
+
sessionId: string | null;
|
|
13
|
+
sessionDigest: string;
|
|
14
|
+
}
|
|
15
|
+
export interface LedgerDecision extends PanelDecision, LedgerSession {
|
|
16
|
+
/** Unique chronological order after joining matching receipts. */
|
|
17
|
+
sequence: number;
|
|
18
|
+
activeMinutes: number | null;
|
|
19
|
+
effectiveSpawns: number | null;
|
|
20
|
+
totalSpawns: number | null;
|
|
21
|
+
totalTokens: number | null;
|
|
22
|
+
window: LedgerWindow | null;
|
|
23
|
+
rate: {
|
|
24
|
+
observed: number;
|
|
25
|
+
threshold: number | null;
|
|
26
|
+
verdict: Verdict;
|
|
27
|
+
} | null;
|
|
28
|
+
usageKnown: boolean;
|
|
29
|
+
spawnsKnown: boolean;
|
|
30
|
+
/** Loaded only when the signed receipt proves the exact policy digest. */
|
|
31
|
+
legacyPolicy: {
|
|
32
|
+
windowActiveMinutes: number;
|
|
33
|
+
spawnCeiling: number;
|
|
34
|
+
} | null;
|
|
35
|
+
}
|
|
36
|
+
/** Join each receipt once. Signed receipt identifiers do not duplicate decisions. */
|
|
37
|
+
export declare function readPanelLedger(home: string): LedgerDecision[];
|
|
38
|
+
/** Accept full ids or unique raw-id/digest prefixes; never silently pick ambiguity. */
|
|
39
|
+
export declare function resolveLedgerSession(rows: LedgerDecision[], selector?: string): LedgerSession | undefined;
|
|
40
|
+
export declare function projectLedgerPanel(rows: LedgerDecision[], selector?: string, at?: number): LivePanelSnapshot;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readPanelLedger = readPanelLedger;
|
|
4
|
+
exports.resolveLedgerSession = resolveLedgerSession;
|
|
5
|
+
exports.projectLedgerPanel = projectLedgerPanel;
|
|
6
|
+
/** Content-free panel projection from the decisions the local gate recorded. */
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const node_string_decoder_1 = require("node:string_decoder");
|
|
11
|
+
const defaults_1 = require("./defaults");
|
|
12
|
+
const policy_1 = require("./policy");
|
|
13
|
+
const receipt_1 = require("./receipt");
|
|
14
|
+
const digest = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
|
|
15
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
16
|
+
const number = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
17
|
+
const positive = (value) => number(value) !== null && Number(value) > 0 ? Number(value) : null;
|
|
18
|
+
const verdict = (value) => value === 'OK' || value === 'WARN' || value === 'STOP' ? value : null;
|
|
19
|
+
const safe = (value, fallback) => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,160}$/.test(value) ? value : fallback;
|
|
20
|
+
const known = (coverage) => coverage === undefined || coverage === 'authoritative' || coverage === 'estimated';
|
|
21
|
+
/** Scan complete history in chunks, including a complete final line without LF. */
|
|
22
|
+
function rows(file) {
|
|
23
|
+
let fd;
|
|
24
|
+
try {
|
|
25
|
+
fd = (0, node_fs_1.openSync)(file, 'r');
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
const out = [], decoder = new node_string_decoder_1.StringDecoder('utf8'), bytes = Buffer.alloc(64 * 1024);
|
|
31
|
+
let pending = '';
|
|
32
|
+
const parse = (line) => { try {
|
|
33
|
+
const value = object(JSON.parse(line));
|
|
34
|
+
if (Object.keys(value).length)
|
|
35
|
+
out.push(value);
|
|
36
|
+
}
|
|
37
|
+
catch { /* Incomplete or malformed rows are not observations. */ } };
|
|
38
|
+
try {
|
|
39
|
+
let length;
|
|
40
|
+
while ((length = (0, node_fs_1.readSync)(fd, bytes, 0, bytes.length, null)) > 0) {
|
|
41
|
+
pending += decoder.write(bytes.subarray(0, length));
|
|
42
|
+
let end;
|
|
43
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
44
|
+
parse(pending.slice(0, end));
|
|
45
|
+
pending = pending.slice(end + 1);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
pending += decoder.end();
|
|
49
|
+
if (pending.trim())
|
|
50
|
+
parse(pending);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
(0, node_fs_1.closeSync)(fd);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
function parseWindow(value) {
|
|
58
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
59
|
+
return null;
|
|
60
|
+
const w = object(value), replay = number(w.replayShare);
|
|
61
|
+
return { activeMinutes: number(w.activeMinutes), windowActiveMinutes: positive(w.windowActiveMinutes),
|
|
62
|
+
spawns: number(w.spawns), tokens: number(w.tokens), spawnCeiling: positive(w.spawnCeiling),
|
|
63
|
+
replayShare: replay !== null && replay <= 1 ? replay : null };
|
|
64
|
+
}
|
|
65
|
+
function decision(raw, sequence) {
|
|
66
|
+
const sessionId = typeof raw.sessionId === 'string' && raw.sessionId.length ? raw.sessionId : null;
|
|
67
|
+
const at = number(raw.at), result = verdict(raw.verdict);
|
|
68
|
+
if (!sessionId || at === null || !Number.isFinite(new Date(at).getTime()) || !result)
|
|
69
|
+
return null;
|
|
70
|
+
const findings = Array.isArray(raw.findings) ? raw.findings.map(object) : [];
|
|
71
|
+
const rate = findings.find(f => f.detector === 'spawn_rate' && number(f.observed) !== null && verdict(f.verdict));
|
|
72
|
+
const totals = object(raw.totals), coverage = object(raw.coverage), window = parseWindow(raw.window);
|
|
73
|
+
return { sessionId, sessionDigest: digest(sessionId), sequence, at, verdict: result,
|
|
74
|
+
id: safe(raw.toolUseId, digest(JSON.stringify(raw)) + ':' + sequence), tool: safe(raw.action ?? raw.tool, 'spawn'),
|
|
75
|
+
blocked: typeof raw.enforced === 'boolean' ? raw.enforced : null,
|
|
76
|
+
reason: findings.map(f => `${safe(f.detector, 'unknown')}:${verdict(f.verdict) ?? 'OK'}`).join(' + ')
|
|
77
|
+
|| (raw.failClosed === true ? 'local fail-closed condition' : result === 'OK' ? 'within policy' : 'reason unavailable'),
|
|
78
|
+
activeMinutes: window?.activeMinutes ?? number(totals.activeMinutes), effectiveSpawns: number(raw.effectiveSpawns),
|
|
79
|
+
totalSpawns: number(totals.spawns), totalTokens: number(totals.tokens), window,
|
|
80
|
+
rate: rate ? { observed: Number(rate.observed), threshold: positive(rate.threshold), verdict: verdict(rate.verdict) } : null,
|
|
81
|
+
usageKnown: known(coverage.usage), spawnsKnown: known(coverage.spawns), legacyPolicy: null };
|
|
82
|
+
}
|
|
83
|
+
function receipt(raw, sequence) {
|
|
84
|
+
const p = object(raw.payload), at = number(p.at), result = verdict(p.verdict);
|
|
85
|
+
if (typeof p.sessionDigest !== 'string' || !/^[a-f0-9]{64}$/.test(p.sessionDigest) || at === null || !Number.isFinite(new Date(at).getTime()) || !result)
|
|
86
|
+
return null;
|
|
87
|
+
const measured = object(p.measured), coverage = object(p.coverage);
|
|
88
|
+
return { sessionId: null, sessionDigest: p.sessionDigest, sequence, at, verdict: result,
|
|
89
|
+
id: safe(p.decisionId, digest(JSON.stringify(p))), tool: safe(p.action, 'unknown'),
|
|
90
|
+
blocked: typeof p.blocked === 'boolean' ? p.blocked : null,
|
|
91
|
+
reason: Array.isArray(p.reasons) && p.reasons.length ? [...new Set(p.reasons.map(reason => safe(reason, 'unknown')))].join(' + ') : result === 'OK' ? 'within policy' : 'reason unavailable',
|
|
92
|
+
activeMinutes: null, effectiveSpawns: number(measured.sessionSpawns), totalSpawns: null, totalTokens: number(measured.sessionTokens),
|
|
93
|
+
window: parseWindow(p.window), rate: null, usageKnown: known(coverage.usage), spawnsKnown: known(coverage.spawns), legacyPolicy: null };
|
|
94
|
+
}
|
|
95
|
+
/** Join each receipt once. Signed receipt identifiers do not duplicate decisions. */
|
|
96
|
+
function readPanelLedger(home) {
|
|
97
|
+
const decisions = rows((0, node_path_1.join)(home, 'decisions.ndjson')).flatMap((raw, i) => { const d = decision(raw, i); return d ? [d] : []; });
|
|
98
|
+
const ids = new Map(decisions.map(d => [d.sessionDigest, d.sessionId]));
|
|
99
|
+
const policy = (0, policy_1.loadPolicy)(home, { notice: false }), policyDigest = digest((0, receipt_1.canonical)(policy));
|
|
100
|
+
const matched = new Set();
|
|
101
|
+
for (const [i, raw] of rows((0, node_path_1.join)(home, 'receipts.ndjson')).entries()) {
|
|
102
|
+
const r = receipt(raw, decisions.length + i);
|
|
103
|
+
if (!r)
|
|
104
|
+
continue;
|
|
105
|
+
try {
|
|
106
|
+
if (object(object(raw.payload).policy).digest === policyDigest && (0, receipt_1.verifyReceipt)(raw)) {
|
|
107
|
+
r.legacyPolicy = { windowActiveMinutes: policy.thresholds.spawnRate.windowActiveMinutes, spawnCeiling: policy.thresholds.spawnRate.stop };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch { /* Unverified policy metadata cannot define a historical window. */ }
|
|
111
|
+
const index = decisions.findIndex((d, j) => !matched.has(j) && d.sessionDigest === r.sessionDigest && d.at === r.at && d.tool === r.tool && d.verdict === r.verdict && d.blocked === r.blocked);
|
|
112
|
+
if (index >= 0) {
|
|
113
|
+
decisions[index] = { ...decisions[index], id: r.id, reason: r.reason, blocked: r.blocked, legacyPolicy: r.legacyPolicy };
|
|
114
|
+
matched.add(index);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
matched.add(decisions.length);
|
|
118
|
+
decisions.push({ ...r, sessionId: ids.get(r.sessionDigest) ?? null });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return decisions.sort((a, b) => a.at - b.at || a.sequence - b.sequence).map((d, sequence) => ({ ...d, sequence }));
|
|
122
|
+
}
|
|
123
|
+
/** Accept full ids or unique raw-id/digest prefixes; never silently pick ambiguity. */
|
|
124
|
+
function resolveLedgerSession(rows, selector) {
|
|
125
|
+
const sessions = new Map();
|
|
126
|
+
for (const r of rows)
|
|
127
|
+
sessions.set(r.sessionDigest, { sessionId: r.sessionId ?? sessions.get(r.sessionDigest)?.sessionId ?? null, sessionDigest: r.sessionDigest });
|
|
128
|
+
if (!selector) {
|
|
129
|
+
const latest = rows.at(-1);
|
|
130
|
+
return latest ? sessions.get(latest.sessionDigest) : undefined;
|
|
131
|
+
}
|
|
132
|
+
const all = [...sessions.values()];
|
|
133
|
+
const exact = all.filter(s => s.sessionId === selector || s.sessionDigest === selector);
|
|
134
|
+
const matching = exact.length ? exact : all.filter(s => s.sessionId?.startsWith(selector) || s.sessionDigest.startsWith(selector));
|
|
135
|
+
if (matching.length > 1)
|
|
136
|
+
throw new Error('Session prefix is ambiguous. Use the full session id or digest.');
|
|
137
|
+
return matching[0];
|
|
138
|
+
}
|
|
139
|
+
/** Older ledgers can prove a whole-lifetime window, but not an arbitrary token window. */
|
|
140
|
+
function legacySpawns(rows, current, windowMinutes) {
|
|
141
|
+
if (!current.spawnsKnown)
|
|
142
|
+
return null;
|
|
143
|
+
if (current.rate)
|
|
144
|
+
return current.rate.observed;
|
|
145
|
+
if (windowMinutes === null || current.activeMinutes === null || current.effectiveSpawns === null || current.tool !== 'spawn')
|
|
146
|
+
return null;
|
|
147
|
+
if (Math.floor(current.activeMinutes) <= windowMinutes)
|
|
148
|
+
return current.effectiveSpawns;
|
|
149
|
+
const first = rows.find(d => d.tool === 'spawn');
|
|
150
|
+
if (!first || first.totalSpawns !== 0 || first.effectiveSpawns !== 1 || first.activeMinutes === null)
|
|
151
|
+
return null;
|
|
152
|
+
const from = Math.max(0, Math.floor(current.activeMinutes) - windowMinutes);
|
|
153
|
+
return Math.floor(first.activeMinutes) >= from ? current.effectiveSpawns : null;
|
|
154
|
+
}
|
|
155
|
+
function projectLedgerPanel(rows, selector, at = Date.now()) {
|
|
156
|
+
const available = rows.filter(d => d.at <= at), session = resolveLedgerSession(available, selector);
|
|
157
|
+
const defaults = defaults_1.DEFAULT_THRESHOLDS.spawnRate;
|
|
158
|
+
const base = { session: 'unavailable', startedAt: at, observedAt: at, elapsedMs: null,
|
|
159
|
+
spawns: null, tokens: null, replayShare: null, windowActiveMinutes: defaults.windowActiveMinutes, spawnCeiling: defaults.stop,
|
|
160
|
+
decisions: [], note: 'No readable ledger decisions. Waiting for local observations.' };
|
|
161
|
+
if (!session)
|
|
162
|
+
return base;
|
|
163
|
+
const selected = available.filter(d => d.sessionDigest === session.sessionDigest), current = selected.at(-1);
|
|
164
|
+
const window = current.window, windowMinutes = window?.windowActiveMinutes ?? current.legacyPolicy?.windowActiveMinutes ?? null;
|
|
165
|
+
const spawns = window ? current.spawnsKnown ? window.spawns : null : legacySpawns(selected, current, windowMinutes);
|
|
166
|
+
const tokens = current.usageKnown ? window ? window.tokens
|
|
167
|
+
: windowMinutes !== null && current.activeMinutes !== null && Math.floor(current.activeMinutes) <= windowMinutes ? current.totalTokens : null : null;
|
|
168
|
+
const decisions = selected.slice(-8).map(({ id, at, tool, verdict, reason, blocked }) => ({ id, at, tool, verdict, reason, blocked }));
|
|
169
|
+
return { ...base, session: (session.sessionId ?? session.sessionDigest).slice(0, 8), sessionDigest: session.sessionDigest, startedAt: selected[0].at, elapsedMs: at - selected[0].at,
|
|
170
|
+
spawns, tokens, replayShare: current.usageKnown ? window?.replayShare ?? null : null,
|
|
171
|
+
windowActiveMinutes: windowMinutes, spawnCeiling: window?.spawnCeiling ?? (current.rate?.verdict === 'STOP' ? current.rate.threshold : null) ?? current.legacyPolicy?.spawnCeiling ?? null,
|
|
172
|
+
decisions, note: window ? 'Ledger decision snapshot. Counters include the proposal evaluated by the hook.'
|
|
173
|
+
: `Ledger decisions. ${tokens === null ? 'Token window and replay share were not recorded.' : 'Replay share was not recorded.'}${spawns === null ? ' Spawn window is unknown.' : ''}${current.legacyPolicy ? ' Policy digest verified.' : ''}` };
|
|
174
|
+
}
|
package/dist/src/live-panel.d.ts
CHANGED
|
@@ -11,8 +11,14 @@ export interface PanelDecision {
|
|
|
11
11
|
}
|
|
12
12
|
export interface LivePanelSnapshot {
|
|
13
13
|
session: string;
|
|
14
|
+
sessionDigest?: string;
|
|
14
15
|
startedAt: number;
|
|
15
16
|
observedAt: number;
|
|
17
|
+
sessionSwitch?: {
|
|
18
|
+
from: string;
|
|
19
|
+
to: string;
|
|
20
|
+
at: number;
|
|
21
|
+
};
|
|
16
22
|
spawns: number | null;
|
|
17
23
|
tokens: number | null;
|
|
18
24
|
replayShare: number | null;
|
|
@@ -25,8 +31,14 @@ export interface LivePanelSnapshot {
|
|
|
25
31
|
note: string;
|
|
26
32
|
stop?: PanelDecision;
|
|
27
33
|
}
|
|
34
|
+
/** The ledger is the single source for decisions, counters and session selection. */
|
|
28
35
|
export declare function panelDecisions(home: string, sessionId: string, at?: number): PanelDecision[];
|
|
29
36
|
export declare function collectLivePanel(home: string, session?: string, now?: number): LivePanelSnapshot;
|
|
37
|
+
/** Record changes of identity, including switches between sessions with the same short prefix. */
|
|
38
|
+
export declare class SessionFollow {
|
|
39
|
+
private previous?;
|
|
40
|
+
update(snapshot: LivePanelSnapshot, now: number): LivePanelSnapshot;
|
|
41
|
+
}
|
|
30
42
|
export declare function spawnBarColor(spawns: number | null, ceiling: number | null): CanvasColor;
|
|
31
43
|
export declare function renderLivePanel(snapshot: LivePanelSnapshot, options?: FrameOptions): Canvas;
|
|
32
44
|
/** STOP report adaptation uses only already-computed metadata, never local I/O. */
|
package/dist/src/live-panel.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.StopHold = void 0;
|
|
3
|
+
exports.StopHold = exports.SessionFollow = void 0;
|
|
4
4
|
exports.panelDecisions = panelDecisions;
|
|
5
5
|
exports.collectLivePanel = collectLivePanel;
|
|
6
6
|
exports.spawnBarColor = spawnBarColor;
|
|
@@ -10,116 +10,29 @@ exports.runLivePanel = runLivePanel;
|
|
|
10
10
|
/** Local, content-free instrument panel. It observes; it never changes admission. */
|
|
11
11
|
const node_crypto_1 = require("node:crypto");
|
|
12
12
|
const node_fs_1 = require("node:fs");
|
|
13
|
-
const node_path_1 = require("node:path");
|
|
14
13
|
const canvas_1 = require("./canvas");
|
|
15
|
-
const
|
|
14
|
+
const ledger_panel_1 = require("./ledger-panel");
|
|
16
15
|
const recording_1 = require("./recording");
|
|
17
|
-
const session_1 = require("./state/session");
|
|
18
16
|
const digest = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
|
|
19
|
-
|
|
20
|
-
const row = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
21
|
-
const safe = (v, fallback) => typeof v === 'string' && /^[A-Za-z0-9_.:-]{1,80}$/.test(v) ? v : fallback;
|
|
22
|
-
const verdict = (v) => v === 'OK' || v === 'WARN' || v === 'STOP' ? v : null;
|
|
23
|
-
function buckets(value) {
|
|
24
|
-
if (!Array.isArray(value) || !value.every(v => Array.isArray(v) && v.length === 2 && number(v[0]) !== null && number(v[1]) !== null))
|
|
25
|
-
return null;
|
|
26
|
-
return new Map(value);
|
|
27
|
-
}
|
|
28
|
-
/** Read a bounded tail and discard an incomplete first/last JSON row. */
|
|
29
|
-
function ledger(file) {
|
|
30
|
-
try {
|
|
31
|
-
const size = (0, node_fs_1.statSync)(file).size, offset = Math.max(0, size - 4 * 1024 * 1024), fd = (0, node_fs_1.openSync)(file, 'r');
|
|
32
|
-
const bytes = Buffer.alloc(size - offset);
|
|
33
|
-
try {
|
|
34
|
-
(0, node_fs_1.readSync)(fd, bytes, 0, bytes.length, offset);
|
|
35
|
-
}
|
|
36
|
-
finally {
|
|
37
|
-
(0, node_fs_1.closeSync)(fd);
|
|
38
|
-
}
|
|
39
|
-
const text = bytes.toString('utf8'), lines = text.slice(offset ? text.indexOf('\n') + 1 : 0, text.lastIndexOf('\n') + 1).split('\n');
|
|
40
|
-
return lines.flatMap(line => { try {
|
|
41
|
-
return [row(JSON.parse(line))];
|
|
42
|
-
}
|
|
43
|
-
catch {
|
|
44
|
-
return [];
|
|
45
|
-
} });
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
return [];
|
|
49
|
-
}
|
|
50
|
-
}
|
|
17
|
+
/** The ledger is the single source for decisions, counters and session selection. */
|
|
51
18
|
function panelDecisions(home, sessionId, at = Date.now()) {
|
|
52
|
-
|
|
53
|
-
const receiptRows = ledger((0, node_path_1.join)(home, 'receipts.ndjson')).flatMap(raw => {
|
|
54
|
-
const p = row(raw.payload);
|
|
55
|
-
if (p.sessionDigest !== sessionDigest || number(p.at) === null || Number(p.at) > at || !verdict(p.verdict))
|
|
56
|
-
return [];
|
|
57
|
-
return [{ id: safe(p.decisionId, digest(JSON.stringify(p))), at: Number(p.at), tool: safe(p.action, 'unknown'), verdict: verdict(p.verdict),
|
|
58
|
-
reason: Array.isArray(p.reasons) ? [...new Set(p.reasons.map(v => safe(v, 'unknown')))].join(' + ') : 'reason unavailable', blocked: p.blocked === true }];
|
|
59
|
-
});
|
|
60
|
-
const decisions = ledger((0, node_path_1.join)(home, 'decisions.ndjson')).flatMap(p => {
|
|
61
|
-
if (p.sessionId !== sessionId || number(p.at) === null || Number(p.at) > at || !verdict(p.verdict))
|
|
62
|
-
return [];
|
|
63
|
-
const findings = Array.isArray(p.findings) ? p.findings.map(row) : [];
|
|
64
|
-
return [{ id: safe(p.toolUseId, digest(JSON.stringify(p))), at: Number(p.at), tool: safe(p.action ?? p.tool, 'spawn'), verdict: verdict(p.verdict),
|
|
65
|
-
reason: findings.map(f => `${safe(f.detector, 'unknown')}:${verdict(f.verdict) ?? 'OK'}`).join(' + ') || (p.failClosed === true ? 'local fail-closed condition' : p.verdict === 'OK' ? 'within policy' : 'reason unavailable'), blocked: p.enforced === true }];
|
|
66
|
-
});
|
|
67
|
-
const merged = [...decisions], joined = new Set();
|
|
68
|
-
for (const d of receiptRows) {
|
|
69
|
-
const index = merged.findIndex((candidate, i) => !joined.has(i) && candidate.at === d.at && candidate.tool === d.tool && candidate.verdict === d.verdict && candidate.blocked === d.blocked);
|
|
70
|
-
if (index >= 0) {
|
|
71
|
-
merged[index] = d;
|
|
72
|
-
joined.add(index);
|
|
73
|
-
}
|
|
74
|
-
else {
|
|
75
|
-
joined.add(merged.length);
|
|
76
|
-
merged.push(d);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return merged.sort((a, b) => a.at - b.at).slice(-8);
|
|
19
|
+
return (0, ledger_panel_1.projectLedgerPanel)((0, ledger_panel_1.readPanelLedger)(home), sessionId, at).decisions;
|
|
80
20
|
}
|
|
81
21
|
function collectLivePanel(home, session, now = Date.now()) {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return
|
|
22
|
+
return (0, ledger_panel_1.projectLedgerPanel)((0, ledger_panel_1.readPanelLedger)(home), session, now);
|
|
23
|
+
}
|
|
24
|
+
/** Record changes of identity, including switches between sessions with the same short prefix. */
|
|
25
|
+
class SessionFollow {
|
|
26
|
+
previous;
|
|
27
|
+
update(snapshot, now) {
|
|
28
|
+
const identity = snapshot.sessionDigest ?? snapshot.session;
|
|
29
|
+
const sessionSwitch = this.previous !== undefined && this.previous !== identity
|
|
30
|
+
? { from: this.previous, to: identity, at: now } : undefined;
|
|
31
|
+
this.previous = identity;
|
|
32
|
+
return { ...snapshot, ...(sessionSwitch ? { sessionSwitch } : {}) };
|
|
93
33
|
}
|
|
94
|
-
const candidates = names.flatMap(name => {
|
|
95
|
-
try {
|
|
96
|
-
const path = (0, node_path_1.join)(home, 'sessions', name);
|
|
97
|
-
if ((0, node_fs_1.statSync)(path).size > 16 * 1024 * 1024)
|
|
98
|
-
return [];
|
|
99
|
-
const raw = row(JSON.parse((0, node_fs_1.readFileSync)(path, 'utf8'))), state = row(raw.state);
|
|
100
|
-
if (typeof state.sessionId !== 'string' || number(state.lastEventAt) === null || number(state.startedAt) === null)
|
|
101
|
-
return [];
|
|
102
|
-
if (session && state.sessionId !== session && !state.sessionId.startsWith(session) && !digest(state.sessionId).startsWith(session))
|
|
103
|
-
return [];
|
|
104
|
-
return [{ raw, state }];
|
|
105
|
-
}
|
|
106
|
-
catch {
|
|
107
|
-
return [];
|
|
108
|
-
}
|
|
109
|
-
}).sort((a, b) => Number(b.state.lastEventAt) - Number(a.state.lastEventAt));
|
|
110
|
-
if (!candidates.length)
|
|
111
|
-
return base;
|
|
112
|
-
const { raw, state } = candidates[0], active = number(state.activeMinutes), spawned = buckets(state.spawnsByActiveMinute), tokens = buckets(state.tokensByActiveMinute);
|
|
113
|
-
const total = number(state.totalTokens), cached = number(state.totalCacheRead), decisions = panelDecisions(home, String(state.sessionId), now);
|
|
114
|
-
const coverage = row(raw.capabilities), gateway = Array.isArray(raw.hosts);
|
|
115
|
-
const spawnKnown = !gateway || ['authoritative', 'estimated'].includes(String(coverage.spawns));
|
|
116
|
-
const usageKnown = !gateway || ['authoritative', 'estimated'].includes(String(coverage.usage));
|
|
117
|
-
return { ...base, session: digest(String(state.sessionId)).slice(0, 8), startedAt: Number(state.startedAt),
|
|
118
|
-
spawns: spawnKnown && spawned && active !== null ? (0, session_1.windowSum)(spawned, active, windowActiveMinutes) : null,
|
|
119
|
-
tokens: usageKnown && tokens && active !== null ? (0, session_1.windowSum)(tokens, active, windowActiveMinutes) : null,
|
|
120
|
-
replayShare: usageKnown && total !== null && cached !== null && total > 0 ? Math.min(1, cached / total) : null, decisions,
|
|
121
|
-
note: row(raw.cursor).usageVersion === undefined && raw.cursor ? 'Legacy stored usage counts; no recount applied.' : gateway ? `Local observations. Coverage: spawns ${safe(coverage.spawns, 'unknown')}, usage ${safe(coverage.usage, 'unknown')}.` : 'Local observations only. Replay share is session cache-read / tokens.' };
|
|
122
34
|
}
|
|
35
|
+
exports.SessionFollow = SessionFollow;
|
|
123
36
|
const compact = (v) => v === null ? { digits: '-', unit: 'unknown' } : v >= 1e9 ? { digits: (v / 1e9).toFixed(2), unit: 'B tokens' } : v >= 1e6 ? { digits: (v / 1e6).toFixed(2), unit: 'M tokens' } : v >= 1e3 ? { digits: (v / 1e3).toFixed(1), unit: 'K tokens' } : { digits: String(Math.round(v)), unit: 'tokens' };
|
|
124
37
|
function spawnBarColor(spawns, ceiling) {
|
|
125
38
|
return spawns === null || ceiling === null ? 'slate' : spawns >= ceiling ? 'red' : spawns >= ceiling * .8 ? 'amber' : 'mint';
|
|
@@ -178,7 +91,7 @@ function panelFromReport(report, at, outcome, subject) {
|
|
|
178
91
|
const note = outcome === 'blocked' ? (subject === 'call' ? 'model call blocked' : 'agent spawn blocked')
|
|
179
92
|
: outcome === 'shadow' ? 'shadow: would have blocked, call allowed' : outcome === 'overridden' ? 'override: call allowed'
|
|
180
93
|
: outcome === 'allowed' ? 'call allowed' : 'STOP boundary · enforcement outcome not recorded';
|
|
181
|
-
return { session: digest(report.sessionId).slice(0, 8), startedAt: at, observedAt: at, elapsedMs: null, controls: false, stopHold: false,
|
|
94
|
+
return { session: (/^[A-Za-z0-9_-]+$/.test(report.sessionId) ? report.sessionId : digest(report.sessionId)).slice(0, 8), startedAt: at, observedAt: at, elapsedMs: null, controls: false, stopHold: false,
|
|
182
95
|
spawns: rate?.observed ?? null, tokens: null, replayShare: Number.isFinite(report.cacheReadRatio) ? report.cacheReadRatio : null,
|
|
183
96
|
windowActiveMinutes: null, spawnCeiling: rate?.verdict === 'STOP' ? rate.threshold : null,
|
|
184
97
|
decisions: [decision], stop: decision, note: `${note}. Unknown window metrics remain unknown.` };
|
|
@@ -190,8 +103,15 @@ class StopHold {
|
|
|
190
103
|
seen = new Set();
|
|
191
104
|
latest;
|
|
192
105
|
update(snapshot, now) {
|
|
106
|
+
if (this.latest && (this.latest.sessionDigest ?? this.latest.session) !== (snapshot.sessionDigest ?? snapshot.session)) {
|
|
107
|
+
this.held = undefined;
|
|
108
|
+
this.until = 0;
|
|
109
|
+
this.seen.clear();
|
|
110
|
+
}
|
|
193
111
|
this.latest = snapshot;
|
|
194
|
-
|
|
112
|
+
// A historical STOP in the right column must not borrow a later decision's counters.
|
|
113
|
+
const latestDecision = snapshot.decisions.at(-1);
|
|
114
|
+
const stop = latestDecision?.verdict === 'STOP' && !this.seen.has(latestDecision.id) ? latestDecision : undefined;
|
|
195
115
|
for (const decision of snapshot.decisions)
|
|
196
116
|
this.seen.add(decision.id);
|
|
197
117
|
if (stop) {
|
|
@@ -260,10 +180,10 @@ async function runLivePanel(home, args) {
|
|
|
260
180
|
}
|
|
261
181
|
}
|
|
262
182
|
else {
|
|
263
|
-
const hold = new StopHold();
|
|
183
|
+
const hold = new StopHold(), follow = new SessionFollow();
|
|
264
184
|
do {
|
|
265
185
|
if (!paused) {
|
|
266
|
-
const now = Date.now(), snapshot = hold.update(collectLivePanel(home, selected, now), now);
|
|
186
|
+
const now = Date.now(), snapshot = follow.update(hold.update(collectLivePanel(home, selected, now), now), now);
|
|
267
187
|
display(snapshot, false, new Date(now).toISOString());
|
|
268
188
|
}
|
|
269
189
|
if (!once)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type LedgerDecision } from './ledger-panel';
|
|
2
|
+
import type { RecordedFrame } from './recording';
|
|
3
|
+
export interface RecordLedgerOptions {
|
|
4
|
+
session: string;
|
|
5
|
+
from?: string;
|
|
6
|
+
to?: string;
|
|
7
|
+
out: string;
|
|
8
|
+
}
|
|
9
|
+
export interface RecordLedgerResult {
|
|
10
|
+
output: string;
|
|
11
|
+
session: string;
|
|
12
|
+
from: string;
|
|
13
|
+
to: string;
|
|
14
|
+
frameCount: number;
|
|
15
|
+
decisionCount: number;
|
|
16
|
+
clippedStopHold: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Require an explicit timezone and reject dates Date.parse would normalize. */
|
|
19
|
+
export declare function ledgerTimestamp(value: string): number;
|
|
20
|
+
export declare function validateCompanionRecording(home: string, output: string, recording: string): void;
|
|
21
|
+
export declare function recordLedgerArguments(args: string[]): RecordLedgerOptions;
|
|
22
|
+
export declare function reconstructLedgerFrames(rows: LedgerDecision[], options: Omit<RecordLedgerOptions, 'out'>): {
|
|
23
|
+
frames: RecordedFrame[];
|
|
24
|
+
session: string;
|
|
25
|
+
from: number;
|
|
26
|
+
to: number;
|
|
27
|
+
decisionCount: number;
|
|
28
|
+
clippedStopHold: boolean;
|
|
29
|
+
};
|
|
30
|
+
export declare function recordLedger(home: string, options: RecordLedgerOptions): RecordLedgerResult;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ledgerTimestamp = ledgerTimestamp;
|
|
4
|
+
exports.validateCompanionRecording = validateCompanionRecording;
|
|
5
|
+
exports.recordLedgerArguments = recordLedgerArguments;
|
|
6
|
+
exports.reconstructLedgerFrames = reconstructLedgerFrames;
|
|
7
|
+
exports.recordLedger = recordLedger;
|
|
8
|
+
/** Reconstruct local instrument-panel observations from immutable ledger history. */
|
|
9
|
+
const node_fs_1 = require("node:fs");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
const ledger_panel_1 = require("./ledger-panel");
|
|
12
|
+
const live_panel_1 = require("./live-panel");
|
|
13
|
+
const USAGE = 'Usage: agentguard-burn record --session <id> [--from <iso>] [--to <iso>] --out <run.jsonl>';
|
|
14
|
+
const MAX_FRAMES = 10000;
|
|
15
|
+
/** Require an explicit timezone and reject dates Date.parse would normalize. */
|
|
16
|
+
function ledgerTimestamp(value) {
|
|
17
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
18
|
+
if (!match)
|
|
19
|
+
throw new Error('Record timestamps must be ISO dates with a timezone and at most millisecond precision.');
|
|
20
|
+
const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
|
|
21
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
22
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
23
|
+
const offset = match[8];
|
|
24
|
+
const at = Date.parse(value);
|
|
25
|
+
if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || Number(match[4]) > 23
|
|
26
|
+
|| Number(match[5]) > 59 || Number(match[6]) > 59 || !Number.isFinite(at) || at < 0
|
|
27
|
+
|| offset !== 'Z' && (Number(offset.slice(1, 3)) > 23 || Number(offset.slice(4)) > 59)) {
|
|
28
|
+
throw new Error('Record timestamps must contain a valid date, time and timezone.');
|
|
29
|
+
}
|
|
30
|
+
return at;
|
|
31
|
+
}
|
|
32
|
+
/** Compare aliases before writing, including a new file below a symlinked directory. */
|
|
33
|
+
function samePath(left, right) {
|
|
34
|
+
try {
|
|
35
|
+
const a = (0, node_fs_1.statSync)(left), b = (0, node_fs_1.statSync)(right);
|
|
36
|
+
if (a.dev === b.dev && a.ino === b.ino)
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
catch { /* A fresh output has no inode yet. */ }
|
|
40
|
+
const physical = (file) => {
|
|
41
|
+
let path = (0, node_path_1.resolve)(file);
|
|
42
|
+
const suffix = [];
|
|
43
|
+
for (;;) {
|
|
44
|
+
try {
|
|
45
|
+
return (0, node_path_1.resolve)((0, node_fs_1.realpathSync)(path), ...suffix);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
const parent = (0, node_path_1.dirname)(path);
|
|
49
|
+
if (parent === path)
|
|
50
|
+
return (0, node_path_1.resolve)(file);
|
|
51
|
+
suffix.unshift((0, node_path_1.basename)(path));
|
|
52
|
+
path = parent;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
return physical(left) === physical(right);
|
|
57
|
+
}
|
|
58
|
+
function validateCompanionRecording(home, output, recording) {
|
|
59
|
+
if (samePath(output, recording))
|
|
60
|
+
throw new Error('Use different paths for --out and --record.');
|
|
61
|
+
if (['decisions.ndjson', 'receipts.ndjson'].some(name => samePath(recording, (0, node_path_1.join)(home, name)))) {
|
|
62
|
+
throw new Error('Recording must not append to a source ledger.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function recordLedgerArguments(args) {
|
|
66
|
+
const fields = {};
|
|
67
|
+
for (let i = 0; i < args.length; i++) {
|
|
68
|
+
const flag = args[i];
|
|
69
|
+
if (!['--session', '--from', '--to', '--out'].includes(flag))
|
|
70
|
+
throw new Error(USAGE);
|
|
71
|
+
const key = flag.slice(2), value = args[++i];
|
|
72
|
+
if (!value || value.startsWith('--') || fields[key] !== undefined)
|
|
73
|
+
throw new Error(USAGE);
|
|
74
|
+
fields[key] = value;
|
|
75
|
+
}
|
|
76
|
+
if (!fields.session || !fields.out)
|
|
77
|
+
throw new Error(USAGE);
|
|
78
|
+
return fields;
|
|
79
|
+
}
|
|
80
|
+
function reconstructLedgerFrames(rows, options) {
|
|
81
|
+
if (!options.session || /[\x00-\x20\x7f]/.test(options.session))
|
|
82
|
+
throw new Error('Record requires a session id or an unambiguous prefix.');
|
|
83
|
+
const selected = (0, ledger_panel_1.resolveLedgerSession)(rows, options.session);
|
|
84
|
+
if (!selected)
|
|
85
|
+
throw new Error(`No ledger decisions match session ${options.session}.`);
|
|
86
|
+
const history = rows.filter(row => row.sessionDigest === selected.sessionDigest);
|
|
87
|
+
if (!history.length)
|
|
88
|
+
throw new Error(`No ledger decisions match session ${options.session}.`);
|
|
89
|
+
const first = history[0], last = history.at(-1);
|
|
90
|
+
const from = options.from === undefined ? first.at : ledgerTimestamp(options.from);
|
|
91
|
+
const to = options.to === undefined ? last.at : ledgerTimestamp(options.to);
|
|
92
|
+
if (from > to)
|
|
93
|
+
throw new Error('Record --from must be at or before --to.');
|
|
94
|
+
if ((to - from) / 1000 + 1 > MAX_FRAMES)
|
|
95
|
+
throw new Error('Recording exceeds the 10,000 frame render limit; select a shorter time range.');
|
|
96
|
+
const within = history.filter(row => row.at >= from && row.at <= to);
|
|
97
|
+
if (!within.length)
|
|
98
|
+
throw new Error('No ledger decisions fall inside the requested time range.');
|
|
99
|
+
const session = selected.sessionId?.slice(0, 8) ?? selected.sessionDigest.slice(0, 8);
|
|
100
|
+
const project = (index, at) => {
|
|
101
|
+
const snapshot = (0, ledger_panel_1.projectLedgerPanel)(history.slice(0, index + 1), selected.sessionDigest, at);
|
|
102
|
+
return { ...snapshot, session, sessionDigest: selected.sessionDigest, startedAt: first.at, observedAt: at, elapsedMs: Math.max(0, at - first.at), controls: false };
|
|
103
|
+
};
|
|
104
|
+
// Seed the hold with prior history without treating an old STOP as a new event.
|
|
105
|
+
const hold = new live_panel_1.StopHold();
|
|
106
|
+
let priorIndex = -1;
|
|
107
|
+
while (priorIndex + 1 < history.length && history[priorIndex + 1].at < from - 2000)
|
|
108
|
+
priorIndex++;
|
|
109
|
+
if (priorIndex >= 0)
|
|
110
|
+
hold.update(project(priorIndex, from - 2000), from - 2000);
|
|
111
|
+
while (priorIndex + 1 < history.length && history[priorIndex + 1].at < from) {
|
|
112
|
+
priorIndex++;
|
|
113
|
+
hold.update(project(priorIndex, history[priorIndex].at), history[priorIndex].at);
|
|
114
|
+
}
|
|
115
|
+
const events = [];
|
|
116
|
+
const decisionTimes = new Set();
|
|
117
|
+
history.forEach((row, index) => {
|
|
118
|
+
if (row.at >= from && row.at <= to) {
|
|
119
|
+
events.push({ at: row.at, index });
|
|
120
|
+
decisionTimes.add(row.at);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
for (let at = from; at <= to; at += 1000)
|
|
124
|
+
if (!decisionTimes.has(at))
|
|
125
|
+
events.push({ at });
|
|
126
|
+
if ((to - from) % 1000 !== 0 && !decisionTimes.has(to))
|
|
127
|
+
events.push({ at: to });
|
|
128
|
+
events.sort((a, b) => a.at - b.at || (a.index ?? -1) - (b.index ?? -1));
|
|
129
|
+
if (events.length > MAX_FRAMES)
|
|
130
|
+
throw new Error('Recording exceeds the 10,000 frame render limit; select a shorter time range.');
|
|
131
|
+
const frames = events.map(event => {
|
|
132
|
+
if (event.index !== undefined)
|
|
133
|
+
priorIndex = event.index;
|
|
134
|
+
else
|
|
135
|
+
while (priorIndex + 1 < history.length && history[priorIndex + 1].at <= event.at)
|
|
136
|
+
priorIndex++;
|
|
137
|
+
const snapshot = hold.update(project(priorIndex, event.at), event.at);
|
|
138
|
+
return { version: 1, at: new Date(event.at).toISOString(), data: { kind: 'live', snapshot }, viewport: { width: 104, height: 35 } };
|
|
139
|
+
});
|
|
140
|
+
const lastStop = history.filter(row => row.at <= to && row.verdict === 'STOP').at(-1);
|
|
141
|
+
return { frames, session, from, to, decisionCount: within.length, clippedStopHold: Boolean(lastStop && lastStop.at + 2000 > to) };
|
|
142
|
+
}
|
|
143
|
+
function recordLedger(home, options) {
|
|
144
|
+
if (!options.out || /[\x00-\x1f\x7f]/.test(options.out))
|
|
145
|
+
throw new Error('Recording output must be a local path without control characters.');
|
|
146
|
+
const output = (0, node_path_1.resolve)(options.out);
|
|
147
|
+
if (['decisions.ndjson', 'receipts.ndjson'].some(name => output === (0, node_path_1.resolve)((0, node_path_1.join)(home, name)))) {
|
|
148
|
+
throw new Error('Recording output must not replace a source ledger.');
|
|
149
|
+
}
|
|
150
|
+
const result = reconstructLedgerFrames((0, ledger_panel_1.readPanelLedger)(home), options);
|
|
151
|
+
const bytes = result.frames.map(frame => JSON.stringify(frame)).join('\n') + '\n';
|
|
152
|
+
if (Buffer.byteLength(bytes) > 128 * 1024 * 1024)
|
|
153
|
+
throw new Error('Recording exceeds the 128 MB render limit; select a shorter time range.');
|
|
154
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(output), { recursive: true, mode: 0o700 });
|
|
155
|
+
try {
|
|
156
|
+
(0, node_fs_1.writeFileSync)(output, bytes, { flag: 'wx', mode: 0o600 });
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error.code === 'EEXIST')
|
|
160
|
+
throw new Error(`Refusing to overwrite existing output: ${output}`);
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
return { output, session: result.session, from: new Date(result.from).toISOString(), to: new Date(result.to).toISOString(),
|
|
164
|
+
frameCount: result.frames.length, decisionCount: result.decisionCount, clippedStopHold: result.clippedStopHold };
|
|
165
|
+
}
|