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
fix(core): verify recorded conflict objects on replay [V4,H16]
Corey Olsonfb4b73d768ea
diff --git a/docs/formats.md b/docs/formats.mdindex a206b8ba..30b3aaa9 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -412,7 +412,7 @@ Each connection also has a temporary `moving(token INTEGER)` table and `status_tThe `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`. Under engine 8 and later, each event by a registered agent also carries a `model` string snapshot in `event_detail`; legacy agents without a declaration use `unknown`. Declared models live under `agent_model:<agent id>` in `board_meta`, without changing the agent table or stable ids. Rejoining with another model appends a `model` event whose common snapshot holds the new declaration. This common snapshot is separate from the per-kind payload fields listed below. The following rows name the emitted kinds and the union of their operation-specific detail keys; CLI accept events additionally carry the frozen-check result described below:-The computed-grant engine adds `grantEngine` to new join, claim and renewal events as a version marker only. It stores no grant or scope: permission is computed from the seat lane, current claim and lease, or the current review reservation. Older event bytes remain unchanged. A new marker prevents an older engine from reinterpreting a narrowed claim; shout, release and review reservation keep their existing engine floors. Reopen still checks the marked seat and target version floor, while its own authority guards decide permission: direct current conflict requests are coordinator-only; automatic review preflight records native-computed evidence bound to the board, actor, item, submitted head, trunk and conflicting files, validated at origin before sealing and replayed without Git. The exact accepting reviewer can withdraw its current verdict independently of a build claim. Older recorded submitted-conflict moves retain their joined-seat authority.+The computed-grant engine adds `grantEngine` to new join, claim and renewal events as a version marker only. It stores no grant or scope: permission is computed from the seat lane, current claim and lease, or the current review reservation. Older event bytes remain unchanged. A new marker prevents an older engine from reinterpreting a narrowed claim; shout, release and review reservation keep their existing engine floors. Reopen still checks the marked seat and target version floor, while its own authority guards decide permission: direct current conflict requests are coordinator-only; automatic review preflight records native-computed evidence bound to the board, actor, item, submitted head, trunk and conflicting files, verified at origin and replay by merging the recorded immutable commits, never the replica current trunk; missing objects refuse without advancing the replay cursor until fetched. The exact accepting reviewer can withdraw its current verdict independently of a build claim. Older recorded submitted-conflict moves retain their joined-seat authority.<!-- events:start -->| Kind | Actor | Detail fields |diff --git a/src/computed-conflict-receipt.js b/src/computed-conflict-receipt.jsindex 00a88b25..6f550fee 100644--- a/src/computed-conflict-receipt.js+++ b/src/computed-conflict-receipt.js@@ -1,6 +1,8 @@-/** Board-bound computed conflict evidence is checked before sealing and replayed without Git [V4,H16]. */+/** Board-bound computed conflict evidence is verified against immutable Git commits before sealing and on replay [V4,H16]. */import { createHash } from 'node:crypto';-import { readFileSync } from 'node:fs';+import { existsSync } from 'node:fs';+import { repoInfo } from './git.js';+import { recordedTrunkMerge } from './trunk-merge.js';import { dirname } from 'node:path';import { join } from 'node:path';import { Refused } from './refused.js';@@ -8,12 +10,6 @@ import { Refused } from './refused.js';const SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;const ID = /^[a-f0-9-]{36}$/u;-/** Resolve the evidence store from the board file, never from a caller-provided path. */-export function computedConflictStore(board) {- const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;- return file ? join(dirname(file), 'computed-conflicts') : null;-}-/** Read the canonical immutable record, rejecting altered, unknown or malformed fields. */export function computedConflictFields(value) {if (!value || value.version !== 1 || !ID.test(value.id ?? '') || !/^[a-f0-9]{32}$/u.test(value.board ?? '')@@ -28,25 +24,60 @@ export function computedConflictFields(value) {return value.digest === digest && Object.keys(value).length === Object.keys(fields).length + 1 ? { ...fields, digest } : null;}-/** Refuse an unbound origin record; another machine validates its sealed canonical record on replay. */-export function requireComputedConflictBound(board, receipt) {- const fields = computedConflictFields(receipt), directory = computedConflictStore(board);- let stored;- try { stored = fields && directory && readFileSync(join(directory, `${fields.id}.json`), 'utf8'); } catch { /* Missing evidence is not authority. */ }- if (!fields || stored !== JSON.stringify(fields) + '\n') throw new Refused('COORDINATOR_ONLY',- 'automatic conflict return requires the native board computation; agents cannot supply conflict assertions');+const VERIFIED_OBJECTS = new WeakMap();++/** Locate this replica's object store; private replicas may use their registered repository's immutable objects. */+function objectStore(board) {+ const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;+ const common = file ? dirname(dirname(file)) : null;+ if (common && existsSync(join(common, 'objects'))) return common;+ const root = board.db.prepare("SELECT agent_path FROM agent WHERE agent_id='coordinator'").get()?.agent_path;+ try { if (root) return repoInfo(root).commonDir; } catch { /* Missing local objects are a recoverable replay refusal. */ }+ throw new Refused('MERGE_CHECK_FAILED', 'fetch the recorded submitted and trunk commits into this replica repository before resuming the move');+}++/** Verify immutable objects before advancing a relay position; missing objects must leave it retryable after fetch. */+export function requireComputedConflictObjects(board, receipt) {+ const fields = computedConflictFields(receipt);+ if (!fields) return null;+ let cache = VERIFIED_OBJECTS.get(board);+ if (!cache) { cache = new Map(); VERIFIED_OBJECTS.set(board, cache); }+ const key = `${fields.head}:${fields.trunk}`;+ if (!cache.has(key)) cache.set(key, recordedTrunkMerge(objectStore(board), fields.head, fields.trunk));+ return cache.get(key);+}++/** A self-hash only detects changes; actual immutable Git conflict verification supplies authority. */+export function requireComputedConflict(board, receipt) {+ const fields = computedConflictFields(receipt);+ if (!fields || JSON.stringify(requireComputedConflictObjects(board, fields)) !== JSON.stringify(fields.files)) {+ throw new Refused('COORDINATOR_ONLY', 'automatic return requires the conflicting files computed from its recorded head and trunk');+ }return fields;}/** Bind recorded evidence to this board's current submitted item and actual actor, on every replica. */-export function computedConflictProblem(board, item, actor, receipt) {+function bindingProblem(board, item, actor, receipt) {const fields = computedConflictFields(receipt);const identity = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get()?.meta_value;const submission = board.db.prepare("SELECT event_id FROM event WHERE item_id=? AND event_kind='submit' ORDER BY event_id DESC LIMIT 1").get(item.item_id)?.event_id;if (!fields || fields.submission !== submission || fields.board !== identity || fields.item !== item.item_id || fields.actor !== actor|| fields.head !== item.item_commit || item.item_status !== 'submitted') return new Refused('COORDINATOR_ONLY','automatic conflict evidence must name this board, actor and current submitted head');- if (board.executionEngineVersion === undefined) requireComputedConflictBound(board, fields);+ return null;+}++/** Check missing objects only after immutable record identity matches the requested current item. */+export function preflightComputedConflict(board, id, actor, receipt) {+ const item = board.db.prepare('SELECT * FROM item WHERE item_id=?').get(id);+ if (item && !bindingProblem(board, item, actor, receipt)) requireComputedConflictObjects(board, receipt);+}++/** Verify the same actual immutable conflict on direct calls and on every replaying replica. */+export function computedConflictProblem(board, item, actor, receipt) {+ const problem = bindingProblem(board, item, actor, receipt);+ if (problem) return problem;+ requireComputedConflict(board, receipt);return null;}@@ -56,3 +87,11 @@ export function conflictValue(receipt, asserted) {const fields = computedConflictFields(receipt);return fields ? { files: fields.files, trunk: fields.trunk } : {};}++/** Refuse a prepared record that is not the current requested item and actual sending actor. */+export function requirePreparedComputedConflict(board, id, actor, receipt) {+ const item = board.db.prepare('SELECT * FROM item WHERE item_id=?').get(id);+ const problem = item ? bindingProblem(board, item, actor, receipt) : new Refused('COORDINATOR_ONLY', 'automatic conflict evidence needs the current submitted item');+ if (problem) throw problem;+ return requireComputedConflict(board, receipt);+}diff --git a/src/computed-conflict-return.js b/src/computed-conflict-return.jsindex d8c4c1a2..90fb82e1 100644--- a/src/computed-conflict-return.js+++ b/src/computed-conflict-return.js@@ -1,16 +1,13 @@/** Native computation of automatic submitted-head returns; callers supply no conflict assertion [V4,H16]. */import { createHash } from 'node:crypto';import { randomUUID } from 'node:crypto';-import { mkdirSync } from 'node:fs';import { realpathSync } from 'node:fs';-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { repoInfo } from './git.js';import { trunkMerge } from './trunk-merge.js';-import { computedConflictStore } from './computed-conflict-receipt.js';import { Refused } from './refused.js';-/** Compute and privately store evidence only for this exact native board and current submitted head. */+/** Compute evidence only for this exact native board and current submitted head. */export function computeConflictReturn(board, id, actor) {const root = board.db.prepare("SELECT agent_path FROM agent WHERE agent_id='coordinator'").get()?.agent_path;const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;@@ -26,9 +23,6 @@ export function computeConflictReturn(board, id, actor) {item: item.item_id, actor, head: item.item_commit, trunk: merge.commit, files: merge.files, at: board.clock.now().toISOString(),submission: board.db.prepare("SELECT event_id FROM event WHERE item_id=? AND event_kind='submit' ORDER BY event_id DESC LIMIT 1").get(item.item_id).event_id };const receipt = { ...fields, digest: createHash('sha256').update(JSON.stringify(fields)).digest('hex') };- const directory = computedConflictStore(board);- mkdirSync(directory, { recursive: true, mode: 0o700 });- writeFileSync(join(directory, `${receipt.id}.json`), JSON.stringify(receipt) + '\n', { flag: 'wx', mode: 0o600 });return receipt;}diff --git a/src/engine.js b/src/engine.jsindex 36547cbb..1188d5eb 100644--- a/src/engine.js+++ b/src/engine.js@@ -1,5 +1,6 @@import { computedReturnArgs } from './computed-conflict-return.js';-import { requireComputedConflictBound } from './computed-conflict-receipt.js';+import { requirePreparedComputedConflict } from './computed-conflict-receipt.js';+import { preflightComputedConflict } from './computed-conflict-receipt.js';import { agentGrantMinimum } from './agent-grant.js';import { requireAgentGrant } from './agent-grant.js';import {@@ -106,7 +107,7 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID(), aif (operation === 'recordGateRun') requireBound(board, values[0]?.receipt);if (operation === 'reopen' && values[1]?.computedConflict !== undefined) {if (values[1].conflict !== undefined) throw new Refused('COORDINATOR_ONLY', 'automatic conflict evidence accepts no caller conflict assertion');- requireComputedConflictBound(board, values[1].computedConflict);+ requirePreparedComputedConflict(board, values[0], values[1].agentId, values[1].computedConflict);}if (operation === 'verify' && values[1]?.sandbox !== undefined) requireOutsideReceipt(board, values[1].sandbox);if (operation === 'release') {@@ -298,6 +299,8 @@ export function applyEngineMove(board, move, { sequence, at, standing = null, en// Existing receipts replay before consulting newer snapshot semantics.const minimumEngine = Math.max(minimumOperationEngine(move.operation, move.args, board, new Date(at)), agentGrantMinimum(board, move));if (move.engine < minimumEngine) throw new Refused('RELAY_MOVE', `${move.operation} cannot act on a checked-composition snapshot from engine ${move.engine}; use engine ${minimumEngine} or newer`);+ // Missing immutable objects abort before a refusal receipt or cursor could make a fetch unrecoverable.+ if (move.operation === 'reopen' && move.args[1]?.computedConflict !== undefined) preflightComputedConflict(board, move.args[0], move.args[1].agentId, move.args[1].computedConflict);const clock = board.clock;const engineVersion = board.executionEngineVersion;board.clock = { now: () => new Date(at) };diff --git a/src/trunk-merge.js b/src/trunk-merge.jsindex 60a4703f..297540f0 100644--- a/src/trunk-merge.js+++ b/src/trunk-merge.js@@ -28,3 +28,15 @@ export function trunkMerge(root, commit, retainedRef = trunkRef(root)) {return { ref: branchRef, commit: tip.stdout.trim(), files: records.slice(0, end < 0 ? records.length : end) };}++/** Verify exactly the recorded immutable commits, independent of this machine's current trunk. */+export function recordedTrunkMerge(gitDirectory, head, trunk) {+ const result = spawnSync('git', ['--no-replace-objects', `--git-dir=${gitDirectory}`, '-c', 'core.quotepath=false',+ 'merge-tree', '--write-tree', '--name-only', '-z', trunk, head], {+ env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,+ });+ if (result.status === 0) return null;+ if (result.status !== 1) throw new Refused('MERGE_CHECK_FAILED', 'fetch the recorded submitted and trunk commits, then resume this move; Git could not verify its immutable conflict');+ const records = result.stdout.split('\0').slice(1), end = records.indexOf('');+ return records.slice(0, end < 0 ? records.length : end);+}diff --git a/test/review-queue.test.js b/test/review-queue.test.jsindex b9ae4e43..1051f00b 100644--- a/test/review-queue.test.js+++ b/test/review-queue.test.js@@ -17,6 +17,7 @@ import { nextReview } from '../src/next-review.js';import { Refused } from '../src/refused.js';import { AGENT_GRANT_ENGINE } from '../src/agent-grant-engine.js';import {+ appliedSequence,applyEngineMove,prepareEngineMove,} from '../src/engine.js';@@ -351,17 +352,20 @@ test('automatic conflict returns bind native evidence and replay without callerassert.equal(evidence.trunk, box.git(box.repo, 'rev-parse', 'HEAD'));assert.deepEqual(evidence.files, ['web/list.html']);assert.equal(evidence.actor, actor, 'the move retains the actual reviewer actor');- const forged = { ...evidence, id: 'ffffffff-ffff-ffff-ffff-ffffffffffff' };- const { digest: ignored, ...forgedFields } = forged;- forged.digest = createHash('sha256').update(JSON.stringify(forgedFields)).digest('hex');- for (const receipt of [forged, { ...evidence, files: ['web/false.html'] }]) {+ /** Rehashing altered data must not make it trusted: immutable Git still decides the actual conflict. */+ const rehash = changes => {+ const { digest, ...fields } = { ...evidence, ...changes };+ return { ...fields, digest: createHash('sha256').update(JSON.stringify(fields)).digest('hex') };+ };+ const forged = rehash({ files: ['web/false.html'] });+ for (const receipt of [forged, rehash({ head: evidence.trunk }), { ...evidence, files: ['web/false.html'] }]) {assert.throws(() => prepareEngineMove(source, 'reopen', [conflicted, { agentId: actor, computedConflict: receipt }]),- error => error.code === 'COORDINATOR_ONLY', 'unbound or mutated evidence cannot be sealed');+ error => error.code === 'COORDINATOR_ONLY', 'false or mutated conflict evidence cannot be sealed');assert.throws(() => store.reopen(source, conflicted, { agentId: actor, computedConflict: receipt }),- error => error.code === 'COORDINATOR_ONLY', 'the direct origin API also requires its own stored evidence');+ error => error.code === 'COORDINATOR_ONLY', 'the direct origin API independently verifies the immutable conflict');}assert.deepEqual(exportBoard(source), original, 'evidence preparation and refusals do not change the board');- /** Each imported replica has no native evidence store or usable coordinator repository binding. */+ /** Each independent SQLite replica verifies the recorded objects, without choosing its own current trunk. */const replica = name => {const board = store.openBoard(join(box.dir, `${name}.sqlite`));copies.push(board); importBoard(board, original); return board;@@ -369,6 +373,8 @@ test('automatic conflict returns bind native evidence and replay without callerfor (const [name, options] of [['flag', { agentId: actor, automaticConflict: true }],['mutated', { agentId: actor, computedConflict: { ...evidence, files: ['web/false.html'] } }],+ ['rehashed', { agentId: actor, computedConflict: forged }],+ ['clean-record', { agentId: actor, computedConflict: rehash({ trunk: evidence.head }) }],['actor', { agentId: store.agentAt(source, box.web).agent_id, computedConflict: evidence }],]) {const board = replica(name);@@ -378,10 +384,16 @@ test('automatic conflict returns bind native evidence and replay without callerassert.equal(store.getItem(board, conflicted).item_status, 'submitted');}const left = replica('valid-left'), right = replica('valid-right');+ const missing = { ...move, args: [conflicted, { agentId: actor, computedConflict: rehash({ trunk: 'f'.repeat(40) }) }] };+ assert.throws(() => applyEngineMove(left, missing, { sequence: 1, at: new Date().toISOString() }),+ error => error.code === 'MERGE_CHECK_FAILED', 'missing immutable objects refuse by name until fetched');+ assert.equal(appliedSequence(left), 0, 'a missing-object refusal does not consume the position needed after fetch');assert.throws(() => prepareEngineMove(left, 'reopen', [conflicted, { agentId: actor, automaticConflict: true }]),error => error.code === 'COORDINATOR_ONLY', 'an imported replica cannot fabricate native origin evidence');assert.throws(() => applyEngineMove(left, { ...move, engine: AGENT_GRANT_ENGINE - 1 }, { sequence: 1, at: new Date().toISOString() }),error => error.code === 'RELAY_MOVE', 'an older engine cannot interpret the new computed-return record');+ // Main now contains the submitted head, while the recorded earlier trunk remains conflicting.+ box.git(box.repo, 'merge', '-q', '--no-edit', '-s', 'ours', evidence.head);const receipt = { sequence: 1, at: new Date().toISOString() };const results = [left, right].map(board => applyEngineMove(board, move, receipt));assert.deepEqual(results[0], results[1]);