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
refactor(board): share canonical readers with CLI [C7,B3]
Corey Olsonfbba963010f8
diff --git a/src/bar-corrections.js b/src/bar-corrections.jsindex 0130fcb8..8cec07cc 100644--- a/src/bar-corrections.js+++ b/src/bar-corrections.js@@ -9,7 +9,7 @@ import { proofEventDetail } from './proof-event-detail.js';* stored, and nothing in the correction record is taken from the move beyond the reason text, so* a relay or API caller cannot mark a reject as the bar's.*/-import { ENGINE_VERSION } from './machine.js';+import { ENGINE_VERSION } from './engine-metadata.js';import { Refused } from './refused.js';/** The engine whose edits carry a reason and refuse an unexplained bar correction; older replays never did. */diff --git a/src/board-query.js b/src/board-query.jsnew file mode 100644index 00000000..5eca18f9--- /dev/null+++ b/src/board-query.js@@ -0,0 +1,392 @@+/** Canonical board queries shared by reads and the synchronous write store [C7]. */+import { COORDINATOR } from './config.js';+import { parseSpec } from './spec.js';+import { BOARD_SENTINEL_ENGINE } from './sentinel-engine.js';+import { Refused } from './refused.js';+export { closeBoard, openBoardForRead, openBoardReadOnly, readEventLogVersion, systemClock } from './board-read-open.js';+export { schemaMissing, writeRefused } from './board-migrate.js';+export { stats } from './board-stats.js';+export { submitInvariantEvents } from './board-hot.js';+export { acceptedVerdict, verdictReviewProblem, verdictsFor } from './verdict-reviews.js';++export const PERSON = 'person';++/**+ * The board's time as ISO text.+ *+ * @param {any} board+ * @returns {string}+ */+export const now = (board) => board.clock.now().toISOString();++/**+ * True while someone holds the item under a lease that has not lapsed.+ *+ * @param {any} board+ * @param {any} item+ * @returns {boolean}+ */+export function isHeld(board, item) {+ return item.item_status === 'claimed' && (item.item_lease_until ?? '') > now(board);+}++/**+ * The item as a reader should see it: a claim whose lease lapsed reads as open (B4).+ *+ * @param {any} board+ * @param {any} item+ * @returns {any}+ */+export function current(board, item) {+ if (item.item_status !== 'claimed' || isHeld(board, item)) return { ...item };+ return { ...item, item_status: 'open', item_owner: null, item_lease_until: null };+}++/** Read an observation only when it still describes the item's current check command. */+export function itemCheckBaseline(board, item) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_check_baseline_${item.item_id}`);+ if (!row) return null;+ const baseline = JSON.parse(row.meta_value);+ return baseline.command === item.item_check ? baseline : null;+}++/** Find review releases after the current submission, optionally for one reviewer [V1,R1].+ * Older releases are ignored because a new submission starts a fresh review.+ */+export function reviewReleasesSinceSubmit(board, itemId, agentId = null) {+ const events = board.db.prepare("SELECT event_id, event_at, event_by, event_kind, event_detail FROM event WHERE item_id=? AND event_kind IN ('submit','release') ORDER BY event_id DESC")+ .all(itemId);+ const releases = [];+ for (const event of events) {+ if (event.event_kind === 'submit') return releases;+ if (event.event_by !== agentId && agentId !== null) continue;+ try {+ const detail = JSON.parse(event.event_detail);+ if (detail.review === true || detail.review === undefined) releases.push({ ...event, legacy: detail.review === undefined,+ reason: detail.reason ?? 'reason not recorded' });+ } catch { /* Ignore malformed legacy details rather than treating them as review releases. */ }+ }+ return releases;+}++/** The persistent local and relay identity of this board (A2). */+export function boardId(board) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_id').meta_value;+}++/**+ * The item with this id, or a refusal naming the id.+ *+ * @param {any} board+ * @param {number} id+ * @returns {any}+ */+export function itemById(board, id) {+ const item = board.db.prepare('SELECT * FROM item WHERE item_id = ?').get(id);+ if (!item) throw new Refused('NO_ITEM', `no item #${id}; see: pullboard list`);+ return item;+}++/**+ * One item as a reader should see it.+ *+ * @param {any} board+ * @param {number} id+ * @returns {any}+ */+export function getItem(board, id) {+ const item = current(board, itemById(board, id));+ const baseline = itemCheckBaseline(board, item);+ return baseline ? { ...item, item_check_baseline: baseline } : item;+}++/**+ * Items, newest first, as a reader should see them. Closed items (verified, withdrawn) only when+ * asked.+ *+ * @param {any} board+ * @param {{ lane?: string, all?: boolean }} [filter]+ * @returns {any[]}+ */+export function listItems(board, { lane, all = false } = {}) {+ const hasLane = lane !== undefined && lane !== null;+ const rows = board.db+ .prepare(`SELECT * FROM item WHERE ${all ? '1' : "item_status NOT IN ('verified','withdrawn')"}${hasLane ? ' AND item_lane=?' : ''} ORDER BY item_id DESC`)+ .all(...(hasLane ? [lane] : []));+ const items = rows.map((item) => current(board, item));+ return items;+}++/** Read a stored status/owner slice, excluding claims whose leases have expired rather than caching items. */+export function itemsInStatus(board, status, owner = null) {+ return board.db.prepare(`SELECT * FROM item WHERE item_status=?${owner === null ? '' : ' AND item_owner=?'} ORDER BY item_id DESC`)+ .all(status, ...(owner === null ? [] : [owner])).map(item => current(board, item)).filter(item => item.item_status === status);+}++/**+ * Who holds an item's review under a live lease (V15), or null. A reservation counts only while the+ * item is submitted and its lease has not run out, and a new submission starts with none.+ *+ * @param {any} board+ * @param {any} item+ * @returns {string | null}+ */+export function reviewHolder(board, item) {+ return item.item_status === 'submitted' && item.item_review_by && (item.item_review_until ?? '') > now(board) ? item.item_review_by : null;+}++/** Count unreserved submissions by whether they are awaiting a first reviewer or were released [R1]. */+export function reviewQueueBreakdown(board) {+ let awaitingFirstReview = 0;+ let releasedWithoutVerdict = 0;+ const releasedItems = [];+ for (const item of itemsInStatus(board, 'submitted').filter((entry) => !reviewHolder(board, entry))) {+ const releases = reviewReleasesSinceSubmit(board, item.item_id);+ if (releases.length) {+ releasedWithoutVerdict += 1;+ releasedItems.push({ item: item.item_id, releases: releases.length, reason: releases[0].reason });+ } else awaitingFirstReview += 1;+ }+ return { awaitingFirstReview, releasedWithoutVerdict, releasedItems };+}++/** Summarize outstanding reviews using live leases and the latest submission's age [Q1,V15]. */+export function reviewQueue(board) {+ const pending = itemsInStatus(board, 'submitted');+ const holders = pending.map((item) => reviewHolder(board, item)).filter(Boolean);+ // Only the current queue needs an age. Seek each item's history, including legacy timestamps,+ // instead of grouping every submission ever made on the board.+ const submittedAt = board.db.prepare("SELECT MAX(event_at) AS at FROM event WHERE item_id=? AND event_kind='submit'");+ const oldestSubmittedAt = pending.map((item) => submittedAt.get(item.item_id).at).filter(Boolean).sort()[0] ?? null;+ return { pending: pending.length, reviewing: new Set(holders).size, reserved: holders.length, oldestSubmittedAt,+ ageMs: oldestSubmittedAt ? Math.max(0, board.clock.now().getTime() - Date.parse(oldestSubmittedAt)) : 0 };+}++/**+ * Shouts that asked for a decision nobody has answered yet, oldest first (B21). An optional+ * recipient limits the queue; an array matches any listed recipient. Without one this returns+ * every open decision for internal readers.+ *+ * @param {any} board+ * @param {string | string[]} [recipient]+ * @returns {any[]}+ */+export function openDecisions(board, recipient = null) {+ if (recipient === null) {+ return board.db+ .prepare('SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id')+ .all();+ }+ const recipients = [...new Set(Array.isArray(recipient) ? recipient : [recipient])];+ if (!recipients.length) return [];+ const marks = recipients.map(() => '?').join(', ');+ return board.db+ .prepare(`SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND ask.shout_to IN (${marks}) AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id`)+ .all(...recipients);+}++/**+ * How many shouts an agent has not read, without marking them.+ *+ * @param {any} board+ * @param {string} agentId+ * @returns {number}+ */+export function unreadCount(board, agentId) {+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(agentId);+ if (!agent) return 0;+ const { total } = board.db+ .prepare(`SELECT COUNT(*) AS total ${UNREAD_SQL}`)+ .get(agent.agent_last_shout_id, agentId, agent.agent_lane, agentId);+ return total;+}++/**+ * The event log, oldest first, for one item or the whole board.+ *+ * @param {any} board+ * @param {{ itemId?: number }} [filter]+ * @returns {any[]}+ */+export function events(board, { itemId } = {}) {+ if (itemId === undefined || itemId === null) {+ return board.db.prepare('SELECT * FROM event ORDER BY event_id').all();+ }+ return board.db.prepare('SELECT * FROM event WHERE item_id = ? ORDER BY event_id').all(itemId);+}++/** Read every move and fact in append order, including superseded facts and full original text [B31,B32]. */+export function itemThread(board, id) {+ itemById(board, id);+ return events(board, { itemId: id }).map((event) => event.event_kind === 'fact'+ ? { type: 'fact', ...factFromEvent(event) }+ : { type: 'move', eventId: event.event_id, kind: event.event_kind, by: event.event_by,+ at: event.event_at, detail: JSON.parse(event.event_detail) });+}++/**+ * Every held lane.+ *+ * @param {any} board+ * @returns {any[]}+ */+export function laneHolds(board) {+ return board.db.prepare('SELECT * FROM hold ORDER BY hold_lane').all();+}++/** Current person decisions, including applied receipts, stored without checkout-dependent state. */+export function rowDecisions(board) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('row_decisions');+ return row ? JSON.parse(row.meta_value) : [];+}++/**+ * The SQL that picks an agent's unread shouts: to it, to its lane, or to all, from anyone else.+ */+export const UNREAD_SQL = `FROM shout WHERE shout_id > ? AND shout_from != ? AND shout_to IN ('all', ?, ?)`;++/**+ * The agent registered for a worktree path, if any.+ *+ * @param {any} board+ * @param {string} path+ * @returns {any}+ */+export function agentAt(board, path) {+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);+ return withModel(board, agent);+}++/** Read one seat and its model without loading every registered seat and model on the board. */+export function agentById(board, id) {+ return withModel(board, board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(id));+}++/** Read the model label kept beside other board metadata, avoiding any board-schema migration. */+export function agentModel(board, id) {+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_model:${id}`)?.meta_value ?? null;+}++/** Attach an agent's model to a row from the legacy stable agent table. */+export function withModel(board, agent) {+ return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id) } : agent;+}++/**+ * Every registered agent, oldest first.+ *+ * @param {any} board+ * @returns {any[]}+ */+export function listAgents(board) {+ return board.db.prepare(`SELECT agent.*, board_meta.meta_value AS agent_model FROM agent+ LEFT JOIN board_meta ON board_meta.meta_key='agent_model:' || agent.agent_id ORDER BY agent.rowid`).all().map(agent => ({ ...agent }));+}++/** The optional engine-20 fields of a fact, present only when its event set them. */+export function decisionFields(detail) {+ return { ...(detail.implies ? { implies: detail.implies } : {}), ...(detail.decision ? { decision: detail.decision } : {}),+ ...(detail.supersededBy ? { supersededBy: detail.supersededBy } : {}) };+}++/** Give facts the same stamped identity on CLI, API, export and replica reads; a never-again keeps its cause [B29,B31,D1]. */+export function factFromEvent(event) {+ const detail = JSON.parse(event.event_detail);+ return { id: detail.id, eventId: event.event_id, kind: detail.kind, text: detail.text,+ by: event.event_by, at: event.event_at, ref: detail.ref ?? null, supersedes: detail.supersedes ?? null, ...decisionFields(detail),+ ...(detail.neverAgain ? { cause: detail.cause, neverAgain: true } : {}) };+}++export const KEY = 'spec_approval_baseline';++/** Validate the exact source carried by an ordered snapshot, including the empty initial set. */+export function validBaseline(value) {+ if (!value || value.version !== 1 || typeof value.file !== 'string' || !value.file+ || !(value.anchor === null || /^[a-f0-9]{40,64}$/u.test(value.anchor)) || !Array.isArray(value.rows)) return false;+ const seen = new Set();+ return value.rows.every(row => {+ if (!row || typeof row.id !== 'string' || typeof row.text !== 'string' || typeof row.source !== 'string'+ || /[\r\n]/u.test(row.source) || seen.has(row.id)) return false;+ const parsed = parseSpec(`## Baseline\n${row.source}\n`).rows;+ seen.add(row.id);+ return parsed.length === 1 && parsed[0].id === row.id && parsed[0].text === row.text && parsed[0].status === 'approved';+ });+}++/** Compare the snapshot payload without incidental event attribution or JSON property order. */+export function canonicalBaseline(baseline) {+ return { version: 1, file: baseline.file, anchor: baseline.anchor,+ rows: baseline.rows.map(({ id, text, source }) => ({ id, text, source })) };+}++/** Distinguish a missing migration marker from an unreadable one without replacing either. */+export function specApprovalBaselineExists(board) {+ return Boolean(board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key=?').get(KEY)+ || board.db.prepare('SELECT 1 FROM event WHERE event_kind=? LIMIT 1').get(KEY));+}++/** Read the original snapshot without interpreting it as authenticated approval or reseeding it. */+export function specApprovalBaseline(board) {+ const stored = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(KEY);+ const events = board.db.prepare('SELECT event_by,event_detail FROM event WHERE event_kind=?').all(KEY);+ if (!stored && !events.length) return null;+ let value;+ let recorded;+ try {+ value = stored && JSON.parse(stored.meta_value);+ recorded = events.length === 1 && events[0].event_by === COORDINATOR && JSON.parse(events[0].event_detail);+ } catch { /* The same typed recovery covers malformed and incompatible records. */ }+ if (!validBaseline(value) || !validBaseline(recorded)+ || JSON.stringify(canonicalBaseline(value)) !== JSON.stringify(canonicalBaseline(recorded))) {+ throw new Refused('SPEC_APPROVAL_BASELINE', 'the approval baseline is unreadable or disagrees with its original event; restore it from a known-good board export');+ }+ return value;+}++/** Pending watches are the person's calls: one Needs-you entry each, with the evidence that proposed it. */+export function sentinelDraftNeeds(rows) {+ return rows.filter(row => row.status === 'pending').map(row => ({+ kind: 'sentinel-draft', id: `sentinel:${row.name}`, ref: row.name,+ check: row.check, directory: row.directory, every: row.every, owner: row.owner, digest: row.digest,+ text: `Sentinel draft: ${row.name} runs ${row.check} ${row.every === 'daily' || row.every === 'hourly' ? row.every : 'every ' + row.every}, reporting to ${row.owner}`,+ what: `pullboard sentinel approve ${row.name}, or decline it with --reason`, target: `sentinel:${row.name}`,+ ...(row.evidence ? { cause: row.evidence.key, evidence: row.evidence } : {}),+ }));+}++/** Read only allocated receipts; legacy events with similar names never enable command execution. */+export function sentinels(board) {+ const rows = new Map();+ const events = board.db.prepare("SELECT * FROM event WHERE event_kind IN ('sentinel-proposal','sentinel-decision','sentinel-start','sentinel-run') ORDER BY event_id").all();+ for (const event of events) {+ const detail = JSON.parse(event.event_detail);+ if (detail.engine !== BOARD_SENTINEL_ENGINE) continue;+ if (event.event_kind === 'sentinel-proposal') {+ rows.set(detail.row.name, { ...detail.row, digest: detail.digest, status: 'pending', proposedBy: event.event_by,+ proposedAt: event.event_at, evidence: detail.evidence ?? null, lastRun: null, activeRun: null, history: [] });+ continue;+ }+ const row = rows.get(detail.name);+ if (!row || row.digest !== detail.digest) continue;+ if (event.event_kind === 'sentinel-decision' && event.event_by === PERSON) {+ row.status = detail.decision === 'approve' ? 'approved' : 'declined';+ row.reason = detail.reason; row.decidedAt = event.event_at; row.activeRun = null;+ } else if (event.event_kind === 'sentinel-start') {+ row.activeRun = { id: detail.run, by: event.event_by, startedAt: event.event_at, until: detail.until };+ } else if (event.event_kind === 'sentinel-run' && row.activeRun?.id === detail.run) {+ row.lastRun = { ...detail.result, id: detail.run, at: event.event_at };+ row.history.push(row.lastRun); row.activeRun = null;+ }+ }+ return [...rows.values()];+}++/** Ask the CLI adapter for the original coordinator-housekeeping write path. */+export class ReadNeedsWrite extends Error {}++/** A matching coordinator needs no write; registration or a path change uses the full store. */+export function ensureCoordinator(board, path) {+ const existing = agentById(board, COORDINATOR);+ if (!existing || existing.agent_path !== path) throw new ReadNeedsWrite('coordinator registration or path update requires the write store');+ return COORDINATOR;+}diff --git a/src/board-read-open.js b/src/board-read-open.jsnew file mode 100644index 00000000..2a84273a--- /dev/null+++ b/src/board-read-open.js@@ -0,0 +1,75 @@+/** Open existing board data without loading move execution [C7]. */+import { existsSync } from 'node:fs';+import { DatabaseSync } from 'node:sqlite';+import { boardBusyError } from './board-access.js';+import { boardIsCurrent } from './board-migrate.js';+import {+ BOARD_BUSY_TIMEOUT_MS,+ EVENT_LOG_VERSION,+ SCHEMA_DIGEST,+ SCHEMA_VERSION,+} from './board-schema-source.js';+import { Refused } from './refused.js';+// Preserve eager validation of feature declarations without loading lifecycle guards.+import './engine-metadata.js';++/**+ * The clock the board reads, real unless a test passes its own.+ */+export const systemClock = { now: () => new Date() };++/**+ * Open an existing board for a command that only reads: read-only, with no write lock and no+ * migration, so a writer holding the lock never stalls it (#1047). `current` says whether this+ * code's migration has run on it; only a write open migrates. Null when there is no board yet.+ */+export function openBoardForRead(file, clock = systemClock) {+ if (file === ':memory:' || !existsSync(file)) return null;+ const db = openBoardReadOnly(file);+ try { readEventLogVersion(db); return { db, clock, readOnly: true, current: boardIsCurrent(db, SCHEMA_DIGEST, SCHEMA_VERSION) }; }+ catch (error) { db.close(); throw error; }+}++/** Open an existing board without migrations, waiting for the same locks as openBoard. */+export function openBoardReadOnly(file) {+ const startedAt = Date.now();+ let db;+ try {+ db = new DatabaseSync(file, { readOnly: true });+ db.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);+ return db;+ } catch (error) {+ try { db?.close(); } catch {}+ throw boardBusyError(file, startedAt, error);+ }+}++/**+ * Read the persisted event format without migrating it, so integrity checks enforce the same+ * compatibility rule as the writable opener while leaving older or damaged evidence intact.+ *+ * @param {DatabaseSync} db+ * @returns {number}+ */+export function readEventLogVersion(db) {+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'board_meta'").get()) return 0;+ const stored = db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('event_log_version');+ const version = stored && /^(?:0|[1-9]\d*)$/u.test(stored.meta_value) ? Number(stored.meta_value) : stored ? NaN : 0;+ if (!Number.isSafeInteger(version) || version < 0) {+ throw new Refused('EVENT_LOG_VERSION', `event log version ${stored?.meta_value ?? 'missing'} is invalid; restore a valid board or upgrade pullboard`);+ }+ if (version > EVENT_LOG_VERSION) {+ throw new Refused('EVENT_LOG_VERSION', `event log version ${version} is newer than this pullboard version ${EVENT_LOG_VERSION}; upgrade pullboard to open this board`);+ }+ return version;+}++/**+ * Close the board's file.+ *+ * @param {{ db: DatabaseSync }} board+ */+export function closeBoard(board) {+ board.db.close();+}+diff --git a/src/board-schema-source.js b/src/board-schema-source.jsnew file mode 100644index 00000000..cdeade66--- /dev/null+++ b/src/board-schema-source.js@@ -0,0 +1,98 @@+/** Shared literal schema/version inputs; both openers validate the same declaration [C7]. */+import { schemaDigest } from './board-migrate.js';++/** Version of the persisted append-only event record format; bump for incompatible format changes. */+export const EVENT_LOG_VERSION = 1;++/** Maximum time a board connection waits for another process to release SQLite's lock. */+export const BOARD_BUSY_TIMEOUT_MS = 10_000;++/** The board's PRAGMA user_version once its triggers are in: losing one after that is news. */+export const SCHEMA_VERSION = 3;++export const SCHEMA = `+ CREATE TABLE IF NOT EXISTS board_meta (+ meta_key TEXT PRIMARY KEY,+ meta_value TEXT NOT NULL+ );+ CREATE TABLE IF NOT EXISTS agent (+ agent_id TEXT PRIMARY KEY,+ agent_lane TEXT NOT NULL,+ agent_path TEXT NOT NULL UNIQUE,+ agent_last_shout_id INTEGER NOT NULL DEFAULT 0,+ agent_route TEXT NOT NULL DEFAULT 'strong',+ agent_family TEXT,+ agent_created_at TEXT NOT NULL+ );+ CREATE TABLE IF NOT EXISTS item (+ item_id INTEGER PRIMARY KEY AUTOINCREMENT,+ item_parent_id INTEGER REFERENCES item (item_id),+ item_lane TEXT NOT NULL,+ item_title TEXT NOT NULL,+ item_criterion TEXT NOT NULL DEFAULT '',+ item_spec_ids TEXT NOT NULL DEFAULT '',+ item_after TEXT NOT NULL DEFAULT '',+ item_brief TEXT NOT NULL DEFAULT '',+ item_route TEXT NOT NULL DEFAULT 'strong',+ item_check TEXT NOT NULL DEFAULT '',+ item_status TEXT NOT NULL DEFAULT 'open',+ item_owner TEXT,+ item_lease_until TEXT,+ item_frozen TEXT,+ item_frozen_digest TEXT,+ item_built_by TEXT,+ item_builder_family TEXT,+ item_commit TEXT,+ item_tree TEXT,+ item_verdict TEXT,+ item_verified_by TEXT,+ item_merged_commit TEXT,+ item_withdrawn_reason TEXT,+ item_hold_reason TEXT,+ item_hold_by TEXT,+ item_hold_at TEXT,+ item_created_by TEXT NOT NULL,+ item_created_at TEXT NOT NULL,+ item_updated_at TEXT NOT NULL+ );+ CREATE INDEX IF NOT EXISTS item_lane_status ON item (item_lane, item_status);+ CREATE TABLE IF NOT EXISTS verdict (+ verdict_id INTEGER PRIMARY KEY AUTOINCREMENT,+ item_id INTEGER NOT NULL REFERENCES item (item_id),+ verdict_by TEXT NOT NULL,+ verdict_verifier_family TEXT,+ verdict_decision TEXT NOT NULL,+ verdict_reason TEXT NOT NULL,+ verdict_note TEXT NOT NULL DEFAULT '',+ verdict_commit TEXT NOT NULL,+ verdict_digest TEXT NOT NULL,+ verdict_head TEXT NOT NULL,+ verdict_at TEXT NOT NULL+ );+ CREATE INDEX IF NOT EXISTS verdict_item_id_verdict_id ON verdict (item_id, verdict_id);+ CREATE TABLE IF NOT EXISTS shout (+ shout_id INTEGER PRIMARY KEY AUTOINCREMENT,+ shout_from TEXT NOT NULL,+ shout_to TEXT NOT NULL,+ shout_text TEXT NOT NULL,+ shout_at TEXT NOT NULL+ );+ CREATE TABLE IF NOT EXISTS event (+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,+ event_at TEXT NOT NULL,+ event_by TEXT NOT NULL,+ event_kind TEXT NOT NULL,+ item_id INTEGER,+ event_detail TEXT NOT NULL DEFAULT '{}'+ );+ CREATE INDEX IF NOT EXISTS event_item_id_event_id ON event (item_id, event_id);+ CREATE TABLE IF NOT EXISTS hold (+ hold_lane TEXT PRIMARY KEY,+ hold_reason TEXT NOT NULL,+ hold_by TEXT NOT NULL,+ hold_at TEXT NOT NULL+ );+`;++/** This code's schema digest, shared unchanged by read and write opens. */+export const SCHEMA_DIGEST = schemaDigest(SCHEMA, EVENT_LOG_VERSION);diff --git a/src/board.js b/src/board.jsindex 0887bd87..f2e2d304 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,40 @@+import {+ closeBoard,+ openBoardForRead,+ openBoardReadOnly,+ readEventLogVersion,+ systemClock,+} from './board-read-open.js';+import {+ BOARD_BUSY_TIMEOUT_MS,+ EVENT_LOG_VERSION,+ SCHEMA,+ SCHEMA_DIGEST,+ SCHEMA_VERSION,+} from './board-schema-source.js';+import {+ PERSON,+ now,+ isHeld,+ current,+ itemCheckBaseline,+ reviewReleasesSinceSubmit,+ boardId,+ itemById,+ getItem,+ listItems,+ itemsInStatus,+ reviewHolder,+ reviewQueueBreakdown,+ reviewQueue,+ openDecisions,+ unreadCount,+ events,+ itemThread,+ laneHolds,+ rowDecisions,+ UNREAD_SQL,+} from './board-query.js';import { logEvent } from './board-event-log.js';export { logEvent };/**@@ -36,12 +73,10 @@ import { ensureHotIndexes } from './board-hot.js';import { boardBusyError } from './board-access.js';export { boardBusyError } from './board-access.js';import {- boardIsCurrent,boardStanding,migrate,recordSchemaStamp,reportDrift,- schemaDigest,} from './board-migrate.js';export { schemaMissing, writeRefused } from './board-migrate.js';import {@@ -151,13 +186,11 @@ export { flakeQuarantines, gateRuns, recordGateRun } from './quarantine.js';export { agentAt, agentById, agentCreator, coordinatorHolder, listAgents, nextSeatId, seatEnrolled, seatLineage, takeCoordinator, withVerifierStanding } from './seats.js';export const ACCEPT_REASON = 'CRITERION_MET';-export const PERSON = 'person';+export { PERSON } from './board-query.js';-/** Version of the persisted append-only event record format; bump for incompatible format changes. */-export const EVENT_LOG_VERSION = 1;+export { EVENT_LOG_VERSION } from './board-schema-source.js';-/** Maximum time a board connection waits for another process to release SQLite's lock. */-export const BOARD_BUSY_TIMEOUT_MS = 10_000;+export { BOARD_BUSY_TIMEOUT_MS } from './board-schema-source.js';const BRIEF_LIMIT = 8000;const REVIEW_RELEASE_COOLDOWN_MS = 60 * 60 * 1000;@@ -170,123 +203,15 @@ export const REJECT_REASONS = ['OTHER',];-/**- * The clock the board reads, real unless a test passes its own.- */-export const systemClock = { now: () => new Date() };--const SCHEMA = `- CREATE TABLE IF NOT EXISTS board_meta (- meta_key TEXT PRIMARY KEY,- meta_value TEXT NOT NULL- );- CREATE TABLE IF NOT EXISTS agent (- agent_id TEXT PRIMARY KEY,- agent_lane TEXT NOT NULL,- agent_path TEXT NOT NULL UNIQUE,- agent_last_shout_id INTEGER NOT NULL DEFAULT 0,- agent_route TEXT NOT NULL DEFAULT 'strong',- agent_family TEXT,- agent_created_at TEXT NOT NULL- );- CREATE TABLE IF NOT EXISTS item (- item_id INTEGER PRIMARY KEY AUTOINCREMENT,- item_parent_id INTEGER REFERENCES item (item_id),- item_lane TEXT NOT NULL,- item_title TEXT NOT NULL,- item_criterion TEXT NOT NULL DEFAULT '',- item_spec_ids TEXT NOT NULL DEFAULT '',- item_after TEXT NOT NULL DEFAULT '',- item_brief TEXT NOT NULL DEFAULT '',- item_route TEXT NOT NULL DEFAULT 'strong',- item_check TEXT NOT NULL DEFAULT '',- item_status TEXT NOT NULL DEFAULT 'open',- item_owner TEXT,- item_lease_until TEXT,- item_frozen TEXT,- item_frozen_digest TEXT,- item_built_by TEXT,- item_builder_family TEXT,- item_commit TEXT,- item_tree TEXT,- item_verdict TEXT,- item_verified_by TEXT,- item_merged_commit TEXT,- item_withdrawn_reason TEXT,- item_hold_reason TEXT,- item_hold_by TEXT,- item_hold_at TEXT,- item_created_by TEXT NOT NULL,- item_created_at TEXT NOT NULL,- item_updated_at TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS item_lane_status ON item (item_lane, item_status);- CREATE TABLE IF NOT EXISTS verdict (- verdict_id INTEGER PRIMARY KEY AUTOINCREMENT,- item_id INTEGER NOT NULL REFERENCES item (item_id),- verdict_by TEXT NOT NULL,- verdict_verifier_family TEXT,- verdict_decision TEXT NOT NULL,- verdict_reason TEXT NOT NULL,- verdict_note TEXT NOT NULL DEFAULT '',- verdict_commit TEXT NOT NULL,- verdict_digest TEXT NOT NULL,- verdict_head TEXT NOT NULL,- verdict_at TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS verdict_item_id_verdict_id ON verdict (item_id, verdict_id);- CREATE TABLE IF NOT EXISTS shout (- shout_id INTEGER PRIMARY KEY AUTOINCREMENT,- shout_from TEXT NOT NULL,- shout_to TEXT NOT NULL,- shout_text TEXT NOT NULL,- shout_at TEXT NOT NULL- );- CREATE TABLE IF NOT EXISTS event (- event_id INTEGER PRIMARY KEY AUTOINCREMENT,- event_at TEXT NOT NULL,- event_by TEXT NOT NULL,- event_kind TEXT NOT NULL,- item_id INTEGER,- event_detail TEXT NOT NULL DEFAULT '{}'- );- CREATE INDEX IF NOT EXISTS event_item_id_event_id ON event (item_id, event_id);- CREATE TABLE IF NOT EXISTS hold (- hold_lane TEXT PRIMARY KEY,- hold_reason TEXT NOT NULL,- hold_by TEXT NOT NULL,- hold_at TEXT NOT NULL- );-`;--/** This code's schema digest: a board stamped with it and its present shape needs no migration. */-const SCHEMA_DIGEST = schemaDigest(SCHEMA, EVENT_LOG_VERSION);+export { systemClock } from './board-read-open.js';-/**- * Open an existing board for a command that only reads: read-only, with no write lock and no- * migration, so a writer holding the lock never stalls it (#1047). `current` says whether this- * code's migration has run on it; only a write open migrates. Null when there is no board yet.- */-export function openBoardForRead(file, clock = systemClock) {- if (file === ':memory:' || !existsSync(file)) return null;- const db = openBoardReadOnly(file);- try { readEventLogVersion(db); return { db, clock, readOnly: true, current: boardIsCurrent(db, SCHEMA_DIGEST, SCHEMA_VERSION) }; }- catch (error) { db.close(); throw error; }-}-/** Open an existing board without migrations, waiting for the same locks as openBoard. */-export function openBoardReadOnly(file) {- const startedAt = Date.now();- let db;- try {- db = new DatabaseSync(file, { readOnly: true });- db.exec(`PRAGMA busy_timeout = ${BOARD_BUSY_TIMEOUT_MS}`);- return db;- } catch (error) {- try { db?.close(); } catch {}- throw boardBusyError(file, startedAt, error);- }-}++++export { openBoardForRead } from './board-read-open.js';++export { openBoardReadOnly } from './board-read-open.js';/*** Open, or create, the board at `file`. Tests pass `:memory:`.@@ -380,8 +305,7 @@ function guardMoves(board) {`);}-/** The board's PRAGMA user_version once its triggers are in: losing one after that is news. */-export const SCHEMA_VERSION = 3;+export { SCHEMA_VERSION } from './board-schema-source.js';const GUARDED = 1;/**@@ -419,25 +343,7 @@ function guardStore(board) {});}-/**- * Read the persisted event format without migrating it, so integrity checks enforce the same- * compatibility rule as the writable opener while leaving older or damaged evidence intact.- *- * @param {DatabaseSync} db- * @returns {number}- */-export function readEventLogVersion(db) {- if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'board_meta'").get()) return 0;- const stored = db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('event_log_version');- const version = stored && /^(?:0|[1-9]\d*)$/u.test(stored.meta_value) ? Number(stored.meta_value) : stored ? NaN : 0;- if (!Number.isSafeInteger(version) || version < 0) {- throw new Refused('EVENT_LOG_VERSION', `event log version ${stored?.meta_value ?? 'missing'} is invalid; restore a valid board or upgrade pullboard`);- }- if (version > EVENT_LOG_VERSION) {- throw new Refused('EVENT_LOG_VERSION', `event log version ${version} is newer than this pullboard version ${EVENT_LOG_VERSION}; upgrade pullboard to open this board`);- }- return version;-}+export { readEventLogVersion } from './board-read-open.js';/** Refuse unknown future event records before migrating anything, and mark older boards current. */function migrateEventLogVersion(db) {@@ -456,27 +362,11 @@ function migrateEventLogVersion(db) {}}-/** The persistent local and relay identity of this board (A2). */-export function boardId(board) {- return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('board_id').meta_value;-}+export { boardId } from './board-query.js';++export { closeBoard } from './board-read-open.js';-/**- * Close the board's file.- *- * @param {{ db: DatabaseSync }} board- */-export function closeBoard(board) {- board.db.close();-}-/**- * The board's time as ISO text.- *- * @param {any} board- * @returns {string}- */-const now = (board) => board.clock.now().toISOString();const TRANSACTION_DEPTH = new WeakMap();@@ -516,18 +406,7 @@ export function recordRelayRefusal(board, { by, sequence, kind, operation, actorlogEvent(board, by, 'relay_refused', itemId, { sequence, kind, operation, actor, code, ...(person ? { person } : {}) }); // who tried it, from engine 73 [E3]}-/**- * The item with this id, or a refusal naming the id.- *- * @param {any} board- * @param {number} id- * @returns {any}- */-export function itemById(board, id) {- const item = board.db.prepare('SELECT * FROM item WHERE item_id = ?').get(id);- if (!item) throw new Refused('NO_ITEM', `no item #${id}; see: pullboard list`);- return item;-}+export { itemById } from './board-query.js';/*** Write some of an item's fields, and its updated time. Field names come from this module only.@@ -544,28 +423,9 @@ function setItem(board, id, fields) {.run(...keys.map((key) => fields[key]), now(board), id);}-/**- * True while someone holds the item under a lease that has not lapsed.- *- * @param {any} board- * @param {any} item- * @returns {boolean}- */-function isHeld(board, item) {- return item.item_status === 'claimed' && (item.item_lease_until ?? '') > now(board);-}-/**- * The item as a reader should see it: a claim whose lease lapsed reads as open (B4).- *- * @param {any} board- * @param {any} item- * @returns {any}- */-function current(board, item) {- if (item.item_status !== 'claimed' || isHeld(board, item)) return { ...item };- return { ...item, item_status: 'open', item_owner: null, item_lease_until: null };-}++/*** Register a worktree as an agent (B3): the main checkout as the one coordinator, any other@@ -925,13 +785,7 @@ function saveCheckBaseline(board, id, baseline) {.run(key, JSON.stringify(baseline));}-/** Read an observation only when it still describes the item's current check command. */-function itemCheckBaseline(board, item) {- const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_check_baseline_${item.item_id}`);- if (!row) return null;- const baseline = JSON.parse(row.meta_value);- return baseline.command === item.item_check ? baseline : null;-}+/** Read the current check's setter from immutable edits, or its original item author [V2]. */export function itemCheckAuthor(board, id) {@@ -1337,17 +1191,7 @@ function correctedNoVerdictReopen(board, id, commit) {&& Boolean(JSON.parse(entry.event_detail).digest));}-/**- * Who holds an item's review under a live lease (V15), or null. A reservation counts only while the- * item is submitted and its lease has not run out, and a new submission starts with none.- *- * @param {any} board- * @param {any} item- * @returns {string | null}- */-export function reviewHolder(board, item) {- return item.item_status === 'submitted' && item.item_review_by && (item.item_review_until ?? '') > now(board) ? item.item_review_by : null;-}+export { reviewHolder } from './board-query.js';/** Validate a newly constructed review release while keeping old sealed replay executable [V1,R1,H16].* @param {any} board@@ -1373,24 +1217,7 @@ export function reviewReleaseNoteProblem(board, itemId, agentId, note) {return null;}-/** Find review releases after the current submission, optionally for one reviewer [V1,R1].- * Older releases are ignored because a new submission starts a fresh review.- */-function reviewReleasesSinceSubmit(board, itemId, agentId = null) {- const events = board.db.prepare("SELECT event_id, event_at, event_by, event_kind, event_detail FROM event WHERE item_id=? AND event_kind IN ('submit','release') ORDER BY event_id DESC")- .all(itemId);- const releases = [];- for (const event of events) {- if (event.event_kind === 'submit') return releases;- if (event.event_by !== agentId && agentId !== null) continue;- try {- const detail = JSON.parse(event.event_detail);- if (detail.review === true || detail.review === undefined) releases.push({ ...event, legacy: detail.review === undefined,- reason: detail.reason ?? 'reason not recorded' });- } catch { /* Ignore malformed legacy details rather than treating them as review releases. */ }- }- return releases;-}+/** Return a reviewer's active one-hour cooldown, if a later submission has not reset it [V1,R1]. */function reviewReleaseCooldown(board, itemId, agentId) {@@ -1401,32 +1228,9 @@ function reviewReleaseCooldown(board, itemId, agentId) {return until > board.clock.now().getTime() ? new Date(until).toISOString() : null;}-/** Count unreserved submissions by whether they are awaiting a first reviewer or were released [R1]. */-export function reviewQueueBreakdown(board) {- let awaitingFirstReview = 0;- let releasedWithoutVerdict = 0;- const releasedItems = [];- for (const item of itemsInStatus(board, 'submitted').filter((entry) => !reviewHolder(board, entry))) {- const releases = reviewReleasesSinceSubmit(board, item.item_id);- if (releases.length) {- releasedWithoutVerdict += 1;- releasedItems.push({ item: item.item_id, releases: releases.length, reason: releases[0].reason });- } else awaitingFirstReview += 1;- }- return { awaitingFirstReview, releasedWithoutVerdict, releasedItems };-}+export { reviewQueueBreakdown } from './board-query.js';-/** Summarize outstanding reviews using live leases and the latest submission's age [Q1,V15]. */-export function reviewQueue(board) {- const pending = itemsInStatus(board, 'submitted');- const holders = pending.map((item) => reviewHolder(board, item)).filter(Boolean);- // Only the current queue needs an age. Seek each item's history, including legacy timestamps,- // instead of grouping every submission ever made on the board.- const submittedAt = board.db.prepare("SELECT MAX(event_at) AS at FROM event WHERE item_id=? AND event_kind='submit'");- const oldestSubmittedAt = pending.map((item) => submittedAt.get(item.item_id).at).filter(Boolean).sort()[0] ?? null;- return { pending: pending.length, reviewing: new Set(holders).size, reserved: holders.length, oldestSubmittedAt,- ageMs: oldestSubmittedAt ? Math.max(0, board.clock.now().getTime() - Date.parse(oldestSubmittedAt)) : 0 };-}+export { reviewQueue } from './board-query.js';/** Offer an eligible review at the queue ratio without claiming or reserving anything [Q1,V15]. */export function reviewOffer(board, { agentId, lane, policy = 'any', familyPolicy = 'off', ratio = 3, runnable = false, routes = ROUTES }) {@@ -1811,28 +1615,9 @@ export function pendingRefreezeProblem(board, id) {: null;}-/**- * Items, newest first, as a reader should see them. Closed items (verified, withdrawn) only when- * asked.- *- * @param {any} board- * @param {{ lane?: string, all?: boolean }} [filter]- * @returns {any[]}- */-export function listItems(board, { lane, all = false } = {}) {- const hasLane = lane !== undefined && lane !== null;- const rows = board.db- .prepare(`SELECT * FROM item WHERE ${all ? '1' : "item_status NOT IN ('verified','withdrawn')"}${hasLane ? ' AND item_lane=?' : ''} ORDER BY item_id DESC`)- .all(...(hasLane ? [lane] : []));- const items = rows.map((item) => current(board, item));- return items;-}+export { listItems } from './board-query.js';-/** Read a stored status/owner slice, excluding claims whose leases have expired rather than caching items. */-export function itemsInStatus(board, status, owner = null) {- return board.db.prepare(`SELECT * FROM item WHERE item_status=?${owner === null ? '' : ' AND item_owner=?'} ORDER BY item_id DESC`)- .all(status, ...(owner === null ? [] : [owner])).map(item => current(board, item)).filter(item => item.item_status === status);-}+export { itemsInStatus } from './board-query.js';/** Return all recorded submitted heads of items still awaiting verification [V1,V17].* Historical heads remain unreviewed after a rejection or resubmission; current pointers also@@ -1855,18 +1640,7 @@ export function unverifiedSubmissions(board) {return [...submissions.values()];}-/**- * One item as a reader should see it.- *- * @param {any} board- * @param {number} id- * @returns {any}- */-export function getItem(board, id) {- const item = current(board, itemById(board, id));- const baseline = itemCheckBaseline(board, item);- return baseline ? { ...item, item_check_baseline: baseline } : item;-}+export { getItem } from './board-query.js';/*** Insert a shout within the caller's transaction.@@ -2081,28 +1855,7 @@ export function shoutDetails(board, id) {return { ...shout, decision_state: shout.shout_decision ? (answer ? 'answered' : 'open') : null, decision_answer: answer };}-/**- * Shouts that asked for a decision nobody has answered yet, oldest first (B21). An optional- * recipient limits the queue; an array matches any listed recipient. Without one this returns- * every open decision for internal readers.- *- * @param {any} board- * @param {string | string[]} [recipient]- * @returns {any[]}- */-export function openDecisions(board, recipient = null) {- if (recipient === null) {- return board.db- .prepare('SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id')- .all();- }- const recipients = [...new Set(Array.isArray(recipient) ? recipient : [recipient])];- if (!recipients.length) return [];- const marks = recipients.map(() => '?').join(', ');- return board.db- .prepare(`SELECT * FROM shout ask WHERE ask.shout_decision = 1 AND ask.shout_to IN (${marks}) AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id) ORDER BY ask.shout_id`)- .all(...recipients);-}+export { openDecisions } from './board-query.js';/** Requests remain visible to the coordinator until a done or declined answer closes them (A2). */export function openRequests(board) {@@ -2111,10 +1864,7 @@ export function openRequests(board) {ORDER BY ask.shout_id`).all();}-/**- * The SQL that picks an agent's unread shouts: to it, to its lane, or to all, from anyone else.- */-const UNREAD_SQL = `FROM shout WHERE shout_id > ? AND shout_from != ? AND shout_to IN ('all', ?, ?)`;+/*** Unread shouts for an agent, oldest first, then marked read.@@ -2139,49 +1889,16 @@ export function inbox(board, agentId) {});}-/**- * How many shouts an agent has not read, without marking them.- *- * @param {any} board- * @param {string} agentId- * @returns {number}- */-export function unreadCount(board, agentId) {- const agent = board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(agentId);- if (!agent) return 0;- const { total } = board.db- .prepare(`SELECT COUNT(*) AS total ${UNREAD_SQL}`)- .get(agent.agent_last_shout_id, agentId, agent.agent_lane, agentId);- return total;-}+export { unreadCount } from './board-query.js';-/**- * The event log, oldest first, for one item or the whole board.- *- * @param {any} board- * @param {{ itemId?: number }} [filter]- * @returns {any[]}- */-export function events(board, { itemId } = {}) {- if (itemId === undefined || itemId === null) {- return board.db.prepare('SELECT * FROM event ORDER BY event_id').all();- }- return board.db.prepare('SELECT * FROM event WHERE item_id = ? ORDER BY event_id').all(itemId);-}+export { events } from './board-query.js';/** Fact labels distinguish observations from judgements reserved to an item's live holder [B29,B30]. */export const FACT_KINDS = Object.freeze(['capture', 'measurement', 'note', 'diff', 'decision', 'rejection', 'supersession', 'root-cause']);const FACT_JUDGEMENTS = new Set(['decision', 'rejection', 'supersession', 'root-cause']);export { factReference };-/** Read every move and fact in append order, including superseded facts and full original text [B31,B32]. */-export function itemThread(board, id) {- itemById(board, id);- return events(board, { itemId: id }).map((event) => event.event_kind === 'fact'- ? { type: 'fact', ...factFromEvent(event) }- : { type: 'move', eventId: event.event_id, kind: event.event_kind, by: event.event_by,- at: event.event_at, detail: JSON.parse(event.event_detail) });-}+export { itemThread } from './board-query.js';/** Add threads to public item projections without changing their existing fields [A1,A2,B32]. */export function projectItemThreads(board, state) {@@ -2493,15 +2210,7 @@ export function laneHold(board, lane) {return board.db.prepare('SELECT * FROM hold WHERE hold_lane = ?').get(lane) ?? null;}-/**- * Every held lane.- *- * @param {any} board- * @returns {any[]}- */-export function laneHolds(board) {- return board.db.prepare('SELECT * FROM hold ORDER BY hold_lane').all();-}+export { laneHolds } from './board-query.js';/** Read an item's coordinator hold, or null when it is available for claims. */export function itemHold(board, id) {@@ -2559,11 +2268,7 @@ export { recordSpecApprovalBaseline, specApprovalBaseline, specApprovalBaselineE// The roadmap's moves live in milestones.js; the board keeps exporting them so the engine replays them.export { addMilestone, canonicalMilestoneTarget, editMilestone, editMilestoneItems, orderMilestoneItems, moveMilestone, removeMilestone, roadmap, shipMilestone } from './milestones.js';-/** Current person decisions, including applied receipts, stored without checkout-dependent state. */-export function rowDecisions(board) {- const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('row_decisions');- return row ? JSON.parse(row.meta_value) : [];-}+export { rowDecisions } from './board-query.js';/** Persist the current decision index inside its caller's board transaction. */function writeRowDecisions(board, records) {diff --git a/src/cli-board-read.js b/src/cli-board-read.jsnew file mode 100644index 00000000..c97dbf83--- /dev/null+++ b/src/cli-board-read.js@@ -0,0 +1,25 @@+/** The CLI's async boundary: ordinary reads load queries, genuine write fallbacks load the full store [C7]. */+import * as store from './board-query.js';+import { withOpenedBoard } from './cli-read-context.js';+import { Refused } from './refused.js';++/** Keep the old full-store fallback and pass its synchronous backend to the same work callback. */+async function writeFallback(ctx, work) {+ const full = await import('./board.js');+ const { withBoard } = await import('./cli-context.js');+ return withBoard(ctx, board => work(board, full));+}++/** Open exactly as the synchronous read API does; only the CLI awaits a needed full-store import. */+export async function withBoardRead(ctx, work) {+ const board = store.openBoardForRead(ctx.file, ctx.clock);+ if (board && !board.current && !ctx.allowSchemaUpgrade) store.closeBoard(board);+ if (!board || (!board.current && !ctx.allowSchemaUpgrade)) return writeFallback(ctx, work);+ try { return await withOpenedBoard(ctx, opened => work(opened, store), board); }+ catch (error) {+ const needsWrite = error instanceof store.ReadNeedsWrite || store.writeRefused(error);+ if (board.current && needsWrite) return writeFallback(ctx, work);+ if (!needsWrite && !store.schemaMissing(error)) throw error;+ throw new Refused('BOARD_SCHEMA_BEHIND', 'this board was made by an older pullboard and a read never upgrades it');+ }+}diff --git a/src/cli-context.js b/src/cli-context.jsindex 2a6db6f0..8f856502 100644--- a/src/cli-context.js+++ b/src/cli-context.js@@ -1,137 +1,35 @@-/**- * What every command shares and a read needs: the checkout's context, the board opened around one piece of work,- * argument parsing and the one-line item format. It loads no gate, relay or landing module, so a read command that- * imports only this pays for nothing it does not run [C7].- */-import { existsSync } from 'node:fs';-import {- isAbsolute,- join,- relative,- resolve,-} from 'node:path';-import { displayAgentName } from './agent-names.js';+/** The synchronous write-board lifecycle and compatible public CLI context exports [C7]. */import * as store from './board.js';-import {- CONFIG_FILE,- loadConfig,-} from './config.js';-import { loadDoctrine } from './doctrine.js';-import {- codeIsFromMain,- differFromHead,- headCommit,- repoInfo,- tryGit,-} from './git.js';import { Refused } from './refused.js';-import { mainPolicy } from './trusted-policy-read.js';-import { MAIN_MERGE_LABEL } from './trunk-conflict.js';--/**- * A positive whole number from an argument, or a refusal naming what was expected.- *- * @param {string | undefined} text- * @param {string} what- * @returns {number}- */-export function idArg(text, what = 'an item id') {- const id = Number(String(text ?? '').replace(/^#/, ''));- if (!Number.isInteger(id) || id < 1) throw new Refused('USAGE', `expected ${what}, got "${text ?? ''}"`);- return id;-}--/**- * A comma list of spec ids from a flag.- *- * @param {string | undefined} text- * @returns {string[]}- */-export const idList = (text) => (text ?? '').split(',').map((id) => id.trim()).filter(Boolean);--/**- * The start of a command an agent can paste anywhere: agent shells often start each command in the- * main checkout, so every command pullboard suggests names its folder (I5).- *- * @param {string} root- * @returns {string}- */-export const shellWord = (text) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replaceAll("'", "'\\''")}'`);--/**- * `cd <folder> &&`, the folder quoted for any POSIX shell: single quotes, so a space, a quote or a- * dollar sign in the path reaches cd as written (I7).- *- * @param {string} root- * @returns {string}- */-export const cdTo = (root) => `cd ${shellWord(root)} &&`;--/**- * Print an item's brief, indented under a heading, when it has one.- *- * @param {any} io- * @param {string} brief- */-export function sayBrief(io, brief) {- if (!brief) return;- io.say('brief:');- brief.split('\n').forEach((line) => io.say(` ${line}`.trimEnd()));-}--/**- * Everything a command needs: the repo, its config, the board's file, and where output goes.- *- * @param {any} io- * @returns {any}- */-export function context(io) {- const info = repoInfo(io.cwd);- if (info.isMain) io.caller?.('coordinator', info.root);- const config = configHere(info);- const file = join(info.commonDir, 'pullboard', 'board.sqlite');- // Where the running code came from costs Git processes, and only a board behind this code's schema needs it.- let allowSchemaUpgrade;- return { info, config, file, get allowSchemaUpgrade() { return allowSchemaUpgrade ??= codeIsFromMain(); },- doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };-}--/**- * This checkout's config. Init is the fix only where pullboard never was (C4): a config deleted- * from a checkout whose last commit has it is restored, and a linked worktree made from a commit- * that lacks it, beside a main checkout that has one, is made again from there.- *- * @param {{ root: string, commonDir: string, isMain: boolean }} info- * @returns {any}- */-function configHere(info) {- try {- return loadConfig(info.root);- } catch (error) {- if (!(error instanceof Refused) || error.code !== 'NO_CONFIG') throw error;- if (tryGit(info.root, ['cat-file', '-e', `HEAD:${CONFIG_FILE}`]).status === 0) {- throw new Refused('NO_CONFIG', `${CONFIG_FILE} is deleted here, though this checkout's last commit has it: restore it: ${cdTo(info.root)} git checkout HEAD -- ${CONFIG_FILE}`);- }- const mainRoot = resolve(info.commonDir, '..');- if (info.isMain || !existsSync(join(mainRoot, CONFIG_FILE))) throw error;- let setup;- try {- setup = uncommittedSetup(mainRoot, loadConfig(mainRoot));- } catch {- // Keep the existing recovery for invalid or incomplete main-checkout configuration.- }- if (setup) {- throw new Refused(- 'NO_CONFIG',- `this worktree has no ${CONFIG_FILE}, and the main checkout has uncommitted Pullboard setup files: ${setup.files.join(', ')}. Commit them in the main checkout first: ${setup.stage}`,- );- }- throw new Refused(- 'NO_CONFIG',- `this worktree's commit has no ${CONFIG_FILE}, though the main checkout has one: make a new worktree from the main checkout, which says what to commit first: ${cdTo(mainRoot)} pullboard worktree <lane> --model "<model name>"`,- );- }-}+import {+ agentDisplayName,+ context,+ withOpenedBoard,+ idArg,+ idList,+ shellWord,+ cdTo,+ sayBrief,+ firstLineOf,+ itemLine,+ setupFiles,+ uncommittedSetup,+ span,+} from './cli-read-context.js';+export {+ idArg,+ idList,+ shellWord,+ cdTo,+ sayBrief,+ context,+ firstLineOf,+ itemLine,+ agentDisplayName,+ setupFiles,+ uncommittedSetup,+ span,+};/*** Open the board, run `work`, and always close it.@@ -153,70 +51,7 @@ export function withBoard(ctx, work, opened) {ctx.io.err(message);},});- // Whether a proven flake stops blocking a landing is the coordinator's setting, read from accepted main on first use.- let quarantine;- board.quarantineEnabled = () => quarantine ??= mainPolicy(ctx.info.root).config.flakes?.quarantine === true;- const firstEvent = board.emittedEvents?.length ?? 0;- /** Forward committed events before releasing either synchronous or asynchronous work. */- const finish = () => {- for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);- store.closeBoard(board);- };- let result;- try {- // Reuse the already-open board to identify a registered seat, without another lock or migration.- if (ctx.io.caller && !ctx.info.isMain && !ctx.io.callerKnown?.(ctx.info.root) && store.agentAt(board, ctx.info.root)) ctx.io.caller('seat', ctx.info.root);- result = work(board);- }- catch (error) { finish(); throw error; }- if (result && typeof result.then === 'function') return result.finally(finish);- finish();- return result;-}--/** How many characters of an earlier verdict's note show prints (N30). */-const NOTE_LINE = 120;--/**- * A note's first line, cut to NOTE_LINE characters with … marking the cut. A line ends at any break- * Unicode makes mandatory (UAX #14): LF, VT, FF, CR, CRLF, NEL, LS and PS. Characters are counted- * as a reader sees them, so a cut never splits an emoji or an accented letter.- *- * @param {string} note- * @returns {string}- */-export function firstLineOf(note) {- const line = note.split(/[\n\v\f\r\x85\u2028\u2029]/)[0];- const characters = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(line)];- return characters.length > NOTE_LINE ? `${characters.slice(0, NOTE_LINE).map((part) => part.segment).join('')}…` : line;-}--/**- * One item on one line: id, status and holder, lane, title, spec ids.- *- * @param {any} item- * @returns {string}- */-export function itemLine(item, name = (id) => id, mainMerge = false) {- const holder = item.item_status === 'claimed' ? ` ${name(item.item_owner)}` : '';- const verifier = item.item_status === 'verified' ? ` by ${name(item.item_verified_by)}` : '';- const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';- const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';- const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';- const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : mainMerge ? ` (${MAIN_MERGE_LABEL})` : '';- const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;- const staleVerdict = item.item_verdict_state ? ` ${item.item_verdict_state.code}` : '';- const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';- return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}${staleVerdict}`;-}--/** Format a stable agent id for human-facing CLI output. */-export function agentDisplayName(agents, config, id) {- if (!id) return '';- const agent = agents.find((entry) => entry.agent_id === id);- if (agent) return displayAgentName(agent, config.agents.names);- if (id === 'person' || id === 'all' || Object.hasOwn(config.lanes, id)) return id;- return displayAgentName({ agent_id: id }, config.agents.names);+ return withOpenedBoard(ctx, work, board);}/** Render only declared actor positions in a refusal, preserving user text and stable JSON ids. */@@ -257,45 +92,3 @@ export function displayedRefusal(io, error) {return agentRefusalText(message, error.code, (id) => agentDisplayName(agents, ctx.config, id));} catch { return message; }}--/**- * The files a new worktree takes from the main checkout's last commit and works by: the config, the- * spec, the practice file, the rules its opening lines name, and the hooks, when git looks for them- * inside each worktree.- *- * @param {string} mainRoot- * @param {any} config- * @returns {string[]}- */-export function setupFiles(mainRoot, config) {- const hooks = tryGit(mainRoot, ['config', '--get', 'core.hooksPath']).stdout;- const inEach = hooks && !isAbsolute(hooks) && !relative(mainRoot, resolve(mainRoot, hooks)).startsWith('..');- return [CONFIG_FILE, config.spec, config.practice, 'AGENTS.md', ...(inEach ? [hooks] : [])].filter(Boolean);-}--/** Find setup files in the main checkout that a new worktree would not receive from HEAD. */-export function uncommittedSetup(mainRoot, config) {- if (headCommit(mainRoot) === null) return null;- const differ = differFromHead(mainRoot, setupFiles(mainRoot, config));- if (!differ.length) return null;- const words = differ.map(({ path }) => shellWord(path)).join(' ');- const force = differ.some(({ ignored }) => ignored) ? ' -f' : '';- return {- files: differ.map(({ path }) => path), differ,- stage: `${cdTo(mainRoot)} git add${force} -- ${words}`,- };-}--/**- * How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.- *- * @param {any} ctx- * @param {string} iso- * @returns {string}- */-export function span(ctx, iso) {- const minutes = Math.round(Math.abs(ctx.clock.now().getTime() - Date.parse(iso)) / 60_000);- if (minutes < 60) return `${minutes}m`;- if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`;- return `${Math.round(minutes / 1440)}d`;-}diff --git a/src/cli-identity.js b/src/cli-identity.jsindex 20878b38..469039cf 100644--- a/src/cli-identity.js+++ b/src/cli-identity.js@@ -1,33 +1,11 @@-/** Caller identity shared by read and write commands without loading their transports [C7,E18]. */+/** Caller identity keeps its synchronous full-store behavior for existing callers [C7,E18]. */import * as store from './board.js';-import { COORDINATOR } from './config.js';-import { displayAgentName } from './agent-names.js';-import { Refused } from './refused.js';+import { identifyCaller as readCaller } from './cli-read-context.js';-/**- * Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.- *- * @param {any} ctx- * @param {any} board- * @returns {{ id: string, lane: string, route?: string, family: string | null, model: string | null, displayName: string }}- */-export function identifyCaller(ctx, board, { environmentAgent, relayLinked }) {- // A CI or cloud session works as the agent its environment token names, on that one board [E18].- const seat = environmentAgent(ctx.info.root, board);- if (seat) return { id: seat.agent_id, lane: seat.agent_lane, route: seat.agent_route, family: seat.agent_family ?? null, model: seat.agent_model ?? 'unknown', displayName: displayAgentName(seat, ctx.config.agents.names) };- if (ctx.info.isMain) {- ctx.io.caller?.('coordinator', ctx.info.root);- const registered = store.agentById(board, COORDINATOR);- const linked = relayLinked(ctx.info.root);- if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');- const id = linked ? COORDINATOR : store.ensureCoordinator(board, ctx.info.root);- const agent = registered ?? store.agentAt(board, ctx.info.root);- return { id, lane: COORDINATOR, family: agent?.agent_family ?? null, model: agent?.agent_model ?? 'unknown', displayName: displayAgentName(agent ?? { agent_id: id }, ctx.config.agents.names) };- }- const agent = store.agentAt(board, ctx.info.root);- if (!agent) {- throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> --model "<model name>" (see: pullboard lanes)');- }- ctx.io.caller?.('seat', ctx.info.root);- return { id: agent.agent_id, lane: agent.agent_lane, route: agent.agent_route, family: agent.agent_family ?? null, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, ctx.config.agents.names) };+/** Resolve the caller through the original full store, including coordinator housekeeping. */+export function identifyCaller(ctx, board, options) {+ const readers = { agentAt: store.agentAt, agentById: store.agentById,+ /** Registration remains a direct synchronous call on the real write path. */+ ensureCoordinator: (opened, path) => store.ensureCoordinator(opened, path) };+ return readCaller(ctx, board, options, readers);}diff --git a/src/cli-read-context.js b/src/cli-read-context.jsnew file mode 100644index 00000000..e7f363ee--- /dev/null+++ b/src/cli-read-context.js@@ -0,0 +1,273 @@+/**+ * What every command shares and a read needs: the checkout's context, the board opened around one piece of work,+ * argument parsing and the one-line item format. It loads no gate, relay or landing module, so a read command that+ * imports only this pays for nothing it does not run [C7].+ */+import { existsSync } from 'node:fs';+import {+ isAbsolute,+ join,+ relative,+ resolve,+} from 'node:path';+import { displayAgentName } from './agent-names.js';+import * as store from './board-query.js';+import {+ CONFIG_FILE,+ COORDINATOR,+ loadConfig,+} from './config.js';+import { loadDoctrine } from './doctrine.js';+import {+ codeIsFromMain,+ differFromHead,+ headCommit,+ repoInfo,+ tryGit,+} from './git.js';+import { Refused } from './refused.js';+import { mainPolicy } from './trusted-policy-read.js';+import { MAIN_MERGE_LABEL } from './trunk-conflict.js';++/**+ * A comma list of spec ids from a flag.+ *+ * @param {string | undefined} text+ * @returns {string[]}+ */+export const idList = (text) => (text ?? '').split(',').map((id) => id.trim()).filter(Boolean);++/**+ * The start of a command an agent can paste anywhere: agent shells often start each command in the+ * main checkout, so every command pullboard suggests names its folder (I5).+ *+ * @param {string} root+ * @returns {string}+ */+export const shellWord = (text) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replaceAll("'", "'\\''")}'`);++/**+ * `cd <folder> &&`, the folder quoted for any POSIX shell: single quotes, so a space, a quote or a+ * dollar sign in the path reaches cd as written (I7).+ *+ * @param {string} root+ * @returns {string}+ */+export const cdTo = (root) => `cd ${shellWord(root)} &&`;++/** How many characters of an earlier verdict's note show prints (N30). */+const NOTE_LINE = 120;++/**+ * A positive whole number from an argument, or a refusal naming what was expected.+ *+ * @param {string | undefined} text+ * @param {string} what+ * @returns {number}+ */+export function idArg(text, what = 'an item id') {+ const id = Number(String(text ?? '').replace(/^#/, ''));+ if (!Number.isInteger(id) || id < 1) throw new Refused('USAGE', `expected ${what}, got "${text ?? ''}"`);+ return id;+}++/**+ * Print an item's brief, indented under a heading, when it has one.+ *+ * @param {any} io+ * @param {string} brief+ */+export function sayBrief(io, brief) {+ if (!brief) return;+ io.say('brief:');+ brief.split('\n').forEach((line) => io.say(` ${line}`.trimEnd()));+}++/**+ * Everything a command needs: the repo, its config, the board's file, and where output goes.+ *+ * @param {any} io+ * @returns {any}+ */+export function context(io) {+ const info = repoInfo(io.cwd);+ if (info.isMain) io.caller?.('coordinator', info.root);+ const config = configHere(info);+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');+ // Where the running code came from costs Git processes, and only a board behind this code's schema needs it.+ let allowSchemaUpgrade;+ return { info, config, file, get allowSchemaUpgrade() { return allowSchemaUpgrade ??= codeIsFromMain(); },+ doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };+}++/**+ * This checkout's config. Init is the fix only where pullboard never was (C4): a config deleted+ * from a checkout whose last commit has it is restored, and a linked worktree made from a commit+ * that lacks it, beside a main checkout that has one, is made again from there.+ *+ * @param {{ root: string, commonDir: string, isMain: boolean }} info+ * @returns {any}+ */+function configHere(info) {+ try {+ return loadConfig(info.root);+ } catch (error) {+ if (!(error instanceof Refused) || error.code !== 'NO_CONFIG') throw error;+ if (tryGit(info.root, ['cat-file', '-e', `HEAD:${CONFIG_FILE}`]).status === 0) {+ throw new Refused('NO_CONFIG', `${CONFIG_FILE} is deleted here, though this checkout's last commit has it: restore it: ${cdTo(info.root)} git checkout HEAD -- ${CONFIG_FILE}`);+ }+ const mainRoot = resolve(info.commonDir, '..');+ if (info.isMain || !existsSync(join(mainRoot, CONFIG_FILE))) throw error;+ let setup;+ try {+ setup = uncommittedSetup(mainRoot, loadConfig(mainRoot));+ } catch {+ // Keep the existing recovery for invalid or incomplete main-checkout configuration.+ }+ if (setup) {+ throw new Refused(+ 'NO_CONFIG',+ `this worktree has no ${CONFIG_FILE}, and the main checkout has uncommitted Pullboard setup files: ${setup.files.join(', ')}. Commit them in the main checkout first: ${setup.stage}`,+ );+ }+ throw new Refused(+ 'NO_CONFIG',+ `this worktree's commit has no ${CONFIG_FILE}, though the main checkout has one: make a new worktree from the main checkout, which says what to commit first: ${cdTo(mainRoot)} pullboard worktree <lane> --model "<model name>"`,+ );+ }+}++/**+ * A note's first line, cut to NOTE_LINE characters with … marking the cut. A line ends at any break+ * Unicode makes mandatory (UAX #14): LF, VT, FF, CR, CRLF, NEL, LS and PS. Characters are counted+ * as a reader sees them, so a cut never splits an emoji or an accented letter.+ *+ * @param {string} note+ * @returns {string}+ */+export function firstLineOf(note) {+ const line = note.split(/[\n\v\f\r\x85\u2028\u2029]/)[0];+ const characters = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(line)];+ return characters.length > NOTE_LINE ? `${characters.slice(0, NOTE_LINE).map((part) => part.segment).join('')}…` : line;+}++/**+ * One item on one line: id, status and holder, lane, title, spec ids.+ *+ * @param {any} item+ * @returns {string}+ */+export function itemLine(item, name = (id) => id, mainMerge = false) {+ const holder = item.item_status === 'claimed' ? ` ${name(item.item_owner)}` : '';+ const verifier = item.item_status === 'verified' ? ` by ${name(item.item_verified_by)}` : '';+ const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';+ const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';+ const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';+ const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : mainMerge ? ` (${MAIN_MERGE_LABEL})` : '';+ const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;+ const staleVerdict = item.item_verdict_state ? ` ${item.item_verdict_state.code}` : '';+ const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';+ return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}${staleVerdict}`;+}++/** Format a stable agent id for human-facing CLI output. */+export function agentDisplayName(agents, config, id) {+ if (!id) return '';+ const agent = agents.find((entry) => entry.agent_id === id);+ if (agent) return displayAgentName(agent, config.agents.names);+ if (id === 'person' || id === 'all' || Object.hasOwn(config.lanes, id)) return id;+ return displayAgentName({ agent_id: id }, config.agents.names);+}++/**+ * The files a new worktree takes from the main checkout's last commit and works by: the config, the+ * spec, the practice file, the rules its opening lines name, and the hooks, when git looks for them+ * inside each worktree.+ *+ * @param {string} mainRoot+ * @param {any} config+ * @returns {string[]}+ */+export function setupFiles(mainRoot, config) {+ const hooks = tryGit(mainRoot, ['config', '--get', 'core.hooksPath']).stdout;+ const inEach = hooks && !isAbsolute(hooks) && !relative(mainRoot, resolve(mainRoot, hooks)).startsWith('..');+ return [CONFIG_FILE, config.spec, config.practice, 'AGENTS.md', ...(inEach ? [hooks] : [])].filter(Boolean);+}++/** Find setup files in the main checkout that a new worktree would not receive from HEAD. */+export function uncommittedSetup(mainRoot, config) {+ if (headCommit(mainRoot) === null) return null;+ const differ = differFromHead(mainRoot, setupFiles(mainRoot, config));+ if (!differ.length) return null;+ const words = differ.map(({ path }) => shellWord(path)).join(' ');+ const force = differ.some(({ ignored }) => ignored) ? ' -f' : '';+ return {+ files: differ.map(({ path }) => path), differ,+ stage: `${cdTo(mainRoot)} git add${force} -- ${words}`,+ };+}++/**+ * How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.+ *+ * @param {any} ctx+ * @param {string} iso+ * @returns {string}+ */+export function span(ctx, iso) {+ const minutes = Math.round(Math.abs(ctx.clock.now().getTime() - Date.parse(iso)) / 60_000);+ if (minutes < 60) return `${minutes}m`;+ if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`;+ return `${Math.round(minutes / 1440)}d`;+}++/** Run work on an opened board with the same caller, quarantine, event and close lifecycle. */+export function withOpenedBoard(ctx, work, board) {+ // Whether a proven flake stops blocking a landing is the coordinator's setting, read from accepted main on first use.+ let quarantine;+ board.quarantineEnabled = () => quarantine ??= mainPolicy(ctx.info.root).config.flakes?.quarantine === true;+ const firstEvent = board.emittedEvents?.length ?? 0;+ /** Forward committed events before releasing either synchronous or asynchronous work. */+ const finish = () => {+ for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);+ store.closeBoard(board);+ };+ let result;+ try {+ // Reuse the already-open board to identify a registered seat, without another lock or migration.+ if (ctx.io.caller && !ctx.info.isMain && !ctx.io.callerKnown?.(ctx.info.root) && store.agentAt(board, ctx.info.root)) ctx.io.caller('seat', ctx.info.root);+ result = work(board);+ }+ catch (error) { finish(); throw error; }+ if (result && typeof result.then === 'function') return result.finally(finish);+ finish();+ return result;+}++/**+ * Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.+ *+ * @param {any} ctx+ * @param {any} board+ * @returns {{ id: string, lane: string, route?: string, family: string | null, model: string | null, displayName: string }}+ */+export function identifyCaller(ctx, board, { environmentAgent, relayLinked }, readers = store) {+ // A CI or cloud session works as the agent its environment token names, on that one board [E18].+ const seat = environmentAgent(ctx.info.root, board);+ if (seat) return { id: seat.agent_id, lane: seat.agent_lane, route: seat.agent_route, family: seat.agent_family ?? null, model: seat.agent_model ?? 'unknown', displayName: displayAgentName(seat, ctx.config.agents.names) };+ if (ctx.info.isMain) {+ ctx.io.caller?.('coordinator', ctx.info.root);+ const registered = readers.agentById(board, COORDINATOR);+ const linked = relayLinked(ctx.info.root);+ if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');+ const id = linked ? COORDINATOR : readers.ensureCoordinator(board, ctx.info.root);+ const agent = registered ?? readers.agentAt(board, ctx.info.root);+ return { id, lane: COORDINATOR, family: agent?.agent_family ?? null, model: agent?.agent_model ?? 'unknown', displayName: displayAgentName(agent ?? { agent_id: id }, ctx.config.agents.names) };+ }+ const agent = readers.agentAt(board, ctx.info.root);+ if (!agent) {+ throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> --model "<model name>" (see: pullboard lanes)');+ }+ ctx.io.caller?.('seat', ctx.info.root);+ return { id: agent.agent_id, lane: agent.agent_lane, route: agent.agent_route, family: agent.agent_family ?? null, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, ctx.config.agents.names) };+}diff --git a/src/commands/list.js b/src/commands/list.jsindex f8ccb338..ba9ecb90 100644--- a/src/commands/list.js+++ b/src/commands/list.js@@ -1,6 +1,6 @@-import { withBoardRead } from '../board-read.js';+import { withBoardRead } from '../cli-board-read.js';/** The pullboard list command, in its own module so an item adding another command never edits these lines. */-import * as store from '../board.js';+import * as store from '../board-query.js';import {mainMergeFor,} from '../trunk-conflict.js';@@ -11,12 +11,12 @@ import {agentDisplayName,context,itemLine,-} from '../cli-context.js';+} from '../cli-read-context.js';/** Run `pullboard list` and return its exit code. */-export function run(io, { first, values }) {+export async function run(io, { first, values }) {const ctx = context(io);- const { items, agents, merging } = withBoardRead(ctx, (board) => {+ const { items, agents, merging } = await withBoardRead(ctx, (board) => {const rows = store.listItems(board, { lane: first, all: values.all });const items = rows.map(verdictProjector(ctx.info.root, board).project);// JSON returns these complete rows; agent names and merge labels belong only to the text rendering.diff --git a/src/commands/show.js b/src/commands/show.jsindex 7ae6c86b..441d6d3d 100644--- a/src/commands/show.js+++ b/src/commands/show.js@@ -1,4 +1,6 @@-import { withBoardRead } from '../board-read.js';+// Pending the legally landed #1114 item-files leaf, keep the existing related-items implementation.+import { relatedItems } from '../board.js';+import { withBoardRead } from '../cli-board-read.js';/** The pullboard show command, in its own module so an item adding another command never edits these lines. */import {displayAgentName,@@ -7,7 +9,7 @@ import {barCorrectionLine,barCorrections,} from '../bar-corrections.js';-import * as store from '../board.js';+import * as store from '../board-query.js';import {agentApprovalLine,itemAgentApprovals,@@ -32,14 +34,14 @@ import {idArg,itemLine,sayBrief,-} from '../cli-context.js';+} from '../cli-read-context.js';import { relayStateExists } from '../local-state.js';/** Run `pullboard show` and return its exit code. */export async function run(io, { first, values }) {const ctx = context(io);const id = idArg(first);- const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoardRead(ctx, (board) => {+ const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = await withBoardRead(ctx, (board) => {const item = verdictProjector(ctx.info.root, board).project(store.getItem(board, id));const result = { item, verdicts: store.verdictsFor(board, id), thread: store.itemThread(board, id),approval: specApprovalState(ctx.info.root, { board, config: ctx.config }) };@@ -47,7 +49,7 @@ export async function run(io, { first, values }) {if (values.json) return result;const history = store.events(board, { itemId: id });return { ...result, moves: history.filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),- related: store.relatedItems(board, item), reviewer: store.reviewHolder(board, item),+ related: relatedItems(board, item), reviewer: store.reviewHolder(board, item),agents: store.listAgents(board), mainMerge: mainMergeFor(board, id), infra: infraNotes.infraNoteOf(history) };});const agentApproved = itemAgentApprovals(item, approval);diff --git a/src/commands/status.js b/src/commands/status.jsindex 158c2493..4601ea8b 100644--- a/src/commands/status.js+++ b/src/commands/status.js@@ -1,8 +1,8 @@-import { withBoardRead } from '../board-read.js';+import { withBoardRead } from '../cli-board-read.js';/** The pullboard status command, in its own module so an item adding another command never edits these lines. */-import * as store from '../board.js';+import * as store from '../board-query.js';import { personNeedsSummary } from '../needs-summary.js';-import { identifyCaller } from '../cli-identity.js';+import { identifyCaller } from '../cli-read-context.js';import { relayStateExists } from '../local-state.js';import { unlinkedRelayStatus } from '../relay-status-fields.js';import {@@ -23,7 +23,7 @@ import {import {context,span,-} from '../cli-context.js';+} from '../cli-read-context.js';/** Run `pullboard status` and return its exit code. */export async function run(io, { values }) {@@ -32,9 +32,9 @@ export async function run(io, { values }) {const relay = hasRelayState ? await import('../relay.js') : null;const environment = hasRelayState && process.env.PULLBOARD_RELAY_TOKEN !== undefined? await import('../relay-environment.js') : null;- const summary = withBoardRead(ctx, (board) => {+ const summary = await withBoardRead(ctx, (board, readers) => {const me = identifyCaller(ctx, board, { environmentAgent: environment?.environmentAgent ?? (() => null),- relayLinked: relay?.relayLinked ?? (() => false) });+ relayLinked: relay?.relayLinked ?? (() => false) }, readers);const mine = store.itemsInStatus(board, 'claimed', me.id);const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),@@ -58,7 +58,7 @@ export async function run(io, { values }) {io.say('optional: add a GitHub origin and run pullboard relay on to link this board');}if (Object.keys(ctx.config.products).length) {- const all = withBoardRead(ctx, (board) => store.listItems(board, { all: true }));+ const all = await withBoardRead(ctx, (board) => store.listItems(board, { all: true }));productSummaries(ctx.config, loadSpec(ctx.info.root, ctx.config), all).forEach((product) => io.say(productLine(product)));}return 0;diff --git a/src/engine-metadata.js b/src/engine-metadata.jsnew file mode 100644index 00000000..88860527--- /dev/null+++ b/src/engine-metadata.js@@ -0,0 +1,59 @@+/** Feature discovery and historical constants, without lifecycle declarations [C7,V4]. */+import {+ ENGINE_CANDIDATE,+ ENGINE_FILE,+ discovered,+} from './discovery.js';+import {+ readdirSync,+ readFileSync,+} from 'node:fs';++export { AUTO_ESCALATE_ENGINE } from './auto-escalate-engine.js';+export { ROW_DRAFT_ENGINE } from './row-draft-engine.js';+export { STRONG_REJECTION_NOTICE_ENGINE } from './strong-rejection-notice-engine.js';+export { SUBMITTED_CONFLICT_ENGINE } from './submitted-conflict-engine.js';+export { WITHDRAW_MILESTONE_ENGINE } from './withdraw-milestone-engine.js';++/**+ * Find every feature engine: each src/*-engine.js leaf declares exactly one `export const NAME_ENGINE = n;` line.+ * A feature that raises the engine adds its own new file and no line of any shared one, so two items adding+ * different engines never conflict [C7,V4]. The value is read as text because machine.js needs it synchronously.+ *+ * @param {URL} directory the folder holding the *-engine.js leaves+ * @returns {Record<string, number>} engine number by file name, in name order+ */+export function discoverEngines(directory = new URL('./', import.meta.url)) {+ const found = {};+ for (const file of discovered(readdirSync(directory), ENGINE_CANDIDATE, ENGINE_FILE, 'feature engine')) {+ const lines = readFileSync(new URL(file, directory), 'utf8').split('\n').filter((line) => /^export const /u.test(line));+ const match = lines.length === 1 ? /^export const [A-Z][A-Z0-9_]*_ENGINE = (\d+);$/u.exec(lines[0]) : null;+ if (!match) throw new Error(`${file} must declare exactly one line \`export const NAME_ENGINE = <number>;\` so ENGINE_VERSION can read it`);+ found[file.slice(0, -'-engine.js'.length)] = Number(match[1]);+ }+ return found;+}++export { REOPEN_FIRST_REFUSAL_ENGINE } from './reopen-first-refusal-engine.js';++/** Every feature engine by name, discovered from the *-engine.js files beside this one. */+export const ENGINE_REGISTRY = discoverEngines();++/** The highest engine number any feature declares. */+export const ENGINE_VERSION = Math.max(...Object.values(ENGINE_REGISTRY));++/**+ * The engine whose relay moves carry seat provenance and verifier standing (#579). It is its own+ * constant because engine slots are allotted per item: whoever lands second renumbers this line.+ */+export const VERIFIER_STANDING_ENGINE = 48;++/** The engine at which reject, reopen and person facts may carry cause keys [D1,H16]. */+export const CAUSE_ENGINE = 30;++/** First released engine binding the checked composition, review trunk and paths [E8,H16]. */+export const VERDICT_REVIEW_ENGINE = 33;++/** First engine carrying explicit milestone ranks in build and review selection [N2,B13,H16]. */+export const MILESTONE_RANK_ENGINE = 34;+diff --git a/src/implies.js b/src/implies.jsindex 6f840523..94548699 100644--- a/src/implies.js+++ b/src/implies.js@@ -1,3 +1,7 @@+import {+ decisionFields,+ factFromEvent,+} from './board-query.js';/*** A decision names the items it changes, and each named item carries it [B29,B30,B31,N29,P6].*@@ -25,7 +29,7 @@ import {join,} from 'node:path';import { COORDINATOR } from './config.js';-import { ENGINE_VERSION } from './machine.js';+import { ENGINE_VERSION } from './engine-metadata.js';import { Refused } from './refused.js';/** The engine whose moves may carry `implies`, or supersede an answer; older replays never do. */@@ -304,11 +308,7 @@ export function requestAnswerRefusal(id, { asPerson }) {: new Refused('NOT_A_DECISION', `request #${id} is not a decision, so it implies and supersedes nothing; answer it with pullboard answer ${id} done or declined <reason>`);}-/** The optional engine-20 fields of a fact, present only when its event set them. */-export function decisionFields(detail) {- return { ...(detail.implies ? { implies: detail.implies } : {}), ...(detail.decision ? { decision: detail.decision } : {}),- ...(detail.supersededBy ? { supersededBy: detail.supersededBy } : {}) };-}+export { decisionFields } from './board-query.js';/** The most fact ids one checkout remembers as shown; older ones age out first. */const SEEN_LIMIT = 2000;@@ -340,10 +340,4 @@ export function takeDecisionNotices(gitDir, held) {return notices;}-/** Give facts the same stamped identity on CLI, API, export and replica reads; a never-again keeps its cause [B29,B31,D1]. */-export function factFromEvent(event) {- const detail = JSON.parse(event.event_detail);- return { id: detail.id, eventId: event.event_id, kind: detail.kind, text: detail.text,- by: event.event_by, at: event.event_at, ref: detail.ref ?? null, supersedes: detail.supersedes ?? null, ...decisionFields(detail),- ...(detail.neverAgain ? { cause: detail.cause, neverAgain: true } : {}) };-}+export { factFromEvent } from './board-query.js';diff --git a/src/machine.js b/src/machine.jsindex e8f4c714..e9444375 100644--- a/src/machine.js+++ b/src/machine.js@@ -9,63 +9,7 @@* broken copy, and checks the declaration against the refusals board.js and cli.js raise today.*/-import {- ENGINE_CANDIDATE,- ENGINE_FILE,- discovered,-} from './discovery.js';-import {- readdirSync,- readFileSync,-} from 'node:fs';--export { AUTO_ESCALATE_ENGINE } from './auto-escalate-engine.js';-export { ROW_DRAFT_ENGINE } from './row-draft-engine.js';-export { STRONG_REJECTION_NOTICE_ENGINE } from './strong-rejection-notice-engine.js';-export { SUBMITTED_CONFLICT_ENGINE } from './submitted-conflict-engine.js';-export { WITHDRAW_MILESTONE_ENGINE } from './withdraw-milestone-engine.js';--/**- * Find every feature engine: each src/*-engine.js leaf declares exactly one `export const NAME_ENGINE = n;` line.- * A feature that raises the engine adds its own new file and no line of any shared one, so two items adding- * different engines never conflict [C7,V4]. The value is read as text because machine.js needs it synchronously.- *- * @param {URL} directory the folder holding the *-engine.js leaves- * @returns {Record<string, number>} engine number by file name, in name order- */-export function discoverEngines(directory = new URL('./', import.meta.url)) {- const found = {};- for (const file of discovered(readdirSync(directory), ENGINE_CANDIDATE, ENGINE_FILE, 'feature engine')) {- const lines = readFileSync(new URL(file, directory), 'utf8').split('\n').filter((line) => /^export const /u.test(line));- const match = lines.length === 1 ? /^export const [A-Z][A-Z0-9_]*_ENGINE = (\d+);$/u.exec(lines[0]) : null;- if (!match) throw new Error(`${file} must declare exactly one line \`export const NAME_ENGINE = <number>;\` so ENGINE_VERSION can read it`);- found[file.slice(0, -'-engine.js'.length)] = Number(match[1]);- }- return found;-}--export { REOPEN_FIRST_REFUSAL_ENGINE } from './reopen-first-refusal-engine.js';--/** Every feature engine by name, discovered from the *-engine.js files beside this one. */-export const ENGINE_REGISTRY = discoverEngines();--/** The highest engine number any feature declares. */-export const ENGINE_VERSION = Math.max(...Object.values(ENGINE_REGISTRY));--/**- * The engine whose relay moves carry seat provenance and verifier standing (#579). It is its own- * constant because engine slots are allotted per item: whoever lands second renumbers this line.- */-export const VERIFIER_STANDING_ENGINE = 48;--/** The engine at which reject, reopen and person facts may carry cause keys [D1,H16]. */-export const CAUSE_ENGINE = 30;--/** First released engine binding the checked composition, review trunk and paths [E8,H16]. */-export const VERDICT_REVIEW_ENGINE = 33;--/** First engine carrying explicit milestone ranks in build and review selection [N2,B13,H16]. */-export const MILESTONE_RANK_ENGINE = 34;+export * from './engine-metadata.js';/** @typedef {'agent' | 'coordinator' | 'clock'} Role */diff --git a/src/needs-summary.js b/src/needs-summary.jsindex e826c3de..23f51232 100644--- a/src/needs-summary.js+++ b/src/needs-summary.js@@ -1,5 +1,5 @@/** Status obligations without loading the dashboard projection [N26,A9]. */-import * as store from './board.js';+import * as store from './board-query.js';import { repoInfo } from './git.js';import { projectRowDecisions } from './row-decisions.js';import { loadSpec } from './spec.js';@@ -14,7 +14,7 @@ import {import {sentinelDraftNeeds,sentinels,-} from './sentinels.js';+} from './board-query.js';/** Keep status's complete obligation list without dashboard history, Git ages, or release notes. */export function personNeedsSummary(root, { board, config }) {diff --git a/src/seats.js b/src/seats.jsindex ddf2a693..a5305883 100644--- a/src/seats.js+++ b/src/seats.js@@ -1,3 +1,10 @@+import {+ agentAt,+ agentById,+ agentModel,+ withModel,+ listAgents,+} from './board-query.js';/*** Seats (B3, H2, V1): who each registered agent is on the board, read from the agent table and the* metadata kept beside it: its model, its route, and from engine 48 the seat that created it, whether@@ -14,32 +21,13 @@ import { Refused } from './refused.js';/** The board's coordinator hold travels with its seats: one main checkout coordinates a linked board (#347). */export { coordinatorHolder, takeCoordinator } from './coordinator-hold.js';-/**- * The agent registered for a worktree path, if any.- *- * @param {any} board- * @param {string} path- * @returns {any}- */-export function agentAt(board, path) {- const agent = board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);- return withModel(board, agent);-}+export { agentAt } from './board-query.js';-/** Read one seat and its model without loading every registered seat and model on the board. */-export function agentById(board, id) {- return withModel(board, board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(id));-}+export { agentById } from './board-query.js';-/** Read the model label kept beside other board metadata, avoiding any board-schema migration. */-export function agentModel(board, id) {- return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_model:${id}`)?.meta_value ?? null;-}+export { agentModel } from './board-query.js';-/** Attach an agent's model to a row from the legacy stable agent table. */-export function withModel(board, agent) {- return agent ? { ...agent, agent_model: agentModel(board, agent.agent_id) } : agent;-}+export { withModel } from './board-query.js';/** Save or clear a model label without changing the shared SQLite schema. */export function saveAgentModel(board, id, model) {@@ -51,16 +39,7 @@ export function saveAgentModel(board, id, model) {.run(`agent_model:${id}`, model);}-/**- * Every registered agent, oldest first.- *- * @param {any} board- * @returns {any[]}- */-export function listAgents(board) {- return board.db.prepare(`SELECT agent.*, board_meta.meta_value AS agent_model FROM agent- LEFT JOIN board_meta ON board_meta.meta_key='agent_model:' || agent.agent_id ORDER BY agent.rowid`).all().map(agent => ({ ...agent }));-}+export { listAgents } from './board-query.js';/*** The route an agent joined on; strong for the coordinator and for ids the board does not know.diff --git a/src/sentinels.js b/src/sentinels.jsindex 3498d211..473fabd4 100644--- a/src/sentinels.js+++ b/src/sentinels.js@@ -1,7 +1,11 @@+import {+ sentinelDraftNeeds,+ sentinels,+} from './board-query.js';/** Person-approved board watches and their append-only run history [A6,D1,D3]. */import { createHash } from 'node:crypto';import { atomic } from './board.js';-import { listAgents } from './board.js';+import { listAgents } from './board-query.js';import { logEvent } from './board.js';import { PERSON } from './board.js';import { shout } from './board.js';@@ -63,48 +67,14 @@ export function rigorSentinelName(key) {return ('rigor-' + slug).slice(0, 64).replace(/[-._]+$/u, '');}-/** Pending watches are the person's calls: one Needs-you entry each, with the evidence that proposed it. */-export function sentinelDraftNeeds(rows) {- return rows.filter(row => row.status === 'pending').map(row => ({- kind: 'sentinel-draft', id: `sentinel:${row.name}`, ref: row.name,- check: row.check, directory: row.directory, every: row.every, owner: row.owner, digest: row.digest,- text: `Sentinel draft: ${row.name} runs ${row.check} ${row.every === 'daily' || row.every === 'hourly' ? row.every : 'every ' + row.every}, reporting to ${row.owner}`,- what: `pullboard sentinel approve ${row.name}, or decline it with --reason`, target: `sentinel:${row.name}`,- ...(row.evidence ? { cause: row.evidence.key, evidence: row.evidence } : {}),- }));-}+export { sentinelDraftNeeds } from './board-query.js';/** Bind approval to every execution and notification field, including schedule and timeout. */export function sentinelDigest(value) {return createHash('sha256').update(JSON.stringify(sentinelDefinition(value))).digest('hex');}-/** Read only allocated receipts; legacy events with similar names never enable command execution. */-export function sentinels(board) {- const rows = new Map();- const events = board.db.prepare("SELECT * FROM event WHERE event_kind IN ('sentinel-proposal','sentinel-decision','sentinel-start','sentinel-run') ORDER BY event_id").all();- for (const event of events) {- const detail = JSON.parse(event.event_detail);- if (detail.engine !== BOARD_SENTINEL_ENGINE) continue;- if (event.event_kind === 'sentinel-proposal') {- rows.set(detail.row.name, { ...detail.row, digest: detail.digest, status: 'pending', proposedBy: event.event_by,- proposedAt: event.event_at, evidence: detail.evidence ?? null, lastRun: null, activeRun: null, history: [] });- continue;- }- const row = rows.get(detail.name);- if (!row || row.digest !== detail.digest) continue;- if (event.event_kind === 'sentinel-decision' && event.event_by === PERSON) {- row.status = detail.decision === 'approve' ? 'approved' : 'declined';- row.reason = detail.reason; row.decidedAt = event.event_at; row.activeRun = null;- } else if (event.event_kind === 'sentinel-start') {- row.activeRun = { id: detail.run, by: event.event_by, startedAt: event.event_at, until: detail.until };- } else if (event.event_kind === 'sentinel-run' && row.activeRun?.id === detail.run) {- row.lastRun = { ...detail.result, id: detail.run, at: event.event_at };- row.history.push(row.lastRun); row.activeRun = null;- }- }- return [...rows.values()];-}+export { sentinels } from './board-query.js';/** All mutations retain their allocated replay minimum and require a registered actor. */function requireSentinelActor(board, agentId, person = false) {diff --git a/src/spec-approval-baseline.js b/src/spec-approval-baseline.jsindex 2541d2e2..5f28938d 100644--- a/src/spec-approval-baseline.js+++ b/src/spec-approval-baseline.js@@ -1,3 +1,10 @@+import {+ KEY,+ validBaseline,+ canonicalBaseline,+ specApprovalBaselineExists,+ specApprovalBaseline,+} from './board-query.js';/** One shared compatibility snapshot, recorded through the board engine, never a person approval. */import {atomic,@@ -7,51 +14,15 @@ import { Refused } from './refused.js';import { parseSpec } from './spec.js';import { COORDINATOR } from './config.js';-const KEY = 'spec_approval_baseline';-/** Distinguish a missing migration marker from an unreadable one without replacing either. */-export function specApprovalBaselineExists(board) {- return Boolean(board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key=?').get(KEY)- || board.db.prepare('SELECT 1 FROM event WHERE event_kind=? LIMIT 1').get(KEY));-}-/** Validate the exact source carried by an ordered snapshot, including the empty initial set. */-function validBaseline(value) {- if (!value || value.version !== 1 || typeof value.file !== 'string' || !value.file- || !(value.anchor === null || /^[a-f0-9]{40,64}$/u.test(value.anchor)) || !Array.isArray(value.rows)) return false;- const seen = new Set();- return value.rows.every(row => {- if (!row || typeof row.id !== 'string' || typeof row.text !== 'string' || typeof row.source !== 'string'- || /[\r\n]/u.test(row.source) || seen.has(row.id)) return false;- const parsed = parseSpec(`## Baseline\n${row.source}\n`).rows;- seen.add(row.id);- return parsed.length === 1 && parsed[0].id === row.id && parsed[0].text === row.text && parsed[0].status === 'approved';- });-}+export { specApprovalBaselineExists } from './board-query.js';-/** Compare the snapshot payload without incidental event attribution or JSON property order. */-function canonicalBaseline(baseline) {- return { version: 1, file: baseline.file, anchor: baseline.anchor,- rows: baseline.rows.map(({ id, text, source }) => ({ id, text, source })) };-}-/** Read the original snapshot without interpreting it as authenticated approval or reseeding it. */-export function specApprovalBaseline(board) {- const stored = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(KEY);- const events = board.db.prepare('SELECT event_by,event_detail FROM event WHERE event_kind=?').all(KEY);- if (!stored && !events.length) return null;- let value;- let recorded;- try {- value = stored && JSON.parse(stored.meta_value);- recorded = events.length === 1 && events[0].event_by === COORDINATOR && JSON.parse(events[0].event_detail);- } catch { /* The same typed recovery covers malformed and incompatible records. */ }- if (!validBaseline(value) || !validBaseline(recorded)- || JSON.stringify(canonicalBaseline(value)) !== JSON.stringify(canonicalBaseline(recorded))) {- throw new Refused('SPEC_APPROVAL_BASELINE', 'the approval baseline is unreadable or disagrees with its original event; restore it from a known-good board export');- }- return value;-}++++export { specApprovalBaseline } from './board-query.js';/** Persist the first ordered snapshot once; later setup or competing replicas cannot expand it. */export function recordSpecApprovalBaseline(board, { agentId, baseline }) {diff --git a/src/spec-approval.js b/src/spec-approval.jsindex c1b9d78d..136a4878 100644--- a/src/spec-approval.js+++ b/src/spec-approval.js@@ -1,7 +1,7 @@/** Approval provenance: a status word is not a person's decision [S1,B26,P6]. */import { readFileSync } from 'node:fs';import { join } from 'node:path';-import * as store from './board.js';+import * as store from './board-query.js';import {gitReadSignature,tryGit,diff --git a/src/trunk-conflict.js b/src/trunk-conflict.jsindex 64fb2116..163ccf05 100644--- a/src/trunk-conflict.js+++ b/src/trunk-conflict.js@@ -11,7 +11,7 @@import {ENGINE_VERSION,SUBMITTED_CONFLICT_ENGINE,-} from './machine.js';+} from './engine-metadata.js';import { Refused } from './refused.js';import { CONFLICT_ENGINE } from './trunk-conflict-engine.js';diff --git a/src/verdict-freshness.js b/src/verdict-freshness.jsindex 1194ba2d..bea430bd 100644--- a/src/verdict-freshness.js+++ b/src/verdict-freshness.js@@ -1,6 +1,6 @@/** Acceptance stays append-only; freshness is derived from the known Git trunk [E8,V8]. */import { spawnSync } from 'node:child_process';-import * as store from './board.js';+import * as store from './board-query.js';import {cleanGitEnvironment,mainCheckout,diff --git a/test/machine.test.js b/test/machine.test.jsindex 4a13d59f..dce8ff24 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -556,7 +556,7 @@ test('a broken copy of the code fails the check: a refusal added wherever a move'NO_ROUTE is raised by reserve but not declared there',], 'reserve reaches the route check through the reviewer checks it shares with a verdict');- const doubleQuoted = editedSource('cli-context.js', /^(?:export )?const cdTo = .*$/m, "const cdTo = (root) => { if (!root) throw new Refused(\"NO_ROOT\", 'no root'); return 'cd ' + root + ' &&'; };");+ const doubleQuoted = editedSource('cli-read-context.js', /^(?:export )?const cdTo = .*$/m, "const cdTo = (root) => { if (!root) throw new Refused(\"NO_ROOT\", 'no root'); return 'cd ' + root + ' &&'; };");assert.deepEqual(codeProblems(MACHINE, doubleQuoted), ['NO_ROOT is raised by submit but not declared there','NO_ROOT is raised by accept and reject but not declared there',