Repository Public Research preview
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : LLM API toolkits8 * File : protocol/mcp/lib/ledger.mjs9 * Module : protocol10 * Repository : https://git.spboucher.ai/llm-api-toolkits11 * Created : 2026-11-1012 * Last Modified : 2026-11-1013 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: dev@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { createHash, randomBytes } from "node:crypto";43import fs from "node:fs";44import path from "node:path";4546/**47 * Research ledger engine. Dependency-free, offline, synchronous.48 *49 * State is one append-only file, `.research/ledger.jsonl`, inside the project root. Each record50 * carries the SHA-256 of the previous record, so an edit, a deletion or a reordering breaks the51 * chain at a known line. `.research/HEAD` remembers the last record, which makes a truncated tail52 * detectable too. This is tamper EVIDENCE against accidents and quiet rewrites, not protection53 * against someone who rewrites the whole chain and HEAD: anchor the head hash somewhere you do not54 * control alone (a commit, a registry, an e-mail) if you need that.55 */56export class LedgerError extends Error {57 constructor(code, message, extra) { super(message); this.code = code; Object.assign(this, extra ?? {}); }58}59export const ENGINE_VERSION = "1.0.0";60const ZERO = "0".repeat(64);61export const sha256 = (data) => createHash("sha256").update(data).digest("hex");6263/** JSON with sorted keys: the same value always serialises to the same bytes. */64export function canonical(v) {65 if (v === null || typeof v !== "object") return JSON.stringify(v ?? null);66 if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;67 return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;68}69const recordHash = (r) => sha256(canonical({ seq: r.seq, ts: r.ts, type: r.type, data: r.data, prev: r.prev }));70const pad = (n) => String(n).padStart(2, "0");71const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);72const micro = (usd) => Math.round(Number(usd) * 1e6);73const usd = (m) => Math.round(m) / 1e6;7475function need(cond, code, message, extra) { if (!cond) throw new LedgerError(code, message, extra); }76function text(v, name, { min = 1, max = 4000 } = {}) {77 need(typeof v === "string" && v.trim().length >= min, "invalid_input", `${name} is required${min > 1 ? ` (at least ${min} characters)` : ""}.`);78 need(v.length <= max, "invalid_input", `${name} is too long (limit ${max} characters).`);79 return v.trim();80}81function oneOf(v, name, values) { need(values.includes(v), "invalid_input", `${name} must be one of: ${values.join(", ")}.`); return v; }82function strings(v, name, { min = 0, max = 50 } = {}) {83 const a = v == null ? [] : Array.isArray(v) ? v : [v];84 need(a.every((x) => typeof x === "string" && x.trim()), "invalid_input", `${name} must be a list of non-empty strings.`);85 need(a.length >= min && a.length <= max, "invalid_input", `${name} needs between ${min} and ${max} entries.`);86 return a.map((x) => x.trim());87}8889export class Ledger {90 constructor({ root = process.env.RESEARCH_LEDGER_ROOT ?? process.cwd(), now = () => new Date() } = {}) {91 const abs = path.resolve(root);92 need(fs.existsSync(abs) && fs.statSync(abs).isDirectory(), "root_missing", `Project root ${abs} is not a directory.`);93 this.root = fs.realpathSync(abs);94 this.dir = path.join(this.root, ".research");95 this.file = path.join(this.dir, "ledger.jsonl");96 this.headFile = path.join(this.dir, "HEAD");97 this.lockFile = path.join(this.dir, "lock");98 this.now = now;99 }100101 /* ───────── storage ───────── */102103 ensureDir() {104 if (fs.existsSync(this.dir) || fs.lstatSync(this.dir, { throwIfNoEntry: false })) {105 const st = fs.lstatSync(this.dir);106 // A symlinked .research could redirect every write outside the project.107 need(!st.isSymbolicLink() && st.isDirectory(), "path_forbidden", ".research must be a real directory inside the project root, not a link.");108 } else fs.mkdirSync(this.dir, { mode: 0o755 });109 }110 /** Resolve a user path to a real file inside the root (never inside .research). */111 confine(p, { mustExist = true } = {}) {112 need(typeof p === "string" && p.length > 0 && !p.includes("\0"), "invalid_input", "A file path is required.");113 const target = path.resolve(this.root, p);114 if (!fs.existsSync(target)) { need(!mustExist, "file_missing", `${p} does not exist.`); return { rel: path.relative(this.root, target).split(path.sep).join("/"), abs: target, exists: false }; }115 const real = fs.realpathSync(target);116 need(real === this.root || real.startsWith(this.root + path.sep), "path_forbidden", `${p} resolves outside the project root (${this.root}).`);117 need(!(real + path.sep).startsWith(this.dir + path.sep), "path_forbidden", "Files inside .research are managed by the ledger and cannot be listed.");118 need(fs.statSync(real).isFile(), "not_a_file", `${p} is not a regular file.`);119 return { rel: path.relative(this.root, real).split(path.sep).join("/"), abs: real, exists: true };120 }121 hashFile(p) { const f = this.confine(p); const data = fs.readFileSync(f.abs); return { path: f.rel, sha256: sha256(data), bytes: data.length }; }122 hashFiles(list, name, { min = 0 } = {}) {123 const paths = strings(list, name, { min, max: 500 });124 const out = paths.map((p) => this.hashFile(p)).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));125 need(new Set(out.map((f) => f.path)).size === out.length, "invalid_input", `${name} lists the same file twice.`);126 return out;127 }128129 withLock(fn) {130 this.ensureDir();131 const deadline = Date.now() + 20000;132 for (;;) {133 try { fs.writeFileSync(this.lockFile, `${process.pid}\n`, { flag: "wx" }); break; }134 catch (e) {135 if (e.code !== "EEXIST") throw e;136 // A lock older than 30 s belongs to a writer that died: a single append takes milliseconds.137 try { if (Date.now() - fs.statSync(this.lockFile).mtimeMs > 30000) { fs.rmSync(this.lockFile, { force: true }); continue; } } catch { continue; }138 need(Date.now() < deadline, "lock_timeout", "Another process holds the ledger lock.");139 sleep(10 + Math.floor(Math.random() * 30));140 }141 }142 try {143 // Any temp file seen while holding the lock was left by an interrupted writer.144 for (const f of fs.readdirSync(this.dir)) if (/\.tmp-/.test(f)) fs.rmSync(path.join(this.dir, f), { force: true });145 return fn();146 } finally { fs.rmSync(this.lockFile, { force: true }); }147 }148 atomicWrite(file, content) {149 const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;150 const fd = fs.openSync(tmp, "wx", 0o644);151 try { fs.writeSync(fd, content); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }152 fs.renameSync(tmp, file);153 }154155 /** Read and verify the chain. Returns the valid prefix and the first problem, if any. */156 read() {157 const out = { exists: fs.existsSync(this.file), records: [], problem: null, warnings: [], head: null, raw: "" };158 if (!out.exists) return out;159 out.raw = fs.readFileSync(this.file, "utf8");160 const lines = out.raw.split("\n");161 if (lines[lines.length - 1] === "") lines.pop();162 let prev = ZERO;163 for (let i = 0; i < lines.length; i++) {164 const at = { line: i + 1, seq: i + 1 };165 let r;166 try { r = JSON.parse(lines[i]); } catch { out.problem = { ...at, kind: "invalid_json", detail: i === lines.length - 1 && !out.raw.endsWith("\n") ? "The last line is incomplete: the file was truncated in the middle of a record." : "This line is not valid JSON." }; break; }167 if (!r || typeof r !== "object" || r.seq !== i + 1) { out.problem = { ...at, kind: "sequence_break", detail: `Expected record ${i + 1}, found ${r?.seq ?? "none"}: a record was deleted, inserted or moved here.` }; break; }168 if (r.prev !== prev) { out.problem = { ...at, kind: "chain_break", detail: `Record ${r.seq} does not point at the record before it: the previous record was replaced, removed or reordered.` }; break; }169 if (r.hash !== recordHash(r)) { out.problem = { ...at, kind: "content_changed", detail: `Record ${r.seq} was edited after it was written (its content no longer matches its hash).` }; break; }170 out.records.push(r); prev = r.hash;171 }172 const last = out.records[out.records.length - 1] ?? null;173 out.head = last ? { seq: last.seq, hash: last.hash } : null;174 if (!out.problem) {175 let head = null;176 try { head = JSON.parse(fs.readFileSync(this.headFile, "utf8")); } catch { /* missing or unreadable HEAD */ }177 if (!head) { if (last) out.warnings.push({ kind: "head_missing", detail: "HEAD is missing; it will be rewritten by the next append. Truncation of the tail cannot be ruled out." }); }178 else if (!last || head.seq > last.seq) out.problem = { line: (last?.seq ?? 0) + 1, seq: (last?.seq ?? 0) + 1, kind: "tail_missing", detail: `HEAD says the ledger had ${head.seq} records but only ${last?.seq ?? 0} remain: records from ${(last?.seq ?? 0) + 1} on were removed.` };179 else if (head.seq === last.seq && head.hash !== last.hash) out.problem = { line: last.seq, seq: last.seq, kind: "head_mismatch", detail: `The last record does not match HEAD: the tail of the ledger was rewritten.` };180 else if (head.seq < last.seq) {181 const anchor = out.records[head.seq - 1];182 if (!anchor || anchor.hash !== head.hash) out.problem = { line: head.seq, seq: head.seq, kind: "head_mismatch", detail: "HEAD points at a record that is no longer in the ledger: the history was rewritten." };183 else out.warnings.push({ kind: "head_stale", detail: `HEAD is ${last.seq - head.seq} record(s) behind: the last append was interrupted after the ledger was written. The next append repairs it.` });184 }185 }186 return out;187 }188 state() {189 const r = this.read();190 need(r.exists && r.records.length > 0, "not_initialised", "No ledger here yet. Run init_project first.");191 need(!r.problem, "ledger_corrupt", `The ledger failed verification at record ${r.problem?.seq}: ${r.problem?.detail} Nothing will be appended until this is resolved (see verify_ledger).`, { problem: r.problem });192 return buildState(r.records);193 }194 /** Append one record. `build` receives the current state and returns {type, data}; numbering happens inside the lock. */195 mutate(build, { allowUninitialised = false } = {}) {196 return this.withLock(() => {197 const r = this.read();198 need(!r.problem, "ledger_corrupt", `The ledger failed verification at record ${r.problem?.seq}: ${r.problem?.detail} Nothing will be appended until this is resolved (see verify_ledger).`, { problem: r.problem });199 need(allowUninitialised || r.records.length > 0, "not_initialised", "No ledger here yet. Run init_project first.");200 const st = buildState(r.records);201 const { type, data } = build(st);202 const last = r.records[r.records.length - 1];203 const rec = { seq: (last?.seq ?? 0) + 1, ts: this.now().toISOString(), type, data, prev: last?.hash ?? ZERO };204 rec.hash = recordHash(rec);205 const body = r.raw === "" || r.raw.endsWith("\n") ? r.raw : r.raw + "\n";206 this.atomicWrite(this.file, body + JSON.stringify(rec) + "\n");207 this.atomicWrite(this.headFile, JSON.stringify({ seq: rec.seq, hash: rec.hash }) + "\n");208 return rec;209 });210 }211212 /* ───────── operations ───────── */213214 init({ title, description, budget_usd, outcome_data }) {215 const data = { title: text(title, "title", { max: 300 }), description: description ? text(description, "description") : null, budget_micro_usd: budget_usd == null ? null : this.money(budget_usd, "budget_usd"), outcome_data: outcome_data ? text(outcome_data, "outcome_data", { max: 1000 }) : null, engine: ENGINE_VERSION };216 const rec = this.mutate((st) => { need(!st.project, "already_initialised", "This project already has a ledger. A ledger is never reset; start a new project directory instead."); return { type: "init", data }; }, { allowUninitialised: true });217 return { initialised: true, ledger: path.relative(this.root, this.file), head: { seq: rec.seq, hash: rec.hash }, project: view(data) };218 }219 money(v, name) { need(typeof v === "number" && Number.isFinite(v) && v >= 0 && v < 1e9, "invalid_input", `${name} must be a non-negative amount in US dollars.`); return micro(v); }220221 registerHypothesis(a) {222 const data = {223 id: a.id == null ? null : text(a.id, "id", { max: 20 }), statement: text(a.statement, "statement", { min: 10 }), direction: oneOf(a.direction ?? "two_sided", "direction", ["positive", "negative", "two_sided", "none"]),224 test: text(a.test, "test", { min: 5 }), decision_rule: text(a.decision_rule, "decision_rule", { min: 5 }), role: oneOf(a.role ?? "primary", "role", ["primary", "secondary"]),225 };226 if (data.id) need(/^H[0-9]+[a-z]?$/.test(data.id), "invalid_input", 'Hypothesis ids look like "H1", "H2", "H3a".');227 const rec = this.mutate((st) => {228 const id = data.id ?? `H${st.hypotheses.size + 1}`;229 need(!st.hypotheses.has(id), "duplicate_id", `Hypothesis ${id} is already registered. Hypotheses are never edited: register a new one and record why.`);230 return { type: "hypothesis", data: { ...data, id, after_freeze: st.freezes.length > 0, after_outcome_data: st.firstOutcomeSeq != null } };231 });232 return { registered: rec.data.id, seq: rec.seq, ...(rec.data.after_freeze ? { warning: "Registered after the protocol was frozen: results for it are exploratory unless an amendment made before outcome data covers it." } : {}) };233 }234235 manifest(files, hypotheses) {236 const lines = files.map((f) => `${f.path}\0${f.sha256}\n`).join("");237 return sha256(lines + canonical(hypotheses));238 }239 freeze({ files, note }) {240 const hashed = this.hashFiles(files, "files", { min: 1 });241 const rec = this.mutate((st) => {242 need(st.freezes.length === 0, "already_frozen", `The protocol was frozen as version ${st.freezes.length} (root ${st.freezes.at(-1)?.root_hash.slice(0, 12)}…). A frozen protocol is changed only through amend_protocol, which records why and whether data had been seen.`);243 need(st.hypotheses.size > 0, "no_hypotheses", "Register at least one hypothesis before freezing: a protocol without a stated hypothesis fixes nothing.");244 const hyp = [...st.hypotheses.values()].map(({ id, statement, direction, test, decision_rule, role }) => ({ id, statement, direction, test, decision_rule, role }));245 return { type: "freeze", data: { version: 1, kind: "freeze", files: hashed, hypotheses: hyp.map((h) => h.id), hypotheses_hash: sha256(canonical(hyp)), root_hash: this.manifest(hashed, hyp), note: note ? text(note, "note") : null, after_outcome_data: st.firstOutcomeSeq != null } };246 });247 return freezeView(rec);248 }249 amend({ files, reason, data_seen, affects }) {250 const hashed = this.hashFiles(files, "files", { min: 1 });251 const why = text(reason, "reason", { min: 10 });252 need(typeof data_seen === "boolean", "invalid_input", "data_seen is required: say whether outcome data had been seen when this amendment was decided.");253 const aff = strings(affects, "affects");254 const rec = this.mutate((st) => {255 need(st.freezes.length > 0, "not_frozen", "Nothing to amend: the protocol has not been frozen yet. Use freeze_protocol.");256 for (const id of aff) need(st.hypotheses.has(id), "unknown_hypothesis", `Unknown hypothesis ${id}.`);257 const prev = st.freezes.at(-1);258 const hyp = [...st.hypotheses.values()].map(({ id, statement, direction, test, decision_rule, role }) => ({ id, statement, direction, test, decision_rule, role }));259 const root = this.manifest(hashed, hyp);260 need(root !== prev.root_hash, "nothing_changed", "The files and hypotheses are identical to the frozen version: there is nothing to amend.");261 const seen = data_seen || st.firstOutcomeSeq != null;262 return { type: "freeze", data: { version: prev.version + 1, kind: "amendment", previous_root_hash: prev.root_hash, files: hashed, hypotheses: hyp.map((h) => h.id), hypotheses_hash: sha256(canonical(hyp)), root_hash: root, reason: why, data_seen: seen, declared_data_seen: data_seen, affects: aff, changed_files: diffFiles(prev.files, hashed) } };263 });264 return { ...freezeView(rec), ...(rec.data.data_seen && !rec.data.declared_data_seen ? { warning: "The ledger already records access to outcome data, so this amendment is treated as made after data were seen." } : {}), ...(rec.data.data_seen ? { consequence: `Results for ${rec.data.affects.length ? rec.data.affects.join(", ") : "every hypothesis"} recorded from now on are exploratory.` } : {}) };265 }266 /** Re-hash the files of the freeze in force. Read-only. */267 verifyProtocol(st = this.state()) {268 const fz = st.freezes.at(-1);269 need(fz, "not_frozen", "The protocol has not been frozen yet.");270 const files = fz.files.map((f) => {271 const abs = path.resolve(this.root, f.path);272 if (!fs.existsSync(abs)) {273 // A missing file may simply have been renamed: look for the same bytes next to where it was.274 let moved = null;275 try { for (const n of fs.readdirSync(path.dirname(abs))) { const c = path.join(path.dirname(abs), n); if (fs.statSync(c).isFile() && fs.statSync(c).size === f.bytes && sha256(fs.readFileSync(c)) === f.sha256) { moved = path.relative(this.root, c).split(path.sep).join("/"); break; } } } catch { /* directory gone */ }276 return { path: f.path, status: "missing", frozen_sha256: f.sha256, ...(moved ? { same_content_found_at: moved } : {}) };277 }278 let cur;279 try { cur = this.hashFile(f.path); } catch (e) { return { path: f.path, status: "unreadable", detail: e.message }; }280 return cur.sha256 === f.sha256 ? { path: f.path, status: "unchanged" } : { path: f.path, status: "changed", frozen_sha256: f.sha256, current_sha256: cur.sha256, frozen_bytes: f.bytes, current_bytes: cur.bytes };281 });282 const hyp = [...st.hypotheses.values()].map(({ id, statement, direction, test, decision_rule, role }) => ({ id, statement, direction, test, decision_rule, role }));283 const added = hyp.filter((h) => !fz.hypotheses.includes(h.id)).map((h) => h.id);284 const changed = files.filter((f) => f.status !== "unchanged");285 return { intact: changed.length === 0, version: fz.version, root_hash: fz.root_hash, frozen_at: fz.ts, files, changed: changed.map((f) => f.path), hypotheses_registered_since: added, ...(changed.length ? { next_step: "Either restore the frozen files, or record the change with amend_protocol (stating whether data had been seen)." } : {}) };286 }287288 markDataAccess({ description, outcome_data = true }) {289 const d = text(description, "description", { min: 5 });290 const rec = this.mutate((st) => ({ type: "data_access", data: { description: d, outcome_data: !!outcome_data, frozen_before: st.freezes.length > 0 } }));291 return { recorded: true, seq: rec.seq, outcome_data: rec.data.outcome_data, ...(rec.data.outcome_data && !rec.data.frozen_before ? { warning: "Outcome data were accessed before any protocol was frozen: no later result can be confirmatory." } : {}) };292 }293294 logDecision(a) {295 const data = { question: text(a.question, "question", { min: 5 }), options: strings(a.options, "options", { min: 2, max: 12 }), choice: text(a.choice, "choice"), rationale: text(a.rationale, "rationale", { min: 10 }), timing: oneOf(a.timing, "timing", ["before_outcome_data", "after_outcome_data"]) };296 const rec = this.mutate((st) => ({ type: "decision", data: { id: `D-${pad(st.decisions.length + 1)}`, ...data, timing_conflict: data.timing === "before_outcome_data" && st.firstOutcomeSeq != null } }));297 return { id: rec.data.id, seq: rec.seq, ...(rec.data.timing_conflict ? { warning: "Declared as made before outcome data, but the ledger already records access to outcome data. The conflict is kept on record." } : {}) };298 }299 logDeviation(a) {300 const data = { protocol_said: text(a.protocol_said, "protocol_said", { min: 5 }), done: text(a.done, "done", { min: 5 }), reason: text(a.reason, "reason", { min: 10 }), impact: oneOf(a.impact, "impact", ["none", "minor", "exploratory"]), hypotheses: strings(a.hypotheses, "hypotheses") };301 const rec = this.mutate((st) => { for (const id of data.hypotheses) need(st.hypotheses.has(id), "unknown_hypothesis", `Unknown hypothesis ${id}.`); return { type: "deviation", data: { id: `V-${pad(st.deviations.length + 1)}`, ...data, after_outcome_data: st.firstOutcomeSeq != null } }; });302 return { id: rec.data.id, seq: rec.seq, impact: rec.data.impact, applies_to: rec.data.hypotheses.length ? rec.data.hypotheses : "all hypotheses" };303 }304305 openGate({ name, criteria, purpose }) {306 const n = text(name, "name", { max: 60 }), c = strings(criteria, "criteria", { min: 1, max: 30 });307 const rec = this.mutate((st) => { const g = st.gates.get(n); need(!g || g.at(-1).closed, "gate_open", `Gate "${n}" is already open. Close it before opening it again.`); return { type: "gate_open", data: { name: n, round: (g?.length ?? 0) + 1, criteria: c, purpose: purpose ? text(purpose, "purpose") : null } }; });308 return { gate: n, round: rec.data.round, seq: rec.seq, criteria: c };309 }310 closeGate({ name, outcome, evidence, conditions, notes }) {311 const n = text(name, "name", { max: 60 }), o = oneOf(outcome, "outcome", ["go", "no_go", "conditional"]), ev = strings(evidence, "evidence", { min: 1, max: 40 }), cond = strings(conditions, "conditions");312 need(o !== "conditional" || cond.length > 0, "invalid_input", "A conditional outcome needs at least one condition to satisfy before proceeding.");313 const rec = this.mutate((st) => { const g = st.gates.get(n)?.at(-1); need(g && !g.closed, "gate_not_open", `Gate "${n}" is not open. Open it first, with its criteria, so the criteria are on record before the evidence.`); return { type: "gate_close", data: { name: n, round: g.round, outcome: o, evidence: ev, conditions: cond, notes: notes ? text(notes, "notes") : null, criteria: g.criteria } }; });314 return { gate: n, round: rec.data.round, outcome: o, seq: rec.seq, ...(o === "no_go" ? { consequence: "No-go is a result. Do not proceed past this gate; reopen it with revised criteria if the plan changes." } : {}) };315 }316317 fingerprint({ command, code, inputs, seed }) { return sha256(canonical({ command, code: code.map((f) => [f.path, f.sha256]), inputs: inputs.map((f) => [f.path, f.sha256]), seed: seed ?? null })); }318 checkRerun(a) {319 const command = text(a.command, "command", { max: 2000 }), code = this.hashFiles(a.code_files, "code_files"), inputs = this.hashFiles(a.input_files, "input_files");320 const fp = this.fingerprint({ command, code, inputs, seed: a.seed });321 const st = this.state();322 const same = st.runs.filter((r) => r.fingerprint === fp), expensive = same.filter((r) => r.expensive && r.status === "completed");323 return { fingerprint: fp, identical_runs: same.map((r) => ({ id: r.id, status: r.status, expensive: r.expensive, ended_at: r.ended_at, outputs: r.outputs })), rerun_advised: expensive.length === 0, ...(expensive.length ? { warning: `An identical run marked expensive already completed (${expensive.map((r) => r.id).join(", ")}). Reuse its outputs. Re-running a costly or non-deterministic step replaces recorded results with different ones; if you must, register the new run with rerun_reason.` } : {}) };324 }325 registerRun(a) {326 const command = text(a.command, "command", { max: 2000 }), code = this.hashFiles(a.code_files, "code_files"), inputs = this.hashFiles(a.input_files, "input_files"), outputs = this.hashFiles(a.output_files, "output_files");327 const data = {328 name: text(a.name, "name", { max: 120 }), command, code, inputs, outputs, seed: a.seed ?? null, status: oneOf(a.status ?? "completed", "status", ["completed", "failed"]), expensive: !!a.expensive, deterministic: a.deterministic !== false,329 started_at: a.started_at ? isoDate(a.started_at, "started_at") : null, ended_at: a.ended_at ? isoDate(a.ended_at, "ended_at") : null, notes: a.notes ? text(a.notes, "notes") : null,330 environment: { node: process.version, platform: process.platform, arch: process.arch, summary: a.environment ? text(a.environment, "environment", { max: 1000 }) : null },331 rerun_reason: a.rerun_reason ? text(a.rerun_reason, "rerun_reason", { min: 10 }) : null,332 };333 data.fingerprint = this.fingerprint({ command, code, inputs, seed: data.seed });334 const rec = this.mutate((st) => {335 const prior = st.runs.filter((r) => r.fingerprint === data.fingerprint && r.expensive && r.status === "completed");336 need(prior.length === 0 || data.rerun_reason, "expensive_rerun", `Run ${prior.map((r) => r.id).join(", ")} already did exactly this and is marked expensive. Reuse its outputs, or register this run with rerun_reason so the repetition is on record.`, { identical_runs: prior.map((r) => r.id) });337 return { type: "run", data: { id: `R-${pad(st.runs.length + 1)}`, ...data, repeats: prior.map((r) => r.id) } };338 });339 return { id: rec.data.id, seq: rec.seq, fingerprint: rec.data.fingerprint, expensive: rec.data.expensive, outputs: rec.data.outputs, ...(rec.data.repeats.length ? { repeats: rec.data.repeats } : {}) };340 }341342 setBudget({ budget_usd, reason }) {343 const m = this.money(budget_usd, "budget_usd"), why = text(reason, "reason", { min: 10 });344 const rec = this.mutate((st) => ({ type: "budget", data: { budget_micro_usd: m, previous_micro_usd: st.budget, reason: why } }));345 return { budget_usd: usd(m), previous_usd: rec.data.previous_micro_usd == null ? null : usd(rec.data.previous_micro_usd), seq: rec.seq };346 }347 recordSpend(a) {348 const int = (v, n) => { if (v == null) return null; need(Number.isInteger(v) && v >= 0, "invalid_input", `${n} must be a non-negative integer.`); return v; };349 const data = { provider: text(a.provider, "provider", { max: 80 }), model: a.model ? text(a.model, "model", { max: 120 }) : null, purpose: text(a.purpose, "purpose", { max: 300 }), cost_micro_usd: this.money(a.cost_usd, "cost_usd"), input_tokens: int(a.input_tokens, "input_tokens"), output_tokens: int(a.output_tokens, "output_tokens"), run_id: a.run_id ? text(a.run_id, "run_id", { max: 20 }) : null };350 const rec = this.mutate((st) => { if (data.run_id) need(st.runs.some((r) => r.id === data.run_id), "unknown_run", `Unknown run ${data.run_id}.`); return { type: "spend", data: { id: `S-${pad(st.spend.length + 1)}`, ...data } }; });351 const rep = this.spendReport();352 return { id: rec.data.id, seq: rec.seq, cost_usd: usd(data.cost_micro_usd), total_usd: rep.total_usd, budget_usd: rep.budget_usd, remaining_usd: rep.remaining_usd, ...(rep.over_budget ? { warning: `Spending (${rep.total_usd} USD) exceeds the declared budget (${rep.budget_usd} USD).` } : {}) };353 }354 spendReport(st = this.state()) {355 const total = st.spend.reduce((s, x) => s + x.cost_micro_usd, 0);356 const group = (key) => { const m = new Map(); for (const x of st.spend) { const k = x[key] ?? "(unspecified)"; const g = m.get(k) ?? { cost: 0, entries: 0, input_tokens: 0, output_tokens: 0 }; g.cost += x.cost_micro_usd; g.entries++; g.input_tokens += x.input_tokens ?? 0; g.output_tokens += x.output_tokens ?? 0; m.set(k, g); } return [...m].map(([k, g]) => ({ [key]: k, cost_usd: usd(g.cost), entries: g.entries, input_tokens: g.input_tokens, output_tokens: g.output_tokens })).sort((a, b) => b.cost_usd - a.cost_usd); };357 return { entries: st.spend.length, total_usd: usd(total), budget_usd: st.budget == null ? null : usd(st.budget), remaining_usd: st.budget == null ? null : usd(st.budget - total), over_budget: st.budget != null && total > st.budget, budget_used_pct: st.budget ? Math.round((total / st.budget) * 10000) / 100 : null, by_provider: group("provider"), by_model: group("model"), by_purpose: group("purpose") };358 }359360 recordResult(a) {361 const data = { hypothesis: text(a.hypothesis, "hypothesis", { max: 20 }), estimate: a.estimate == null ? null : typeof a.estimate === "number" ? a.estimate : text(String(a.estimate), "estimate", { max: 300 }), uncertainty: a.uncertainty ? text(a.uncertainty, "uncertainty", { max: 300 }) : null, verdict: oneOf(a.verdict, "verdict", ["confirmed", "not_confirmed", "inconclusive"]), notes: a.notes ? text(a.notes, "notes") : null, run_id: a.run_id ? text(a.run_id, "run_id", { max: 20 }) : null };362 const rec = this.mutate((st) => {363 need(st.hypotheses.has(data.hypothesis), "unknown_hypothesis", `Unknown hypothesis ${data.hypothesis}. Register it first (it will be exploratory if the protocol is already frozen).`);364 if (data.run_id) need(st.runs.some((r) => r.id === data.run_id), "unknown_run", `Unknown run ${data.run_id}.`);365 const intact = st.freezes.length ? this.verifyProtocol(st) : null;366 const cls = classify(st, data.hypothesis, Infinity, intact ? intact.intact : null);367 return { type: "result", data: { id: `X-${pad(st.results.length + 1)}`, ...data, status: cls.status, status_reasons: cls.reasons, protocol_intact: intact ? intact.intact : null, protocol_version: st.freezes.at(-1)?.version ?? null, protocol_root_hash: st.freezes.at(-1)?.root_hash ?? null } };368 });369 return { id: rec.data.id, seq: rec.seq, hypothesis: data.hypothesis, verdict: data.verdict, status: rec.data.status, status_reasons: rec.data.status_reasons };370 }371372 logQuestion({ question }) { const q = text(question, "question", { min: 5 }); const rec = this.mutate((st) => ({ type: "question", data: { id: `Q-${pad(st.questions.length + 1)}`, question: q } })); return { id: rec.data.id, seq: rec.seq }; }373 resolveQuestion({ id, answer }) {374 const qid = text(id, "id", { max: 20 }), ans = text(answer, "answer", { min: 3 });375 const rec = this.mutate((st) => { const q = st.questions.find((x) => x.id === qid); need(q, "unknown_question", `Unknown question ${qid}.`); need(!q.answer, "already_resolved", `${qid} is already resolved.`); return { type: "question_resolved", data: { id: qid, answer: ans } }; });376 return { id: qid, resolved: true, seq: rec.seq };377 }378379 status() {380 const r = this.read();381 need(r.exists && r.records.length > 0, "not_initialised", "No ledger here yet. Run init_project first.");382 if (r.problem) return { ledger_ok: false, problem: r.problem, next_step: "Run verify_ledger and restore the ledger from a copy whose head hash you trust. Nothing can be appended until then." };383 const st = buildState(r.records);384 const fz = st.freezes.at(-1);385 let protocol = { frozen: false };386 if (fz) { const v = this.verifyProtocol(st); protocol = { frozen: true, version: fz.version, root_hash: fz.root_hash, frozen_at: fz.ts, intact: v.intact, changed_files: v.changed, amendments: st.freezes.length - 1 }; }387 const gates = [...st.gates].map(([name, rounds]) => { const g = rounds.at(-1); return { name, round: g.round, state: g.closed ? g.outcome : "open", ...(g.closed ? { conditions: g.conditions } : { criteria: g.criteria }) }; });388 const pending = [...st.hypotheses.values()].filter((h) => !st.results.some((x) => x.hypothesis === h.id)).map((h) => h.id);389 const next = [];390 if (st.hypotheses.size === 0) next.push("Register the hypotheses (register_hypothesis).");391 else if (!fz) next.push("Freeze the protocol before touching outcome data (freeze_protocol).");392 if (fz && !protocol.intact) next.push(`Protocol files changed since the freeze (${protocol.changed_files.join(", ")}): restore them or record an amendment.`);393 for (const g of gates) { if (g.state === "open") next.push(`Gate "${g.name}" is open: gather evidence against its criteria and close it.`); if (g.state === "conditional") next.push(`Gate "${g.name}" is conditional: ${g.conditions.join("; ")}`); if (g.state === "no_go") next.push(`Gate "${g.name}" closed as no-go: do not proceed past it.`); }394 const openQ = st.questions.filter((q) => !q.answer);395 if (openQ.length) next.push(`${openQ.length} open question(s) to resolve.`);396 if (fz && pending.length && gates.every((g) => g.state !== "open" && g.state !== "no_go")) next.push(`No result recorded yet for: ${pending.join(", ")}.`);397 const spend = this.spendReport(st);398 if (spend.over_budget) next.push(`Spending is over budget (${spend.total_usd} of ${spend.budget_usd} USD).`);399 return {400 ledger_ok: true, warnings: r.warnings, project: view(st.project), head: r.head, records: r.records.length, last_activity: r.records.at(-1).ts,401 protocol, outcome_data_accessed: st.firstOutcomeSeq != null,402 hypotheses: [...st.hypotheses.values()].map((h) => ({ id: h.id, role: h.role, statement: h.statement, result: st.results.filter((x) => x.hypothesis === h.id).map((x) => `${x.verdict} (${x.status})`).at(-1) ?? null })),403 gates, open_questions: openQ.map((q) => ({ id: q.id, question: q.question })),404 counts: { decisions: st.decisions.length, deviations: st.deviations.length, runs: st.runs.length, expensive_runs: st.runs.filter((x) => x.expensive).length, results: st.results.length },405 spend: { total_usd: spend.total_usd, budget_usd: spend.budget_usd, remaining_usd: spend.remaining_usd },406 recent: r.records.slice(-8).map((x) => ({ seq: x.seq, at: x.ts, what: summarise(x) })), next_steps: next,407 };408 }409410 verifyLedger() {411 const r = this.read();412 if (!r.exists) return { ok: false, initialised: false, records: 0, detail: "No ledger file here." };413 return { ok: !r.problem, initialised: true, records_verified: r.records.length, head: r.head, first_problem: r.problem, warnings: r.warnings, guarantee: "Each record carries the hash of the one before it, and HEAD remembers the last one: an edited, deleted, reordered or truncated record is detected. Someone who rewrites the whole chain and HEAD is not: anchor the head hash outside this directory if that matters." };414 }415416 exportReport({ write = false } = {}) {417 const st = this.state(), r = this.read();418 const fz = st.freezes.at(-1), proto = fz ? this.verifyProtocol(st) : null, spend = this.spendReport(st);419 const results = st.results.map((x) => ({ ...x, status_now: classify(st, x.hypothesis, x.seq, x.protocol_intact) }));420 const json = {421 generated_at: this.now().toISOString(), engine: ENGINE_VERSION, project: view(st.project), ledger: { records: r.records.length, head: r.head },422 protocol: fz ? { frozen: true, versions: st.freezes.map((f) => ({ version: f.version, kind: f.kind, at: f.ts, root_hash: f.root_hash, files: f.files, reason: f.reason ?? null, data_seen: f.data_seen ?? f.after_outcome_data ?? false, affects: f.affects ?? [] })), current_files_intact: proto.intact, changed_files: proto.changed } : { frozen: false },423 outcome_data_first_accessed: st.firstOutcomeSeq == null ? null : r.records[st.firstOutcomeSeq - 1].ts,424 hypotheses: [...st.hypotheses.values()].map(strip), decisions: st.decisions.map(strip), deviations: st.deviations.map(strip),425 gates: [...st.gates].flatMap(([, rounds]) => rounds.map(strip)), runs: st.runs.map(strip), spend: { ...spend, entries_detail: st.spend.map((x) => ({ ...strip(x), cost_usd: usd(x.cost_micro_usd) })) },426 results: results.map(({ status_now, ...x }) => ({ ...strip(x), status: status_now.status, status_reasons: status_now.reasons })), open_questions: st.questions.filter((q) => !q.answer).map(strip),427 };428 const md = renderMarkdown(json);429 let files = null;430 if (write) {431 const dir = path.join(this.dir, "reports");432 this.withLock(() => { fs.mkdirSync(dir, { recursive: true }); this.atomicWrite(path.join(dir, `report-${pad(r.records.length)}.md`), md); this.atomicWrite(path.join(dir, `report-${pad(r.records.length)}.json`), JSON.stringify(json, null, 2) + "\n"); });433 files = [`.research/reports/report-${pad(r.records.length)}.md`, `.research/reports/report-${pad(r.records.length)}.json`];434 }435 return { markdown: md, json, written: files };436 }437}438439/* ───────── pure helpers ───────── */440441function isoDate(v, name) { const d = new Date(v); need(typeof v === "string" && !Number.isNaN(d.getTime()), "invalid_input", `${name} must be an ISO date-time.`); return d.toISOString(); }442function diffFiles(before, after) {443 const b = new Map(before.map((f) => [f.path, f.sha256])), a = new Map(after.map((f) => [f.path, f.sha256]));444 return { added: [...a.keys()].filter((p) => !b.has(p)), removed: [...b.keys()].filter((p) => !a.has(p)), modified: [...a.keys()].filter((p) => b.has(p) && b.get(p) !== a.get(p)) };445}446const strip = ({ seq, ts, ...rest }) => ({ ...rest, seq, at: ts });447const view = (p) => (p ? { title: p.title, description: p.description, outcome_data: p.outcome_data ?? null, budget_usd: p.budget_micro_usd == null ? null : usd(p.budget_micro_usd) } : null);448const freezeView = (rec) => ({ version: rec.data.version, kind: rec.data.kind, root_hash: rec.data.root_hash, seq: rec.seq, frozen_at: rec.ts, files: rec.data.files, hypotheses: rec.data.hypotheses, ...(rec.data.changed_files ? { changed_files: rec.data.changed_files } : {}), ...(rec.data.after_outcome_data ? { warning: "Frozen after outcome data were accessed: results cannot be confirmatory under this protocol." } : {}), anchor: "Record this root hash somewhere outside the project (a commit message, a registry entry) to prove later what was fixed in advance." });449450export function buildState(records) {451 const st = { project: null, budget: null, hypotheses: new Map(), freezes: [], firstOutcomeSeq: null, dataAccess: [], decisions: [], deviations: [], gates: new Map(), runs: [], spend: [], results: [], questions: [] };452 for (const r of records) {453 const d = { ...r.data, seq: r.seq, ts: r.ts };454 switch (r.type) {455 case "init": st.project = d; st.budget = d.budget_micro_usd; break;456 case "budget": st.budget = d.budget_micro_usd; break;457 case "hypothesis": st.hypotheses.set(d.id, d); break;458 case "freeze": st.freezes.push(d); if (d.kind === "amendment" && d.data_seen && st.firstOutcomeSeq == null) st.firstOutcomeSeq = r.seq; break;459 case "data_access": st.dataAccess.push(d); if (d.outcome_data && st.firstOutcomeSeq == null) st.firstOutcomeSeq = r.seq; break;460 case "decision": st.decisions.push(d); break;461 case "deviation": st.deviations.push(d); break;462 case "gate_open": st.gates.set(d.name, [...(st.gates.get(d.name) ?? []), { ...d, closed: false }]); break;463 case "gate_close": { const g = st.gates.get(d.name)?.at(-1); if (g) Object.assign(g, { closed: true, outcome: d.outcome, evidence: d.evidence, conditions: d.conditions, notes: d.notes, closed_at: r.ts, closed_seq: r.seq }); break; }464 case "run": st.runs.push(d); break;465 case "spend": st.spend.push(d); break;466 case "result": st.results.push(d); if (st.firstOutcomeSeq == null) st.firstOutcomeSeq = r.seq; break;467 case "question": st.questions.push(d); break;468 case "question_resolved": { const q = st.questions.find((x) => x.id === d.id); if (q) { q.answer = d.answer; q.resolved_at = r.ts; } break; }469 default: break; // unknown record types from a newer engine are kept in the chain and ignored here470 }471 }472 return st;473}474475/**476 * Confirmatory or exploratory? Derived from the timeline, never declared by hand.477 * A result is confirmatory only if its hypothesis was fixed by a protocol version frozen before any478 * outcome data were accessed, nothing since has loosened that commitment, and the frozen files are intact.479 */480export function classify(st, id, atSeq = Infinity, protocolIntact = null) {481 const reasons = [];482 const freezes = st.freezes.filter((f) => f.seq < atSeq);483 const first = st.firstOutcomeSeq != null && st.firstOutcomeSeq < atSeq ? st.firstOutcomeSeq : null;484 if (freezes.length === 0) return { status: "exploratory", reasons: ["No protocol was frozen before this result."] };485 const preData = freezes.filter((f) => first == null || f.seq < first);486 if (preData.length === 0) return { status: "exploratory", reasons: ["The protocol was first frozen after outcome data had been accessed."] };487 if (!preData.at(-1).hypotheses.includes(id)) reasons.push("The hypothesis was registered after the last protocol version frozen before outcome data.");488 for (const f of freezes) if (f.kind === "amendment" && f.data_seen && (f.affects.length === 0 || f.affects.includes(id))) reasons.push(`The protocol was amended after outcome data were seen (version ${f.version}).`);489 // A deviation describes how the work was actually done, so it applies even when it is written down late.490 const devs = st.deviations.filter((v) => v.hypotheses.length === 0 || v.hypotheses.includes(id));491 for (const v of devs) if (v.impact === "exploratory") reasons.push(`Deviation ${v.id} removes confirmatory status.`);492 if (protocolIntact === false) reasons.push("The protocol files no longer matched the frozen manifest when the result was recorded (an unrecorded change).");493 if (reasons.length) return { status: "exploratory", reasons };494 const minor = devs.filter((v) => v.impact === "minor").map((v) => v.id);495 if (minor.length) return { status: "confirmatory_with_deviations", reasons: [`Minor deviations apply: ${minor.join(", ")}.`] };496 return { status: "confirmatory", reasons: [`Hypothesis fixed by protocol version ${preData.at(-1).version}, frozen before outcome data.`] };497}498499function summarise(r) {500 const d = r.data;501 switch (r.type) {502 case "init": return `project initialised: ${d.title}`;503 case "hypothesis": return `hypothesis ${d.id} registered`;504 case "freeze": return d.kind === "amendment" ? `protocol amended to version ${d.version}` : "protocol frozen (version 1)";505 case "data_access": return `data accessed${d.outcome_data ? " (outcome data)" : ""}: ${d.description}`;506 case "decision": return `${d.id}: ${d.question} → ${d.choice}`;507 case "deviation": return `${d.id} (${d.impact}): ${d.done}`;508 case "gate_open": return `gate "${d.name}" opened`;509 case "gate_close": return `gate "${d.name}" closed: ${d.outcome}`;510 case "run": return `${d.id} ${d.status}${d.expensive ? " (expensive)" : ""}: ${d.name}`;511 case "spend": return `${d.id}: ${usd(d.cost_micro_usd)} USD, ${d.provider} — ${d.purpose}`;512 case "budget": return `budget set to ${usd(d.budget_micro_usd)} USD`;513 case "result": return `${d.id}: ${d.hypothesis} ${d.verdict} (${d.status})`;514 case "question": return `${d.id}: ${d.question}`;515 case "question_resolved": return `${d.id} resolved`;516 default: return r.type;517 }518}519520const esc = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/\n+/g, " ");521export function renderMarkdown(j) {522 const L = [];523 const p = (...x) => L.push(...x);524 p(`# Transparency report — ${j.project.title}`, "", `Generated ${j.generated_at} from a ledger of ${j.ledger.records} records (head \`${j.ledger.head.hash}\`).`, "");525 if (j.project.description) p(j.project.description, "");526 p("## Protocol", "");527 if (!j.protocol.frozen) p("**No protocol was frozen.** Every result below is exploratory.", "");528 else {529 p("| Version | Kind | Frozen at | Root hash | After outcome data | Reason |", "|---|---|---|---|---|---|");530 for (const v of j.protocol.versions) p(`| ${v.version} | ${v.kind} | ${v.at} | \`${v.root_hash}\` | ${v.data_seen ? "yes" : "no"} | ${esc(v.reason ?? "")} |`);531 p("", `Files in the current version: ${j.protocol.versions.at(-1).files.map((f) => `\`${f.path}\``).join(", ")}.`, j.protocol.current_files_intact ? "The files on disk match the frozen manifest." : `**The files on disk differ from the frozen manifest:** ${j.protocol.changed_files.map((f) => `\`${f}\``).join(", ")}.`, "");532 }533 p(`Outcome data first accessed: ${j.outcome_data_first_accessed ?? "not recorded"}.`, "");534 p("## Hypotheses and results", "", "| Id | Role | Statement | Decision rule | Verdict | Status | Estimate | Uncertainty |", "|---|---|---|---|---|---|---|---|");535 for (const h of j.hypotheses) {536 const rs = j.results.filter((x) => x.hypothesis === h.id);537 if (rs.length === 0) p(`| ${h.id} | ${h.role} | ${esc(h.statement)} | ${esc(h.decision_rule)} | not reported | — | — | — |`);538 for (const x of rs) p(`| ${h.id} | ${h.role} | ${esc(h.statement)} | ${esc(h.decision_rule)} | ${x.verdict.replace("_", " ")} | ${x.status.replace(/_/g, " ")} | ${esc(x.estimate ?? "—")} | ${esc(x.uncertainty ?? "—")} |`);539 }540 p("");541 const expl = j.results.filter((x) => x.status !== "confirmatory");542 if (expl.length) { p("Why some results are not plainly confirmatory:", ""); for (const x of expl) p(`- ${x.id} (${x.hypothesis}): ${x.status_reasons.join(" ")}`); p(""); }543 const unreported = j.hypotheses.filter((h) => !j.results.some((x) => x.hypothesis === h.id));544 if (unreported.length) p(`Registered but not reported: ${unreported.map((h) => h.id).join(", ")}. A registered hypothesis without a result is itself a finding to explain.`, "");545 p("## Decisions", "");546 if (!j.decisions.length) p("None recorded.", "");547 for (const d of j.decisions) p(`- **${d.id}** (${d.at.slice(0, 10)}, ${d.timing.replace(/_/g, " ")}${d.timing_conflict ? ", **declared timing conflicts with the ledger**" : ""}) — ${d.question} Options: ${d.options.join(" / ")}. Chosen: **${d.choice}**. ${d.rationale}`);548 if (j.decisions.length) p("");549 p("## Deviations from the protocol", "");550 if (!j.deviations.length) p("None recorded.", "");551 for (const v of j.deviations) p(`- **${v.id}** (impact: ${v.impact}; ${v.hypotheses.length ? v.hypotheses.join(", ") : "all hypotheses"}) — Protocol: ${v.protocol_said} Done: ${v.done} Why: ${v.reason}`);552 if (j.deviations.length) p("");553 p("## Gates", "");554 if (!j.gates.length) p("None recorded.", "");555 for (const g of j.gates) p(`- **${g.name}** (round ${g.round}): ${g.closed ? g.outcome.replace("_", "-") : "open"}. Criteria: ${g.criteria.join("; ")}.${g.closed ? ` Evidence: ${g.evidence.join("; ")}.` : ""}${g.conditions?.length ? ` Conditions: ${g.conditions.join("; ")}.` : ""}`);556 if (j.gates.length) p("");557 p("## Runs", "");558 if (!j.runs.length) p("None recorded.", "");559 else { p("| Id | Name | Status | Expensive | Deterministic | Seed | Fingerprint | Outputs |", "|---|---|---|---|---|---|---|---|"); for (const r of j.runs) p(`| ${r.id} | ${esc(r.name)} | ${r.status} | ${r.expensive ? "yes" : "no"} | ${r.deterministic ? "yes" : "no"} | ${r.seed ?? "—"} | \`${r.fingerprint.slice(0, 16)}\` | ${r.outputs.map((o) => `\`${o.path}\` (\`${o.sha256.slice(0, 12)}\`)`).join(", ") || "—"} |`); p(""); const rep = j.runs.filter((r) => r.repeats?.length); for (const r of rep) p(`- ${r.id} repeats ${r.repeats.join(", ")}: ${r.rerun_reason}`); if (rep.length) p(""); }560 p("## Spending", "", `Total: **${j.spend.total_usd} USD** over ${j.spend.entries} entries.${j.spend.budget_usd != null ? ` Budget: ${j.spend.budget_usd} USD; remaining: ${j.spend.remaining_usd} USD${j.spend.over_budget ? " (**over budget**)" : ""}.` : " No budget was declared."}`, "");561 if (j.spend.by_purpose.length) { p("| Purpose | Cost (USD) | Entries |", "|---|---|---|"); for (const x of j.spend.by_purpose) p(`| ${esc(x.purpose)} | ${x.cost_usd} | ${x.entries} |`); p(""); }562 if (j.open_questions.length) { p("## Open questions", ""); for (const q of j.open_questions) p(`- ${q.id}: ${q.question}`); p(""); }563 p("## How to check this report", "", "Run `verify_ledger` (or `ledger.mjs check`) on the project: it re-computes the hash chain. Compare the head hash above with any copy of it recorded elsewhere. Run `verify_protocol` to re-hash the protocol files against the frozen manifest.", "");564 return L.join("\n");565}566