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
feat(core): validate merged commit receipts [R3,R1]
Corey Olson8dc79b4bdc0a
diff --git a/docs/api.md b/docs/api.mdindex d003ce8f..46478e05 100644--- a/docs/api.md+++ b/docs/api.md@@ -12,6 +12,8 @@ A successful command returns the fields listed below. `version` is always the nuWhen `add` or `edit` supplies a new nonempty check, Pullboard measures it once in a temporary checkout of the current `main` commit. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `green`, `red`, or `unavailable`. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when filing, showing, or reserving the item for review. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. The captured observation travels with the board move, so replicas store the result without executing the command.+`merged <id> <commit>` records only a commit reachable from the primary checkout's branch that contains the item's submitted commit or has the same stable patch id as the item's change from its claim base. Other commits are refused with `NOT_MERGED`; `--note "why"` records an exceptional receipt and keeps the note in that item's `merged` event.+<!-- api-command-shapes:start -->| Command | Required top-level fields || --- | --- |diff --git a/src/board.js b/src/board.jsindex 60db3e95..dd79dff9 100644--- a/src/board.js+++ b/src/board.js@@ -1213,9 +1213,9 @@ function coordinatorOnly(agentId, what) {** @param {any} board* @param {number} id- * @param {{ agentId: string, commit: string }} merge+ * @param {{ agentId: string, commit: string, note?: string }} merge*/-export function merged(board, id, { agentId, commit }) {+export function merged(board, id, { agentId, commit, note = '' }) {coordinatorOnly(agentId, 'records merges');atomic(board, () => {const item = itemById(board, id);@@ -1223,7 +1223,7 @@ export function merged(board, id, { agentId, commit }) {throw new Refused('NOT_VERIFIED', `item #${id} is ${item.item_status}; merge verified work only`);}setItem(board, id, { item_merged_commit: commit });- logEvent(board, agentId, 'merged', id, { commit });+ logEvent(board, agentId, 'merged', id, { commit, ...(note.trim() ? { note: note.trim() } : {}) });});}diff --git a/src/cli.js b/src/cli.jsindex ac2e81c4..acb8d7e7 100644--- a/src/cli.js+++ b/src/cli.js@@ -14,7 +14,7 @@ import { loadDoctrine } from './doctrine.js';import { requirePersonChannel } from './person.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';import { digestOf, gateReport, runGate, runShell } from './gate.js';-import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';+import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked } from './git.js';import {FIX_NOTE,applyFixers,@@ -1847,7 +1847,25 @@ function workCommands(io, args) {merged: () => act(async (ctx, board, me) => {const commit = resolveCommit(ctx.info.root, second ?? '');if (!commit) throw new Refused('NO_COMMIT', `no commit "${second ?? ''}" in this repo`);- await ordered(ctx, board, 'merged', [idArg(first), { agentId: me.id, commit }]);+ const id = idArg(first);+ const note = (textArg(io, values, 'note') ?? '').trim();+ const item = store.getItem(board, id);+ if (item.item_status === 'verified') {+ const trunk = mainCheckout(ctx.info.root);+ const itemCommit = item.item_commit;+ const itemOnCandidate = contains(ctx.info.root, itemCommit, commit);+ const candidateOnTrunk = Boolean(trunk?.commit && contains(ctx.info.root, commit, trunk.commit));+ const parent = tryGit(ctx.info.root, ['rev-parse', '--verify', '--quiet', `${commit}^`]);+ const itemPatch = item.item_claim_head ? patchId(ctx.info.root, item.item_claim_head, itemCommit) : null;+ const candidatePatch = parent.status === 0 ? patchId(ctx.info.root, parent.stdout, commit) : null;+ const carriesPatch = Boolean(itemPatch && candidatePatch && itemPatch === candidatePatch);+ if (!note && !(candidateOnTrunk && (itemOnCandidate || carriesPatch))) {+ const trunkName = trunk?.branch ?? 'the unavailable primary trunk';+ const trunkAt = trunk?.commit ? ` at ${trunk.commit}` : '';+ throw new Refused('NOT_MERGED', `commit ${commit} is not on trunk ${trunkName}${trunkAt}, or does not contain item commit ${itemCommit} or carry its patch; merge that work onto ${trunkName}, or use --note "why"`);+ }+ }+ await ordered(ctx, board, 'merged', [id, { agentId: me.id, commit, note }]);io.result?.({ id: idArg(first), commit });io.say(`#${first} merged as ${commit.slice(0, 12)}`);return 0;diff --git a/src/git.js b/src/git.jsindex 28e8cfc3..561bab76 100644--- a/src/git.js+++ b/src/git.js@@ -88,6 +88,22 @@ export function tryGit(cwd, args) {return { status: result.status ?? 1, stdout: (result.stdout ?? '').trim() };}+/**+ * Compute the stable patch id for a commit range, or null when Git cannot produce one.+ *+ * @param {string} root+ * @param {string} base+ * @param {string} commit+ * @returns {string | null}+ */+export function patchId(root, base, commit) {+ const env = cleanGitEnvironment();+ const diff = spawnSync('git', [...GIT_FLAGS, 'diff', base, commit], { cwd: root, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ if (diff.status !== 0 || !diff.stdout) return null;+ const result = spawnSync('git', [...GIT_FLAGS, 'patch-id', '--stable'], { cwd: root, env, encoding: 'utf8', input: diff.stdout });+ return result.status === 0 ? result.stdout.trim().split(/\s+/u)[0] || null : null;+}+/*** Find a main checkout whose `.git/config` marks it bare despite files beside its git directory.* This check uses the filesystem and explicit config path so inherited Git repository variablesdiff --git a/test/merged.test.js b/test/merged.test.jsnew file mode 100644index 00000000..dade07d7--- /dev/null+++ b/test/merged.test.js@@ -0,0 +1,143 @@+/** Merged receipts only record item work on the primary trunk, unless noted [R3,R1]. */+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { after, test } from 'node:test';+import * as store from '../src/board.js';+import { main } from '../src/cli.js';++const TEMP_DIRS = [];+const HOUR = 3_600_000;++/** Remove fixture repositories and their real SQLite boards after tests finish. */+function cleanup() {+ for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });+}++after(cleanup);++/** Run a command and keep its actual output for useful assertion failures. */+async function command(box, args, cwd = box.repo) {+ let stdout = '';+ let stderr = '';+ const code = await main(args, { cwd,+ stdout: { isTTY: false, write: (part) => { stdout += part; } },+ stderr: { write: (part) => { stderr += part; } } });+ return { code, stdout, stderr };+}++/** Create an initialized real repo with one verified item commit and its claim base. */+async function fixture(t) {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-merged-'));+ TEMP_DIRS.push(dir);+ const repo = join(dir, 'repo');+ mkdirSync(repo);+ const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Merged fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Merged fixture', GIT_COMMITTER_EMAIL: '[email protected]' };+ /** Run Git in this isolated fixture with its private identity. */+ const git = (...args) => execFileSync('git', args, { cwd: repo, env, encoding: 'utf8', stdio: 'pipe' }).trim();+ git('init', '-q', '-b', 'main');+ const initialized = await main(['init'], { cwd: repo, stdout: { isTTY: false, write() {} }, stderr: { write() {} } });+ assert.equal(initialized, 0, 'pullboard initializes the fixture');+ writeFileSync(join(repo, 'SPEC.md'), '# Fixture\n\n## G · Goals\n- G1 [approved, must] Work is tracked. | gate: true\n');+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true', verify: 'any', lanes: { web: { owns: ['web/'], specs: ['G1'] } }, shared: [] }));+ git('add', '-A'); git('commit', '-q', '-m', 'chore: initialize fixture');+ const base = git('rev-parse', 'HEAD');+ const builder = join(dir, 'builder');+ git('worktree', 'add', '-q', builder, '-b', 'web/builder');+ const joined = await command({ repo }, ['join', 'web'], builder);+ assert.equal(joined.code, 0, `${joined.stdout}${joined.stderr}`);+ const board = store.openBoard(join(repo, '.git', 'pullboard', 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ store.ensureCoordinator(board, repo);+ const agentId = store.listAgents(board).find((agent) => agent.agent_lane === 'web').agent_id;+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Tracked work', criterion: 'The item change is retained.', specIds: ['G1'] });+ const frozen = JSON.stringify({ criterion: 'The item change is retained.' });+ const digest = createHash('sha256').update(frozen).digest('hex');+ store.claim(board, id, { agentId, lane: 'web', leaseMs: HOUR, freeze: () => ({ text: frozen, digest }), head: base });+ mkdirSync(join(builder, 'web'));+ writeFileSync(join(builder, 'web', 'work.txt'), 'item change\n');+ execFileSync('git', ['add', 'web/work.txt'], { cwd: builder, env });+ execFileSync('git', ['commit', '-q', '-m', 'feat(web): retain item work [G1]'], { cwd: builder, env });+ const itemCommit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: builder, env, encoding: 'utf8' }).trim();+ store.submit(board, id, { agentId, commit: itemCommit, tree: execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { cwd: builder, env, encoding: 'utf8' }).trim() });+ store.verify(board, id, { agentId: 'coordinator', decision: 'ACCEPT', note: 'confirmed the committed file', head: itemCommit, digest, policy: 'any' });+ return { dir, repo, builder, env, git, board, id, base, itemCommit };+}++/** Read the latest merge event and decode its immutable detail. */+function mergeEvent(box) {+ const event = store.events(box.board, { itemId: box.id }).filter((entry) => entry.event_kind === 'merged').at(-1);+ return event ? JSON.parse(event.event_detail) : null;+}++/** Invoke merged and assert that its refusal names both the primary trunk and item commit. */+async function refusesUncarried(box, candidate) {+ const result = await command(box, ['merged', String(box.id), candidate, '--json']);+ assert.equal(result.code, 1, `${result.stdout}${result.stderr}`);+ const output = `${result.stdout}${result.stderr}`;+ assert.match(output, /NOT_MERGED/u);+ assert.match(output, /refs\/heads\/main/u);+ assert.ok(output.includes(box.itemCommit), 'the refusal identifies the item commit');+ assert.equal(mergeEvent(box), null, 'a refusal does not record a merge');+}++test('[R3,R1] merged refuses the root and deleted side-branch commits', async (t) => {+ const rootCase = await fixture(t);+ await refusesUncarried(rootCase, rootCase.base);++ const sideCase = await fixture(t);+ sideCase.git('switch', '-c', 'unrelated');+ writeFileSync(join(sideCase.repo, 'unrelated.txt'), 'unrelated\n');+ sideCase.git('add', 'unrelated.txt');+ sideCase.git('commit', '-q', '-m', 'chore: unrelated work');+ sideCase.git('merge', '--no-ff', '-m', 'chore(test): merge item on side [G1]', 'web/builder');+ const deleted = sideCase.git('rev-parse', 'HEAD');+ assert.doesNotThrow(() => sideCase.git('merge-base', '--is-ancestor', sideCase.itemCommit, deleted), 'the off-trunk candidate contains the item commit');+ sideCase.git('switch', 'main');+ sideCase.git('branch', '-D', 'unrelated');+ await refusesUncarried(sideCase, deleted);+});++test('[R3,R1] merged records fast-forward, merge, rebased and squashed work', async (t) => {+ const fastForward = await fixture(t);+ fastForward.git('merge', '--ff-only', 'web/builder');+ assert.equal((await command(fastForward, ['merged', String(fastForward.id), fastForward.itemCommit])).code, 0);+ assert.equal(mergeEvent(fastForward).commit, fastForward.itemCommit);++ const merge = await fixture(t);+ writeFileSync(join(merge.repo, 'trunk.txt'), 'trunk change\n');+ merge.git('add', 'trunk.txt'); merge.git('commit', '-q', '-m', 'chore: advance trunk');+ merge.git('merge', '--no-ff', '--no-edit', 'web/builder');+ const mergeCommit = merge.git('rev-parse', 'HEAD');+ assert.equal((await command(merge, ['merged', String(merge.id), mergeCommit])).code, 0);+ assert.equal(mergeEvent(merge).commit, mergeCommit);++ const rebased = await fixture(t);+ writeFileSync(join(rebased.repo, 'trunk.txt'), 'trunk change\n');+ rebased.git('add', 'trunk.txt'); rebased.git('commit', '-q', '-m', 'chore: advance trunk [G1]');+ rebased.git('cherry-pick', rebased.itemCommit);+ const rebasedCommit = rebased.git('rev-parse', 'HEAD');+ assert.notEqual(rebasedCommit, rebased.itemCommit, 'the item change was replayed on the advanced trunk');+ assert.equal((await command(rebased, ['merged', String(rebased.id), rebasedCommit])).code, 0);+ assert.equal(mergeEvent(rebased).commit, rebasedCommit);++ const squash = await fixture(t);+ squash.git('merge', '--squash', 'web/builder');+ squash.git('commit', '-q', '-m', 'feat(web): squash item work [G1]');+ const squashCommit = squash.git('rev-parse', 'HEAD');+ assert.equal((await command(squash, ['merged', String(squash.id), squashCommit])).code, 0);+ assert.equal(mergeEvent(squash).commit, squashCommit);+});++test('[R3,R1] --note records an otherwise uncarried merge receipt', async (t) => {+ const box = await fixture(t);+ const result = await command(box, ['merged', String(box.id), box.base, '--note', 'recorded outside trunk']);+ assert.equal(result.code, 0, `${result.stdout}${result.stderr}`);+ assert.equal(mergeEvent(box).commit, box.base);+ assert.equal(mergeEvent(box).note, 'recorded outside trunk');+});