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
chore(merge): integrate accepted frozen verify policy [H16,O2]
Corey Olson682c00347185
diff --cc docs/formats.mdindex c6dae437,399f3d54..5bf2728d--- a/docs/formats.md+++ b/docs/formats.md@@@ -257,7 -260,17 +260,17 @@@ The `event` table is a SQLite schema ob| `row_apply` | coordinator | `events` |<!-- events:end -->+ A CLI `accept` event includes `check: "none"` when no frozen item check ran or `check: "green"` when it passed. Older accept events and records without this field read as `unknown`; the result stays in event detail and does not change the board schema or event-log version.++ Item facts use the existing append-only `event` table and event-log version 1. A `fact` event's actor and timestamp stamp its author and time; its detail carries a stable string `id`, typed `kind`, exact `text`, optional `ref` binding or `null`, and superseded fact id or `null`. Allowed kinds are `capture`, `measurement`, `note`, `diff`, `decision`, `rejection`, `supersession` and `root-cause`. Judgement kinds and any correction using `supersedes` require the item's live holder or the coordinator. A correction must refer to a fact on the same item; it adds a new event and preserves every earlier fact.++ A binding is `{path, start, end, commit}`: a relative repository path, a positive ascending inclusive line range and a full 40-character hexadecimal commit id. It identifies code without storing source or requiring Git on a replica. Fact ids are generated UUIDs locally. A sealed `appendFact` operation uses its executable move id as its fact id, so replicas keep corrections bound to the same fact even when local event sequence ids differ. Native export/import retains these event rows without a separate fact table or schema upgrade.++ The derived `thread` in CLI `show` JSON and API v1 item state is an array in ascending event order. Move entries are `{type: "move", eventId, kind, by, at, detail}`. Fact entries are `{type: "fact", id, eventId, kind, text, by, at, ref, supersedes}`. `eventId` is the board's numeric event sequence; `id` is the stable fact identity used by corrections. `by` and `at` come from the immutable event author and UTC timestamp. `detail` retains a move's original structured payload. Nullable `ref` and `supersedes` preserve omitted fields as `null`. Superseded facts remain in the array beside their corrections.++ Engine version 3 adds the sealed `appendFact` operation. It is the single engine increment reserved for the release after 0.7.0; other changes in that release reuse version 3. Older supported operations remain replayable; an older client refuses a version-3 move before applying it. The sealed envelope, CLI/API envelope, schema and event-log layout versions are unchanged.+-New CLI claims include a `policy` object (`version: 1`, `commit`) in the frozen criterion. It pins the coordinator checkout’s committed configuration on its attached main branch. A temporary detached review checkout refuses new policy-dependent claims or project gates with `NO_POLICY`; the coordinator returns to its main branch. Existing frozen submissions remain verifiable. Legacy claims use their recorded claim-base commit. A CLI `submit` records the pre-merge coordinator HEAD as optional `policyCommit`; historical doctor and acceptance checks use this snapshot when allowing unchanged foreign files brought in from MAIN. Verified dependencies may also contribute unchanged files in their own lanes before a MAIN merge; foreign deletion or replacement is not authorized by an unrelated dependency’s tree. The complete candidate diff against both claim base and frozen MAIN is checked with rename detection disabled, preserving deleted paths and whitespace in names. Frozen item checks run against the exact submitted commit in an isolated checkout when accepting and auditing; repairing a reviewer’s checkout cannot make a red submission green.+New CLI claims include a `policy` object (`version: 1`, `commit`, `verify: { policy, family }`) in the frozen criterion. It pins the coordinator checkout’s committed configuration on its attached main branch and captures that commit’s verification and family rules. Relay verification uses those shared frozen values, ignoring policy values supplied by the sealed move; missing or invalid captured values produce `NO_POLICY` with an explicit refreeze step. An ordinary criterion recheck preserves legacy frozen bytes and their digest. An explicit refreeze captures the pinned commit’s verification rules and establishes a new digest. A temporary detached review checkout refuses new policy-dependent claims or project gates with `NO_POLICY`; the coordinator returns to its main branch. Existing frozen submissions remain verifiable. Legacy claims use their recorded claim-base commit. A CLI `submit` records the pre-merge coordinator HEAD as optional `policyCommit`; historical doctor and acceptance checks use this snapshot when allowing unchanged foreign files brought in from MAIN. Verified dependencies may also contribute unchanged files in their own lanes before a MAIN merge; foreign deletion or replacement is not authorized by an unrelated dependency’s tree. The complete candidate diff against both claim base and frozen MAIN is checked with rename detection disabled, preserving deleted paths and whitespace in names. Frozen item checks run against the exact submitted commit in an isolated checkout when accepting and auditing; repairing a reviewer’s checkout cannot make a red submission green.Person answer events additionally record their `channel`, either `terminal` or `view`, including the forwarded answer to the original asker. Agent answers omit that field.diff --cc src/cli.jsindex a7b1dec4,8ef4d045..6e32b967--- a/src/cli.js+++ b/src/cli.js@@@ -54,9 -54,9 +54,9 @@@ import { listResources } from './resourimport { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { exportView, serveView } from './serve.js';import { serveApi } from './api.js';- import { doctorProblems } from './doctor.js';+ import { doctorProblems, doctrineProblems } from './doctor.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';-import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';+import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';diff --cc src/engine.jsindex 8b8e821a,aa913388..837b87d6--- a/src/engine.js+++ b/src/engine.js@@@ -81,8 -87,12 +87,12 @@@ function validateMove(move)}/** Restore only the frozen criterion callback; no receiver runs another machine's Git or shell. */-function executableArgs(move) {+function executableArgs(move, board) {const args = structuredClone(move.args);+ if (move.operation === 'appendFact') {+ if (!args[1] || typeof args[1] !== 'object' || Array.isArray(args[1])) throw new Refused('RELAY_MOVE', 'a fact needs its typed arguments; use the current Pullboard engine');+ args[1].factId = move.id;+ }if (['claim', 'refreeze'].includes(move.operation)) {const options = args[1];if (!options || !Object.hasOwn(options, 'frozen')) throw new Refused('RELAY_MOVE', 'the claim has no frozen criterion; send it with the current pullboard engine');@@@ -172,7 -168,11 +183,11 @@@ export function applyEngineMove(board,board.clock = { now: () => new Date(at) };const firstEvent = board.emittedEvents?.length ?? 0;try {- const result = store.atomic(board, () => store[move.operation](board, ...executableArgs(move, board)));+ const result = store.atomic(board, () => {+ const problem = requestMoveProblem(board, move);+ if (problem) throw problem;- return store[move.operation](board, ...executableArgs(move));++ return store[move.operation](board, ...executableArgs(move, board));+ });outcome = { result: result ?? null, events: (board.emittedEvents?.slice(firstEvent) ?? []).map((event) => ({ ...event })) };} catch (error) {if (!(error instanceof Refused)) throw error;diff --cc test/relay-sealed.test.jsindex 50b569f4,46ed25f3..bd0a3f34--- a/test/relay-sealed.test.js+++ b/test/relay-sealed.test.js@@@ -1,11 -1,11 +1,12 @@@/** Two real clients and encrypted CLI records exercise the relay without sharing their key [A4,H7]. */import assert from 'node:assert/strict';-import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';-import { spawn, spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';+import { delimiter, join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+ import { createServer } from 'node:http';-import { join, resolve } from 'node:path';import { test } from 'node:test';import { serveRelay } from '../relay/service.js';import { createRelayAuth } from '../relay/auth.js';@@@ -113,41 -105,127 +114,162 @@@ function replayClient(root, env, ...arg});}+/** Replay through the native CLI while acknowledging but suppressing checkpoint writes to the fixture relay. */+function replayClientWithoutCheckpoint(root, env) {+ const cliURL = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;+ const script = `+ import { main } from ${JSON.stringify(cliURL)};+ const realFetch = globalThis.fetch;+ let checkpointWrites = 0;+ globalThis.fetch = async (input, init = {}) => {+ const url = typeof input === 'string' ? input : input.url;+ if (init.method === 'PUT' && /\\/state(?:\\?|$)/.test(url)) {+ checkpointWrites += 1;+ return new Response(JSON.stringify({ version: 1, state: JSON.parse(init.body) }), { status: 200, headers: { 'content-type': 'application/json' } });+ }+ return realFetch(input, init);+ };+ let output = '';+ let diagnostics = '';+ const code = await main(['export', '--json'], { cwd: process.cwd(), stdout: { write(part) { output += part; } }, stderr: { write(part) { diagnostics += part; } } });+ console.log(JSON.stringify({ code, checkpointWrites, document: JSON.parse(output), diagnosticCount: diagnostics.length }));+ `;+ return new Promise((done, fail) => {+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ child.stderr.resume();+ child.once('error', error => { clearTimeout(timer); fail(error); });+ child.once('close', code => {+ clearTimeout(timer);+ if (code !== 0) return fail(new Error('isolated native client failed during checkpoint-suppressed replay'));+ try { done(JSON.parse(stdout)); } catch { fail(new Error('checkpoint-suppressed native client returned invalid JSON')); }+ });+ });+}++ /** Keep each client on its own replay path by blocking checkpoint publication, forwarding all reads to the real relay. */+ async function independentReplayOrigin(t, origin) {+ const proxy = createServer(async (request, response) => {+ if (request.method === 'PUT' && request.url.endsWith('/state')) {+ response.writeHead(403, { 'content-type': 'application/json' });+ response.end(JSON.stringify({ version: 1, error: { code: 'HUMAN_REQUIRED', message: 'fixture checkpoint publication disabled' } }));+ return;+ }+ try {+ const reply = await fetch(origin + request.url, { headers: { authorization: request.headers.authorization ?? '' } });+ response.writeHead(reply.status, { 'content-type': 'application/json' });+ response.end(Buffer.from(await reply.arrayBuffer()));+ } catch {+ response.writeHead(502, { 'content-type': 'application/json' });+ response.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture relay unavailable' } }));+ }+ });+ await new Promise((done, fail) => { proxy.once('error', fail); proxy.listen(0, '127.0.0.1', done); });+ t.after(() => new Promise(done => proxy.close(done)));+ return 'http://127.0.0.1:' + proxy.address().port;+ }++ /** Capture a real linked command's warnings and structured refusal without changing its exit status. */+ function replayResult(root, env, ...args) {+ return new Promise((done, fail) => {+ const child = spawn(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '', stderr = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ child.stderr.setEncoding('utf8').on('data', part => { stderr += part; });+ child.once('error', error => { clearTimeout(timer); fail(error); });+ child.once('close', code => {+ clearTimeout(timer);+ if (code === null) return fail(new Error('isolated relay command did not finish'));+ try { done({ document: JSON.parse(stdout), stderr, status: code }); }+ catch { fail(new Error('isolated relay read did not return JSON')); }+ });+ });+ }++ test('two real clients stop before sender checks for newer operations and actor layouts without advancing [H16]', async t => {+ const unknown = { version: 1, engine: 4, id: 'future-operation', operation: 'futureOp', args: [{ agentId: 'remote-1' }] };+ const shifted = { version: 1, engine: 4, id: 'future-claim', operation: 'claim', args: [1, {}, { agentId: 'remote-1' }] };+ for (const [name, moves] of [['new operation', [unknown]], ['new actor layout', [shifted]], ['current engine sender checks', [unknown, shifted].map(move => ({ ...move, engine: 3 }))]]) {+ await t.test(name, async sub => {+ const box = await fixture(sub);+ const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ let document;+ try {+ checkpointSequence(source, 0);+ document = JSON.parse(JSON.stringify(exportBoard(source)));+ } finally { store.closeBoard(source); }+ const remote = await box.auth.issueToken(box.person.token, { board: box.id, agent: 'remote-1' });+ const roots = [box.root, join(box.directory, 'second-client')];+ const homes = [box.home, join(box.directory, 'second-home')];+ const envs = homes.map(home => ({ ...box.env, HOME: home, PULLBOARD_HOME: home }));+ mkdirSync(roots[1]); mkdirSync(homes[1], { mode: 0o700 });+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: roots[1], env: envs[1] }).status, 0);+ await replayClient(roots[1], envs[1], 'init');+ const native = join(box.directory, 'native.json');+ writeFileSync(native, JSON.stringify(document), { mode: 0o600 });+ await replayClient(roots[1], envs[1], 'import', native);+ const links = roots.map(root => join(root, '.git/pullboard/relay.json'));+ for (let index = 0; index < roots.length; index += 1) {+ const keyDirectory = join(homes[index], 'relay-keys');+ mkdirSync(keyDirectory, { mode: 0o700 });+ writeFileSync(join(keyDirectory, box.id + '.key'), box.key.toString('base64url') + '\n', { mode: 0o600 });+ const replayOrigin = await independentReplayOrigin(sub, box.origin);+ writeFileSync(links[index], JSON.stringify({ version: 1, mode: 'ordered', board: box.id, url: replayOrigin, repository: 'fixture/repository', token: box.person.token, sequence: 0, cursor: document.tables.event.at(-1).event_id }) + '\n', { mode: 0o600 });+ }+ const originalLinks = links.map(file => readFileSync(file, 'utf8'));+ const initialSnapshot = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(document)), { boardId: box.id, kind: 'snapshot', sequence: 0 })).toString('base64url');+ assert.equal((await box.call(box.path + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: initialSnapshot } })).status, 200);+ for (let index = 0; index < moves.length; index += 1) {+ const sequence = index + 1;+ const sealed = Buffer.from(await sealMove(box.key, new TextEncoder().encode(JSON.stringify(moves[index])), { boardId: box.id, kind: 'move', sequence })).toString('base64url');+ const uploaded = await box.call(box.path + '/moves', { method: 'POST', token: remote.token, body: { sequence, sealed } });+ assert.equal(uploaded.status, 200);+ assert.equal(uploaded.body.event.sender.agent, 'remote-1');+ }+ const results = [];+ for (let index = 0; index < roots.length; index += 1) {+ const result = await replayResult(roots[index], envs[index], 'export');+ assert.equal(result.status, 0);+ results.push(result.document);+ if (moves[0].engine === 4) {+ assert.match((result.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\].*engine version 4.*engine version 3.*upgrade pullboard/, 'future records stop before interpreting the sending agent');+ assert.deepEqual(result.document.tables, document.tables, 'no board row, receipt or persisted cursor changes');+ assert.equal(readFileSync(links[index], 'utf8'), originalLinks[index], 'the saved transport cursor is unchanged');+ const retried = await replayResult(roots[index], envs[index], 'export');+ assert.match((retried.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\]/);+ assert.equal(retried.status, 0);+ assert.deepEqual(retried.document.tables, document.tables, 'retry still stops at the same unapplied record');+ const attempted = await replayResult(roots[index], envs[index], 'add', document.tables.item[0].item_lane, 'Later local move must wait');+ assert.equal(attempted.status, 1);+ assert.equal(attempted.document.error.code, 'ENGINE_VERSION');+ assert.match(attempted.document.error.message, /engine version 4.*engine version 3/);+ assert.equal(readFileSync(links[index], 'utf8'), originalLinks[index]);+ const board = store.openBoard(join(roots[index], '.git/pullboard/board.sqlite'));+ try { assert.deepEqual(JSON.parse(JSON.stringify(exportBoard(board))).tables, document.tables, 'a later local mutation cannot pass the future record'); }+ finally { store.closeBoard(board); }+ } else {+ assert.doesNotMatch((result.document.diagnostics ?? []).join('\n'), /\[ENGINE_VERSION\]/);+ assert.deepEqual(result.document.tables.item, document.tables.item);+ assert.deepEqual(result.document.tables.shout, document.tables.shout);+ assert.deepEqual(result.document.tables.verdict, document.tables.verdict);+ const refused = result.document.tables.event.filter(row => row.event_kind === 'relay_refused');+ assert.deepEqual(refused.map(row => JSON.parse(row.event_detail).code), ['RELAY_SENDER_MISMATCH', 'RELAY_SENDER_MISMATCH']);+ assert.ok(refused.every(row => row.event_by === 'remote-1'));+ assert.equal(result.document.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value, '2');+ assert.equal(JSON.parse(readFileSync(links[index], 'utf8')).sequence, 2);+ }+ }+ assert.deepEqual(results[0].tables, results[1].tables, 'the two independent clients retain identical board rows');+ const snapshot = await box.call(box.path + '/state');+ assert.equal(snapshot.body.state.sequence, 0);+ assert.equal(snapshot.body.state.sealed, initialSnapshot, 'neither client replaced independent replay with a shared checkpoint');+ });+ }+ });+test('two real clients refuse forged relay actors and person-only requests while advancing identically [H2,H16]', async t => {const box = await fixture(t);const source = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));