Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(stats): maintain event proof counters [R1,R2,C7]
Corey Olsonb27e74cfb56b
diff --git a/src/bar-corrections.js b/src/bar-corrections.jsindex 0474bd11..0130fcb8 100644--- a/src/bar-corrections.js+++ b/src/bar-corrections.js@@ -1,3 +1,4 @@+import { proofEventDetail } from './proof-event-detail.js';/*** A corrected bar records why the old one was wrong [B10,B31,R1].*@@ -90,7 +91,7 @@ export function barStats(history, verdicts, boundary) {const of = (agent) => (result[agent] ??= { corrections: 0, barRejects: 0, buildRejects: 0 });for (const event of history) {if (event.event_kind === 'add') creators.set(event.item_id, event.event_by);- const correction = event.event_kind === 'edit' ? JSON.parse(event.event_detail).barCorrection : null;+ const correction = event.event_kind === 'edit' ? proofEventDetail(event).barCorrection : null;if (!correction) continue;if (correction.reject) explained.add(correction.reject.verdict);if (!inWindow(event.event_at)) continue;diff --git a/src/board.js b/src/board.jsindex ef087044..5809a5aa 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,5 @@+import { appendProofCounter } from './proof-counters.js';+import { ensureProofCounters } from './proof-counters.js';/*** The board (B1–B7, V1–V8, R1–R3): items, claims, submissions, verdicts and shouts in one SQLite* file in the git common dir, so every worktree sees the same board and nothing is committed.@@ -522,15 +524,25 @@ export function atomic(board, work) {* @param {Date} [at] An enabled move may share one instant with its deadline.*/export function logEvent(board, by, kind, itemId, detail = {}, at) {- const model = agentModel(board, by);- const isAgent = Boolean(board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(by));- const recorded = { ...detail, ...((board.executionEngineVersion ?? ENGINE_VERSION) >= 8 && isAgent ? { model: model ?? 'unknown' } : {}),- ...(board.movePerson ? { person: board.movePerson } : {}) }; // The person behind a relayed move, from engine 73 (engine.js) [E3].- const inserted = board.db- .prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)')- .run(at ? at.toISOString() : now(board), by, kind, itemId, JSON.stringify(recorded));- board.lastEvent = board.db.prepare('SELECT * FROM event WHERE event_id = ?').get(inserted.lastInsertRowid);- (board.emittedEvents ??= []).push(board.lastEvent);+ board.db.exec('SAVEPOINT proof_event_append');+ try {+ ensureProofCounters(board);+ const model = agentModel(board, by);+ const isAgent = Boolean(board.db.prepare('SELECT 1 FROM agent WHERE agent_id = ?').get(by));+ const recorded = { ...detail, ...((board.executionEngineVersion ?? ENGINE_VERSION) >= 8 && isAgent ? { model: model ?? 'unknown' } : {}),+ ...(board.movePerson ? { person: board.movePerson } : {}) }; // The person behind a relayed move, from engine 73 (engine.js) [E3].+ const inserted = board.db+ .prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)')+ .run(at ? at.toISOString() : now(board), by, kind, itemId, JSON.stringify(recorded));+ const event = board.db.prepare('SELECT * FROM event WHERE event_id = ?').get(inserted.lastInsertRowid);+ appendProofCounter(board, event);+ board.db.exec('RELEASE proof_event_append');+ board.lastEvent = event;+ (board.emittedEvents ??= []).push(event);+ } catch (error) {+ board.db.exec('ROLLBACK TO proof_event_append; RELEASE proof_event_append');+ throw error;+ }}/** Log an authenticated relay refusal without making an item, shout or verdict move [H2,H16]. */diff --git a/src/caught.js b/src/caught.jsindex 24ad7f34..a938f493 100644--- a/src/caught.js+++ b/src/caught.js@@ -1,3 +1,4 @@+import { proofEventDetail } from './proof-event-detail.js';/*** What the board caught, read from events it already records [N26,D1]: a quiet list for* `pullboard stats` and `pullboard digest`, shown only when someone asks.@@ -24,7 +25,7 @@ export const CAUGHT_KINDS = [* @returns {any}*/function detailOf(event) {- try { return JSON.parse(event.event_detail) ?? {}; } catch { return {}; }+ try { return proofEventDetail(event) ?? {}; } catch { return {}; }}/**diff --git a/src/digest.js b/src/digest.jsindex 22ff2afb..365748cc 100644--- a/src/digest.js+++ b/src/digest.js@@ -1,3 +1,4 @@+import { counterCaught } from './proof-counter-read.js';/*** `pullboard digest`: a short Markdown briefing of one board, for a person or a chat assistant* that can read the repo but never the board [A2,N26].@@ -217,7 +218,7 @@ function render(db, { name, now, root, config }) {const stuck = health.stuck.map((entry) => `- ${entry.item ? label(entry.item) : text(entry.subject, 60)}: ${text(entry.title, 240)}, since ${text(entry.since, 40)}: ${text(entry.why, 400)}\n Next, ${owner(entry.owner)}: ${text(entry.next, 300)}`);// What the board caught in the last month, from moves it already recorded; shown here and never pushed.const windowStart = new Date(now.getTime() - CAUGHT_DAYS * 86_400_000).toISOString();- const caught = caughtFrom(db.prepare('SELECT * FROM event ORDER BY event_id').all(), db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all(), windowStart);+ const caught = counterCaught({ db }, windowStart) ?? caughtFrom(db.prepare('SELECT * FROM event ORDER BY event_id').all(), db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all(), windowStart);const caughtLabels = new Map(CAUGHT_KINDS.map(({ kind, label }) => [kind, label]));const caughtEntries = caught.entries.slice().reverse().map((entry) =>`- ${caughtLabels.get(entry.kind)}: ${entry.item === null ? 'no item' : label(entry.item)}, ${text(entry.at, 40)}: ${text(entry.text, 400)}`);diff --git a/src/exchange.js b/src/exchange.jsindex d767a96f..b65a7c0c 100644--- a/src/exchange.js+++ b/src/exchange.js@@ -1,3 +1,5 @@+import { PROOF_COUNTER_PREFIX } from './proof-counters.js';+import { rebuildProofCounters } from './proof-counters.js';/*** Export and import whole board files (A7), including their AUTOINCREMENT counters, so a copy can* continue producing the same ids after its rows are restored.@@ -43,6 +45,13 @@ function columnsOf(db, table) {return db.prepare(`PRAGMA table_info(${identifier(table)})`).all().map(({ name }) => name);}+/** Read native rows without fetching large local proof projections into an export or digest. */+function nativeRows(db, table) {+ if (table === 'board_meta') return db.prepare('SELECT * FROM board_meta WHERE meta_key < ? OR meta_key >= ? ORDER BY rowid')+ .all(PROOF_COUNTER_PREFIX, 'local:proof-stats;');+ return db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all();+}+/*** Capture every board table and row in the stable v1 document format.* @param {{ db: any }} board@@ -54,7 +63,7 @@ export function exportBoard(board) {try {const tables = Object.fromEntries(tableNames(db).map((table) => [table,- db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all(),+ nativeRows(db, table),]));db.exec('COMMIT');return { version: VERSION, tables };@@ -72,6 +81,7 @@ export function semanticBoardDigest(document) {...document,tables: {...tables,+ ...(Array.isArray(tables.board_meta) ? { board_meta: tables.board_meta.filter(row => !row.meta_key.startsWith(PROOF_COUNTER_PREFIX)) } : {}),agent: tables.agent.map(({ agent_last_shout_id, ...row }) => row),},};@@ -123,7 +133,7 @@ function validateDocument(db, document, names) {/** Only the generated identity is disposable when restoring a fresh board (A2, A7). */function hasOnlyIdentity(db, { baseline = false } = {}) {- const rows = db.prepare('SELECT * FROM board_meta').all();+ const rows = nativeRows(db, 'board_meta');const identity = rows.find((row) => row.meta_key === 'board_id');const eventLog = rows.find((row) => row.meta_key === 'event_log_version');return /^[0-9a-f]{32}$/.test(identity?.meta_value ?? '')@@ -216,7 +226,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigestif (expectedNativeDigest !== null) {const current = { version: VERSION, tables: Object.fromEntries(names.map((table) => [table,- db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all(),+ nativeRows(db, table),])) };const actual = semanticBoardDigest(current);if (actual !== expectedNativeDigest) throw new Refused('RELAY_LOCAL_CHANGED', 'the local board changed before checkpoint restore; its changes were preserved, export them and retry recovery');@@ -241,6 +251,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigestconst sql = `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;const insert = db.prepare(sql);for (const row of document.tables[table]) {+ if (table === 'board_meta' && row.meta_key.startsWith(PROOF_COUNTER_PREFIX)) continue;let restored = row;if (replace && expectedNativeDigest !== null && table === 'agent' && localAgentCursors.has(row.agent_id)) {const localCursor = localAgentCursors.get(row.agent_id);@@ -256,6 +267,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigestfor (const row of document.tables.sqlite_sequence ?? []) {if (!setSequence.run(row.seq, row.name).changes) db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)').run(row.name, row.seq);}+ rebuildProofCounters(board);for (const { name, sql } of storeTriggers()) db.exec(sql);db.exec('COMMIT');return { tables: names };diff --git a/src/proof-counter-read.js b/src/proof-counter-read.jsnew file mode 100644index 00000000..23b16a23--- /dev/null+++ b/src/proof-counter-read.js@@ -0,0 +1,68 @@+/** Read small proof aggregates and projected facts without replaying the native event log [R1,R2]. */+import { barStats } from './bar-corrections.js';+import { caughtFrom } from './caught.js';+import { decodedProofEvent } from './proof-event-detail.js';+import { currentProofCounters } from './proof-counters.js';+import { proofCounterRows } from './proof-counters.js';+import { projectFlowStats } from './stats-flow.js';++/** Assemble selected-window counters from timestamped contributions, not decoded native events. */+function windowCounts(facts, boundary) {+ const start = Date.parse(boundary);+ const selected = facts.filter(row => row.at >= start);+ const merged = new Set(selected.filter(row => row.merged).map(row => row.item));+ const anomalies = new Set(selected.filter(row => row.merged && row.anomaly).map(row => row.item));+ const dates = selected.map(row => row.date).sort((a, b) => Date.parse(a) - Date.parse(b));+ return { since: boundary, submissions: selected.filter(row => row.submitted).length,+ rejections: selected.filter(row => row.rejected).length, merged: merged.size, mergedWithoutAccept: anomalies.size,+ firstEventAt: dates[0] ?? null, lastEventAt: dates.at(-1) ?? null };+}++/** Attribute a date window using the family recorded at each move, including older declarations. */+function windowActors(facts, boundary) {+ const actors = new Map();+ const families = new Map();+ for (const row of facts) {+ if (row.at < Date.parse(boundary) || ['board', 'person'].includes(row.by)) continue;+ if (!actors.has(row.by)) actors.set(row.by, { id: row.by, moves: 0, families: new Set() });+ const actor = actors.get(row.by); actor.moves += 1; actor.families.add(row.family);+ if (!families.has(row.family)) families.set(row.family, { name: row.family, moves: 0, agents: new Set() });+ const family = families.get(row.family); family.moves += 1; family.agents.add(row.by);+ }+ return { agents: [...actors.values()].map(actor => ({ ...actor, families: [...actor.families].sort() })).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),+ families: [...families.values()].map(family => ({ ...family, agents: family.agents.size })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) };+}++/** Retain the independently specified ordinal reject/verdict pairing while decoding only catch shards. */+export function counterCaught(board, boundary) {+ if (!currentProofCounters(board)) return null;+ const history = proofCounterRows(board, 'catch').map(row => decodedProofEvent(row, row.detail));+ const verdicts = board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all();+ return caughtFrom(history, verdicts, boundary);+}++/** Project observation-time queues from append-time item/actor facts, keeping clock expiry dynamic. */+export function counterProofStats(board, boundary, now) {+ const summary = currentProofCounters(board);+ if (!summary) return null;+ const items = proofCounterRows(board, 'item');+ const actors = proofCounterRows(board, 'actor');+ const facts = boundary ? proofCounterRows(board, 'event') : null;+ const counts = boundary ? windowCounts(facts, boundary) : {+ since: null, submissions: summary.submissions, rejections: summary.rejections, merged: summary.merged,+ mergedWithoutAccept: summary.mergedWithoutAccept, firstEventAt: summary.firstEventAt, lastEventAt: summary.lastEventAt,+ };+ counts.rejectionShare = counts.submissions ? counts.rejections / counts.submissions : 0;+ const attributed = boundary ? windowActors(facts, boundary) : {+ agents: actors.map(actor => ({ id: actor.id, moves: actor.moves, families: [...actor.families].sort() })).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),+ families: proofCounterRows(board, 'family').sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),+ };+ const creators = items.filter(item => item.creator !== undefined).map(item => ({ event_kind: 'add', item_id: item.id, event_by: item.creator }));+ const corrections = proofCounterRows(board, 'bar').map(row => decodedProofEvent({ ...row, event_kind: 'edit' }, row.detail));+ const verdicts = board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all();+ const flow = { items: items.filter(item => item.id !== null && item.id !== undefined).map(item => item.flow),+ actors: actors.filter(actor => actor.id !== 'clock').map(actor => actor.flow), dailyEvents: proofCounterRows(board, 'daily') };+ return { ...counts, agentCount: attributed.agents.length, familyCount: attributed.families.length, ...attributed,+ bars: barStats([...creators, ...corrections], verdicts, boundary), caught: counterCaught(board, boundary),+ flow: projectFlowStats(flow, boundary, now, counts) };+}diff --git a/src/proof-counters.js b/src/proof-counters.jsnew file mode 100644index 00000000..064d6c37--- /dev/null+++ b/src/proof-counters.js@@ -0,0 +1,163 @@+/** Rebuildable, local proof projections maintained with the event that produced them [R1,R2]. */+import { moveFlowItem } from './stats-flow.js';+import { roleOf } from './stats-flow.js';++export const PROOF_COUNTER_PREFIX = 'local:proof-stats:';+const PREFIX = `${PROOF_COUNTER_PREFIX}v1:`;++/** Encode non-finite timestamps with external paths, so user detail objects cannot collide with markers. */+function encode(value) {+ const numbers = [];+ /** Copy a small shard while recording only non-JSON numeric values. */+ const visit = (field, path) => {+ if (typeof field === 'number' && !Number.isFinite(field)) { numbers.push([path, String(field)]); return null; }+ if (Array.isArray(field)) return field.map((child, index) => visit(child, [...path, index]));+ if (field && typeof field === 'object') return Object.fromEntries(Object.entries(field).map(([key, child]) => [key, visit(child, [...path, key])]));+ return field;+ };+ return JSON.stringify({ data: visit(value, []), numbers });+}++/** Restore exactly the projection-owned numeric paths, leaving arbitrary user detail shapes intact. */+function decode(text) {+ const { data, numbers } = JSON.parse(text);+ for (const [path, number] of numbers) {+ let parent = data;+ for (const key of path.slice(0, -1)) parent = parent[key];+ parent[path.at(-1)] = Number(number);+ }+ return data;+}++/** Read a single small derived record; none of these keys is exported native state. */+export function proofCounter(board, key) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(PREFIX + key);+ return row ? decode(row.meta_value) : null;+}++/** Replace one affected shard without rewriting the board's accumulated history. */+function put(board, key, value) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')+ .run(PREFIX + key, encode(value));+}++/** Read one kind of projection in event insertion order, preserving historical tie ordering. */+export function proofCounterRows(board, kind) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key GLOB ? ORDER BY rowid').all(`${PREFIX}${kind}:*`)+ .map(row => decode(row.meta_value));+}++/** Remove local projections without modifying any native event or verdict. */+export function clearProofCounters(board) {+ board.db.prepare('DELETE FROM board_meta WHERE meta_key GLOB ?').run(`${PROOF_COUNTER_PREFIX}*`);+}++/** Start a bounded all-time aggregate; window-specific contributions live in separate event shards. */+function emptySummary() {+ return { last: 0, submissions: 0, rejections: 0, merged: 0, mergedWithoutAccept: 0,+ firstEventAt: null, lastEventAt: null, invalid: false };+}++/** Advance an item's acceptance audit separately from its flow lifecycle, whose rules differ. */+function countItem(summary, item, event, detail) {+ const selected = { submitted: false, rejected: false, merged: false, anomaly: false };+ if (event.event_kind === 'submit') {+ item.submitted = detail.commit; delete item.accepted; summary.submissions += 1; selected.submitted = true;+ } else if (event.event_kind === 'accept') {+ if (detail.commit && detail.commit === item.submitted) item.accepted = detail.commit;+ } else if (event.event_kind === 'reject') {+ delete item.accepted; summary.rejections += 1; selected.rejected = true;+ } else if (event.event_kind === 'merged') {+ selected.merged = true;+ selected.anomaly = !item.accepted;+ if (!item.merged) { item.merged = true; summary.merged += 1; }+ if (selected.anomaly && !item.anomaly) { item.anomaly = true; summary.mergedWithoutAccept += 1; }+ }+ return selected;+}++/** Update recorded family totals and latest flow role with only the acting seat's records. */+function countActor(board, event, detail, at) {+ const id = event.event_by;+ if (['board', 'person'].includes(id)) return null;+ const key = `actor:${encodeURIComponent(id)}`;+ const actor = proofCounter(board, key) ?? { id, moves: 0, families: [], declared: 'unknown', flow: { id, lane: 'unknown', role: 'unknown' } };+ if (Object.hasOwn(detail, 'family')) actor.declared = typeof detail.family === 'string' && detail.family.trim() ? detail.family : 'unknown';+ const familyName = actor.declared;+ const familyKey = `family:${encodeURIComponent(familyName)}`;+ const family = proofCounter(board, familyKey) ?? { name: familyName, agents: 0, moves: 0 };+ if (!actor.families.includes(familyName)) { actor.families.push(familyName); family.agents += 1; }+ actor.moves += 1; family.moves += 1;+ if (event.event_kind === 'join' && detail.lane) actor.flow.lane = detail.lane;+ actor.flow.role = id === 'coordinator' ? 'coordinator' : roleOf(event.event_kind, detail) ?? actor.flow.role;+ actor.flow.lastAt = at;+ put(board, key, actor); put(board, familyKey, family);+ return familyName;+}++/** Retain only catch-bearing events, with decoded details rather than another full raw-event replay. */+function keepCatch(event, detail) {+ return event.event_kind === 'reject' || event.event_kind === 'test-quarantine' ||+ event.event_kind === 'reopen' && (detail.conflict || detail.landingFailure) ||+ event.event_kind === 'flake-observation' || event.event_kind === 'health-failure' && event.event_by === 'sentinel';+}++/** Fold exactly this event into affected item/actor shards and the small aggregate. */+export function appendProofCounter(board, event) {+ const summary = proofCounter(board, 'summary') ?? emptySummary();+ board.onProofStatsEvent?.(event);+ let detail;+ try { detail = JSON.parse(event.event_detail); }+ catch (error) { if (!(error instanceof SyntaxError)) throw error; summary.invalid = true; }+ if (detail === null || detail === undefined) summary.invalid = true;+ const at = Date.parse(event.event_at);+ if (!Number.isFinite(at)) summary.invalid = true;+ summary.last = event.event_id;+ if (summary.invalid) { put(board, 'summary', summary); return; }+ if (summary.firstEventAt === null || at < Date.parse(summary.firstEventAt)) summary.firstEventAt = event.event_at;+ if (summary.lastEventAt === null || at >= Date.parse(summary.lastEventAt)) summary.lastEventAt = event.event_at;+ const key = `item:${event.item_id}`;+ const item = proofCounter(board, key) ?? { id: event.item_id, flow: { id: event.item_id, lane: 'unknown' } };+ const contribution = countItem(summary, item, event, detail);+ const family = countActor(board, event, detail, at);+ if (event.item_id !== null && event.item_id !== undefined) {+ if (event.event_kind === 'add') item.creator = event.event_by;+ if (event.event_kind === 'add' || event.event_kind === 'merged' && item.flow.mergeAt === undefined) {+ put(board, `daily:${event.event_id}`, { at, kind: event.event_kind === 'add' ? 'added' : 'merged' });+ }+ moveFlowItem(item.flow, event, detail, at);+ put(board, key, item);+ } else if (['submit', 'accept', 'reject', 'merged'].includes(event.event_kind)) {+ // Legacy counts also audit a null item id, while flow deliberately excludes it.+ put(board, key, item);+ }+ put(board, `event:${event.event_id}`, { at, date: event.event_at, by: event.event_by, family, item: event.item_id, ...contribution });+ if (event.event_kind === 'edit' && detail.barCorrection) {+ put(board, `bar:${event.event_id}`, { event_id: event.event_id, event_at: event.event_at, event_by: event.event_by, item_id: event.item_id, detail: { barCorrection: detail.barCorrection } });+ }+ if (keepCatch(event, detail)) {+ put(board, `catch:${event.event_id}`, { event_id: event.event_id, event_at: event.event_at, event_by: event.event_by, event_kind: event.event_kind, item_id: event.item_id, detail });+ }+ put(board, 'summary', summary);+}++/** Rebuild from authoritative history inside the caller's existing write transaction. */+export function rebuildProofCounters(board) {+ clearProofCounters(board);+ put(board, 'summary', emptySummary());+ for (const event of board.db.prepare('SELECT * FROM event ORDER BY event_id').iterate()) appendProofCounter(board, event);+}++/** Catch up an older writer once; ordinary current-writer appends then decode only their new event. */+export function ensureProofCounters(board) {+ const summary = proofCounter(board, 'summary');+ if (!summary) { rebuildProofCounters(board); return; }+ for (const event of board.db.prepare('SELECT * FROM event WHERE event_id>? ORDER BY event_id').iterate(summary.last)) appendProofCounter(board, event);+}++/** Readers never take a write lock to warm or repair a derived cache. */+export function currentProofCounters(board) {+ const summary = proofCounter(board, 'summary');+ const last = board.db.prepare('SELECT coalesce(max(event_id),0) AS id FROM event').get().id;+ return summary && !summary.invalid && summary.last === last ? summary : null;+}diff --git a/src/proof-event-detail.js b/src/proof-event-detail.jsnew file mode 100644index 00000000..cefb96f1--- /dev/null+++ b/src/proof-event-detail.js@@ -0,0 +1,12 @@+/** Share an already-decoded event only inside the proof projection, never in native history. */+const decoded = Symbol('proof event detail');++/** Attach an internal decoded value without adding anything to serialized event records. */+export function decodedProofEvent(event, detail) {+ return { ...event, [decoded]: detail };+}++/** Read an internal projection or decode the original immutable event for legacy readers. */+export function proofEventDetail(event) {+ return Object.hasOwn(event, decoded) ? event[decoded] : JSON.parse(event.event_detail);+}diff --git a/src/stats-flow.js b/src/stats-flow.jsindex db498f1f..8bde4bbe 100644--- a/src/stats-flow.js+++ b/src/stats-flow.js@@ -1,3 +1,4 @@+import { proofEventDetail } from './proof-event-detail.js';/** Flow times, queues and recommendations from recorded lifecycle evidence [R1,R2]. */const MINUTE = 60_000;const STAGES = ['build', 'reviewWait', 'review', 'mergeWait'];@@ -19,7 +20,7 @@ function interval(start, end) {}/** Identify role-bearing moves without guessing a role from an agent's lane. */-function roleOf(kind, detail) {+export function roleOf(kind, detail) {if (['reserve', 'accept', 'reject', 'verify'].includes(kind) || kind === 'release' && detail.review) return 'verifier';if (['claim', 'submit'].includes(kind) || kind === 'release' && !detail.review) return 'builder';return null;@@ -34,7 +35,7 @@ function expireClaim(item, at) {}/** Replay one lifecycle move; its first claim and first merge survive rework and repeated receipts. */-function move(item, event, detail, at) {+export function moveFlowItem(item, event, detail, at) {expireClaim(item, at);switch (event.event_kind) {case 'add':@@ -150,7 +151,7 @@ export function prepareFlowHistory(history) {const actors = new Map();const dailyEvents = [];for (const event of history) {- const detail = JSON.parse(event.event_detail);+ const detail = proofEventDetail(event);const at = Date.parse(event.event_at);const id = event.event_by;if (!['board', 'person', 'clock'].includes(id)) {@@ -165,7 +166,7 @@ export function prepareFlowHistory(history) {const item = items.get(event.item_id);if (event.event_kind === 'add') dailyEvents.push({ at, kind: 'added' });if (event.event_kind === 'merged' && item.mergeAt === undefined) dailyEvents.push({ at, kind: 'merged' });- move(item, event, detail, at);+ moveFlowItem(item, event, detail, at);}const frozenItems = [...items.values()].map((item) => Object.freeze({...item,diff --git a/src/stats.js b/src/stats.jsindex e0679f64..d6360ace 100644--- a/src/stats.js+++ b/src/stats.js@@ -1,3 +1,5 @@+import { counterProofStats } from './proof-counter-read.js';+import { proofEventDetail } from './proof-event-detail.js';/** Public proof numbers derived from the append-only event log [R1,R2]. */import { events } from './board.js';import { Refused } from './refused.js';@@ -28,7 +30,7 @@ function countsFrom(history, boundary) {const submitted = new Map();const accepted = new Map();for (const event of history) {- const detail = JSON.parse(event.event_detail);+ const detail = proofEventDetail(event);if (event.event_kind === 'submit') {submitted.set(event.item_id, detail.commit);accepted.delete(event.item_id);@@ -69,7 +71,7 @@ function actorsFrom(history, boundary) {for (const event of history) {const id = event.event_by;if (id === 'board' || id === 'person') continue;- const detail = JSON.parse(event.event_detail);+ const detail = proofEventDetail(event);if (Object.hasOwn(detail, 'family')) {declared.set(id, typeof detail.family === 'string' && detail.family.trim() ? detail.family : 'unknown');}@@ -98,6 +100,8 @@ function actorsFrom(history, boundary) {/** Assemble the public statistics shared by the CLI and local board state from one event snapshot. */export function proofStats(board, { since, now = Date.now() } = {}) {const boundary = sinceDate(since);+ const counted = counterProofStats(board, boundary, now);+ if (counted) return counted;const history = events(board);const counts = countsFrom(history, boundary);const verdicts = board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all();