Skip to content

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.

fix(merge): preserve versioned conflict replay [H16,V4]

Corey Olson7d3bfab33266
diff --git a/src/computed-conflict-receipt.js b/src/computed-conflict-receipt.js
index 3206d75b..a15868f2 100644
--- a/src/computed-conflict-receipt.js
+++ b/src/computed-conflict-receipt.js
@@ -15,13 +15,13 @@ const ID = /^[a-f0-9-]{36}$/u;
/** 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 ?? '')
+ if (!value || ![1, 2].includes(value.version) || !ID.test(value.id ?? '') || !/^[a-f0-9]{32}$/u.test(value.board ?? '')
|| !Number.isSafeInteger(value.item) || value.item < 1 || typeof value.actor !== 'string' || !value.actor || value.actor.length > 128 || /[\r\n\0]/u.test(value.actor)
|| !Number.isSafeInteger(value.submission) || value.submission < 1
|| !SHA.test(value.head ?? '') || !SHA.test(value.trunk ?? '') || !Array.isArray(value.files)
|| !value.files.length || value.files.length > 4096 || value.files.some(file => typeof file !== 'string' || !file || file.length > 4096 || file.includes('\0'))
|| new Set(value.files).size !== value.files.length || typeof value.at !== 'string' || !Number.isFinite(Date.parse(value.at))) return null;
- const fields = { version: 1, id: value.id, board: value.board, item: value.item, actor: value.actor,
+ const fields = { version: value.version, id: value.id, board: value.board, item: value.item, actor: value.actor,
head: value.head, trunk: value.trunk, files: [...value.files], at: value.at, submission: value.submission };
const digest = createHash('sha256').update(JSON.stringify(fields)).digest('hex');
return value.digest === digest && Object.keys(value).length === Object.keys(fields).length + 1 ? { ...fields, digest } : null;
@@ -47,8 +47,8 @@ export function requireComputedConflictObjects(board, receipt) {
refuseRecordedHistoryOverrides(gitDirectory);
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(gitDirectory, fields.head, fields.trunk));
+ const key = `${fields.version}:${fields.head}:${fields.trunk}`;
+ if (!cache.has(key)) cache.set(key, recordedTrunkMerge(gitDirectory, fields.head, fields.trunk, { version: fields.version }));
return cache.get(key);
}
@@ -63,6 +63,7 @@ export function requireComputedConflict(board, receipt) {
/** Fresh authoring must use the current trunk; recorded acknowledgments return before this mutation path. */
function requireCurrentConflict(board, fields) {
+ if (fields.version !== 2) throw new Refused('COORDINATOR_ONLY', 'fresh automatic returns need current mechanical conflict evidence; compute a new return');
const root = board.db.prepare("SELECT agent_path FROM agent WHERE agent_id='coordinator'").get()?.agent_path;
if (!root) throw new Refused('COORDINATOR_ONLY', 'fresh automatic return needs the registered native trunk');
const current = trunkMerge(root, fields.head);
diff --git a/src/computed-conflict-return.js b/src/computed-conflict-return.js
index 90fb82e1..fb1431cf 100644
--- a/src/computed-conflict-return.js
+++ b/src/computed-conflict-return.js
@@ -19,7 +19,7 @@ export function computeConflictReturn(board, id, actor) {
if (!board.db.prepare('SELECT agent_id FROM agent WHERE agent_id=?').get(actor)) throw new Refused('NOT_JOINED', 'join before selecting a review');
const merge = trunkMerge(root, item.item_commit);
if (!merge.files?.length) throw new Refused('NOT_CONFLICTING', 'the submitted head merges cleanly; no automatic return is needed');
- const fields = { version: 1, id: randomUUID(), board: board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value,
+ const fields = { version: 2, id: randomUUID(), board: board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value,
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') };
diff --git a/src/mechanical-merge-engine.js b/src/mechanical-merge-engine.js
new file mode 100644
index 00000000..4cea7245
--- /dev/null
+++ b/src/mechanical-merge-engine.js
@@ -0,0 +1,2 @@
+/** Version-two computed conflicts use mechanical merge policy; version-one replay stays unchanged [H16]. */
+export const MECHANICAL_MERGE_ENGINE = 130;
diff --git a/src/mechanical-merge.js b/src/mechanical-merge.js
index 59b00ec6..5f2f9164 100644
--- a/src/mechanical-merge.js
+++ b/src/mechanical-merge.js
@@ -1,4 +1,4 @@
-/** Conservative additive-only resolution of explicitly known registry/table regions [B3,R3,C7]. */
+/** Shared conservative data-only conflict decisions; candidate generators run only during landing [B3,R3,C7]. */
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
@@ -177,14 +177,13 @@ function sourceResolution(path, base, ours, theirs) {
} catch { return null; /* Invalid snapshots remain ordinary conflicts, never guessed data. */ }
}
const keyed = mergeMechanicalSources(path, base, ours, theirs);
- if (keyed) return { kind: 'keyed', ...keyed };
- const source = additiveSource(base, ours, theirs);
+ const source = keyed?.source ?? additiveSource(base, ours, theirs);
if (source === null) return null;
if (/\.(?:js|mjs|cjs)$/u.test(path)) {
const args = path.endsWith('.cjs') ? ['--check'] : ['--input-type=module', '--check'];
if (spawnSync(process.execPath, args, { input: source, env: cleanGitEnvironment(), maxBuffer: 1024 * 1024 }).status !== 0) return null;
}
- return { kind: 'add-only', source, keys: [] };
+ return keyed ? { kind: 'keyed', ...keyed } : { kind: 'add-only', source, keys: [] };
}
/** Run Git against explicit immutable objects, never inherited repository selectors or replacement refs. */
diff --git a/src/moves/reopen.js b/src/moves/reopen.js
index 3c309ba3..8b75b13d 100644
--- a/src/moves/reopen.js
+++ b/src/moves/reopen.js
@@ -1,3 +1,4 @@
+import { MECHANICAL_MERGE_ENGINE } from '../mechanical-merge-engine.js';
import { AGENT_GRANT_ENGINE } from '../agent-grant-engine.js';
import { VERDICT_WITHDRAW_ENGINE } from '../verdict-withdraw-engine.js';
import { MERGE_ONLY_VERDICT_ENGINE } from '../merge-only-verdict-engine.js';
@@ -32,7 +33,8 @@ function existingEngine(args, board, at) {
/** Keep verdict withdrawal as an independent maximum over every prior first-match floor [H16]. */
function minimumEngine(args, board, at) {
const carried = board && board.db.prepare("SELECT 1 FROM item i JOIN event e ON e.item_id = i.item_id WHERE i.item_id = ? AND e.event_kind = 'merge-only-accept' AND json_extract(e.event_detail,'$.commit') = i.item_commit LIMIT 1").get(args[0]);
- return Math.max(carried ? MERGE_ONLY_VERDICT_ENGINE : 1,
+ return Math.max(args[1]?.computedConflict?.version === 2 ? MECHANICAL_MERGE_ENGINE : 1,
+ carried ? MERGE_ONLY_VERDICT_ENGINE : 1,
args[1]?.computedConflict !== undefined ? AGENT_GRANT_ENGINE : 1,
args[1]?.withdrawVerdict === true ? VERDICT_WITHDRAW_ENGINE : 1, existingEngine(args, board, at));
}
diff --git a/src/trunk-merge.js b/src/trunk-merge.js
index cdc2345c..47aec828 100644
--- a/src/trunk-merge.js
+++ b/src/trunk-merge.js
@@ -28,12 +28,32 @@ export function trunkMerge(root, commit, retainedRef = trunkRef(root)) {
/** Verify exactly the recorded immutable commits, independent of this machine's current trunk. */
-export function recordedTrunkMerge(gitDirectory, head, trunk) {
+export function recordedTrunkMerge(gitDirectory, head, trunk, { version = 2 } = {}) {
+ if (version === 1) return plainRecordedTrunkMerge(gitDirectory, head, trunk);
const files = mechanicalConflictFiles(gitDirectory, trunk, head, { gitDirectory });
if (files === null) throw new Refused('MERGE_CHECK_FAILED', 'fetch the recorded submitted and trunk commits, then resume this move; Git could not verify its immutable conflict');
return files.length ? files : null;
}
+/** Preserve version-one immutable evidence exactly: mechanical policy never reinterprets historical receipts. */
+function plainRecordedTrunkMerge(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,
+ });
+ // Git may return 1 for an invalid/missing merge parent as well as for a real conflict.
+ // Only a merge result carrying its output tree can establish either clean or conflicting state.
+ const output = (result.stdout ?? '').split('\0');
+ if (![0, 1].includes(result.status) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(output[0].trim())) {
+ throw new Refused('MERGE_CHECK_FAILED', 'fetch the recorded submitted and trunk commits, then resume this move; Git could not verify its immutable conflict');
+ }
+ if (result.status === 0) return null;
+ const records = output.slice(1), end = records.indexOf('');
+ const files = records.slice(0, end < 0 ? records.length : end);
+ if (!files.length) throw new Refused('MERGE_CHECK_FAILED', 'Git did not provide conflict paths for the recorded commits; fetch their complete objects before resuming');
+ return files;
+}
+
/** Refuse local history overrides before trusting either a fresh or cached immutable conflict result. */
export function refuseRecordedHistoryOverrides(gitDirectory) {
diff --git a/test/mechanical-merge.test.js b/test/mechanical-merge.test.js
index 0d36f5bd..0910c22e 100644
--- a/test/mechanical-merge.test.js
+++ b/test/mechanical-merge.test.js
@@ -11,6 +11,14 @@ import { recordedTrunkMerge, trunkMerge } from '../src/trunk-merge.js';
import { resolveMechanicalMerge } from '../src/train-mechanical-merge.js';
import { createE2eHelpers } from './e2e-helpers.js';
import { json } from './land-board-fixture.js';
+import { createHash, randomUUID } from 'node:crypto';
+import * as store from '../src/board.js';
+import { appliedSequence, prepareEngineMove } from '../src/engine.js';
+import { requireComputedConflict, requireComputedConflictObjects } from '../src/computed-conflict-receipt.js';
+import { withRecordedConflictContext } from '../src/recorded-conflict-context.js';
+import reopenMove from '../src/moves/reopen.js';
+import { MECHANICAL_MERGE_ENGINE } from '../src/mechanical-merge-engine.js';
+import { AGENT_GRANT_ENGINE } from '../src/agent-grant-engine.js';
const directories = [];
after(() => directories.forEach(root => rmSync(root, { recursive: true, force: true })));
@@ -106,6 +114,10 @@ for (const [name, path, base, left, right] of [
['a decreased counter', 'snapshot.json', '{"value":2}\n', '{"value":1}\n', '{"value":3}\n'],
['delete versus edit', 'snapshot.json', '{"value":null}\n', '{}\n', '{"value":1}\n'],
['an invalid JavaScript union', 'src/cli.js', 'export {};\n', 'const value = 1;\nexport {};\n', 'const value = 2;\nexport {};\n'],
+ ['keyed additions with invalid JavaScript context', 'src/api-moves.js',
+ 'export = ;\nconst MOVES = {\n base: { item: true },\n};\n',
+ 'export = ;\nconst MOVES = {\n left: { item: true },\n base: { item: true },\n};\n',
+ 'export = ;\nconst MOVES = {\n right: { item: true },\n base: { item: true },\n};\n'],
]) {
test(`${name} remains a real conflict [B3,R3,C7]`, () => {
const box = fixture(path, base, left, right);
@@ -138,7 +150,7 @@ function boardFixture() {
}
/** Obtain a genuine independently verified submission with ordinary fixture authority and immutable Git bytes. */
-function accepted(box, number, files) {
+function accepted(box, number, files, { verify = true } = {}) {
const builder = join(box.dir, `builder-${number}`);
box.git(box.repo, 'worktree', 'add', '-q', '--detach', builder, 'main');
json(box, builder, 'join', 'web');
@@ -151,6 +163,7 @@ function accepted(box, number, files) {
assert.equal(commit.status, 0, commit.stderr);
const head = box.git(builder, 'rev-parse', 'HEAD');
json(box, builder, 'submit', String(id));
+ if (!verify) return id;
box.git(box.repo, 'checkout', '-q', '--detach', head);
try { json(box, box.repo, 'verify', String(id), 'accept', '--as', 'coordinator', '--note', 'checked the private fixture contribution'); }
finally { box.git(box.repo, 'checkout', '-q', 'main'); }
@@ -167,14 +180,44 @@ test('public land retains JSON and Markdown additions, while a same-line edit re
assert.deepEqual(JSON.parse(box.git(box.repo, 'show', 'main:test/snapshot.json')), { base: true, left: true, right: true });
assert.match(box.git(box.repo, 'show', 'main:docs/api.md'), /Left\.\nRight\./u);
assert.equal(box.git(box.remote, 'rev-parse', 'main'), box.git(box.repo, 'rev-parse', 'main'));
- const conflict = accepted(box, 3, { 'docs/api.md': '# Edited by item\n\nLeft.\nRight.\nEnd.\n' });
- writeFileSync(join(box.repo, 'docs/api.md'), '# Edited by trunk\n\nLeft.\nRight.\nEnd.\n');
- box.git(box.repo, 'add', '-A');
- box.git(box.repo, 'commit', '-q', '-m', 'chore: conflicting private trunk change');
- const preview = json(box, box.repo, 'land', '--dry-run');
- assert.deepEqual(preview.conflicts, [{ id: conflict, files: ['docs/api.md'] }]);
- const returned = json(box, box.repo, 'land');
+ const competing = accepted(box, 3, { 'docs/api.md': '# Edited by first item\n\nLeft.\nRight.\nEnd.\n' });
+ const conflict = accepted(box, 4, { 'docs/api.md': '# Edited by second item\n\nLeft.\nRight.\nEnd.\n' });
+ const returned = json(box, box.repo, 'land', '--max', '2');
+ assert.deepEqual(returned.landed, [competing], 'both accepts are fresh against the batch base; their actual composition exposes the conflict');
assert.deepEqual(returned.conflicts.map(entry => entry.id), [conflict]);
const item = json(box, box.repo, 'show', String(conflict));
assert.equal(item.item_status, 'open', 'a real conflicting accepted submission returns to its builder');
});
+
+test('version-one conflict replay keeps its original Git meaning while fresh mechanical returns use engine130 [H16,V4]', t => {
+ const box = boardFixture();
+ const id = accepted(box, 1, { 'test/snapshot.json': '{"base":true,"left":true}\n' }, { verify: false });
+ writeFileSync(join(box.repo, 'test/snapshot.json'), '{"base":true,"right":true}\n');
+ box.git(box.repo, 'add', '-A');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: independent snapshot addition');
+ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));
+ t.after(() => store.closeBoard(board));
+ const item = store.getItem(board, id);
+ const fields = { version: 1, id: randomUUID(), board: board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value,
+ item: id, actor: 'coordinator', head: item.item_commit, trunk: box.git(box.repo, 'rev-parse', 'HEAD'),
+ files: ['test/snapshot.json'], 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(id).event_id };
+ /** Self-hashes bind bytes; the real recorded Git objects independently establish their meaning. */
+ const receipt = value => ({ ...value, digest: createHash('sha256').update(JSON.stringify(value)).digest('hex') });
+ const historical = receipt(fields), mechanical = receipt({ ...fields, version: 2 });
+ assert.deepEqual(requireComputedConflictObjects(board, historical), fields.files);
+ assert.equal(requireComputedConflictObjects(board, mechanical), null, 'version participates in the immutable-object cache key');
+ assert.throws(() => requireComputedConflict(board, mechanical), error => error.code === 'COORDINATOR_ONLY',
+ 'a version-two self-hash cannot turn a mechanically clean snapshot into a conflict');
+ assert.throws(() => prepareEngineMove(board, 'reopen', [id, { agentId: 'coordinator', automaticConflict: true }]),
+ error => error.code === 'NOT_CONFLICTING', 'fresh selection cannot return this additive conflict');
+ assert.throws(() => store.reopen(board, id, { agentId: 'coordinator', computedConflict: historical }),
+ error => error.code === 'COORDINATOR_ONLY', 'historical semantics are not a fresh-authoring escape');
+ assert.equal(reopenMove.minimumEngine([id, { computedConflict: historical }]), AGENT_GRANT_ENGINE);
+ assert.equal(reopenMove.minimumEngine([id, { computedConflict: mechanical }]), MECHANICAL_MERGE_ENGINE);
+ const options = { agentId: 'coordinator', computedConflict: historical };
+ const move = { operation: 'reopen', args: [id, options], engine: AGENT_GRANT_ENGINE };
+ withRecordedConflictContext(board, move, { sequence: appliedSequence(board) + 1, at: fields.at }, () => store.reopen(board, id, options));
+ assert.equal(store.getItem(board, id).item_status, 'open', 'a validated historical replay retains its recorded outcome');
+ assert.deepEqual(JSON.parse(store.events(board, { itemId: id }).at(-1).event_detail).computedConflict, historical);
+});