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.

feat(sync): share ordered moves through Git [H11,H10,C3]

Corey Olson7786475a9512
diff --git a/src/cli-sync.js b/src/cli-sync.js
index 95af3e69..81b576d8 100644
--- a/src/cli-sync.js
+++ b/src/cli-sync.js
@@ -10,6 +10,8 @@ import { Refused } from './refused.js';
import { syncRelay } from './relay.js';
import { executePersonRequests } from './relay-request-execution.js';
import { autoLinkProject } from './relay-setup.js';
+import { gitSyncLinked } from './local-state.js';
+import { context, withBoard } from './cli-context.js';
/** Codes a checkout with no board refuses with, which the sync around a command keeps quiet. */
const QUIET = ['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'];
@@ -27,6 +29,10 @@ async function reportQuietly(io, error) {
/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
export async function retrySync(io) {
try {
+ if (io.relayCommand?.cliOperation !== 'sync' && gitSyncLinked(io.cwd)) {
+ const ctx = context(io);
+ await withBoard(ctx, board => import('./sync.js').then(sync => sync.syncGitBoard(io.cwd, board, io)));
+ }
io.relayOutbox ??= () => relayOutboxSetting(io.cwd);
await syncRelay(io.cwd, io);
await retryCheckBaselines(io.cwd, io);
@@ -36,7 +42,7 @@ export async function retrySync(io) {
/** Before a command: link this project when the machine links new ones, sync, then run the person's waiting requests. */
export async function syncBefore(io, main) {
- try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }
+ try { if (io.relayCommand?.cliOperation !== 'sync' && !gitSyncLinked(io.cwd)) await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }
await retrySync(io);
try { await executePersonRequests(io.cwd, io, main); }
catch (error) { await reportQuietly(io, error); }
diff --git a/src/cli.js b/src/cli.js
index 6a572f5a..b9e7dc84 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -10,6 +10,7 @@ import {
barCoverageForPolicy,
} from './bar-coverage.js';
import { identifyCaller } from './cli-identity.js';
+import { gitSyncLinked } from './local-state.js';
/**
* The pullboard command line: every command, bound to who is asking (B3, R3). The main checkout is the
* coordinator; every other worktree is the agent that joined from it.
@@ -583,7 +584,9 @@ export async function ordered(ctx, board, operation, args) {
const values = [{ agentId, baseline: initialBaseline }];
const baselineIo = ctx.io.personRequest || ctx.io.personRequestMoveId
? { ...ctx.io, personRequest: undefined, personRequestMoveId: undefined } : ctx.io;
- return relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
+ return gitSyncLinked(ctx.info.root)
+ ? (await import('./sync.js')).gitBoardOperation(ctx.info.root, board, 'recordSpecApprovalBaseline', values, baselineIo)
+ : relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
? relayOperation(ctx.info.root, 'recordSpecApprovalBaseline', values, baselineIo, undefined,
() => store.recordSpecApprovalBaseline(board, ...values))
: store.recordSpecApprovalBaseline(board, ...values);
@@ -601,9 +604,12 @@ export async function ordered(ctx, board, operation, args) {
if (requested && board.lastEvent !== before) ctx.io.recordedMove = true;
return result;
};
- const result = await withItemSession(ctx.info, operation, args, () => relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io, command, applyRequested,
- requested ? () => { ctx.io.recordedMove = true; } : undefined) : applyRequested());
+ const result = await withItemSession(ctx.info, operation, args, async () => gitSyncLinked(ctx.info.root)
+ ? (await import('./sync.js')).gitBoardOperation(ctx.info.root, board, operation, args, ctx.io)
+ : relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command, applyRequested,
+ requested ? () => { ctx.io.recordedMove = true; } : undefined) : applyRequested());
+ if (requested && gitSyncLinked(ctx.info.root)) ctx.io.recordedMove = true;
return result;
};
const digest = agentSessionDigest();
@@ -706,7 +712,7 @@ export function refuseRemoteCoordinatorModel(ctx, command) {
/** Resolve the caller with the existing environment and relay identity checks. */
export function whoAmI(ctx, board) {
- return identifyCaller(ctx, board, { environmentAgent, relayLinked });
+ return identifyCaller(ctx, board, { environmentAgent, relayLinked: root => relayLinked(root) || gitSyncLinked(root) });
}
/**
diff --git a/src/commands/hook.js b/src/commands/hook.js
index 8ed1a414..d991a311 100644
--- a/src/commands/hook.js
+++ b/src/commands/hook.js
@@ -26,6 +26,7 @@ import {
FIX_NOTE,
preCommitProblems,
prePushProblems,
+ gitBoardDataPush,
pushesTrunk,
} from '../hooks.js';
import {
@@ -88,6 +89,10 @@ export async function hookCommand(io, { first, second }) {
problems = commitMsgProblems(message, { rules: ctx.config.commits, spec, doctrine: ctx.doctrine, claimedItems });
} else if (first === 'pre-push') {
const refsText = await readStdin(io.stdin);
+ if (gitBoardDataPush(info.root, refsText)) {
+ io.say('pre-push: validated append-only board data; no code refs are updated');
+ return 0;
+ }
problems = prePushProblems(info.root, refsText);
if (!problems.length) {
const landing = pushesTrunk(refsText, trunkRef(info.root));
diff --git a/src/commands/relay.js b/src/commands/relay.js
index ac3f4fc0..f6c30fea 100644
--- a/src/commands/relay.js
+++ b/src/commands/relay.js
@@ -1,5 +1,6 @@
/** The pullboard relay command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
+import { gitSyncLinked } from '../local-state.js';
import {
requirePersonChannel,
} from '../person.js';
@@ -46,6 +47,7 @@ import {
/** Run `pullboard relay` and return its exit code. */
export async function run(io, { first, second, rest, values }) {
+ if (['on', 'join'].includes(first) && gitSyncLinked(io.cwd)) throw new Refused('GIT_SYNC_LINKED', 'this board already shares moves through Git; it cannot start a second move order', 'keep using pullboard sync for this board');
if (values['new-browser'] && first !== 'pair') throw new Refused('USAGE', 'pullboard relay pair --new-browser');
if (first === 'recover') {
if (second || rest.length || !values.skip || values.url || values.all) throw new Refused('USAGE', 'pullboard relay recover --skip <exact blocked next sequence>');
diff --git a/src/commands/sync.js b/src/commands/sync.js
new file mode 100644
index 00000000..9f3f73f0
--- /dev/null
+++ b/src/commands/sync.js
@@ -0,0 +1,16 @@
+/** Explicit opt-in to account-free sharing through the repository's own Git remote [H11]. */
+import { context, withBoard } from '../cli-context.js';
+import { relayLinked, relayRecovered } from '../relay.js';
+import { syncGitBoard } from '../sync.js';
+import { Refused } from '../refused.js';
+
+/** Publish or receive the board's acknowledged Git prefix without signing into a relay account. */
+export async function run(io, { first }) {
+ if (first) throw new Refused('USAGE', 'pullboard sync takes no arguments; it shares through origin');
+ const ctx = context(io);
+ if (relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)) throw new Refused('GIT_SYNC_LINKED', 'this board already uses the relay; it cannot use a second move order', 'keep syncing this board through its relay');
+ const result = await withBoard(ctx, board => syncGitBoard(ctx.info.root, board, io, { settlePending: true }));
+ io.result?.(result);
+ io.say(`board shared through origin at move ${result.sequence}`);
+ return 0;
+}
diff --git a/src/git-sync-format.js b/src/git-sync-format.js
new file mode 100644
index 00000000..7deb3000
--- /dev/null
+++ b/src/git-sync-format.js
@@ -0,0 +1,65 @@
+/** Validate the one data-only ref that carries account-free board moves [H11]. */
+import { git, gitChildEnv } from './git.js';
+import { Refused } from './refused.js';
+
+export const GIT_BOARD_REF = 'refs/pullboard/board';
+const SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
+
+/** Refuse malformed data before it can bypass a code-push gate or reach the board engine. */
+function invalid() {
+ throw new Refused('GIT_SYNC_LOG', 'the Git board ref must contain only a linear validated board-data log', 'restore the append-only refs/pullboard/board data history before syncing');
+}
+
+/** Validate one commit's sole JSON blob, parent shape, envelope and executable move shape. */
+export function validateGitBoardCommit(root, sha, expectedParent) {
+ if (!SHA.test(sha)) invalid();
+ let parents;
+ let entries;
+ let payload;
+ try {
+ const env = gitChildEnv(root);
+ parents = git(root, ['show', '-s', '--format=%P', sha], { env }).split(/\s+/u).filter(Boolean);
+ entries = git(root, ['ls-tree', sha], { env });
+ if (!/^100644 blob [0-9a-f]{40,64}\tpayload\.json$/u.test(entries)) invalid();
+ payload = JSON.parse(git(root, ['show', sha + ':payload.json'], { env, maxBuffer: 64 * 1024 * 1024 }));
+ } catch (error) { if (error instanceof Refused) throw error; invalid(); }
+ if (parents.length > 1 || expectedParent !== undefined && parents.join('') !== (expectedParent ?? '')) invalid();
+ if (!payload || payload.version !== 1 || !['baseline', 'move'].includes(payload.kind)) invalid();
+ if (payload.kind === 'baseline') {
+ if (parents.length || payload.snapshot?.version !== 1 || !payload.snapshot.tables ||
+ !Array.isArray(payload.snapshot.tables.board_meta) || !Array.isArray(payload.snapshot.tables.agent) ||
+ Object.keys(payload).sort().join(',') !== 'kind,snapshot,version') invalid();
+ } else {
+ const move = payload.move;
+ if (parents.length !== 1 || !Number.isSafeInteger(payload.sequence) || payload.sequence < 1 ||
+ !Number.isFinite(Date.parse(payload.at)) || typeof payload.at !== 'string' ||
+ Object.keys(payload).sort().join(',') !== 'at,kind,move,sequence,version' ||
+ !move || move.version !== 1 || !Number.isSafeInteger(move.engine) || move.engine < 1 ||
+ !/^[A-Za-z0-9_-]{1,80}$/u.test(move.id ?? '') || typeof move.operation !== 'string' || !Array.isArray(move.args)) invalid();
+ }
+ return payload;
+}
+
+/** Recognize exclusively validated board-data pushes; mixed/code ref updates keep all ordinary gates. */
+export function gitBoardDataPush(root, refsText) {
+ const lines = refsText.split('\n').filter(line => line.trim());
+ if (!lines.length || lines.some(line => line.trim().split(/\s+/u)[2] !== GIT_BOARD_REF)) return false;
+ for (const line of lines) {
+ const [, local, , previous] = line.trim().split(/\s+/u);
+ if (!SHA.test(local ?? '') || /^0+$/u.test(local)) invalid();
+ const initial = /^0+$/u.test(previous ?? '');
+ if (!initial && !SHA.test(previous ?? '')) invalid();
+ const names = git(root, ['rev-list', '--reverse', '--first-parent', ...(initial ? [local] : [previous + '..' + local])], { env: gitChildEnv(root) }).split('\n').filter(Boolean);
+ let parent = initial ? null : previous;
+ let sequence = initial ? 0 : validateGitBoardCommit(root, previous).sequence ?? 0;
+ if (!names.length && local !== previous) invalid();
+ for (const name of names) {
+ const record = validateGitBoardCommit(root, name, parent);
+ if (parent ? record.kind !== 'move' || record.sequence !== sequence + 1 : record.kind !== 'baseline') invalid();
+ sequence = record.sequence ?? 0;
+ parent = name;
+ }
+ if (parent !== local) invalid();
+ }
+ return true;
+}
diff --git a/src/help.js b/src/help.js
index 0bf71342..752ee9e6 100644
--- a/src/help.js
+++ b/src/help.js
@@ -166,6 +166,8 @@ Work
pullboard digest [--out <file>] [--watch] a short Markdown briefing of this board for a person or a chat assistant;
secrets redacted; --out replaces a file, --watch rewrites it after every move
pullboard import <file> restore a versioned export into an empty board
+ pullboard sync opt in to sharing one board through origin without an account
+ reads work offline; moves need remote acknowledgement
Coordinator
pullboard sweep --run "<checker>" --check "<checker on {file}>" [--route light] [--max 20] [--dry-run]
@@ -306,7 +308,7 @@ const HELP_EXAMPLES = {
verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',
watch: 'pullboard watch --to web', answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',
status: 'pullboard status', view: 'pullboard view', digest: 'pullboard digest --out briefing.md', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
- relay: 'pullboard relay on --all', 'relay recover': 'pullboard relay recover --skip 12',
+ relay: 'pullboard relay on --all', 'relay recover': 'pullboard relay recover --skip 12', sync: 'pullboard sync',
'lane add': 'pullboard lane add web --owns apps/web/', lane: 'pullboard lane add web --owns apps/web/',
queue: 'pullboard queue', roadmap: 'pullboard roadmap', rigor: 'pullboard rigor', 'rigor quality': 'pullboard rigor quality --rule silent-catch', 'rigor draft': 'pullboard rigor draft "refusal:MERGE_LOST" "Merges keep every hunk" --check "node bin/checks/merges.js" --red 0123456 --green 89abcde', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
'milestone order': 'pullboard milestone order "0.7.0" 13,12',
diff --git a/src/hooks.js b/src/hooks.js
index 87e29b9f..91ba3be8 100644
--- a/src/hooks.js
+++ b/src/hooks.js
@@ -7,6 +7,8 @@ import {
execFileSync,
spawnSync,
} from 'node:child_process';
+import { gitBoardDataPush } from './git-sync-format.js';
+export { gitBoardDataPush };
import { hostname } from 'node:os';
import {
chmodSync,
@@ -740,6 +742,7 @@ export function deletedRowProblems(root, paths) {
* @returns {string[]}
*/
export function prePushProblems(root, refsText) {
+ if (gitBoardDataPush(root, refsText)) return [];
if (tryGit(root, ['diff', '--quiet', 'HEAD']).status !== 0) {
return ['commit or stash your changes first; the gate must check what you push'];
}
diff --git a/src/local-state.js b/src/local-state.js
index 3000a875..9eb25ea3 100644
--- a/src/local-state.js
+++ b/src/local-state.js
@@ -35,6 +35,11 @@ export function relayLinkFile(commonDir) {
return join(commonDir, 'pullboard', 'relay.json');
}
+/** Whether this machine explicitly enabled account-free Git board sharing [H11]. */
+export function gitSyncLinked(root) {
+ return existsSync(join(repoInfo(root).commonDir, 'pullboard', 'git-sync.json'));
+}
+
/** A repository's notice that its relay copy was deleted, which relay status still reads. */
export function relayDeletedFile(commonDir) {
return join(commonDir, 'pullboard', 'relay-deleted.json');
@@ -72,7 +77,7 @@ export function syncMayAct(cwd) {
// Outside a repository every step refuses quietly with these codes; any other failure takes the full path.
return !(error instanceof Refused && ['NOT_A_REPO', 'CORE_BARE'].includes(error.code));
}
- if (existsSync(relayLinkFile(info.commonDir))) return true;
+ if (existsSync(relayLinkFile(info.commonDir)) || existsSync(join(info.commonDir, 'pullboard', 'git-sync.json'))) return true;
const receipts = baselineReceiptDirectory(info.commonDir);
return existsSync(receipts) && readdirSync(receipts).some((name) => BASELINE_RECEIPT.test(name));
}
diff --git a/src/spec-approval-bootstrap.js b/src/spec-approval-bootstrap.js
index 4f2c4c62..92976c05 100644
--- a/src/spec-approval-bootstrap.js
+++ b/src/spec-approval-bootstrap.js
@@ -9,10 +9,11 @@ import {
relayRecovered,
} from './relay.js';
import { captureSpecApprovalBaseline } from './spec-approval.js';
+import { gitSyncLinked } from './local-state.js';
/** Establish cold local authority inside the checkout lease; linked and recovered moves keep relay authority. */
export function ensureSpecApprovalCoordinator(ctx, board, baseline) {
- if (!baseline || !ctx.info.isMain || relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)) return;
+ if (!baseline || !ctx.info.isMain || relayLinked(ctx.info.root) || relayRecovered(ctx.info.root) || gitSyncLinked(ctx.info.root)) return;
ensureCoordinator(board, ctx.info.root);
}
diff --git a/src/sync.js b/src/sync.js
new file mode 100644
index 00000000..c3d2b330
--- /dev/null
+++ b/src/sync.js
@@ -0,0 +1,216 @@
+/** Account-free ordered moves on the repository's own Git remote [H11,H10]. */
+import { spawn } from 'node:child_process';
+import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import * as store from './board.js';
+import { exportBoard, importBoard, semanticBoardDigest } from './exchange.js';
+import { appliedSequence, applyEngineMove, engineReceipt, prepareEngineMove } from './engine.js';
+import { gitChildEnv, repoInfo } from './git.js';
+import { locked } from './relay-lock.js';
+import { Refused } from './refused.js';
+import { GIT_BOARD_REF, validateGitBoardCommit } from './git-sync-format.js';
+
+const PREFIX = 'local:git-sync:';
+const CACHE = 'refs/pullboard/cache';
+
+/** Keep the transport marker and pending intent in the shared Git directory of this machine. */
+function paths(root) {
+ const info = repoInfo(root);
+ const folder = join(info.commonDir, 'pullboard');
+ return { marker: join(folder, 'git-sync.json'), pending: join(folder, 'git-sync-pending.json') };
+}
+
+/** Detect an explicitly enabled Git transport without making network requests. */
+export function gitSyncLinked(root) {
+ return existsSync(paths(root).marker);
+}
+
+/** Run real Git with repository selectors scrubbed and captured output. */
+function git(root, args, input = '') {
+ return new Promise((resolve, reject) => {
+ const child = spawn('git', ['--no-replace-objects', ...args], { cwd: root, env: gitChildEnv(root), stdio: ['pipe', 'pipe', 'pipe'] });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8').on('data', value => { stdout += value; });
+ child.stderr.setEncoding('utf8').on('data', value => { stderr += value; });
+ child.on('error', reject);
+ child.on('close', status => resolve({ status, stdout: stdout.trim(), stderr: stderr.trim() }));
+ child.stdin.on('error', () => {});
+ child.stdin.end(input);
+ });
+}
+
+/** Turn a Git failure into a stable named refusal, without claiming an unacknowledged move succeeded. */
+async function required(root, args, input) {
+ const result = await git(root, args, input);
+ if (result.status !== 0) throw new Refused('GIT_SYNC_REMOTE', 'the repository remote did not acknowledge Git board sync; local reads remain available and the pending move is preserved', 'restore access to origin, then retry the command or run pullboard sync');
+ return result.stdout;
+}
+
+/** Atomically replace a local marker or sealed pending intent before any network publication. */
+function save(file, value) {
+ const temporary = file + '.' + randomUUID() + '.tmp';
+ writeFileSync(temporary, JSON.stringify(value) + '\n', { mode: 0o600 });
+ renameSync(temporary, file);
+}
+
+/** Read transport metadata committed in the same SQLite transaction as its replayed move. */
+function meta(board, key) {
+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(PREFIX + key)?.meta_value ?? null;
+}
+
+/** Remember the exact applied Git prefix together with its native last event. */
+function remember(board, tip) {
+ const put = board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value');
+ put.run(PREFIX + 'tip', tip);
+ put.run(PREFIX + 'event', String(board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS id FROM event').get().id));
+}
+
+/** Refuse local event writes made outside the enabled ordered transport instead of overwriting them. */
+function requirePrefix(board) {
+ if (meta(board, 'tip') === null) return;
+ const event = String(board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS id FROM event').get().id);
+ if (event !== meta(board, 'event')) throw new Refused('GIT_SYNC_LOCAL_CHANGED', 'this board has local moves outside its shared Git prefix; they were preserved', 'export the local board and ask the coordinator to reconcile it before syncing');
+}
+
+/** Fetch only the dedicated board ref; a missing ref means this remote has no shared board yet. */
+async function fetchTip(root) {
+ const advertised = await required(root, ['ls-remote', '--refs', 'origin', GIT_BOARD_REF]);
+ if (!advertised) return null;
+ await required(root, ['fetch', '--no-tags', 'origin', '+' + GIT_BOARD_REF + ':' + CACHE]);
+ return required(root, ['rev-parse', CACHE]);
+}
+
+/** Write a data-only Git commit without touching the worktree, index or code refs. */
+async function commit(root, payload, parent) {
+ const blob = await required(root, ['hash-object', '-w', '--stdin'], JSON.stringify(payload) + '\n');
+ const tree = await required(root, ['mktree'], '100644 blob ' + blob + '\tpayload.json\n');
+ return required(root, ['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', 'pullboard: ordered board data']);
+}
+
+/** Append with an exact compare-and-swap lease; normal push hooks remain in force. */
+async function publish(root, head, previous) {
+ const result = await git(root, ['push', '--porcelain', '--force-with-lease=' + GIT_BOARD_REF + ':' + (previous ?? ''), 'origin', head + ':' + GIT_BOARD_REF]);
+ return result.status === 0;
+}
+
+/** Validate the whole linear data log before importing or applying any of its prefix. */
+async function log(root, tip) {
+ const names = (await required(root, ['rev-list', '--reverse', '--first-parent', tip])).split('\n');
+ const records = [];
+ let parent = null;
+ for (const name of names) {
+ const payload = await validateGitBoardCommit(root, name, parent);
+ if (payload.kind !== (parent ? 'move' : 'baseline') || parent && payload.sequence !== records.length) throw new Refused('GIT_SYNC_LOG', 'the Git board log is not a contiguous ordered prefix', 'restore the append-only refs/pullboard/board history before syncing');
+ records.push({ hash: name, payload });
+ parent = name;
+ }
+ return records;
+}
+
+/** Import only a fresh clone, then replay acknowledged moves through the existing deterministic engine. */
+async function reconcile(root, board) {
+ requirePrefix(board);
+ const tip = await fetchTip(root);
+ if (!tip) {
+ if (meta(board, 'tip')) throw new Refused('GIT_SYNC_LOG', 'the shared Git board ref disappeared; the local prefix was preserved', 'restore refs/pullboard/board on origin before syncing');
+ return null;
+ }
+ const records = await log(root, tip);
+ let local = meta(board, 'tip');
+ if (!local) {
+ const snapshot = records[0].payload.snapshot;
+ if (semanticBoardDigest(exportBoard(board)) !== semanticBoardDigest(snapshot)) importBoard(board, snapshot);
+ store.atomic(board, () => remember(board, records[0].hash));
+ local = records[0].hash;
+ }
+ const offset = records.findIndex(record => record.hash === local);
+ if (offset < 0) throw new Refused('GIT_SYNC_LOG', 'the remote rewrote this machine\'s acknowledged board prefix; local state was preserved', 'restore the append-only refs/pullboard/board history before syncing');
+ for (const { hash, payload } of records.slice(offset + 1)) {
+ store.atomic(board, () => {
+ applyEngineMove(board, payload.move, { sequence: payload.sequence, at: payload.at });
+ remember(board, hash);
+ });
+ }
+ save(paths(root).marker, { version: 1, remote: 'origin', ref: GIT_BOARD_REF });
+ return tip;
+}
+
+/** Establish one baseline, resolving simultaneous initial publishers without merging unrelated local boards. */
+async function establish(root, board) {
+ let tip = await reconcile(root, board);
+ if (tip) return tip;
+ if (appliedSequence(board) !== 0) throw new Refused('GIT_SYNC_LINKED', 'this board already has relay-ordered history; Git sync cannot start a second transport', 'use the existing relay for this board, or initialize a separate board');
+ const snapshot = exportBoard(board);
+ const initial = await commit(root, { version: 1, kind: 'baseline', snapshot }, null);
+ if (await publish(root, initial, null)) {
+ store.atomic(board, () => remember(board, initial));
+ save(paths(root).marker, { version: 1, remote: 'origin', ref: GIT_BOARD_REF });
+ return initial;
+ }
+ tip = await reconcile(root, board);
+ if (!tip) throw new Refused('GIT_SYNC_REMOTE', 'origin refused the initial shared board; no move was recorded', 'restore write access to origin, then run pullboard sync');
+ return tip;
+}
+
+/** Publish the same sealed intent after a rejected or uncertain push, recognizing an already accepted ID. */
+async function settle(root, board, pending) {
+ for (let attempt = 0; attempt < 8; attempt++) {
+ const tip = await reconcile(root, board);
+ if (!tip) throw new Refused('GIT_SYNC_LOG', 'the shared Git board ref disappeared; the pending move was preserved', 'restore refs/pullboard/board before retrying');
+ const previous = engineReceipt(board, pending.move.id);
+ if (previous) {
+ rmSync(paths(root).pending, { force: true });
+ return previous.outcome;
+ }
+ const payload = { version: 1, kind: 'move', sequence: appliedSequence(board) + 1, at: new Date().toISOString(), move: pending.move };
+ const head = await commit(root, payload, tip);
+ if (await publish(root, head, tip)) {
+ await reconcile(root, board);
+ const receipt = engineReceipt(board, pending.move.id);
+ if (!receipt) throw new Refused('GIT_SYNC_LOG', 'the acknowledged Git move has no replay receipt; the pending move was preserved', 'restore the complete shared Git log before retrying');
+ rmSync(paths(root).pending, { force: true });
+ return receipt.outcome;
+ }
+ }
+ throw new Refused('GIT_SYNC_REMOTE', 'origin did not acknowledge the shared move after competing pushes; the same sealed move is pending', 'restore access to origin, then retry the command or run pullboard sync');
+}
+
+/** Sync only after explicit opt-in; a normal read catches network refusals and keeps its local prefix. */
+export async function syncGitBoard(root, board, io, { settlePending = false } = {}) {
+ const file = paths(root);
+ return locked(file.marker, async () => {
+ save(file.marker, { version: 1, remote: 'origin', ref: GIT_BOARD_REF });
+ await establish(root, board);
+ const pending = existsSync(file.pending) ? JSON.parse(readFileSync(file.pending, 'utf8')) : null;
+ const outcome = settlePending && pending ? await settle(root, board, pending) : null;
+ if (outcome?.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
+ return { version: 1, ref: GIT_BOARD_REF, sequence: appliedSequence(board), pending: pending && !settlePending ? pending.move.id : null };
+ }, io);
+}
+
+/** Route a mutation through the single remote order, retaining a pending intent before its first push. */
+export async function gitBoardOperation(root, board, operation, args, io = {}) {
+ const file = paths(root);
+ return locked(file.marker, async () => {
+ // An enabled replica seals its intent before its first network attempt, including an outage.
+ if (!meta(board, 'tip')) await establish(root, board);
+ const command = JSON.stringify(io.relayCommand ?? { operation, args });
+ let pending = existsSync(file.pending) ? JSON.parse(readFileSync(file.pending, 'utf8')) : null;
+ let outcome;
+ if (pending) {
+ outcome = await settle(root, board, pending);
+ if (pending.command === command && pending.move.operation === operation) {
+ if (outcome.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
+ return outcome.result;
+ }
+ if (outcome.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
+ }
+ pending = { version: 1, command, at: new Date().toISOString(), move: prepareEngineMove(board, operation, args) };
+ save(file.pending, pending);
+ outcome = await settle(root, board, pending);
+ if (outcome.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
+ return outcome.result;
+ }, io);
+}
diff --git a/test/sync.test.js b/test/sync.test.js
index 2ef9729c..bc6ddcad 100644
--- a/test/sync.test.js
+++ b/test/sync.test.js
@@ -1,7 +1,7 @@
/** @pullboard-test-input source-tree */
/** Two independent Git clones and SQLite replicas exercise account-free sharing [H11]. */
import assert from 'node:assert/strict';
-import { chmodSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { test } from 'node:test';
import { createE2eHelpers } from './e2e-helpers.js';
@@ -55,3 +55,41 @@ test('two machines share a board through git [H11]', async t => {
assert.equal(board.tables.event.filter(event => event.event_kind === 'claim').length, 1, 'only the winning claim becomes a move');
}
});
+
+test('Git sharing preserves offline reads, a pending move and ordinary code gates [H11,H10,C3]', t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project();
+ const remote = join(box.dir, 'remote.git');
+ box.git(box.dir, 'clone', '--bare', box.repo, remote);
+ box.git(box.repo, 'remote', 'add', 'origin', remote);
+ document(box.run(box.repo, 'sync', '--json'), 'enable Git board sharing');
+ renameSync(remote, remote + '.offline');
+ assert.equal(document(box.run(box.repo, 'export'), 'read the board while offline').tables.item.length, 0);
+ const refused = box.run(box.repo, 'add', 'web', 'One pending move', '--json');
+ assert.notEqual(refused.code, 0, 'an offline move cannot report success');
+ assert.equal(JSON.parse(refused.out).error.code, 'GIT_SYNC_REMOTE');
+ const pendingFile = join(box.repo, '.git', 'pullboard', 'git-sync-pending.json');
+ assert.ok(existsSync(pendingFile), 'the refused command retains its sealed intent');
+ const moveId = JSON.parse(readFileSync(pendingFile, 'utf8')).move.id;
+ assert.equal(document(box.run(box.repo, 'export'), 'offline read does not apply the pending move').tables.item.length, 0);
+ renameSync(remote + '.offline', remote);
+ const recovered = document(box.run(box.repo, 'add', 'web', 'One pending move', '--json'), 'retry the same public command');
+ assert.equal(recovered.item.item_id, 1);
+ assert.equal(existsSync(pendingFile), false);
+ const exported = document(box.run(box.repo, 'export'), 'read the acknowledged pending move');
+ assert.equal(exported.tables.item.length, 1, 'the retried command creates one item');
+ assert.ok(exported.tables.board_meta.some(row => row.meta_key === 'relay_receipt_' + moveId), 'the original sealed identity was acknowledged');
+ writeFileSync(join(box.repo, 'web.txt'), 'a source change\n');
+ box.git(box.repo, 'add', 'web.txt');
+ box.git(box.repo, 'commit', '-m', 'feat(web): a code change [G1]');
+ writeFileSync(join(box.repo, 'RED'), 'the code gate fails\n');
+ assert.notEqual(box.tryGit(box.repo, 'push', 'origin', 'HEAD:main').status, 0, 'ordinary code pushes still run and fail the code gate');
+ document(box.run(box.repo, 'add', 'web', 'Board data while code gate is red', '--json'), 'normal Git push accepts validated board data without shipping code');
+ const before = box.git(box.repo, 'ls-remote', 'origin', 'refs/pullboard/board');
+ const tip = before.split(/\s/u)[0];
+ const wrongTree = box.git(box.repo, 'rev-parse', 'HEAD^{tree}');
+ const badData = box.git(box.repo, 'commit-tree', wrongTree, '-p', tip, '-m', 'not board data');
+ assert.notEqual(box.tryGit(box.repo, 'push', 'origin', badData + ':refs/pullboard/board').status, 0, 'a fast-forward code tree cannot masquerade as the board-data ref');
+ assert.equal(box.git(box.repo, 'ls-remote', 'origin', 'refs/pullboard/board'), before, 'the malformed data push leaves the remote untouched');
+});