Skip to content

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.

perf(rigor): project repeat state for resume [D1,N19,C7]

Corey Olson486ac1d7c200
diff --git a/src/board.js b/src/board.js
index f96ed3be..539c88a1 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1,3 +1,4 @@
+import { ensureRigorCounters } from './rigor-counters.js';
import { LAND_COLLISION_ENGINE } from './landing-collision-engine.js';
import {
lineOrderEnabled,
@@ -7,10 +8,8 @@ import {
} from './line-order.js';
export { lineSettings, setLineSetting } from './line-settings.js';
-import {
- applyOutsideIntake,
- approveOutside as applyOutsideApproval,
-} from './outside-store.js';
+import { applyOutsideIntake } from './outside-store.js';
+import { approveOutside as applyOutsideApproval } from './outside-store.js';
import {
outsideSandboxProblem,
outsideBuildProblem,
@@ -19,16 +18,12 @@ import {
saveOutsideSource,
} from './outside-source.js';
import { FILE_GROWTH_NOTICE_ENGINE } from './file-growth-notice-engine.js';
-import {
- recordBarRevision,
- barReadyProblem,
-} from './bar-readiness.js';
+import { recordBarRevision } from './bar-readiness.js';
+import { barReadyProblem } from './bar-readiness.js';
export { setBarReady, signBar } from './bar-readiness.js';
-import {
- coordinatorCheck,
- normalizeCheckBaseline,
- saveCheckBaseline,
-} from './item-check-baseline.js';
+import { coordinatorCheck } from './item-check-baseline.js';
+import { normalizeCheckBaseline } from './item-check-baseline.js';
+import { saveCheckBaseline } from './item-check-baseline.js';
export { coordinatorCheck, completeCheckBaseline, itemCheckAuthor } from './item-check-baseline.js';
import {
closeBoard,
@@ -319,6 +314,7 @@ export function openBoard(file, clock = systemClock, { isMain, onDiagnostic } =
db.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);
if (file !== ':memory:' && isMain !== false) db.exec('PRAGMA journal_mode = WAL');
const board = { db, clock };
+ let warmProjection = true;
if (isMain !== false || file === ':memory:') {
// Migrate and audit only a board whose version is behind; a drifted shape is reported and left alone (#1047).
const standing = boardStanding(db, SCHEMA_DIGEST, SCHEMA_VERSION, readEventLogVersion(db) < EVENT_LOG_VERSION);
@@ -330,13 +326,14 @@ export function openBoard(file, clock = systemClock, { isMain, onDiagnostic } =
guardStore(board);
}
if (standing === 'behind' || standing === 'unstamped') recordSchemaStamp(db, SCHEMA_DIGEST);
- if (standing === 'drifted') reportDrift(file, onDiagnostic);
+ if (standing === 'drifted') { warmProjection = false; reportDrift(file, onDiagnostic); }
} else {
// Read compatibility before any local effect; persistent schema belongs to trunk alone.
readEventLogVersion(db);
reportSharedSchema(file, sharedSchemaDiagnostic(db, expectedBoardSchema(SCHEMA, migrate, storeTriggers)), onDiagnostic);
}
guardMoves(board);
+ if (warmProjection) atomic(board, () => ensureRigorCounters(board));
return board;
} catch (error) {
try { db?.close(); } catch {}
diff --git a/src/commands/resume.js b/src/commands/resume.js
index 0888bd6a..cfabe803 100644
--- a/src/commands/resume.js
+++ b/src/commands/resume.js
@@ -180,7 +180,7 @@ export async function resumeHere(io, view, diagnostics = false, { json = false }
health: recordedHealthFindings(board),
all,
needsYou: personNeeds(needsState),
- ...(me.id === COORDINATOR ? { rigor: { undrafted: needsState.rigorUndrafted } } : {}),
+ ...(me.id === COORDINATOR ? { rigor: { undrafted: needsState.rigorUndrafted, ...(needsState.rigorNotice ? { notice: needsState.rigorNotice } : {}) } } : {}),
...(decisionSections ? { ...decisions, ...(diagnostics ? verifiedMergeGroups(root, pendingMerges, shouts, ctx.clock.now().getTime()) : {}),
flow: proofStats(board, { now: ctx.clock.now().getTime() }).flow } : {}),
requests: me.id === COORDINATOR ? store.openRequests(board) : [],
@@ -307,6 +307,7 @@ export async function resumeHere(io, view, diagnostics = false, { json = false }
section(card.needsYou, (need) => need.kind === 'decision'
? `waiting on the person: #${need.id} from ${need.ref} (${span(ctx, need.at)}): ${firstLine(need.text)}`
: `needs the person: ${need.ref}: ${firstLine(need.text)} (${need.what})`);
+ if (card.rigor?.notice) say(card.rigor.notice);
section(card.rigor?.undrafted ?? [], (cause) => `Rigor needs a proved draft: ${cause.key}, items ${cause.items.map(item => `#${item.id}`).join(', ')}; pullboard rigor draft "${cause.key.replaceAll('"', '\\"')}" "<rule>" --check "<command>" --red <commit> --green <commit>`);
if (card.toVerify.length) say('review queue:');
section(card.toVerify, (item) => ` to verify: #${item.item_id} ${item.item_lane} (${span(ctx, item.item_updated_at)})`);
diff --git a/src/needs-state.js b/src/needs-state.js
index 34d76906..a5c1868a 100644
--- a/src/needs-state.js
+++ b/src/needs-state.js
@@ -1,3 +1,4 @@
+import { resumeRigorCounters } from './rigor-counters.js';
/** Read the existing shared board projection with current unapplied person decisions [N26,A9]. */
import { join } from 'node:path';
import * as store from './board.js';
@@ -11,10 +12,7 @@ import { projectState } from './serve.js';
import { loadConfig } from './config.js';
import { loadSpec } from './spec.js';
import { loadDoctrine } from './doctrine.js';
-import {
- rigorDraftNeeds,
- undraftedRigor,
-} from './rigor-notices.js';
+import { rigorDraftNeeds } from './rigor-notices.js';
import { personNeeds } from './needs.js';
import { recentBlocks } from './needs-summary.js';
export { personNeedsSummary, recentBlocks } from './needs-summary.js';
@@ -39,8 +37,9 @@ export function personNeedsState(root, { board: providedBoard = null, includeRig
const rows = projectRowDecisions(decisions, { root, spec: loadSpec(root, config).rows, practice: loadDoctrine(root, config).rows });
const drafts = store.rowDrafts(board);
const rigorDrafts = rigorDraftNeeds(rows, drafts, decisions);
+ const rigor = includeRigorUndrafted ? resumeRigorCounters(board, rows, { person: store.PERSON, drafts, decisions }) : null;
const projected = { ...state, rigorDrafts, sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(info.commonDir, board), ...(includeRigorUndrafted
- ? { rigorUndrafted: undraftedRigor(store.events(board), rows, { person: store.PERSON, drafts, decisions }) } : {}) };
+ ? { rigorUndrafted: rigor.causes, rigorNotice: rigor.notice } : {}) };
return { ...projected, needs: personNeeds(projected) };
} finally {
if (!providedBoard) store.closeBoard(board);
diff --git a/src/proof-counters.js b/src/proof-counters.js
index b065db9f..f501441b 100644
--- a/src/proof-counters.js
+++ b/src/proof-counters.js
@@ -1,3 +1,5 @@
+import { appendRigorCounter } from './rigor-counters.js';
+import { ensureRigorCounters } from './rigor-counters.js';
import { NATIVE_FLAKE_ENGINE } from './flake-engine.js';
/** Rebuildable, local proof projections maintained with the event that produced them [R1,R2]. */
import { moveFlowItem } from './stats-flow.js';
@@ -106,6 +108,7 @@ function keepCatch(event, detail) {
/** Fold exactly this event into affected item/actor shards and the small aggregate. */
export function appendProofCounter(board, event) {
+ appendRigorCounter(board, event);
const summary = proofCounter(board, 'summary') ?? emptySummary();
board.onProofStatsEvent?.(event);
let detail;
@@ -157,12 +160,14 @@ function replayProofTail(board, cursor) {
/** Rebuild from authoritative history inside the caller's existing write transaction. */
export function rebuildProofCounters(board) {
clearProofCounters(board);
+ ensureRigorCounters(board);
put(board, 'summary', emptySummary());
replayProofTail(board, 0);
}
/** Catch up an older writer once; ordinary current-writer appends then decode only their new event. */
export function ensureProofCounters(board) {
+ ensureRigorCounters(board);
const summary = proofCounter(board, 'summary');
if (!summary) { rebuildProofCounters(board); return; }
replayProofTail(board, summary.last);
diff --git a/src/resume-needs.js b/src/resume-needs.js
index 79c099eb..6148110e 100644
--- a/src/resume-needs.js
+++ b/src/resume-needs.js
@@ -5,13 +5,15 @@ import { projectFit } from './blueprint-fit.js';
import { repoInfo } from './git.js';
import { personNeedsSummary } from './needs-summary.js';
import { personNeeds } from './needs.js';
-import { undraftedRigor } from './rigor-notices.js';
+import { resumeRigorCounters } from './rigor-counters.js';
/** Extend the indexed summary only for resume; retain exact row decisions, fit and coordinator Rigor. */
export function resumeNeeds(root, { board, config, includeRigorUndrafted = false }) {
const summary = personNeedsSummary(root, { board, config });
// Resume consumes obligations, not dashboard items. Fit still decorates every current spec row.
const fitted = projectFit(pendingFit(repoInfo(root).commonDir), { ...summary, items: [] });
+ const rigor = includeRigorUndrafted ? resumeRigorCounters(board, summary, { person: store.PERSON,
+ drafts: store.rowDrafts(board), decisions: store.rowDecisions(board) }) : null;
return { ...fitted, needs: personNeeds(fitted), ...(includeRigorUndrafted
- ? { rigorUndrafted: undraftedRigor(store.events(board), summary, { person: store.PERSON }) } : {}) };
+ ? { rigorUndrafted: rigor.causes, rigorNotice: rigor.notice } : {}) };
}
diff --git a/src/rigor-counter-state.js b/src/rigor-counter-state.js
new file mode 100644
index 00000000..24686be8
--- /dev/null
+++ b/src/rigor-counter-state.js
@@ -0,0 +1,85 @@
+/** Sufficient per-cause state for resume, without retaining or replaying raw history [D1,N19]. */
+import { causeProblem } from './rigor.js';
+import { causeReading } from './rigor.js';
+import { eventCauses } from './rigor.js';
+import { isMergeConflict } from './rigor.js';
+import { parseSpec } from './spec.js';
+import { readRigorSource } from './rigor-source.js';
+import { automaticSourceFromText } from './rigor-auto-source.js';
+import { readAutomaticRigorSource } from './rigor-auto-source.js';
+
+/** Match the legacy notice reader's typed person decline, including old row-shaped metadata. */
+function declineKey(event, detail, person) {
+ if (event.event_kind !== 'row_decision' || event.event_by !== person || detail.record?.decision !== 'decline'
+ || typeof detail.record.source !== 'string') return null;
+ let rows;
+ try { rows = parseSpec(`## Source\n${detail.record.source}\n`).rows; }
+ catch { return null; } // Optional historical metadata cannot refuse an otherwise valid move.
+ return rows.length === 1 ? (readRigorSource(rows[0].source)
+ ?? readAutomaticRigorSource(automaticSourceFromText(rows[0].text)))?.key ?? null : null;
+}
+
+/** Only the person's typed never-again fact immediately qualifies a cause. */
+function neverKey(event, detail, person) {
+ return event.event_kind === 'fact' && event.event_by === person && detail.neverAgain === true
+ && typeof detail.cause === 'string' && !causeProblem(detail.cause) ? detail.cause : null;
+}
+
+/** Return only the small set of cause shards that this event can change. */
+export function rigorCounterKeys(event, person) {
+ const detail = JSON.parse(event.event_detail);
+ return [...new Set([...eventCauses(event), neverKey(event, detail, person), declineKey(event, detail, person)]
+ .filter(key => key && !isMergeConflict(key)))];
+}
+
+/** Describe one cause's event contribution for the persistent writer and bounded in-memory fold. */
+export function rigorCounterChange(key, event, person) {
+ const detail = JSON.parse(event.event_detail);
+ return { never: neverKey(event, detail, person) === key, caused: eventCauses(event).includes(key),
+ declined: declineKey(event, detail, person) === key, commit: detail.commit };
+}
+
+/** Initialize a cause independently of its event's age or its current repeat eligibility. */
+function emptyCause(key) {
+ return { key, reads: causeReading(key), items: [], seen: [], occurrences: 0,
+ healthOccurrences: 0, flakeOccurrences: 0, neverAgain: false, declined: null };
+}
+
+/** Fold one relevant event; item and commit insertion order matches the independent legacy oracle. */
+export function advanceRigorCounter(previous, key, event, person) {
+ const next = previous ? structuredClone(previous) : emptyCause(key);
+ const { never, caused, declined, commit } = rigorCounterChange(key, event, person);
+ if ((never || caused) && event.item_id !== null && !next.seen.includes(event.item_id)) next.seen.push(event.item_id);
+ if (never || caused) {
+ let item = next.items.find(row => row.id === event.item_id);
+ if (event.item_id !== null && !item) { item = { id: event.item_id, commits: [] }; next.items.push(item); }
+ if (never) next.neverAgain = true;
+ else {
+ next.occurrences += 1;
+ if (event.event_kind === 'flake-observation') next.flakeOccurrences += 1;
+ if (['health-failure', 'sentinel-failure'].includes(event.event_kind)) next.healthOccurrences += 1;
+ if (item && commit && !item.commits.includes(commit)) item.commits.push(commit);
+ }
+ }
+ if (declined) next.declined = [...next.seen];
+ return next;
+}
+
+/** A decline stays quiet for old items even when they fail again at a new commit. */
+export function rigorCounterEligible(cause) {
+ const repeated = cause.neverAgain || cause.healthOccurrences >= 2 || cause.flakeOccurrences >= 2
+ || cause.items.length >= 2 || cause.items.some(item => item.commits.length >= 2);
+ return Boolean(repeated && (!cause.declined || cause.items.some(item => !cause.declined.includes(item.id))));
+}
+
+/** Expose the exact legacy report shape, without internal counters or person-decline snapshots. */
+export function rigorCounterResult(cause) {
+ return { key: cause.key, reads: cause.reads, occurrences: cause.occurrences, neverAgain: cause.neverAgain,
+ items: cause.items.map(item => ({ id: item.id, commits: [...item.commits] })).sort((a, b) => a.id - b.id) };
+}
+
+/** Preserve the legacy report's deterministic presentation order across independently stored shards. */
+export function sortRigorCounters(causes) {
+ return causes.sort((a, b) => Number(b.neverAgain) - Number(a.neverAgain) || b.items.length - a.items.length
+ || b.occurrences - a.occurrences || a.key.localeCompare(b.key));
+}
diff --git a/src/rigor-counters.js b/src/rigor-counters.js
new file mode 100644
index 00000000..ba3f38e8
--- /dev/null
+++ b/src/rigor-counters.js
@@ -0,0 +1,261 @@
+/** Local, rebuildable per-cause Rigor projection with a bounded read-only compatibility tail [D1,N19]. */
+import { advanceRigorCounter } from './rigor-counter-state.js';
+import { rigorCounterChange } from './rigor-counter-state.js';
+import { rigorCounterEligible } from './rigor-counter-state.js';
+import { rigorCounterKeys } from './rigor-counter-state.js';
+import { rigorCounterResult } from './rigor-counter-state.js';
+import { sortRigorCounters } from './rigor-counter-state.js';
+import { undraftedRigor } from './rigor-notices.js';
+import { readRigorSource } from './rigor-source.js';
+import { automaticRigorNeeds } from './rigor-auto-source.js';
+import { causeReading } from './rigor.js';
+import { createHash } from 'node:crypto';
+
+const PREFIX = 'local:proof-stats:rigor:v1:';
+export const RIGOR_TAIL_LIMIT = 256;
+export const RIGOR_COLD_NOTICE = 'The repeats are computed from the full history because this board has no current summary yet.';
+
+/** Preserve legacy decoded numeric values; JSON-valid historical exponents can become non-finite in JavaScript. */
+function encode(value) {
+ const numbers = [];
+ /** Keep non-finite markers outside user values, so no historical detail shape can collide with them. */
+ 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 only the projection-owned marker paths, following the existing proof-counter codec convention. */
+function decode(text) {
+ const { data, numbers } = JSON.parse(text);
+ for (const [path, value] of numbers) {
+ let parent = data;
+ for (const key of path.slice(0, -1)) parent = parent[key];
+ parent[path.at(-1)] = Number(value);
+ }
+ return data;
+}
+
+/** Read one projection-owned JSON record, separately from authoritative board metadata. */
+function get(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 only the cause affected by a new event, not the accumulated event log. */
+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));
+}
+
+/** Version and cursor belong together: an old writer cannot make a stale summary current. */
+function emptySummary(person) { return { version: 1, person, last: 0, active: [], invalid: false }; }
+
+/** Writer and reader agree on the projection version and its structurally valid recorded cursor. */
+function validSummary(summary, person) {
+ return summary?.version === 1 && summary.person === person && Number.isSafeInteger(summary.last) && summary.last >= 0
+ && Array.isArray(summary.active) && summary.active.every(key => typeof key === 'string');
+}
+
+/** Separate scalar qualification from per-item and per-commit history, which grows independently. */
+function emptyHeader(key) {
+ return { key, reads: causeReading(key), occurrences: 0, healthOccurrences: 0, flakeOccurrences: 0,
+ neverAgain: false, itemCount: 0, multiCommit: false, latestItemAt: 0, declinedAt: null };
+}
+
+/** JSON preserves every accepted JavaScript cause string, including a historical lone surrogate. */
+function shardKey(key) { return `cause:${encodeURIComponent(JSON.stringify(key))}`; }
+
+/** Decode only our own derived metadata key, never infer cause identity from surrounding prose. */
+function causeFromShard(key) { return JSON.parse(decodeURIComponent(key.slice('cause:'.length))); }
+
+/** A cursor makes the person's decline exact without rewriting a growing set of old item ids. */
+function headerEligible(header) {
+ return Boolean((header.neverAgain || header.healthOccurrences >= 2 || header.flakeOccurrences >= 2
+ || header.itemCount >= 2 || header.multiCommit) && (header.declinedAt === null || header.latestItemAt > header.declinedAt));
+}
+
+/** Primitive commit identity matches Set; distinct decoded historical objects remain distinct occurrences. */
+function commitKey(value, eventId) {
+ return typeof value === 'object' ? `event:${eventId}`
+ : createHash('sha256').update(encode([typeof value, value])).digest('hex');
+}
+
+/** Fold one durable event with only scalar/header and affected item/commit writes. */
+function persist(board, summary, event, person) {
+ let keys = [];
+ if (!summary.invalid) {
+ try { keys = rigorCounterKeys(event, person); }
+ catch (error) {
+ // Only malformed historical JSON or an actual null detail can make this derived fold unusable.
+ // Database and programming failures remain visible; the legacy reader retains its original failure.
+ if (!(error instanceof SyntaxError) && !(error instanceof TypeError && JSON.parse(event.event_detail) === null)) throw error;
+ summary.invalid = true;
+ }
+ }
+ for (const key of keys) {
+ const base = shardKey(key) + ':';
+ const header = get(board, base + 'header') ?? emptyHeader(key);
+ const change = rigorCounterChange(key, event, person);
+ if ((change.never || change.caused) && event.item_id !== null) {
+ const itemKey = base + `item:${event.item_id}`;
+ let item = get(board, itemKey);
+ if (!item) {
+ item = { id: event.item_id, firstSeenAt: event.event_id, commits: 0 };
+ header.itemCount += 1;
+ header.latestItemAt = event.event_id;
+ }
+ if (change.caused && !change.never && change.commit) {
+ const identity = base + `commit:${event.item_id}:` + commitKey(change.commit, event.event_id);
+ if (!get(board, identity)) {
+ put(board, identity, { id: event.item_id, value: change.commit });
+ item.commits += 1;
+ if (item.commits >= 2) header.multiCommit = true;
+ }
+ }
+ put(board, itemKey, item);
+ }
+ if (change.never) header.neverAgain = true;
+ else if (change.caused) {
+ header.occurrences += 1;
+ if (event.event_kind === 'flake-observation') header.flakeOccurrences += 1;
+ if (['health-failure', 'sentinel-failure'].includes(event.event_kind)) header.healthOccurrences += 1;
+ }
+ if (change.declined) header.declinedAt = event.event_id;
+ put(board, base + 'header', header);
+ const index = summary.active.indexOf(key);
+ if (headerEligible(header)) { if (index < 0) summary.active.push(key); }
+ else if (index >= 0) summary.active.splice(index, 1);
+ }
+ summary.last = event.event_id;
+ put(board, 'summary', summary);
+}
+
+/** Keep only currently actionable cause keys on the hot path; single failures remain separate shards. */
+function fold(summary, event, read, write, person, drafted = new Set()) {
+ for (const key of rigorCounterKeys(event, person)) {
+ if (drafted.has(key)) continue;
+ const shard = shardKey(key);
+ const cause = advanceRigorCounter(read(shard), key, event, person);
+ write(shard, cause);
+ const index = summary.active.indexOf(key);
+ if (rigorCounterEligible(cause)) { if (index < 0) summary.active.push(key); }
+ else if (index >= 0) summary.active.splice(index, 1);
+ }
+ summary.last = event.event_id;
+}
+
+/** Append alongside the native event; replayed proof-counter history cannot double-count a cause. */
+export function appendRigorCounter(board, event, person = 'person') {
+ let summary = get(board, 'summary');
+ // A first current-writer append on an old board must include all earlier events, not skip them.
+ if (!validSummary(summary, person)) { ensureRigorCounters(board, person); summary = get(board, 'summary'); }
+ if (event.event_id <= summary.last) return;
+ const first = board.db.prepare('SELECT event_id FROM event WHERE event_id>? ORDER BY event_id LIMIT 1').get(summary.last);
+ if (first?.event_id !== event.event_id) {
+ // A present older-writer summary also needs its entire gap before this new append can be current.
+ ensureRigorCounters(board, person);
+ return;
+ }
+ persist(board, summary, event, person);
+}
+
+/** Rebuild batches on an existing writable initialization/import path, never a steady resume read. */
+export function ensureRigorCounters(board, person = 'person') {
+ board.db.exec('SAVEPOINT rigor_projection');
+ try {
+ let summary = get(board, 'summary');
+ const last = board.db.prepare('SELECT coalesce(max(event_id),0) AS id FROM event').get().id;
+ if (!validSummary(summary, person) || summary.last > last) {
+ board.db.prepare('DELETE FROM board_meta WHERE meta_key GLOB ?').run(PREFIX + '*');
+ summary = emptySummary(person);
+ put(board, 'summary', summary);
+ }
+ const query = board.db.prepare('SELECT * FROM event WHERE event_id>? ORDER BY event_id LIMIT 256');
+ while (true) {
+ const batch = query.all(summary.last);
+ if (!batch.length) break;
+ for (const event of batch) persist(board, summary, event, person);
+ }
+ board.db.exec('RELEASE rigor_projection');
+ } catch (error) {
+ board.db.exec('ROLLBACK TO rigor_projection; RELEASE rigor_projection');
+ throw error;
+ }
+}
+
+/** Read one indexed metadata prefix; arbitrary cause text is never interpreted as a glob pattern. */
+function records(board, prefix) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key>=? AND meta_key<? ORDER BY rowid')
+ .all(PREFIX + prefix, PREFIX + prefix + '\uffff').map(row => decode(row.meta_value));
+}
+
+/** Materialize item/commit history only for an actionable output cause or a cause touched by the bounded tail. */
+function readCause(board, key) {
+ const base = shardKey(key) + ':';
+ const header = get(board, base + 'header');
+ if (!header) return null;
+ const rows = records(board, base + 'item:');
+ const items = rows.map(row => ({ id: row.id, commits: [] }));
+ const byId = new Map(items.map(item => [item.id, item]));
+ for (const commit of records(board, base + 'commit:')) byId.get(commit.id)?.commits.push(commit.value);
+ return { ...header, items, seen: rows.map(row => row.id),
+ declined: header.declinedAt === null ? null : rows.filter(row => row.firstSeenAt <= header.declinedAt).map(row => row.id) };
+}
+
+/** Live or approved typed rows suppress the exact cause; standard doctrine is not a local draft. */
+function draftedCauses(state, drafts, decisions) {
+ const rows = [...(state.spec ?? []), ...(state.practice ?? []).filter(row => row.origin !== 'standard')];
+ const keys = new Set(rows.filter(row => row.decision?.decision === 'approve'
+ || (!row.decision && ['draft', 'pending', 'approved'].includes(row.status)))
+ .map(row => readRigorSource(row.source)?.key).filter(Boolean));
+ for (const need of automaticRigorNeeds(state, drafts, decisions)) keys.add(need.cause);
+ return keys;
+}
+
+/** A cold or beyond-bound older-writer board remains complete and visibly outside the steady bound. */
+function coldRigor(board, state, options) {
+ const history = board.db.prepare('SELECT event_id,event_at,event_by,event_kind,item_id,event_detail FROM event ORDER BY event_id').all();
+ return { causes: undraftedRigor(history, state, options), notice: RIGOR_COLD_NOTICE };
+}
+
+/** Read eligible compact shards plus at most 256 indexed events; never silently extend an unbounded tail. */
+function readResumeRigorCounters(board, state, { person = 'person', drafts = [], decisions = [] } = {}) {
+ const options = { person, drafts, decisions };
+ const stored = get(board, 'summary');
+ if (!validSummary(stored, person) || stored.invalid) return coldRigor(board, state, options);
+ const summary = structuredClone(stored);
+ const last = board.db.prepare('SELECT coalesce(max(event_id),0) AS id FROM event').get().id;
+ if (summary.last > last) return coldRigor(board, state, options);
+ const tail = board.db.prepare('SELECT * FROM event WHERE event_id>? ORDER BY event_id LIMIT 257').all(summary.last);
+ if (tail.length > RIGOR_TAIL_LIMIT) return coldRigor(board, state, options);
+ const changed = new Map();
+ const drafted = draftedCauses(state, drafts, decisions);
+ /** Read a cause once from the database and thereafter from this bounded in-memory tail. */
+ const read = key => changed.has(key) ? changed.get(key) : readCause(board, causeFromShard(key));
+ for (const event of tail) fold(summary, event, read, (key, value) => changed.set(key, value), person, drafted);
+ const causes = [];
+ for (const key of summary.active) {
+ if (drafted.has(key)) continue;
+ const cause = read(shardKey(key));
+ if (!cause) return coldRigor(board, state, options);
+ if (rigorCounterEligible(cause)) causes.push(rigorCounterResult(cause));
+ }
+ return { causes: sortRigorCounters(causes), notice: null };
+}
+
+/** Cursor, cause shards and bounded tail must belong to one read snapshot even during another writer's append. */
+export function resumeRigorCounters(board, state, options) {
+ board.db.exec('SAVEPOINT rigor_read');
+ try {
+ const result = readResumeRigorCounters(board, state, options);
+ board.db.exec('RELEASE rigor_read');
+ return result;
+ } catch (error) {
+ board.db.exec('ROLLBACK TO rigor_read; RELEASE rigor_read');
+ throw error;
+ }
+}
diff --git a/test/query-plans.test.js b/test/query-plans.test.js
index e5c79c30..fe2d3364 100644
--- a/test/query-plans.test.js
+++ b/test/query-plans.test.js
@@ -28,10 +28,9 @@ const SHOUTS = 23_000;
const SEATS = 800;
const sandboxes = [];
// Reads that fold the whole history by design, so no index can serve them, each with the item that
-// rewrites it: coordinator resume's undrafted Rigor in personNeedsState (#1052) and resume's
-// proofStats (#1051). The test fails if one stops scanning while still listed, so the list can only
+// rewrites it: resume's proofStats (#1051). The test fails if one stops scanning while still listed, so the list can only
// shrink.
-const WHOLE_HISTORY = ['personNeedsState', 'proofStats'];
+const WHOLE_HISTORY = ['proofStats'];
after(() => {
for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });
@@ -48,15 +47,19 @@ function fixture() {
import { appendFileSync } from 'node:fs';
import childProcess from 'node:child_process';
import { syncBuiltinESMExports } from 'node:module';
+let gitDepth = 0;
for (const name of ['spawnSync', 'execFileSync']) {
const original = childProcess[name];
/** Measure actual synchronous Git calls without substituting their results or environment. */
childProcess[name] = function (command, ...args) {
const started = performance.now();
+ const git = command === 'git';
+ if (git) gitDepth += 1;
try { return original.call(this, command, ...args); }
finally {
- if (command === 'git' && process.env.PULLBOARD_GIT_TIMING_LOG) {
- appendFileSync(process.env.PULLBOARD_GIT_TIMING_LOG, JSON.stringify({ milliseconds: performance.now() - started }) + '\\n');
+ if (git) gitDepth -= 1;
+ if (git && gitDepth === 0 && process.env.PULLBOARD_GIT_TIMING_LOG) {
+ appendFileSync(process.env.PULLBOARD_GIT_TIMING_LOG, JSON.stringify({ pid: process.pid, milliseconds: performance.now() - started }) + '\\n');
}
}
};
@@ -93,7 +96,7 @@ DatabaseSync.prototype.prepare = function (sql, ...rest) {
const argv = [...(record ? ['--import', pathToFileURL(preload).href] : []), ...(node ? [] : [BIN]), ...args];
const result = runFixtureChild(process.execPath, argv, { cwd, env: { ...env, PULLBOARD_QUERY_LOG: log,
...(timing ? { PULLBOARD_GIT_TIMING_LOG: join(dir, 'git-timing.log') } : {}) }, encoding: 'utf8' });
- return { code: result.status, out: result.stdout ?? '', err: result.failure ?? result.stderr ?? '' };
+ return { code: result.status, pid: result.pid, out: result.stdout ?? '', err: result.failure ?? result.stderr ?? '' };
};
git('init', '-q', '-b', 'main');
assert.equal(run(repo, ['init']).code, 0);
@@ -171,13 +174,15 @@ test('coordinator resume never reads the whole event history for rigor [C7,D1,N1
for (const line of readFileSync(box.log, 'utf8').split('\n').filter(Boolean)) {
const row = JSON.parse(line);
if (!/resume-needs\.js|rigor-counters\.js/u.test(row.stack) || !/\bFROM event\b/iu.test(row.sql)) continue;
- const plan = board.db.prepare(`EXPLAIN QUERY PLAN ${row.sql}`).all().map(entry => entry.detail);
+ const bindings = row.sql.includes('?') ? [0] : []; // The only hot event parameter is the recorded integer cursor.
+ const plan = board.db.prepare(`EXPLAIN QUERY PLAN ${row.sql}`).all(...bindings).map(entry => entry.detail);
plans.push({ sql: row.sql, plan });
assert.ok(!plan.some(detail => /^SCAN event\b/u.test(detail)), `Rigor must use indexed state/tail, never whole-history: ${row.sql}\n${plan.join('\n')}`);
}
assert.ok(plans.length > 0, 'the real coordinator resume executed an observed Rigor event-cursor/tail query');
const gitMs = readFileSync(join(box.dir, 'git-timing.log'), 'utf8').split('\n').filter(Boolean)
- .reduce((total, line) => total + JSON.parse(line).milliseconds, 0);
+ .map(line => JSON.parse(line)).filter(row => row.pid === result.pid)
+ .reduce((total, row) => total + row.milliseconds, 0);
assert.ok(gitMs <= wallMs, 'only actual nonoverlapping synchronous Git durations are excluded');
const excludingGit = wallMs - gitMs;
console.log(`# coordinator resume wall ${wallMs.toFixed(2)} ms; actual Git ${gitMs.toFixed(2)} ms; excluding Git ${excludingGit.toFixed(2)} ms`);
diff --git a/test/rigor-auto.test.js b/test/rigor-auto.test.js
index 79660a51..a1e42b56 100644
--- a/test/rigor-auto.test.js
+++ b/test/rigor-auto.test.js
@@ -7,6 +7,10 @@ import { join } from 'node:path';
import { after, test } from 'node:test';
import * as store from '../src/board.js';
import { personNeedsState } from '../src/needs-state.js';
+import { resumeNeeds } from '../src/resume-needs.js';
+import { resumeRigorCounters } from '../src/rigor-counters.js';
+import { RIGOR_COLD_NOTICE } from '../src/rigor-counters.js';
+import { clearProofCounters } from '../src/proof-counters.js';
import { readDigest } from '../src/digest.js';
import { submitFixture } from './board-submit-fixture.js';
import { runFixtureChild, runFixtureGit } from './fixture-child.js';
@@ -77,7 +81,7 @@ function fixture() {
advance: ms => { now = new Date(now.getTime() + ms); }, close: () => store.closeBoard(board) };
}
-test('a repeated cause becomes a draft row in Needs you with no command run [D1,D3,S1]', () => {
+test('a repeated cause becomes a draft row in Needs you with no command run [D1,D3,S1,N19]', () => {
const box = fixture();
try {
const before = ['SPEC.md', 'DOCTRINE.md', 'pullboard.json'].map(file => readFileSync(join(box.root, file), 'utf8'));
@@ -94,6 +98,20 @@ test('a repeated cause becomes a draft row in Needs you with no command run [D1,
assert.ok(needs.every(need => need.unproved === true && need.proof == null));
assert.ok(needs.some(need => need.evidence.items.map(item => item.id).join(',') === `${one},${two}`));
+ const coordinator = resumeNeeds(box.root, { board: box.board, config: loadConfig(box.root), includeRigorUndrafted: true });
+ assert.ok(coordinator.rigorUndrafted.every(cause => !needs.some(need => need.cause === cause.key)),
+ 'an automatically drafted repeat is not also listed as undrafted advice [N19]');
+ const options = { person: store.PERSON, drafts: store.rowDrafts(box.board), decisions: store.rowDecisions(box.board) };
+ const hot = resumeRigorCounters(box.board, coordinator, options);
+ assert.deepEqual(hot.causes, coordinator.rigorUndrafted);
+ assert.equal(hot.notice, null);
+ const nativeEvents = store.events(box.board).length;
+ clearProofCounters(box.board);
+ const cold = resumeRigorCounters(box.board, coordinator, options);
+ assert.deepEqual(cold.causes, hot.causes, 'cold compatibility applies the same automatic-draft suppression');
+ assert.equal(cold.notice, RIGOR_COLD_NOTICE);
+ assert.equal(store.events(box.board).length, nativeEvents, 'cold compatibility never writes a native move');
+
for (const title of ['First merge collision', 'Second merge collision']) {
const id = box.submit(title);
store.reopen(box.board, id, { agentId: 'coordinator', conflict: { files: ['src/shared.js'], trunk: 'd'.repeat(40) } });
diff --git a/test/rigor-counter-state.test.js b/test/rigor-counter-state.test.js
new file mode 100644
index 00000000..49dfbbdf
--- /dev/null
+++ b/test/rigor-counter-state.test.js
@@ -0,0 +1,90 @@
+/** Every history prefix retains the legacy repeat and exact person-decline semantics [D1,N19,H16]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { advanceRigorCounter } from '../src/rigor-counter-state.js';
+import { rigorCounterEligible } from '../src/rigor-counter-state.js';
+import { rigorCounterKeys } from '../src/rigor-counter-state.js';
+import { rigorCounterResult } from '../src/rigor-counter-state.js';
+import { sortRigorCounters } from '../src/rigor-counter-state.js';
+import { undraftedRigor } from '../src/rigor-notices.js';
+import { rigorSource } from '../src/rigor-source.js';
+import { automaticRigorSource } from '../src/rigor-auto-source.js';
+import { HEALTH_SENTINEL_ENGINE } from '../src/health-receipts.js';
+import { BOARD_SENTINEL_ENGINE } from '../src/sentinel-engine.js';
+import { NATIVE_FLAKE_ENGINE } from '../src/flake-engine.js';
+
+/** Produce a real typed row source; an ordinary prose note must never suppress a repeat. */
+function source(key) {
+ const cause = { key, items: [], occurrences: 0, neverAgain: false };
+ const proof = { check: 'test -f fixed', red: { commit: 'a'.repeat(40), exit: 1 }, green: { commit: 'b'.repeat(40), exit: 0 } };
+ return `- G9 [draft, must] A proved rule | source: ${rigorSource(cause, proof)}`;
+}
+
+/** A board-generated unproved proposal is also a typed person-decline source after #1138. */
+function automaticSource(key) {
+ const cause = { key, items: [{ id: 6, commits: ['a'.repeat(40)] }, { id: 7, commits: ['b'.repeat(40)] }],
+ occurrences: 2, neverAgain: false };
+ return `- G10 [draft, must] A proposal Source: ${automaticRigorSource(cause, [1, 2])}`;
+}
+
+/** Build events in their durable append order, with deliberate old and null-item cases. */
+function history() {
+ const rows = [];
+ /** Preserve exact native event fields used by both the independent oracle and new fold. */
+ const add = (kind, item, detail, by = 'tests-1') => rows.push({ event_id: rows.length + 1,
+ event_at: new Date(Date.UTC(2026, 0, 1) + rows.length * 1000).toISOString(),
+ event_kind: kind, event_by: by, item_id: item, event_detail: JSON.stringify(detail) });
+ add('reject', 1, { cause: 'row:G1', commit: 'a'.repeat(40) });
+ add('reopen', 1, { cause: 'row:G1', commit: 'a'.repeat(40) });
+ add('reject', 1, { cause: 'row:G1', commit: 'b'.repeat(40) });
+ add('row_decision', null, { record: { decision: 'decline', source: source('row:G1') } }, 'person');
+ add('reject', 1, { cause: 'row:G1', commit: 'c'.repeat(40) });
+ add('reject', 2, { cause: 'row:G1', commit: 'c'.repeat(40) });
+ add('row_decision', null, { record: { decision: 'decline', source: source('row:G1') } }, 'person');
+ add('fact', 1, { cause: 'doctrine:C3', neverAgain: true }, 'person');
+ add('fact', 2, { cause: 'doctrine:C4', neverAgain: true }, 'tests-1');
+ add('reject', 3, { cause: 'refusal:MERGE_CONFLICT' });
+ add('reject', 4, { cause: 'refusal:MERGE_CONFLICT' });
+ add('reopen', 3, { landingFailure: { tests: [{ file: 'test/one.js', name: 'fails' }, { file: 'test/one.js', name: 'fails' }] } });
+ add('reject', 4, { cause: 'test:test/one.js::fails' });
+ add('row_decision', null, { record: { decision: 'decline', source: source('test:test/one.js::fails') } }, 'tests-1');
+ add('row_decision', null, { record: { decision: 'decline', source: 'ordinary prose' } }, 'person');
+ for (const engine of [HEALTH_SENTINEL_ENGINE - 1, HEALTH_SENTINEL_ENGINE, HEALTH_SENTINEL_ENGINE]) {
+ add('health-failure', null, { cause: 'sentinel:health', engine }, 'sentinel');
+ }
+ add('health-failure', null, { cause: 'sentinel:forged', engine: HEALTH_SENTINEL_ENGINE }, 'tests-1');
+ for (const engine of [BOARD_SENTINEL_ENGINE - 1, BOARD_SENTINEL_ENGINE, BOARD_SENTINEL_ENGINE]) {
+ add('sentinel-failure', null, { cause: 'sentinel:board', engine }, 'sentinel');
+ }
+ for (const engine of [NATIVE_FLAKE_ENGINE - 1, NATIVE_FLAKE_ENGINE, NATIVE_FLAKE_ENGINE]) {
+ add('flake-observation', null, { engine, observation: { classification: 'flake', file: 'test/flake.js', name: 'sometimes' } });
+ }
+ add('row_decision', null, { record: { decision: 'decline', source: source('sentinel:health') } }, 'person');
+ add('health-failure', null, { cause: 'sentinel:health', engine: HEALTH_SENTINEL_ENGINE }, 'sentinel');
+ add('health-failure', 5, { cause: 'sentinel:health', engine: HEALTH_SENTINEL_ENGINE }, 'sentinel');
+ add('reject', 6, { causes: ['row:G2', 'conflict:src/hot.js', 'row:G2'], commit: 'a'.repeat(40) });
+ add('reopen', 7, { causes: ['row:G2', 'conflict:src/hot.js'], commit: 'b'.repeat(40) });
+ add('row_decision', null, { record: { decision: 'decline', source: automaticSource('row:G2') } }, 'person');
+ add('reject', 7, { cause: 'row:G2', commit: 'c'.repeat(40) });
+ add('reject', 8, { cause: 'row:G2', commit: 'd'.repeat(40) });
+ return rows;
+}
+
+test('compact Rigor causes equal the unchanged legacy oracle after every prefix [D1,N19,H16]', () => {
+ const events = history(), shards = new Map();
+ for (let n = 0; n < events.length; n += 1) {
+ const event = events[n];
+ for (const key of rigorCounterKeys(event, 'person')) shards.set(key, advanceRigorCounter(shards.get(key), key, event, 'person'));
+ const actual = sortRigorCounters([...shards.values()].filter(rigorCounterEligible).map(rigorCounterResult));
+ const expected = undraftedRigor(events.slice(0, n + 1), { spec: [], practice: [] }, { person: 'person' });
+ assert.deepEqual(actual, expected, `history prefix ${n + 1}: ${event.event_kind}`);
+ if (n === 2) assert.deepEqual(actual.find(cause => cause.key === 'row:G1').items[0].commits, ['a'.repeat(40), 'b'.repeat(40)]);
+ if (n === 4) assert.ok(!actual.some(cause => cause.key === 'row:G1'), 'a new commit on an old item does not override the person');
+ if (n === 5) assert.ok(actual.some(cause => cause.key === 'row:G1'), 'a genuinely new item revives the declined cause');
+ }
+ const final = sortRigorCounters([...shards.values()].filter(rigorCounterEligible).map(rigorCounterResult));
+ assert.ok(final.some(cause => cause.key === 'doctrine:C3' && cause.neverAgain && cause.occurrences === 0));
+ assert.ok(!final.some(cause => ['doctrine:C4', 'refusal:MERGE_CONFLICT', 'sentinel:forged', 'conflict:src/hot.js'].includes(cause.key)));
+ assert.equal(final.find(cause => cause.key === 'sentinel:health').occurrences, 4);
+ assert.equal(final.find(cause => cause.key === 'test:test/flake.js::sometimes').occurrences, 2);
+});
diff --git a/test/rigor-counters.test.js b/test/rigor-counters.test.js
new file mode 100644
index 00000000..312ebf6d
--- /dev/null
+++ b/test/rigor-counters.test.js
@@ -0,0 +1,244 @@
+/** Rigor remains complete across cold boards, older writers and derived-state rebuilds [D1,N19,H16]. */
+import assert from 'node:assert/strict';
+import { mkdtempSync } from 'node:fs';
+import { rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { clearProofCounters } from '../src/proof-counters.js';
+import { rebuildProofCounters } from '../src/proof-counters.js';
+import { ensureRigorCounters } from '../src/rigor-counters.js';
+import { resumeRigorCounters } from '../src/rigor-counters.js';
+import { RIGOR_COLD_NOTICE } from '../src/rigor-counters.js';
+import { RIGOR_TAIL_LIMIT } from '../src/rigor-counters.js';
+import { undraftedRigor } from '../src/rigor-notices.js';
+import { rigorSource } from '../src/rigor-source.js';
+
+const PREFIX = 'local:proof-stats:rigor:v1:';
+
+/** Exercise the actual SQLite store, retaining a file that can also be opened strictly read-only. */
+function fixture(t) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-rigor-counter-'));
+ const file = join(dir, 'board.sqlite');
+ const board = store.openBoard(file);
+ const item = store.addItem(board, { lane: 'core', title: 'Old rigor cause', criterion: 'Works.', by: 'coordinator' });
+ t.after(() => { store.closeBoard(board); rmSync(dir, { recursive: true, force: true }); });
+ return { board, file, item };
+}
+
+/** Simulate an older native writer that appends valid event rows but knows no Rigor projection. */
+function oldAppend(board, kind, item, detail, by = 'tests-1') {
+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES(?,?,?,?,?)')
+ .run('2026-01-01T00:00:00.000Z', by, kind, item, JSON.stringify(detail));
+}
+
+/** Seed an old repeat at two real commits, not an empty-history performance shortcut. */
+function oldRepeat(board, item) {
+ oldAppend(board, 'reject', item, { cause: 'row:G1', commit: 'a'.repeat(40) });
+ oldAppend(board, 'reopen', item, { cause: 'row:G1', commit: 'b'.repeat(40) });
+}
+
+/** Compare complete output against the independent legacy implementation. */
+function expected(board, state = { spec: [], practice: [] }) {
+ return undraftedRigor(store.events(board), state, { person: store.PERSON });
+}
+
+/** Count connection mutations to prove a read-only compatibility fold never warms itself. */
+function changes(board) { return board.db.prepare('SELECT total_changes() AS n').get().n; }
+
+test('cold Rigor is complete and loud, and the next actual native write makes it hot [D1,N19,H16]', t => {
+ const { board, file, item } = fixture(t);
+ oldRepeat(board, item);
+ board.db.prepare('DELETE FROM board_meta WHERE meta_key GLOB ?').run(PREFIX + '*');
+ const readonly = { db: new DatabaseSync(file, { readOnly: true }) };
+ try {
+ const before = changes(readonly);
+ const cold = resumeRigorCounters(readonly, {});
+ assert.deepEqual(cold.causes, expected(board));
+ assert.equal(cold.notice, RIGOR_COLD_NOTICE);
+ assert.equal(changes(readonly), before);
+ } finally { readonly.db.close(); }
+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'A current native write.' });
+ const hot = resumeRigorCounters(board, {});
+ assert.deepEqual(hot.causes, expected(board), 'the first current append must not skip older history');
+ assert.equal(hot.notice, null);
+});
+
+test('a bounded older-writer tail folds read-only and an over-bound gap is loudly complete [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ oldRepeat(board, item);
+ ensureRigorCounters(board);
+ for (let n = 0; n < RIGOR_TAIL_LIMIT; n += 1) oldAppend(board, 'fact', item, { kind: 'note', text: `older ${n}` });
+ const before = changes(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+ assert.equal(changes(board), before);
+ oldAppend(board, 'fact', item, { cause: 'doctrine:C3', neverAgain: true }, store.PERSON);
+ const cold = resumeRigorCounters(board, {});
+ assert.deepEqual(cold.causes, expected(board));
+ assert.equal(cold.notice, RIGOR_COLD_NOTICE, 'a present summary cannot silently consume an unbounded tail');
+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'The current writer catches up.' });
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+});
+
+test('proof-counter clear and rebuild cannot leave Rigor falsely current or empty [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ oldRepeat(board, item);
+ ensureRigorCounters(board);
+ const oracle = expected(board);
+ rebuildProofCounters(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, oracle);
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+ clearProofCounters(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, oracle);
+ assert.equal(resumeRigorCounters(board, {}).notice, RIGOR_COLD_NOTICE);
+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'Rebuild after clear.' });
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+});
+
+test('a current append catches up a present older-writer gap and rebuilds an older projection version [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ ensureRigorCounters(board);
+ oldRepeat(board, item);
+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'Current write after an old writer.' });
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+ const key = PREFIX + 'summary';
+ const summary = JSON.parse(board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key).meta_value);
+ summary.data.version = 0;
+ board.db.prepare('UPDATE board_meta SET meta_value=? WHERE meta_key=?').run(JSON.stringify(summary), key);
+ assert.equal(resumeRigorCounters(board, {}).notice, RIGOR_COLD_NOTICE);
+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'Current write after a previous projection version.' });
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(resumeRigorCounters(board, {}).notice, null);
+});
+
+test('persistent decline cursors stay quiet for an old item and revive only for a new item [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ oldRepeat(board, item);
+ ensureRigorCounters(board);
+ const cause = expected(board)[0];
+ const proof = { check: 'test -f fixed', red: { commit: 'a'.repeat(40), exit: 1 }, green: { commit: 'b'.repeat(40), exit: 0 } };
+ const source = `- G9 [draft, must] A proved rule | source: ${rigorSource(cause, proof)}`;
+ oldAppend(board, 'row_decision', null, { record: { decision: 'decline', source } }, store.PERSON);
+ ensureRigorCounters(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, []);
+ oldAppend(board, 'reject', item, { cause: 'row:G1', commit: 'c'.repeat(40) });
+ ensureRigorCounters(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.deepEqual(expected(board), [], 'a new commit on the same item cannot override a decline');
+ const nextItem = store.addItem(board, { lane: 'core', title: 'A different item', criterion: 'Works.', by: 'coordinator' });
+ oldAppend(board, 'reject', nextItem, { cause: 'row:G1', commit: 'd'.repeat(40) });
+ ensureRigorCounters(board);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, expected(board));
+ assert.equal(expected(board).length, 1);
+});
+
+test('persistent cause keys preserve percent signs, glob characters and accepted historical Unicode [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ const keys = ['test:test/a*.js::a percent % and [brackets]', 'test:test/unicode.js::' + String.fromCharCode(0xd800)];
+ for (const cause of keys) {
+ oldAppend(board, 'reject', item, { cause, commit: 'a'.repeat(40) });
+ oldAppend(board, 'reject', item, { cause, commit: 'b'.repeat(40) });
+ }
+ ensureRigorCounters(board);
+ const oracle = expected(board);
+ assert.equal(oracle.length, 2, 'both keys are accepted by the unchanged legacy grammar');
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, oracle);
+});
+
+test('a derived JSON shard does not normalize historical decoded commits to null [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ for (const commit of ['1e400', '-1e400']) {
+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES(?,?,?,?,?)')
+ .run('2026-01-01T00:00:00.000Z', 'tests-1', 'reject', item, `{"cause":"row:G1","commit":${commit}}`);
+ }
+ ensureRigorCounters(board);
+ const oracle = expected(board);
+ assert.deepEqual(oracle[0].items[0].commits, [Infinity, -Infinity]);
+ assert.deepEqual(resumeRigorCounters(board, {}).causes, oracle);
+});
+
+test('typed draft decisions suppress only their cause and local doctrine, just like legacy [D1,N19,H16]', t => {
+ const { board, item } = fixture(t);
+ oldRepeat(board, item);
+ ensureRigorCounters(board);
+ const cause = expected(board)[0];
+ const proof = { check: 'test -f fixed', red: { commit: 'a'.repeat(40), exit: 1 }, green: { commit: 'b'.repeat(40), exit: 0 } };
+ const source = rigorSource(cause, proof);
+ for (const state of [
+ { spec: [{ source, status: 'draft' }] },
+ { spec: [{ source, status: 'declined', decision: { decision: 'approve' } }] },
+ { practice: [{ source, status: 'draft', origin: 'standard' }] },
+ { practice: [{ source, status: 'draft', origin: 'local' }] },
+ { spec: [{ source: 'ordinary prose', status: 'draft' }] },
+ ]) assert.deepEqual(resumeRigorCounters(board, state).causes, expected(board, state));
+});
+
+test('a read-only Rigor snapshot cannot mix an old cursor with a newly committed cause shard [D1,N19,H16]', t => {
+ const { board, file, item } = fixture(t);
+ oldRepeat(board, item);
+ ensureRigorCounters(board);
+ const oldResult = expected(board);
+ const readonly = { db: new DatabaseSync(file, { readOnly: true }) };
+ const original = DatabaseSync.prototype.prepare;
+ let interleaved = false;
+ /** Commit a real second-connection update immediately after the reader observes its old summary. */
+ DatabaseSync.prototype.prepare = function (sql, ...rest) {
+ const statement = original.call(this, sql, ...rest);
+ if (this !== readonly.db || sql !== 'SELECT meta_value FROM board_meta WHERE meta_key=?') return statement;
+ return new Proxy(statement, {
+ /** Keep native statement receivers intact while interleaving exactly one summary read. */
+ get(target, property) {
+ if (property === 'get') return (...args) => {
+ const result = target.get(...args);
+ if (args[0] === PREFIX + 'summary' && !interleaved) {
+ interleaved = true;
+ oldAppend(board, 'reject', item, { cause: 'row:G1', commit: 'c'.repeat(40) });
+ ensureRigorCounters(board);
+ }
+ return result;
+ };
+ const value = Reflect.get(target, property, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ };
+ try {
+ const before = changes(readonly);
+ const result = resumeRigorCounters(readonly, {});
+ assert.equal(interleaved, true);
+ const newResult = expected(board);
+ assert.ok(JSON.stringify(result.causes) === JSON.stringify(oldResult)
+ || JSON.stringify(result.causes) === JSON.stringify(newResult), 'one complete snapshot, never a double-folded new shard');
+ assert.equal(result.notice, null);
+ assert.equal(changes(readonly), before);
+ } finally {
+ DatabaseSync.prototype.prepare = original;
+ readonly.db.close();
+ }
+});
+
+
+test('malformed historical detail preserves native writes and the legacy read failure [D1,N19,H16]', t => {
+ const { board, file } = fixture(t);
+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES(?,?,?,?,?)')
+ .run('2026-01-01T00:00:00.000Z', 'tests-1', 'reject', null, '{broken');
+ let failure;
+ try { undraftedRigor(store.events(board), {}, { person: 'person' }); }
+ catch (error) { failure = error; }
+ assert.ok(failure instanceof SyntaxError, 'retain the independent legacy refusal');
+ store.closeBoard(store.openBoard(file));
+ const before = store.events(board).length;
+ store.logEvent(board, 'tests-1', 'shout', null, { text: 'a later valid native move' });
+ assert.equal(store.events(board).length, before + 1);
+ const summary = JSON.parse(board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(PREFIX + 'summary').meta_value).data;
+ assert.equal(summary.invalid, true);
+ assert.equal(summary.last, store.events(board).at(-1).event_id);
+ assert.throws(() => resumeRigorCounters(board, {}), error => error.constructor === failure.constructor && error.message === failure.message,
+ 'a caught-up invalid projection delegates to the exact legacy reader, never empty or falsely green');
+});