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
docs: document versioned board formats
Corey Olson19a9dc9125e8
diff --git a/docs/formats.md b/docs/formats.mdnew file mode 100644index 00000000..d59cf884--- /dev/null+++ b/docs/formats.md@@ -0,0 +1,233 @@+# File formats++This page describes the text files people edit and the SQLite board kept inside `.git`. The row parser is in `src/spec.js`; board declarations and migrations are in `src/board.js`; lifecycle guards are generated from `src/machine.js`.++## SPEC.md and PRACTICE.md++Both files use the shared row grammar in `src/spec.js`, whose version is `SPEC_GRAMMAR_VERSION`. Either file may declare the current version on its own line as `<!-- pullboard-grammar N -->`; without a marker, the file uses the current grammar. A marker inside a fenced code example is ignored. The parser accepts only the version it reads and refuses a mismatched or invalid marker with `A5_GRAMMAR_VERSION`; upgrade Pullboard or use a file written for its grammar. Pullboard does not rewrite these files during an upgrade.++A section begins with `## `; a row must be beneath a section and occupies one line:++```text+- ID [status[, tier]] requirement text | gate: <command> | serves: <ID, ID> | signers: <principal, principal>+```++The identifier expression, statuses and tiers below come from the parser:++<!-- id-pattern:start -->+| Identifier | Parser expression |+| --- | --- |+| `ID` | `^[A-Za-z]+\d+(?:\.\d+)*$` |+<!-- id-pattern:end -->++<!-- statuses:start -->+| Status | Meaning |+| --- | --- |+| `approved` | decided and in force |+| `draft` | proposed, not decided |+| `pending` | open question |+| `fact` | true today |+| `wont` | not building; the row stays permanent |+| `retired` | no longer in force; the row stays permanent |+<!-- statuses:end -->++<!-- tiers:start -->+| Tier | Meaning |+| --- | --- |+| `must` | An approved must row names a gate. Other statuses may omit it. |+| `aim` | An aim; no gate is required. |+<!-- tiers:end -->++After the requirement text, `gate:` names the check, `serves:` names comma-separated ids, and `signers:` names comma-separated SSH principals; each field may be omitted. Signers must be unique and contain no spaces or commas, and list the exact principals required for signed sign-offs. Other trailing keys are recorded as unknown and rejected by `spec check`. A malformed row-like line is an error, and rows inside fenced code blocks are examples rather than input. IDs are permanent: mark a cut row `wont` or `retired` instead of deleting it.++The row object returned by `parseSpec` has these fields:++`parseSpec` also returns `grammarVersion`, equal to `SPEC_GRAMMAR_VERSION` after the file's marker has been checked.++<!-- parser-fields:start -->+| Parsed field | Meaning |+| --- | --- |+| `id` | Stable row identifier. |+| `status` | One token from the status list. |+| `tier` | Optional second token: must or aim. |+| `text` | Requirement text before trailing fields. |+| `gate` | Check named by gate, or an empty string. |+| `serves` | Comma-separated ids named by serves, or an empty list. |+| `signers` | Comma-separated SSH principals named by signers, or an empty list. |+| `unknown` | Unrecognized trailing fields; spec check reports them. |+| `section` | Containing ## heading. |+| `line` | 1-based source line. |+<!-- parser-fields:end -->++## SQLite board schema++The board file is in the repository's Git common directory at `.git/pullboard/board.sqlite`. File-backed connections use WAL mode, so `board.sqlite-wal` and `board.sqlite-shm` can sit beside it while connections are open. SQLite `PRAGMA user_version` records the board schema version; it also marks whether trigger repairs are reported in the event log. Schema objects are created from `src/board.js` when a board opens.++<!-- format-versions:start -->+| Format | Version | Version source | Upgrade rule |+| --- | --- | --- | --- |+| `CLI JSON envelope` | `1` | `JSON_SHAPES.version` in `src/json.js` | Keep optional fields additive within version 1; bump the envelope version for incompatible command/export shapes. |+| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means 1) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. |+| `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. |+| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`; event rows do not store a separate version marker | This append-only record format has its own version, independent of `SCHEMA_VERSION`. Preserve event rows when the board schema changes. |+<!-- format-versions:end -->++On open, Pullboard creates missing tables and indexes, then adds each missing column with `ALTER TABLE ... ADD COLUMN` and its declared default; it does not replace the board file or existing rows. It restores missing or changed declared triggers and removes stale `machine_` triggers. A board that already has its guard marker records trigger repair in a `guards` event, including missing, changed and stale trigger names; an older board receives the current marker after installation. Existing event rows are preserved.++The following live SQLite declarations include nullability, defaults, primary and unique keys, and foreign keys:++<!-- board-columns:start -->+| Table | Column | Type | Rules |+| --- | --- | --- | --- |+| `agent` | `agent_id` | `TEXT` | `PRIMARY KEY` |+| `agent` | `agent_lane` | `TEXT` | `NOT NULL` |+| `agent` | `agent_path` | `TEXT` | `NOT NULL`; `UNIQUE` |+| `agent` | `agent_last_shout_id` | `INTEGER` | `NOT NULL`; `DEFAULT 0` |+| `agent` | `agent_route` | `TEXT` | `NOT NULL`; `DEFAULT 'strong'` |+| `agent` | `agent_family` | `TEXT` | `nullable` |+| `agent` | `agent_created_at` | `TEXT` | `NOT NULL` |+| `board_meta` | `meta_key` | `TEXT` | `PRIMARY KEY` |+| `board_meta` | `meta_value` | `TEXT` | `NOT NULL` |+| `event` | `event_id` | `INTEGER` | `PRIMARY KEY` |+| `event` | `event_at` | `TEXT` | `NOT NULL` |+| `event` | `event_by` | `TEXT` | `NOT NULL` |+| `event` | `event_kind` | `TEXT` | `NOT NULL` |+| `event` | `item_id` | `INTEGER` | `nullable` |+| `event` | `event_detail` | `TEXT` | `NOT NULL`; `DEFAULT '{}'` |+| `hold` | `hold_lane` | `TEXT` | `PRIMARY KEY` |+| `hold` | `hold_reason` | `TEXT` | `NOT NULL` |+| `hold` | `hold_by` | `TEXT` | `NOT NULL` |+| `hold` | `hold_at` | `TEXT` | `NOT NULL` |+| `item` | `item_id` | `INTEGER` | `PRIMARY KEY` |+| `item` | `item_parent_id` | `INTEGER` | `nullable`; `REFERENCES item(item_id)` |+| `item` | `item_lane` | `TEXT` | `NOT NULL` |+| `item` | `item_title` | `TEXT` | `NOT NULL` |+| `item` | `item_criterion` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_spec_ids` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_after` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_brief` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_route` | `TEXT` | `NOT NULL`; `DEFAULT 'strong'` |+| `item` | `item_check` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_status` | `TEXT` | `NOT NULL`; `DEFAULT 'open'` |+| `item` | `item_owner` | `TEXT` | `nullable` |+| `item` | `item_lease_until` | `TEXT` | `nullable` |+| `item` | `item_frozen` | `TEXT` | `nullable` |+| `item` | `item_frozen_digest` | `TEXT` | `nullable` |+| `item` | `item_built_by` | `TEXT` | `nullable` |+| `item` | `item_builder_family` | `TEXT` | `nullable` |+| `item` | `item_commit` | `TEXT` | `nullable` |+| `item` | `item_tree` | `TEXT` | `nullable` |+| `item` | `item_verdict` | `TEXT` | `nullable` |+| `item` | `item_verified_by` | `TEXT` | `nullable` |+| `item` | `item_merged_commit` | `TEXT` | `nullable` |+| `item` | `item_withdrawn_reason` | `TEXT` | `nullable` |+| `item` | `item_created_by` | `TEXT` | `NOT NULL` |+| `item` | `item_created_at` | `TEXT` | `NOT NULL` |+| `item` | `item_updated_at` | `TEXT` | `NOT NULL` |+| `item` | `item_claim_head` | `TEXT` | `nullable` |+| `item` | `item_files` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `item` | `item_review_by` | `TEXT` | `nullable` |+| `item` | `item_review_until` | `TEXT` | `nullable` |+| `shout` | `shout_id` | `INTEGER` | `PRIMARY KEY` |+| `shout` | `shout_from` | `TEXT` | `NOT NULL` |+| `shout` | `shout_to` | `TEXT` | `NOT NULL` |+| `shout` | `shout_text` | `TEXT` | `NOT NULL` |+| `shout` | `shout_at` | `TEXT` | `NOT NULL` |+| `shout` | `shout_decision` | `INTEGER` | `NOT NULL`; `DEFAULT 0` |+| `shout` | `shout_answers` | `INTEGER` | `nullable` |+| `shout` | `shout_evidence_kind` | `TEXT` | `nullable` |+| `shout` | `shout_evidence_outcome` | `TEXT` | `nullable` |+| `shout` | `shout_evidence_item` | `INTEGER` | `nullable` |+| `shout` | `shout_evidence_commit` | `TEXT` | `nullable` |+| `shout` | `shout_request` | `INTEGER` | `NOT NULL`; `DEFAULT 0` |+| `shout` | `shout_request_outcome` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `verdict` | `verdict_id` | `INTEGER` | `PRIMARY KEY` |+| `verdict` | `item_id` | `INTEGER` | `NOT NULL`; `REFERENCES item(item_id)` |+| `verdict` | `verdict_by` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_verifier_family` | `TEXT` | `nullable` |+| `verdict` | `verdict_decision` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_reason` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_note` | `TEXT` | `NOT NULL`; `DEFAULT ''` |+| `verdict` | `verdict_commit` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_digest` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_head` | `TEXT` | `NOT NULL` |+| `verdict` | `verdict_at` | `TEXT` | `NOT NULL` |+<!-- board-columns:end -->++<!-- board-indexes:start -->+| Index | Table | Columns | Unique |+| --- | --- | --- | --- |+| `item_lane_status` | `item` | `item_lane`, `item_status` | no |+<!-- board-indexes:end -->++`src/machine.js` declares the lifecycle and retained records. `src/board.js` installs these persistent triggers in the board file:++<!-- board-triggers:start -->+| Trigger | Table |+| --- | --- |+| `machine_event_delete` | `event` |+| `machine_event_update` | `event` |+| `machine_fields_claimed` | `item` |+| `machine_fields_submitted` | `item` |+| `machine_fields_verified` | `item` |+| `machine_fields_withdrawn` | `item` |+| `machine_item_delete` | `item` |+| `machine_item_move` | `item` |+| `machine_item_start` | `item` |+| `machine_item_state` | `item` |+| `machine_proof_verified` | `item` |+| `machine_verdict_delete` | `verdict` |+| `machine_verdict_update` | `verdict` |+<!-- board-triggers:end -->++`machine_item_start`, `machine_item_state` and `machine_item_move` guard lifecycle states and moves. `machine_fields_*` requires each state's fields; `machine_proof_*` requires its proof. `machine_item_delete` keeps item rows, while `machine_verdict_*` and `machine_event_*` make those records append-only.++Each connection also has a temporary `moving(token INTEGER)` table and `status_through_moves` trigger. The trigger allows status changes only while `moveItem` holds the token; these objects are not stored in the board file.++<!-- temp-columns:start -->+| Table | Column | Type | Rules |+| --- | --- | --- | --- |+| `moving` | `token` | `INTEGER` | `nullable` |+<!-- temp-columns:end -->++<!-- temp-triggers:start -->+| Trigger | Table |+| --- | --- |+| `status_through_moves` | `item` |+<!-- temp-triggers:end -->++## Event log++The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its append-only record format has the independent `EVENT_LOG_VERSION`. Each event has an increasing integer id, an ISO timestamp, the actor, the event kind, an optional item id, and a JSON object in `event_detail`. Board moves append their event inside the same immediate transaction as the move. Events are append-only; board triggers reject updates and deletes. The actor column is the acting agent id, except guard-repair events, which use `board`. The following rows name the emitted kinds and the union of their detail keys:++<!-- events:start -->+| Kind | Actor | Detail fields |+| --- | --- | --- |+| `join` | joining agent | `lane`, `route` |+| `family` | agent | `family` |+| `moved` | coordinator | `path` |+| `add` | item creator | `lane`, `specIds`, `after`, `route` |+| `edit` | editor | `brief`, `route`, `criterion`, `check`, `unfrozen` |+| `escalate` | builder | `from`, `to`, `note`, `attempt` |+| `attempt` | reporting agent | `n`, `seconds`, `result` |+| `claim` | builder | `leaseUntil`, `digest` |+| `renew` | builder | `leaseUntil`, `digest` |+| `release` | builder | — |+| `submit` | builder | `commit`, `tree` |+| `reserve` | reviewer | `until` |+| `accept` | reviewer | `reason`, `commit` |+| `reject` | reviewer | `reason`, `commit` |+| `merged` | coordinator | `commit` |+| `withdraw` | coordinator | `reason` |+| `refreeze` | coordinator | `before`, `after` |+| `hold` | coordinator | `lane`, `reason` |+| `unhold` | coordinator | `lane` |+| `guards` | board | `missing`, `changed`, `stale` |+| `shout` | sender | `shout`, `to`, `decision`, `request`, `answers` |+| `pass` | coordinator | `shout`, `to`, `decision`, `request`, `answers` |+| `answer` | answerer | `shout`, `to`, `decision`, `request`, `answers`, `outcome` |+<!-- events:end -->++Migration preserves event rows and adds only schema objects that are missing.++The schema, trigger and parser tables in this guide are checked against live `openBoard(':memory:')` and `parseSpec` results by `docs/formats.test.js`.diff --git a/docs/formats.test.js b/docs/formats.test.jsnew file mode 100644index 00000000..87e0946b--- /dev/null+++ b/docs/formats.test.js@@ -0,0 +1,346 @@+/** Keep the format guide aligned with parser behavior and the live SQLite schema [A5]. */+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+import { COORDINATOR } from '../src/config.js';+import { JSON_SHAPES } from '../src/json.js';+import {+ ACCEPT_REASON,+ answerDecision,+ addItem,+ claim,+ closeBoard,+ editItem,+ EVENT_LOG_VERSION,+ ensureCoordinator,+ escalate,+ events,+ holdLane,+ merged,+ openBoard,+ passDecision,+ PERSON,+ recordAttempt,+ refreeze,+ register,+ release,+ releaseLane,+ reserveReview,+ SCHEMA_VERSION,+ submit,+ shout,+ verify,+ withdraw,+} from '../src/board.js';+import { ID_RE, SPEC_GRAMMAR_VERSION, STATUSES, TIERS, lintSpec, parseSpec } from '../src/spec.js';++const guide = readFileSync(new URL('./formats.md', import.meta.url), 'utf8');++/** Return the text inside a named marked documentation block. */+function block(start, end) {+ const begin = guide.indexOf(start);+ const finish = guide.indexOf(end, begin + start.length);+ assert.notEqual(begin, -1, `guide has block start ${start}`);+ assert.notEqual(finish, -1, `guide has block end ${end}`);+ return guide.slice(begin + start.length, finish);+}++/** Read names from the first code-formatted cell of each row in a marked table. */+function listedValues(start, end) {+ return block(start, end).split(/\r?\n/).flatMap((line) => {+ const match = /^\| `([^`]+)` \|/.exec(line);+ return match ? [match[1]] : [];+ });+}++/** Parse table, column, type and rules from the documented live schema. */+function documentedColumns(start, end) {+ const result = {};+ for (const line of block(start, end).split(/\r?\n/)) {+ const row = /^\| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| (.+) \|$/.exec(line);+ if (!row) continue;+ const [, table, column, type, cell] = row;+ const fields = result[table] ?? [];+ fields.push({ column, type, rules: [...cell.matchAll(/`([^`]+)`/g)].map((match) => match[1]) });+ result[table] = fields;+ }+ return result;+}++/** Describe live columns from SQLite's null, default, key and reference metadata. */+function liveColumns(db, schema) {+ const tables = db.prepare(`SELECT name FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`).all();+ return Object.fromEntries(tables.map(({ name }) => {+ const columns = db.prepare(`PRAGMA ${schema}.table_info(${name})`).all();+ const foreignKeys = db.prepare(`PRAGMA ${schema}.foreign_key_list(${name})`).all();+ const indexes = db.prepare(`PRAGMA ${schema}.index_list(${name})`).all();+ const uniqueColumns = indexes.filter((index) => index.unique && index.origin !== 'pk')+ .flatMap((index) => db.prepare(`PRAGMA ${schema}.index_info(${index.name})`).all())+ .map((column) => column.name);+ return [name, columns.map((column) => {+ const rules = [];+ if (column.pk) rules.push('PRIMARY KEY');+ else rules.push(column.notnull ? 'NOT NULL' : 'nullable');+ if (column.dflt_value !== null) rules.push(`DEFAULT ${column.dflt_value}`);+ if (uniqueColumns.includes(column.name)) rules.push('UNIQUE');+ for (const foreignKey of foreignKeys.filter((key) => key.from === column.name)) {+ rules.push(`REFERENCES ${foreignKey.table}(${foreignKey.to})`);+ }+ return { column: column.name, type: column.type, rules };+ })];+ }));+}++/** Read persistent and connection-local trigger declarations from SQLite. */+function liveTriggers(db, schema) {+ return db.prepare(`SELECT name, tbl_name FROM ${schema}.sqlite_master WHERE type = 'trigger' ORDER BY name`)+ .all().map(({ name, tbl_name }) => [name, tbl_name]);+}++/** Parse documented persistent or temporary trigger names and target tables. */+function documentedTriggers(start, end) {+ return block(start, end).split(/\r?\n/).flatMap((line) => {+ const row = /^\| `([^`]+)` \| `([^`]+)` \|$/.exec(line);+ return row ? [[row[1], row[2]]] : [];+ });+}++/** Read named indexes and their fields from the live database. */+function liveIndexes(db) {+ const indexes = db.prepare("SELECT name, tbl_name FROM main.sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%' ORDER BY name").all();+ return indexes.map(({ name, tbl_name }) => ({+ name,+ table: tbl_name,+ columns: db.prepare(`PRAGMA main.index_info(${name})`).all().map((column) => column.name),+ unique: db.prepare(`PRAGMA main.index_list(${tbl_name})`).all().find((index) => index.name === name).unique ? 'yes' : 'no',+ }));+}++/** Parse documented columns for an index. */+function documentedIndexes() {+ return block('<!-- board-indexes:start -->', '<!-- board-indexes:end -->').split(/\r?\n/).flatMap((line) => {+ const row = /^\| `([^`]+)` \| `([^`]+)` \| (.+) \| (yes|no) \|$/.exec(line);+ return row ? [{ name: row[1], table: row[2], columns: [...row[3].matchAll(/`([^`]+)`/g)].map((match) => match[1]), unique: row[4] }] : [];+ });+}++/** Exercise each board event through the public API and return the rows it actually records. */+function recordEventContract() {+ const board = openBoard(':memory:');+ const coordinator = ensureCoordinator(board, '/coordinator');+ const builder = register(board, { lane: 'docs', path: '/builder' });+ register(board, { lane: 'docs', path: '/builder', family: 'codex' });+ const reviewer = register(board, { lane: 'tests', path: '/reviewer' });+ register(board, { lane: 'small', path: '/small', route: 'light' });+ ensureCoordinator(board, '/coordinator-moved');+ shout(board, { from: builder, to: 'all', text: 'sample announcement', lanes: ['docs', 'tests'] });+ const passed = shout(board, { from: builder, to: coordinator, text: 'sample decision', lanes: ['docs', 'tests'], decision: true });+ passDecision(board, passed, { agentId: coordinator, note: 'ask the person', lanes: ['docs', 'tests'] });+ const personQuestion = shout(board, { from: coordinator, to: PERSON, text: 'sample person decision', lanes: ['docs', 'tests'], decision: true });+ answerDecision(board, personQuestion, { agentId: coordinator, text: 'approved', lanes: ['docs', 'tests'], asPerson: true });+ const request = shout(board, { from: PERSON, to: coordinator, text: 'sample request', lanes: ['docs', 'tests'], request: true });+ answerDecision(board, request, { agentId: coordinator, text: 'done', lanes: ['docs', 'tests'] });+ const freeze = (digest) => () => ({ text: `criterion-${digest}`, digest });+ const first = addItem(board, { by: coordinator, lane: 'docs', title: 'Accepted example', criterion: 'Initial', specIds: ['A1'], route: 'strong' });+ editItem(board, first, { agentId: coordinator, brief: 'Files: docs/formats.md\nTest: docs/formats.test.js', route: 'mid', criterion: 'Changed', check: 'node test' });+ recordAttempt(board, first, { agentId: builder, n: 1, seconds: 2, result: 'failed' });+ claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('first') });+ claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('unused') });+ escalate(board, first, { agentId: builder, note: 'attempted once', attempt: '1' });+ claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('unused') });+ release(board, first, builder);+ editItem(board, first, { agentId: coordinator, criterion: 'Updated after claim' });+ refreeze(board, first, { agentId: coordinator, freeze: freeze('second') });+ claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('unused') });+ const acceptedCommit = 'a'.repeat(40);+ submit(board, first, { agentId: builder, commit: acceptedCommit, tree: 'b'.repeat(40), files: ['docs/formats.md'] });+ reserveReview(board, first, { agentId: reviewer, leaseMs: 60_000, policy: 'agents' });+ verify(board, first, { agentId: reviewer, decision: 'ACCEPT', reason: ACCEPT_REASON, note: 'checked the example', head: acceptedCommit, digest: 'second', policy: 'agents' });+ merged(board, first, { agentId: coordinator, commit: 'c'.repeat(40) });++ const rejected = addItem(board, { by: coordinator, lane: 'docs', title: 'Rejected example' });+ claim(board, rejected, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('rejected') });+ const rejectedCommit = 'd'.repeat(40);+ submit(board, rejected, { agentId: builder, commit: rejectedCommit, tree: 'e'.repeat(40) });+ verify(board, rejected, { agentId: reviewer, decision: 'REJECT', reason: 'TEST_FAILURE', note: 'the fixture failed', head: rejectedCommit, digest: 'rejected', policy: 'agents' });++ const withdrawn = addItem(board, { by: coordinator, lane: 'docs', title: 'Withdrawn example' });+ withdraw(board, withdrawn, { agentId: coordinator, reason: 'duplicate fixture' });+ holdLane(board, 'view', { agentId: coordinator, reason: 'fixture hold' });+ releaseLane(board, 'view', { agentId: coordinator });+ const rows = events(board).map((row) => ({ ...row, detail: JSON.parse(row.event_detail) }));+ closeBoard(board);+ return { rows, actors: { [coordinator]: 'coordinator', [builder]: 'builder', [reviewer]: 'reviewer', board: 'board' } };+}++/** Reopen a file after removing old-format objects and report the repaired guard event. */+function exerciseUpgrade() {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-formats-'));+ const file = join(directory, 'board.sqlite');+ let board;+ try {+ board = openBoard(file);+ assert.equal(board.db.prepare('PRAGMA user_version').get().user_version, SCHEMA_VERSION,+ 'opening an older board advances its schema version in place');+ ensureCoordinator(board, join(directory, 'coordinator'));+ addItem(board, { by: COORDINATOR, lane: 'docs', title: 'Preserved row' });+ assert.equal(board.db.prepare('PRAGMA journal_mode').get().journal_mode, 'wal');+ const originalEvents = events(board).length;+ closeBoard(board);+ board = null;++ const old = new DatabaseSync(file);+ old.exec('ALTER TABLE shout DROP COLUMN shout_evidence_kind; DROP TABLE hold; DROP INDEX item_lane_status; DROP TRIGGER machine_event_update; CREATE TRIGGER machine_old_extra AFTER INSERT ON item BEGIN SELECT 1; END; PRAGMA user_version = 1;');+ old.close();++ board = openBoard(file);+ assert.equal(board.db.prepare("SELECT item_title FROM item").get().item_title, 'Preserved row');+ assert.ok(board.db.prepare('PRAGMA table_info(shout)').all().some((column) => column.name === 'shout_evidence_kind'));+ assert.ok(board.db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'hold'").get());+ assert.ok(board.db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'item_lane_status'").get());+ assert.equal(board.db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'machine_old_extra'").get(), undefined);+ const repair = events(board).find((row) => row.event_kind === 'guards');+ assert.ok(repair, 'reopening reports repaired/missing/stale guards in the event log');+ assert.equal(events(board).length, originalEvents + 1, 'reopening preserves old events and appends one guard-repair event');+ assert.deepEqual(JSON.parse(repair.event_detail), {+ missing: ['machine_event_update'], changed: [], stale: ['machine_old_extra'],+ });+ return events(board).map((row) => ({ ...row, detail: JSON.parse(row.event_detail) }));+ } finally {+ if (board) closeBoard(board);+ rmSync(directory, { recursive: true, force: true });+ }+}++/** Parse the event manifest and compare it with event rows produced by real board operations. */+function documentedEvents() {+ const lines = block('<!-- events:start -->', '<!-- events:end -->').split(/\r?\n/);+ const result = {};+ for (const line of lines) {+ const row = /^\| `([^`]+)` \| ([^|]+) \| (.+) \|$/.exec(line);+ if (!row) continue;+ const [, kind, actor, fields] = row;+ result[kind] = { actor: actor.trim(), fields: [...fields.matchAll(/`([^`]+)`/g)].map((match) => match[1]).sort() };+ }+ return result;+}++test('[A5] the grammar table describes values the parser actually reads', () => {+ assert.equal(ID_RE.source, '^[A-Za-z]+\\d+(?:\\.\\d+)*$');+ assert.deepEqual(listedValues('<!-- statuses:start -->', '<!-- statuses:end -->'), STATUSES);+ assert.deepEqual(listedValues('<!-- tiers:start -->', '<!-- tiers:end -->'), TIERS);++ const source = [+ '# Example',+ 'intro before a section',+ '## Sample section',+ '- A1 [approved, must] Requirement text. | gate: node test | serves: B2, C3 | signers: [email protected], AB | custom: preserved',+ ].join('\n');+ const parsed = parseSpec(source);+ assert.equal(parsed.sections[0].name, 'Sample section');+ assert.deepEqual(parsed.rows[0], {+ id: 'A1', status: 'approved', tier: 'must', text: 'Requirement text.', gate: 'node test',+ serves: ['B2', 'C3'], signers: ['[email protected]', 'AB'], unknown: ['custom: preserved'], section: 'Sample section', line: 4,+ });+ assert.deepEqual(listedValues('<!-- parser-fields:start -->', '<!-- parser-fields:end -->'), Object.keys(parsed.rows[0]));+ assert.match(guide, /\| gate: <command> \| serves: <ID, ID> \| signers: <principal, principal>/);++ const noTier = parseSpec('## Plain\n- A1 [draft] Row without a tier.\n');+ assert.equal(noTier.rows[0].tier, '');+ assert.deepEqual(lintSpec(parseSpec('## Must\n- A1 [approved, must] Must names a gate.\n')).filter((finding) => finding.level === 'error').map((finding) => finding.message), [+ 'an approved must-row names its gate: | gate: <the test or check that proves it>',+ ]);+});++test('[A5] SPEC.md and PRACTICE.md use the exported grammar version', () => {+ assert.equal(SPEC_GRAMMAR_VERSION, 1);+ const versions = block('<!-- format-versions:start -->', '<!-- format-versions:end -->');+ const versionOf = (name) => {+ const match = new RegExp('^\\| `' + name + '` \\| `(\\d+)` \\|', 'm').exec(versions);+ assert.ok(match, `guide declares ${name} version`);+ return Number(match[1]);+ };+ assert.equal(versionOf('CLI JSON envelope'), JSON_SHAPES.version);+ assert.equal(versionOf('row grammar'), SPEC_GRAMMAR_VERSION);+ assert.equal(versionOf('board schema'), SCHEMA_VERSION);+ assert.equal(versionOf('event log'), EVENT_LOG_VERSION);+ assert.match(versions, /`SPEC_GRAMMAR_VERSION`/);+ assert.match(versions, /`JSON_SHAPES\.version`/);+ assert.match(versions, /`SCHEMA_VERSION`/);+ assert.match(versions, /`EVENT_LOG_VERSION`/);++ for (const file of ['SPEC.md', 'PRACTICE.md']) {+ const body = `## Sample\n- A1 [draft] Row text.\n`;+ assert.equal(parseSpec(body).grammarVersion, SPEC_GRAMMAR_VERSION, `${file} without a marker defaults to the current grammar`);+ assert.equal(parseSpec(`<!-- pullboard-grammar ${SPEC_GRAMMAR_VERSION} -->\n${body}`).grammarVersion, SPEC_GRAMMAR_VERSION, `${file} accepts the current marker`);+ assert.throws(+ () => parseSpec(`<!-- pullboard-grammar ${SPEC_GRAMMAR_VERSION + 1} -->\n${body}`),+ (error) => error?.code === 'A5_GRAMMAR_VERSION'+ && error.message.includes(`grammar ${SPEC_GRAMMAR_VERSION + 1}`)+ && error.message.includes(`reads grammar ${SPEC_GRAMMAR_VERSION}`)+ && error.message.includes('upgrade Pullboard'),+ `${file} refuses a different declared grammar with a usable next step`,+ );+ assert.throws(() => parseSpec(`<!-- pullboard-grammar invalid -->\n${body}`), (error) => error?.code === 'A5_GRAMMAR_VERSION', `${file} refuses an invalid marker`);+ assert.equal(parseSpec(`\`\`\`text\n<!-- pullboard-grammar ${SPEC_GRAMMAR_VERSION + 1} -->\n\`\`\`\n${body}`).grammarVersion, SPEC_GRAMMAR_VERSION, `${file} ignores a marker in a fenced example`);+ }+});++test('[A5] schema, versions, event kinds and event detail fields match live behavior', () => {+ const board = openBoard(':memory:');+ try {+ const version = board.db.prepare('PRAGMA user_version').get().user_version;+ assert.equal(version, SCHEMA_VERSION);+ assert.deepEqual(documentedColumns('<!-- board-columns:start -->', '<!-- board-columns:end -->'), liveColumns(board.db, 'main'));+ assert.deepEqual(documentedColumns('<!-- temp-columns:start -->', '<!-- temp-columns:end -->'), liveColumns(board.db, 'temp'));+ assert.deepEqual(documentedTriggers('<!-- board-triggers:start -->', '<!-- board-triggers:end -->'), liveTriggers(board.db, 'main'));+ assert.deepEqual(documentedTriggers('<!-- temp-triggers:start -->', '<!-- temp-triggers:end -->'), liveTriggers(board.db, 'temp'));+ assert.deepEqual(documentedIndexes(), liveIndexes(board.db));+ const versions = block('<!-- format-versions:start -->', '<!-- format-versions:end -->');+ const versionOf = (name) => {+ const match = new RegExp('^\\| `' + name + '` \\| `(\\d+)` \\|', 'm').exec(versions);+ assert.ok(match, `guide declares ${name} version`);+ return Number(match[1]);+ };+ assert.equal(versionOf('CLI JSON envelope'), JSON_SHAPES.version);+ assert.equal(versionOf('row grammar'), SPEC_GRAMMAR_VERSION);+ assert.equal(versionOf('board schema'), SCHEMA_VERSION);+ assert.equal(versionOf('event log'), EVENT_LOG_VERSION);+ } finally {+ closeBoard(board);+ }++ const { rows, actors } = recordEventContract();+ const repairedRows = exerciseUpgrade();+ const actualRows = [...rows, ...repairedRows];+ const actual = {};+ const actorByKind = {+ join: 'joining agent',+ family: 'agent',+ moved: 'coordinator',+ add: 'item creator',+ edit: 'editor',+ attempt: 'reporting agent',+ guards: 'board',+ shout: 'sender',+ pass: 'coordinator',+ answer: 'answerer',+ };+ for (const row of actualRows) {+ const kind = row.event_kind;+ const entry = actual[kind] ?? { actors: new Set(), fields: new Set() };+ const actor = actorByKind[kind] ?? actors[row.event_by] ?? 'unknown';+ entry.actors.add(actor);+ for (const field of Object.keys(row.detail)) entry.fields.add(field);+ actual[kind] = entry;+ }+ const documented = documentedEvents();+ assert.deepEqual(Object.keys(documented).sort(), Object.keys(actual).sort());+ for (const [kind, expected] of Object.entries(documented)) {+ assert.deepEqual([...actual[kind].actors].sort(), [expected.actor]);+ assert.deepEqual([...actual[kind].fields].sort(), expected.fields);+ }+});