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): resolve mechanical conflicts consistently [B3,R3,C7]

Corey Olson851b1f9163b7
diff --git a/src/health.js b/src/health.js
index 186ba942..7f41ce65 100644
--- a/src/health.js
+++ b/src/health.js
@@ -1,3 +1,4 @@
+import { mechanicalConflictFiles } from './mechanical-merge.js';
import { localDependencyIds } from './item-dependencies.js';
/**
* `pullboard health`: every stuck item on the board, why it is stuck, since when, the one next step
@@ -567,12 +568,7 @@ function trunkTip(root) {
*/
export function conflictFiles(root, trunk, commit) {
if (!/^[0-9a-f]{40,64}$/u.test(commit ?? '')) return null;
- const merge = tryGit(root, ['-c', 'core.quotepath=false', 'merge-tree', '--write-tree', '--name-only', '-z', trunk, commit]);
- if (merge.status === 0) return [];
- if (merge.status !== 1) return null;
- const parts = merge.stdout.split('\0').slice(1);
- const end = parts.indexOf('');
- return parts.slice(0, end < 0 ? parts.length : end);
+ return mechanicalConflictFiles(root, trunk, commit);
}
/** The index of the current release, as localReleaseRank counts it: the first with unverified local work. */
diff --git a/src/land.js b/src/land.js
index c0cdbb0e..3242bcd7 100644
--- a/src/land.js
+++ b/src/land.js
@@ -7,7 +7,8 @@ import {
} from './land-collisions.js';
/** Coordinator landing batches retain exact Git and gate receipts across interruptions [B3,R3]. */
import { assignEngineNumbers } from './engine-numbers.js';
-import { resolveMechanicalMerge } from './train-mechanical-merge.js';
+import { resolveMechanicalIndex } from './mechanical-merge.js';
+import { mechanicalConflictFiles } from './mechanical-merge.js';
import { writeFormatTable } from './format-registry.js';
import {
createHash,
@@ -275,16 +276,16 @@ async function mergeGroup(state, items) {
if (result.status !== 0) {
const files = tryGit(batch.root, ['diff', '--name-only', '--diff-filter=U']).stdout.split('\n').filter(Boolean);
if (!files.length) throw new Refused('LAND_MERGE', `merge of #${item.item_id} failed outside a conflict: ${result.stderr || result.stdout}; inspect ${batch.root} and its hooks before adopting`);
- const resolved = resolveMechanicalMerge(batch.root, files);
- if (resolved) {
+ const resolution = resolveMechanicalIndex(batch.root, files);
+ if (!resolution.files.length) {
git(batch.root, ['add', '--', ...files]);
git(batch.root, ['commit', '--no-edit']);
- resolutions.push({ id: item.item_id, files, entries: resolved });
+ resolutions.push({ id: item.item_id, files, entries: resolution.entries });
state.say(`mechanical merge #${item.item_id}: ${files.join(', ')}`);
} else {
git(batch.root, ['merge', '--abort']);
- conflicts.push({ id: item.item_id, files, trunk, commit: item.item_commit, reviewedCommit: checked });
- state.say(`conflict #${item.item_id}: ${files.join(', ')}`);
+ conflicts.push({ id: item.item_id, files: resolution.files, trunk, commit: item.item_commit, reviewedCommit: checked });
+ state.say(`conflict #${item.item_id}: ${resolution.files.join(', ')}`);
continue;
}
}
@@ -1325,12 +1326,9 @@ export async function runLandingBatch({ root, board, config, write, say, owner,
if (selected.ready.length && !landsOnTrunk(config)) requirePushTarget(root, trunk.branch);
const conflicts = [];
for (const item of selected.ready) {
- const merge = tryGit(root, ['merge-tree', '--write-tree', '--name-only', '-z', trunk.commit, item.item_landing_commit]);
- if (merge.status === 1) {
- const parts = merge.stdout.split('\0').slice(1);
- const end = parts.indexOf('');
- conflicts.push({ id: item.item_id, files: parts.slice(0, end < 0 ? parts.length : end) });
- } else if (merge.status !== 0) throw new Refused('LAND_MERGE', 'Git could not preview the landing; restore its objects and retry the dry run');
+ const files = mechanicalConflictFiles(root, trunk.commit, item.item_landing_commit);
+ if (files === null) throw new Refused('LAND_MERGE', 'Git could not preview the landing; restore its objects and retry the dry run');
+ if (files.length) conflicts.push({ id: item.item_id, files });
}
return { batch: null, landed: [], conflicts, blocked: selected.blocked, culprits: [], flakes: [], items: selected.ready.map((item) => item.item_id) };
}
diff --git a/src/mechanical-merge.js b/src/mechanical-merge.js
new file mode 100644
index 00000000..59b00ec6
--- /dev/null
+++ b/src/mechanical-merge.js
@@ -0,0 +1,256 @@
+/** Conservative additive-only resolution of explicitly known registry/table regions [B3,R3,C7]. */
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { randomUUID } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+import { cleanGitEnvironment } from './git.js';
+
+/** Locate a known keyed region without interpreting or executing candidate JavaScript. */
+function region(path, source) {
+ const lines = source.split('\n');
+ let start;
+ let end;
+ let key;
+ if (path === 'src/api-moves.js') {
+ start = lines.indexOf('const MOVES = {');
+ end = lines.indexOf('};', start + 1);
+ const field = "(?:[A-Za-z][A-Za-z0-9]*): (?:true|false|\\[(?:'[A-Za-z0-9-]+'(?:, '[A-Za-z0-9-]+')*)?\\])";
+ const entry = new RegExp(`^ (?:'([a-z][a-z0-9-]*)'|([A-Za-z][A-Za-z0-9]*)): \\{ ${field}(?:, ${field})* \\},$`, 'u');
+ key = line => entry.exec(line)?.slice(1).find(Boolean);
+ } else if (path === 'docs/formats.md') {
+ start = lines.indexOf('| Format | Version | Version source | Upgrade rule |');
+ if (lines[start + 1] !== '| --- | --- | --- | --- |') return null;
+ start += 1;
+ end = lines.indexOf('<!-- format-versions:end -->', start + 1);
+ key = line => /^\| `([^`|]+)` \| `\d+` \| .+ \| .+ \|$/u.exec(line)?.[1];
+ } else return null;
+ if (start < 0 || end <= start) return null;
+ const entries = lines.slice(start + 1, end).map(line => ({ key: key(line), line }));
+ if (entries.some(entry => !entry.key) || new Set(entries.map(entry => entry.key)).size !== entries.length) return null;
+ return { prefix: lines.slice(0, start + 1).join('\n'), suffix: lines.slice(end).join('\n'), entries };
+}
+
+/** Only insertions are admissible: every original entry and every surrounding byte stays unchanged. */
+function additions(base, side) {
+ if (!side || side.prefix !== base.prefix || side.suffix !== base.suffix) return null;
+ const original = new Map(base.entries.map(entry => [entry.key, entry.line]));
+ let position = 0;
+ const gaps = Array.from({ length: base.entries.length + 1 }, () => []);
+ for (const entry of side.entries) {
+ if (original.has(entry.key)) {
+ if (base.entries[position]?.key !== entry.key || original.get(entry.key) !== entry.line) return null;
+ position += 1;
+ } else gaps[position].push(entry);
+ }
+ return position === base.entries.length ? gaps : null;
+}
+
+/** Preserve both contributors' entry order, using the key only to break independent insertion ties. */
+function mergeGap(left, right) {
+ const entries = new Map();
+ const edges = new Map();
+ for (const side of [left, right]) {
+ for (const entry of side) {
+ if (entries.has(entry.key) && entries.get(entry.key) !== entry.line) return null;
+ entries.set(entry.key, entry.line);
+ if (!edges.has(entry.key)) edges.set(entry.key, new Set());
+ }
+ for (let index = 1; index < side.length; index += 1) edges.get(side[index - 1].key).add(side[index].key);
+ }
+ const result = [];
+ while (entries.size) {
+ const key = [...entries.keys()].sort().find(candidate => ![...edges.values()].some(next => next.has(candidate)));
+ if (key === undefined) return null;
+ result.push({ key, line: entries.get(key) });
+ entries.delete(key);
+ edges.delete(key);
+ }
+ return result;
+}
+
+/** Return a union only when all three exact sources differ solely by permitted keyed insertions. */
+export function mergeMechanicalSources(path, ancestor, ours, theirs) {
+ const base = region(path, ancestor);
+ if (!base) return null;
+ const left = additions(base, region(path, ours));
+ const right = additions(base, region(path, theirs));
+ if (!left || !right) return null;
+ const locations = new Map();
+ const entries = [];
+ for (let index = 0; index < left.length; index += 1) {
+ const gap = mergeGap(left[index], right[index]);
+ if (!gap) return null;
+ for (const entry of gap) {
+ if (locations.has(entry.key) && locations.get(entry.key) !== index) return null;
+ locations.set(entry.key, index);
+ entries.push(entry);
+ }
+ if (base.entries[index]) entries.push(base.entries[index]);
+ }
+ if (!locations.size) return null;
+ return { source: [base.prefix, ...entries.map(entry => entry.line), base.suffix].join('\n'), keys: [...locations.keys()] };
+}
+
+const MISSING = Symbol('missing');
+const CONFLICT = Symbol('conflict');
+const GENERATED = new Map([['docs/lifecycle.md', ['bin/pullboard.js', 'lifecycle']]]);
+
+/** Compare JSON values structurally, without confusing absent keys with explicit null. */
+function identity(value) {
+ if (value === MISSING) return MISSING;
+ if (Array.isArray(value)) return `[${value.map(identity).join(',')}]`;
+ if (value !== null && typeof value === 'object') return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${identity(value[key])}`).join(',')}}`;
+ return JSON.stringify(value);
+}
+
+/** Merge snapshot data; deletions win only over unchanged values, and only jointly raised counters use max. */
+function jsonValue(base, ours, theirs) {
+ if (identity(ours) === identity(theirs)) return ours;
+ if (identity(ours) === identity(base)) return theirs;
+ if (identity(theirs) === identity(base)) return ours;
+ if (ours === MISSING || theirs === MISSING) return CONFLICT;
+ if (Array.isArray(ours) && Array.isArray(theirs) && (Array.isArray(base) || base === MISSING)) {
+ const old = new Set((base === MISSING ? [] : base).map(identity));
+ const left = new Set(ours.map(identity)), right = new Set(theirs.map(identity));
+ const result = new Map();
+ for (const value of [...ours, ...theirs]) {
+ const key = identity(value);
+ if (!old.has(key) || (left.has(key) && right.has(key))) result.set(key, value);
+ }
+ return [...result.values()];
+ }
+ const object = value => value !== null && value !== MISSING && typeof value === 'object' && !Array.isArray(value);
+ if (object(ours) && object(theirs) && (object(base) || base === MISSING)) {
+ const original = base === MISSING ? {} : base;
+ const result = Object.create(null);
+ for (const key of new Set([...Object.keys(original), ...Object.keys(ours), ...Object.keys(theirs)])) {
+ const merged = jsonValue(Object.hasOwn(original, key) ? original[key] : MISSING,
+ Object.hasOwn(ours, key) ? ours[key] : MISSING, Object.hasOwn(theirs, key) ? theirs[key] : MISSING);
+ if (merged === CONFLICT) return CONFLICT;
+ if (merged !== MISSING) result[key] = merged;
+ }
+ return result;
+ }
+ if ([base, ours, theirs].every(value => typeof value === 'number') && ours > base && theirs > base) return Math.max(ours, theirs);
+ return CONFLICT;
+}
+
+/** Union only conflicts whose ancestor hunk is empty; replacements and deletions remain conflicts. */
+function additiveSource(base, ours, theirs) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-merge-data-'));
+ try {
+ const paths = [ours, base, theirs].map((source, index) => {
+ const path = join(directory, String(index));
+ writeFileSync(path, source, { mode: 0o600 });
+ return path;
+ });
+ const label = randomUUID();
+ const merged = spawnSync('git', ['merge-file', '-p', '--diff3', '-L', label, '-L', label, '-L', label, ...paths],
+ { env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
+ if (merged.status === 0) return merged.stdout;
+ if (merged.status === null || merged.status < 1 || merged.status > 127) return null;
+ const lines = merged.stdout.split(/(?<=\n)/u);
+ const result = [];
+ for (let index = 0; index < lines.length; index += 1) {
+ if (lines[index] !== `<<<<<<< ${label}\n`) { result.push(lines[index]); continue; }
+ const left = [], original = [], right = [];
+ while (++index < lines.length && lines[index] !== `||||||| ${label}\n`) left.push(lines[index]);
+ while (++index < lines.length && lines[index] !== '=======\n') original.push(lines[index]);
+ while (++index < lines.length && lines[index] !== `>>>>>>> ${label}\n`) right.push(lines[index]);
+ if (index >= lines.length || original.length) return null;
+ result.push(...left, ...right);
+ }
+ return result.join('');
+ } finally { rmSync(directory, { recursive: true, force: true }); }
+}
+
+/** Resolve only declared generated output, structural JSON or genuine additions; never execute candidate code. */
+function sourceResolution(path, base, ours, theirs) {
+ if (GENERATED.has(path)) return { kind: 'generated', keys: [] };
+ if (path.endsWith('.json')) {
+ try {
+ const merged = jsonValue(JSON.parse(base), JSON.parse(ours), JSON.parse(theirs));
+ if (merged === CONFLICT) return null;
+ const indent = /\n([ \t]+)\S/u.exec(ours)?.[1];
+ return { kind: 'json', keys: Object.keys(merged ?? {}), source: JSON.stringify(merged, null, indent) + (ours.endsWith('\n') ? '\n' : '') };
+ } 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);
+ 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: [] };
+}
+
+/** Run Git against explicit immutable objects, never inherited repository selectors or replacement refs. */
+function gitData(root, args, gitDirectory) {
+ return spawnSync('git', ['--no-replace-objects', ...(gitDirectory ? [`--git-dir=${gitDirectory}`] : []), '-c', 'core.quotepath=false', ...args],
+ { cwd: root, env: cleanGitEnvironment(), maxBuffer: 32 * 1024 * 1024 });
+}
+
+/** Read exactly three regular-file stages with identical modes and valid UTF-8, refusing deletes and symlinks. */
+function stageResolution(root, path, records, gitDirectory) {
+ if (records.length !== 3 || records.some((record, index) => record.stage !== index + 1 || record.mode !== records[0].mode)
+ || !['100644', '100755'].includes(records[0].mode)) return null;
+ const sources = records.map(record => gitData(root, ['cat-file', 'blob', record.hash], gitDirectory));
+ if (sources.some(result => result.status !== 0 || !Buffer.isBuffer(result.stdout)
+ || !Buffer.from(result.stdout.toString('utf8'), 'utf8').equals(result.stdout))) return null;
+ return sourceResolution(path, ...sources.map(result => result.stdout.toString('utf8')));
+}
+
+/** Parse Git's stage records using NUL framing, retaining unusual path bytes and original conflict order. */
+function stages(output) {
+ const byPath = new Map();
+ for (const record of output) {
+ const match = /^(\d+) ([a-f0-9]+) ([123])\t([\s\S]+)$/u.exec(record);
+ if (!match) continue;
+ if (!byPath.has(match[4])) byPath.set(match[4], []);
+ byPath.get(match[4]).push({ mode: match[1], hash: match[2], stage: Number(match[3]) });
+ }
+ return byPath;
+}
+
+/** Classify the same virtual merge for health and immutable replay without touching any index or checkout. */
+export function mechanicalConflictFiles(root, trunk, head, { gitDirectory } = {}) {
+ const result = gitData(root, ['merge-tree', '--write-tree', '-z', trunk, head], gitDirectory);
+ const output = result.stdout?.toString('utf8').split('\0') ?? [];
+ if (![0, 1].includes(result.status) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(output[0]?.trim() ?? '')) return null;
+ if (result.status === 0) return [];
+ const end = output.indexOf('', 1);
+ const entries = stages(output.slice(1, end < 0 ? undefined : end));
+ if (!entries.size) return null;
+ return [...entries].filter(([path, records]) => !stageResolution(root, path, records, gitDirectory)).map(([path]) => path);
+}
+
+/** Resolve a landing index using the identical decisions; generators execute only in this about-to-be-gated tree. */
+export function resolveMechanicalIndex(root, files) {
+ const result = gitData(root, ['ls-files', '--stage', '-z', '--', ...files]);
+ const entries = stages(result.stdout?.toString('utf8').split('\0') ?? []);
+ const resolutions = [], remaining = [];
+ for (const path of files) {
+ const resolution = result.status === 0 ? stageResolution(root, path, entries.get(path) ?? []) : null;
+ if (resolution) resolutions.push({ path, ...resolution });
+ else remaining.push(path);
+ }
+ if (remaining.length) return { files: remaining, entries: [] };
+ for (const entry of resolutions.filter(entry => entry.kind !== 'generated')) writeFileSync(join(root, entry.path), entry.source);
+ for (const entry of resolutions.filter(entry => entry.kind === 'generated')) {
+ const generated = spawnSync(process.execPath, GENERATED.get(entry.path),
+ { cwd: root, env: cleanGitEnvironment(), timeout: 30_000, maxBuffer: 32 * 1024 * 1024 });
+ if (generated.status !== 0) return { files: [entry.path], entries: [] };
+ writeFileSync(join(root, entry.path), generated.stdout);
+ }
+ return { files: [], entries: resolutions.map(({ path, keys, kind }) => ({ path, keys, kind })) };
+}
+
+/** Preserve the legacy all-or-nothing landing API and its resolution receipt entries. */
+export function resolveMechanicalMerge(root, files) {
+ const result = resolveMechanicalIndex(root, files);
+ return result.files.length ? null : result.entries;
+}
+
diff --git a/src/train-mechanical-merge.js b/src/train-mechanical-merge.js
index e3299e3f..fd33f3af 100644
--- a/src/train-mechanical-merge.js
+++ b/src/train-mechanical-merge.js
@@ -1,112 +1,2 @@
-/** Conservative additive-only resolution of explicitly known registry/table regions [B3,R3,C7]. */
-import { writeFileSync } from 'node:fs';
-import { spawnSync } from 'node:child_process';
-import { join } from 'node:path';
-import { cleanGitEnvironment } from './git.js';
-
-/** Locate a known keyed region without interpreting or executing candidate JavaScript. */
-function region(path, source) {
- const lines = source.split('\n');
- let start;
- let end;
- let key;
- if (path === 'src/api-moves.js') {
- start = lines.indexOf('const MOVES = {');
- end = lines.indexOf('};', start + 1);
- const field = "(?:[A-Za-z][A-Za-z0-9]*): (?:true|false|\\[(?:'[A-Za-z0-9-]+'(?:, '[A-Za-z0-9-]+')*)?\\])";
- const entry = new RegExp(`^ (?:'([a-z][a-z0-9-]*)'|([A-Za-z][A-Za-z0-9]*)): \\{ ${field}(?:, ${field})* \\},$`, 'u');
- key = line => entry.exec(line)?.slice(1).find(Boolean);
- } else if (path === 'docs/formats.md') {
- start = lines.indexOf('| Format | Version | Version source | Upgrade rule |');
- if (lines[start + 1] !== '| --- | --- | --- | --- |') return null;
- start += 1;
- end = lines.indexOf('<!-- format-versions:end -->', start + 1);
- key = line => /^\| `([^`|]+)` \| `\d+` \| .+ \| .+ \|$/u.exec(line)?.[1];
- } else return null;
- if (start < 0 || end <= start) return null;
- const entries = lines.slice(start + 1, end).map(line => ({ key: key(line), line }));
- if (entries.some(entry => !entry.key) || new Set(entries.map(entry => entry.key)).size !== entries.length) return null;
- return { prefix: lines.slice(0, start + 1).join('\n'), suffix: lines.slice(end).join('\n'), entries };
-}
-
-/** Only insertions are admissible: every original entry and every surrounding byte stays unchanged. */
-function additions(base, side) {
- if (!side || side.prefix !== base.prefix || side.suffix !== base.suffix) return null;
- const original = new Map(base.entries.map(entry => [entry.key, entry.line]));
- let position = 0;
- const gaps = Array.from({ length: base.entries.length + 1 }, () => []);
- for (const entry of side.entries) {
- if (original.has(entry.key)) {
- if (base.entries[position]?.key !== entry.key || original.get(entry.key) !== entry.line) return null;
- position += 1;
- } else gaps[position].push(entry);
- }
- return position === base.entries.length ? gaps : null;
-}
-
-/** Preserve both contributors' entry order, using the key only to break independent insertion ties. */
-function mergeGap(left, right) {
- const entries = new Map();
- const edges = new Map();
- for (const side of [left, right]) {
- for (const entry of side) {
- if (entries.has(entry.key) && entries.get(entry.key) !== entry.line) return null;
- entries.set(entry.key, entry.line);
- if (!edges.has(entry.key)) edges.set(entry.key, new Set());
- }
- for (let index = 1; index < side.length; index += 1) edges.get(side[index - 1].key).add(side[index].key);
- }
- const result = [];
- while (entries.size) {
- const key = [...entries.keys()].sort().find(candidate => ![...edges.values()].some(next => next.has(candidate)));
- if (key === undefined) return null;
- result.push({ key, line: entries.get(key) });
- entries.delete(key);
- edges.delete(key);
- }
- return result;
-}
-
-/** Return a union only when all three exact sources differ solely by permitted keyed insertions. */
-export function mergeMechanicalSources(path, ancestor, ours, theirs) {
- const base = region(path, ancestor);
- if (!base) return null;
- const left = additions(base, region(path, ours));
- const right = additions(base, region(path, theirs));
- if (!left || !right) return null;
- const locations = new Map();
- const entries = [];
- for (let index = 0; index < left.length; index += 1) {
- const gap = mergeGap(left[index], right[index]);
- if (!gap) return null;
- for (const entry of gap) {
- if (locations.has(entry.key) && locations.get(entry.key) !== index) return null;
- locations.set(entry.key, index);
- entries.push(entry);
- }
- if (base.entries[index]) entries.push(base.entries[index]);
- }
- if (!locations.size) return null;
- return { source: [base.prefix, ...entries.map(entry => entry.line), base.suffix].join('\n'), keys: [...locations.keys()] };
-}
-
-/** Resolve every unmerged file together, or leave the entire merge untouched for normal reopening. */
-export function resolveMechanicalMerge(root, files) {
- const resolutions = [];
- for (const path of files) {
- const index = spawnSync('git', ['--no-optional-locks', 'ls-files', '--stage', '-z', '--', path],
- { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8' });
- const records = (index.stdout ?? '').split('\0').filter(Boolean);
- const modes = records.map(record => /^(100644|100755) [a-f0-9]+ [123]\t/u.exec(record)?.[1]);
- if (index.status !== 0 || records.length !== 3 || modes.some(mode => !mode || mode !== modes[0])) return null;
- const stages = [1, 2, 3].map(stage => spawnSync('git', ['--no-optional-locks', 'show', `:${stage}:${path}`],
- { cwd: root, env: cleanGitEnvironment() }));
- if (stages.some(stage => stage.status !== 0 || !Buffer.isBuffer(stage.stdout)
- || !Buffer.from(stage.stdout.toString('utf8'), 'utf8').equals(stage.stdout))) return null;
- const merged = mergeMechanicalSources(path, ...stages.map(stage => stage.stdout.toString('utf8')));
- if (!merged) return null;
- resolutions.push({ path, ...merged });
- }
- for (const entry of resolutions) writeFileSync(join(root, entry.path), entry.source);
- return resolutions.map(({ path, keys }) => ({ path, keys }));
-}
+/** Compatibility exports for the shared mechanical merge decisions [B3,R3,C7]. */
+export { mergeMechanicalSources, resolveMechanicalMerge } from './mechanical-merge.js';
diff --git a/src/trunk-merge.js b/src/trunk-merge.js
index 5ff2ff47..cdc2345c 100644
--- a/src/trunk-merge.js
+++ b/src/trunk-merge.js
@@ -6,6 +6,7 @@ import { cleanGitEnvironment } from './git.js';
import { mainCheckout } from './git.js';
import { trunkRef } from './trusted-policy-read.js';
import { Refused } from './refused.js';
+import { mechanicalConflictFiles } from './mechanical-merge.js';
/** Merge a commit onto the trunk tip in memory: the ref, the tip, and the conflicting files or null [B34,V6].
*
@@ -20,34 +21,17 @@ export function trunkMerge(root, commit, retainedRef = trunkRef(root)) {
if (!branchRef?.startsWith('refs/heads/')) throw new Refused('NO_TRUNK', 'no trunk branch was recorded; check out the trunk branch in the main checkout once and run pullboard inbox');
const tip = spawnSync('git', ['--no-replace-objects', 'rev-parse', '--verify', '--quiet', branchRef + '^{commit}'], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8' });
if (tip.status !== 0) throw new Refused('NO_TRUNK', 'the recorded trunk branch has no readable tip; check out the trunk branch in the main checkout once and run pullboard inbox');
- const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.quotepath=false', 'merge-tree', '--write-tree', '--name-only', '-z', tip.stdout.trim(), commit], {
- cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
- });
- if (result.status === 0) return { ref: branchRef, commit: tip.stdout.trim(), files: null };
- if (result.status !== 1) throw new Refused('MERGE_CHECK_FAILED', 'Git could not check the candidate against the trunk; use Git 2.38 or newer, restore its objects and retry');
- const records = result.stdout.split('\0').slice(1);
- const end = records.indexOf('');
- return { ref: branchRef, commit: tip.stdout.trim(), files: records.slice(0, end < 0 ? records.length : end) };
+ const files = mechanicalConflictFiles(root, tip.stdout.trim(), commit);
+ if (files === null) throw new Refused('MERGE_CHECK_FAILED', 'Git could not check the candidate against the trunk; use Git 2.38 or newer, restore its objects and retry');
+ return { ref: branchRef, commit: tip.stdout.trim(), files: files.length ? files : null };
}
/** 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,
- });
- // 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;
+ 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;
}
diff --git a/test/mechanical-merge.test.js b/test/mechanical-merge.test.js
index 39ff3d6f..0d36f5bd 100644
--- a/test/mechanical-merge.test.js
+++ b/test/mechanical-merge.test.js
@@ -9,9 +9,13 @@ import { cleanGitEnvironment } from '../src/git.js';
import { conflictFiles } from '../src/health.js';
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';
const directories = [];
after(() => directories.forEach(root => rmSync(root, { recursive: true, force: true })));
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
/** Build divergent real commits without inherited Git identity or repository selectors. */
function fixture(path, base, left, right, extra = {}) {
@@ -113,3 +117,64 @@ for (const [name, path, base, left, right] of [
assert.deepEqual(readFileSync(join(box.root, path)), before, 'a refused resolution leaves the merge for normal conflict handling');
});
}
+
+/** Configure an ordinary private board and actual publication remote for public landing controls. */
+function boardFixture() {
+ const box = e2e.project('true');
+ const config = JSON.parse(readFileSync(join(box.repo, 'pullboard.json'), 'utf8'));
+ config.lanes.web.owns.push('docs/', 'test/');
+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify(config, null, 2));
+ mkdirSync(join(box.repo, 'docs'), { recursive: true });
+ mkdirSync(join(box.repo, 'test'), { recursive: true });
+ writeFileSync(join(box.repo, 'docs/api.md'), '# API\n\nEnd.\n');
+ writeFileSync(join(box.repo, 'test/snapshot.json'), '{"base":true}\n');
+ box.git(box.repo, 'add', '-A');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: configure mechanical landing fixture');
+ const remote = join(box.dir, 'origin.git');
+ box.git(box.dir, 'init', '-q', '--bare', remote);
+ box.git(box.repo, 'remote', 'add', 'origin', remote);
+ box.git(box.repo, 'push', '-q', '-u', 'origin', 'main');
+ return { ...box, remote };
+}
+
+/** Obtain a genuine independently verified submission with ordinary fixture authority and immutable Git bytes. */
+function accepted(box, number, files) {
+ const builder = join(box.dir, `builder-${number}`);
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', builder, 'main');
+ json(box, builder, 'join', 'web');
+ const id = json(box, box.repo, 'add', 'web', `Mechanical contribution ${number}`, '--specs', 'G1',
+ '--criterion', 'retain the actual contributed file contents', '--check', 'true').item.item_id;
+ json(box, builder, 'claim', String(id));
+ for (const [path, source] of Object.entries(files)) writeFileSync(join(builder, path), source);
+ box.git(builder, 'add', '-A');
+ const commit = e2e.commitFile(box, builder, Object.keys(files)[0], Object.values(files)[0], `feat(web): contribution ${number} [G1]`);
+ assert.equal(commit.status, 0, commit.stderr);
+ const head = box.git(builder, 'rev-parse', 'HEAD');
+ json(box, builder, 'submit', String(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'); }
+ return id;
+}
+
+test('public land retains JSON and Markdown additions, while a same-line edit really reopens [B3,R3,C7]', () => {
+ const box = boardFixture();
+ const left = accepted(box, 1, { 'test/snapshot.json': '{"base":true,"left":true}\n', 'docs/api.md': '# API\n\nLeft.\nEnd.\n' });
+ const right = accepted(box, 2, { 'test/snapshot.json': '{"base":true,"right":true}\n', 'docs/api.md': '# API\n\nRight.\nEnd.\n' });
+ const landed = json(box, box.repo, 'land', '--max', '2');
+ assert.deepEqual(landed.landed, [left, right]);
+ assert.deepEqual(landed.conflicts, []);
+ 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');
+ 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');
+});