Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): G2 door, strict sources commit to Git before the database row (GBRA-133)

garrytan92bb758c0573
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 30abd8e8be..25bea044d6 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -53,6 +53,7 @@ import { segmentWriteScope } from '../page-body/ingest.ts';
import { publicationBeliefOptions, withBeliefBatch } from '../belief/ledger.ts';
import { markBeliefCommits } from '../belief/append.ts';
import { classifyPgAccessError } from '../pg-access-classify.ts';
+import { commitThroughDoor, doorCommitLanded, doorMarker, replayAfterDoorCommit, sourceCanonicalGit, strictChanged } from './git-door.ts';
interface PreparedMutationBase {
sourceExclusive?: boolean;
@@ -526,7 +527,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
`This host does not hold source ${row.source_id}'s canonical worktree, or the file of ${row.slug} resolves outside it, so request ${row.request_id} wrote no file. Inspect the owner; the write publishes only on the host that owns the source.`,
{ fix: ownerStatusFix(row.source_id) });
const { record, bytes } = pageRecoveryRecord(row, prepared.file, binding);
- if (prepared.file.expectedBeforeHash !== undefined && record.beforeHash !== prepared.file.expectedBeforeHash) {
+ if (await sourceCanonicalGit(engine, row.source_id)) record.door = await doorMarker(binding.local_path!);
+ // G2: a strict write replayed after its door commit landed finds its own bytes, committed (git-door.ts).
+ if (prepared.file.expectedBeforeHash !== undefined && record.beforeHash !== prepared.file.expectedBeforeHash && !await replayAfterDoorCommit(record)) {
// A coordinated writer (a withdrawal mirror) also advanced the page:
// reprepare against it. Bytes changed at an unchanged revision are an
// uncoordinated edit.
@@ -579,6 +582,8 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared; nothing was written to its checkout.',
'Retry the write with a new request_id; it is now stored database-only.');
}
+ const door = recovery?.version === 1 ? recovery : null;
+ if (door && await sourceCanonicalGit(tx, row.source_id, true) !== !!door.door) throw strictChanged(row.source_id);
if (recovery) {
const records = recoveryFiles(recovery);
for (const record of records) if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) {
@@ -612,7 +617,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
const final = skill ? null : await publicationPostimage(tx, row, prepared);
decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await recordPublicationFenceTrend(tx, row, outcome);
- await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared));
+ // G2: a strict source's file is committed before its row; its Git effect only pushes.
+ if (door?.door) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await commitThroughDoor(door.door.root, [{ path: door.path, note: prepared.file?.commit }], lock ?? undefined) });
+ await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared, { pushOnly: !!door?.door }));
if (prepared.afterEffects) await withCoordinatedWrite(tx, [row.source_id], () => prepared.afterEffects!(tx, outcome), publicationAttribution(row, prepared.trust));
await hooks.boundary?.('before_commit', row);
const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);
@@ -721,7 +728,10 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
hooks.fileBoundary?.('before_restore', current, index);
const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);
if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');
- if (record.staging?.before) {
+ // G2: a strict publication whose commit landed keeps the committed file; Git holds it.
+ if (current.recovery.version === 1 && await doorCommitLanded(record)) {
+ if (record.staging?.before) await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record, { priorIntact: true }));
+ } else if (record.staging?.before) {
await withFilesystemPublication([record.root], async () => {
if (actual === record.afterHash && actual !== record.beforeHash) restoreBeforeStage(record, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));
else cleanupRecoveryStaging(record, { priorIntact: actual === record.beforeHash });
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 32a7ab2ce5..a0f0eae5a7 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -26,7 +26,7 @@ import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,
outcome: Record<string, unknown>, prepared?: PreparedMutation,
/** A grouped publication completes its members after queueing all of them, then calls `reconcileFinishedBatch` itself. */
- opts: { deferBatchReconcile?: boolean } = {}): Promise<void> {
+ opts: { deferBatchReconcile?: boolean; /** G2 (git-door.ts): the file is already committed; its Git effect only pushes. */ pushOnly?: boolean } = {}): Promise<void> {
if (prepared?.noop || prepared?.target === 'skill_bundle') return;
await declarePersistenceProtocol(tx);
const revision = snapshot?.revision;
@@ -43,8 +43,8 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
const commit = prepared.file.commit;
queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
expected_hash: prepared.file.content === null ? null : fileContentHash(prepared.file.content),
- ...(commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });
- if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
+ ...(opts.pushOnly ? { push_only: true } : commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });
+ if (!opts.pushOnly && outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
if (snapshot && !snapshot.page.deleted_at) {
if (!prepared?.deferEmbedding) queue('embedding');
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 8bc79c6034..3f402f5dcc 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -80,6 +80,8 @@ export interface PersistenceEffect {
commit_subject?: string;
commit_line?: string;
commit_trailer?: string;
+ /** G2 (git-door.ts): the file was committed with its publication (a strict source); the effect only pushes. */
+ push_only?: boolean;
/** Consecutive execution failures of the current Git or withdrawal target. */
target_failures?: number;
/** GBRA-133: consecutive `writer_busy` retries of this streak, when the streak began and when its last retry was recorded (ISO). */
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 04f93e470e..006145786b 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -907,6 +907,8 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
return;
}
const targets: { effect: PersistenceEffect; path: string; attempt: EffectAttempt }[] = [];
+ // G2 (git-door.ts): a strict source's file was committed with its publication; its effect only joins the push.
+ const committedAtPublication: PersistenceEffect[] = [];
let reclaimed = false;
try {
for (const effect of effects) {
@@ -922,6 +924,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
if (!own?.local_path || own.local_path !== binding.local_path) throw opError('source_changed', 'The effect canonical binding changed.',
`Source ${effect.source_id}'s canonical checkout no longer matches the worktree this Git group is committing, so its file was left out. Check the owner; the effect resumes under the current binding.`,
{ fix: effectStatusFix(effect) });
+ if (effect.data.push_only === true) { committedAtPublication.push(effect); continue; }
const path = await singleFileGitTarget(engine, effect, { ...own, local_path: own.local_path }, attempt);
if (path !== null) targets.push({ effect, path, attempt });
} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
@@ -940,6 +943,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
else if (outcome.reason === 'target_absent' && !ahead) await completeEffect(engine, effect, outcome);
else pending.items.push({ effect, outcome, target: attempt.target });
}
+ for (const effect of committedAtPublication) pending.items.push({ effect, outcome: { git: 'committed', at: 'publication' } });
if (pending.items.length) unpushed.set(binding.local_path, pending);
} catch (error) {
for (const { effect, attempt } of targets) await recordFailure(engine, effect, error, opts.signal, attempt.target);
diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.ts
new file mode 100644
index 0000000000..f56fd06722
--- /dev/null
+++ b/src/core/persistence/git-door.ts
@@ -0,0 +1,75 @@
+/**
+ * G2, the door (plans/git-canonical-build.md): a source whose row says `config.canonical = "git"` (strict, default off)
+ * commits each published file to Git before its database row commits. publishMutation and publishGroup commit the
+ * published paths with one path-only `commit --only` under the worktree's writer lock, after the files are renamed into
+ * place and before the database transaction commits, and stamp the commit on the receipt
+ * (`outcome.persistence.git_commit`). The Git effect of such a write only pushes.
+ *
+ * Recovery inverts for those writes: the recovery record names the HEAD it was prepared against (`door`), and a
+ * publication that stopped after its commit landed keeps the committed file instead of restoring the prior bytes.
+ * The request is queued again; its replay finds the file already holding the bytes it publishes, committed, and
+ * completes the database row against it (page-prepare.ts).
+ */
+import { relative, sep } from 'node:path';
+import { OperationError, opError } from '../ops/contract.ts';
+import { commitGitTargets } from './effect-git.ts';
+import type { GitCommitNote } from './effect-model.ts';
+import { hashFile } from './large-file.ts';
+import type { FileRecoveryRecord, SqlEngine } from './model.ts';
+import type { NativeLockHandle } from './native-lock.ts';
+import { committedBlob, headBlob, headCommit } from './pending-import.ts';
+
+/** Whether `sourceId` is a strict (git-canonical) source; `lock` reads its row FOR SHARE inside a publication. */
+export async function sourceCanonicalGit(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ strict: boolean }>(
+ `SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);
+ return row?.strict === true;
+}
+
+/** The door marker a strict publication's recovery record carries: the checkout it commits in and the HEAD it started from. */
+export async function doorMarker(root: string): Promise<NonNullable<FileRecoveryRecord['door']>> {
+ return { root, head: await headCommit(root) };
+}
+
+/** The refusal when a strict source's flag changed between preparation and publication. */
+export function strictChanged(sourceId: string): OperationError {
+ return new OperationError('source_changed', `Source ${sourceId}'s canonical mode changed after this write was prepared; nothing was published.`,
+ 'Retry the write with a new request_id.');
+}
+
+/**
+ * Commits the published files of one publication with one path-only commit under the caller's writer lock and returns
+ * the commit HEAD then names (the commit that holds these bytes, also when every path was already committed). A
+ * target Git refuses throws, so the publication rolls back and recovery restores the prior bytes.
+ */
+export async function commitThroughDoor(root: string, files: { path: string; note?: GitCommitNote }[], writerLock?: NativeLockHandle): Promise<string | null> {
+ const rel = (path: string) => relative(root, path).split(sep).join('/');
+ const notes = new Map(files.flatMap(file => file.note ? [[rel(file.path), file.note] as const] : []));
+ const outcomes = await commitGitTargets(root, files.map(file => rel(file.path)), undefined, notes, writerLock ? { writerLock } : undefined);
+ for (const [path, outcome] of outcomes) if (outcome instanceof OperationError) {
+ throw opError(outcome.code === 'git_target_ignored' ? 'git_target_ignored' : 'git_unavailable', `The strict source's commit of ${path} failed, so this write was not published.`,
+ `${outcome.message} A strict (canonical: git) source publishes a file only once Git holds it; recovery restores the prior bytes. Fix the checkout (git status on the brain host), then retry the write with a new request_id.`);
+ }
+ return headCommit(root);
+}
+
+/** Whether the working tree and HEAD both hold the record's published state at its path (its bytes, or no entry for a removal). */
+export async function holdsCommittedAfter(record: FileRecoveryRecord & { door: NonNullable<FileRecoveryRecord['door']> }): Promise<boolean> {
+ if (record.afterHash === null) return hashFile(record.path) === null && await headBlob(record.door.root, record.path) === null;
+ return hashFile(record.path) === record.afterHash && await committedBlob(record.door.root, record.path) !== null;
+}
+
+/**
+ * Whether the door commit of a stopped strict publication landed: HEAD moved past the record's starting point and
+ * holds the published state. Such a file is kept, never restored.
+ */
+export async function doorCommitLanded(record: FileRecoveryRecord): Promise<boolean> {
+ if (!record.door) return false;
+ const head = await headCommit(record.door.root);
+ return !!head && head !== record.door.head && await holdsCommittedAfter({ ...record, door: record.door });
+}
+
+/** A strict write replayed after its door commit landed: the file already holds the bytes it publishes, committed. */
+export async function replayAfterDoorCommit(record: FileRecoveryRecord): Promise<boolean> {
+ return !!record.door && record.beforeHash === record.afterHash && await holdsCommittedAfter({ ...record, door: record.door });
+}
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 2b8ab2ea8d..9e72fb256f 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -54,6 +54,7 @@ import { timePublicationStep } from './publication-timing.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
import { boundPublication, declarePublication, publicationLeaseMs, publicationTransaction, type PublicationBound } from './publication-deadline.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { commitThroughDoor, doorMarker, sourceCanonicalGit, strictChanged } from './git-door.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { isWriteTargetContained } from '../path-confine.ts';
@@ -255,7 +256,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (lane) lane.coordinationPath ??= binding.coordination_path;
let releaseCapacity: (() => void) | null = null;
const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
- let committed = false;
+ let committed = false, strict = false;
const timed: { apply: ReturnType<typeof laneApplyBegin> | null } = { apply: null };
try {
// The recovery check and the journal limits the recovery record is sized against go out together.
@@ -282,6 +283,9 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (file.expectedBeforeHash !== undefined && member.record.beforeHash !== file.expectedBeforeHash) return none;
files.set(i, member);
}
+ // G2 (git-door.ts): a strict source's members are committed together before the transaction commits.
+ strict = files.size > 0 && await sourceCanonicalGit(engine, head.source_id);
+ if (strict) { const door = await doorMarker(binding.local_path); for (const member of files.values()) member.record.door = door; }
if (files.size) {
await prepareRecoveries(engine, [...files.values()], transaction, limits);
for (const [i, member] of files) recorded.set(i, member);
@@ -307,16 +311,18 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
() => members.length ? tx.executeRaw(`UPDATE persistence_requests r SET publication_started=true FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token)
WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' RETURNING r.id`, [members.map(row => row.id), members.map(row => row.execution_token)]) : Promise.resolve([]),
() => prepared.some(member => member.file) ? sourceMirrorReadOnly(tx, head.source_id, true) : Promise.resolve(false),
+ () => recorded.size ? sourceCanonicalGit(tx, head.source_id, true) : Promise.resolve(strict),
() => tx.lockPageKeys(keys),
// The owner's host binding every file member's Git effect records (a STABLE_IN_GROUP read), fetched with the guards.
() => prepared.some(member => member.file && !member.noop) ? tx.executeRaw(HOST_BINDING_SQL, [head.worktree_id]) : Promise.resolve([]),
...storedAuthorizationReads(tx, rows, true),
]).then(results => {
- const [, live, started, readOnly] = results as [unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean];
+ const [, live, started, readOnly, strictNow] = results as [unknown, Awaited<ReturnType<typeof guardOwnership>>, unknown[], boolean, boolean];
if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.', 'Inspect the source owner with gbrain sources writer status; do not claim or transfer the source to push this write.');
if (started.length !== members.length) throw new OperationError('write_claim_lost', 'Execution claim changed before publication.', 'Another worker holds the request; inspect it rather than resubmitting.');
// A file target prepared before the source became a read-only mirror is never published (as in publishMutation, noop included).
if (readOnly) throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared.', 'The members publish one at a time.');
+ if (strictNow !== strict) throw strictChanged(head.source_id);
});
// The coordinated write's settings statement follows that pipeline. When the pipeline fails first, the
// transaction reports that failure (postgres.js names the cause of a 25P02 abort), not the settings statement's abort.
@@ -373,7 +379,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);
effects = async () => {
await recordPublicationFenceTrend(tx, row, outcome);
- await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, member, singleWrite(row) ? {} : { deferBatchReconcile: true }));
+ await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: !singleWrite(row), pushOnly: strict && !!file }));
};
outcomes.push(outcome);
} catch (error) { throw tag(error, i); }
@@ -382,6 +388,11 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}, publicationAttribution(head, prepared[0]!.trust));
// #5984 lanes: applied concurrently, committed in manifest order.
if (lane) { timed.apply?.turn(); await faultPoint('lane:applied', { requestId: head.request_id, sourceId: head.source_id, operation: head.operation }); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
+ // G2: one path-only commit for every member's file, in commit order, before the rows commit; a shared lease never reclaims an index lock.
+ if (strict && recorded.size) {
+ const commit = await commitThroughDoor(binding.local_path!, [...recorded].map(([i, member]) => ({ path: member.record.path, note: prepared[i]!.file?.commit })), lane || joined ? undefined : lock);
+ for (const i of recorded.keys()) Object.assign(outcomes[i]!.persistence as object, { git_state: 'committed', git_commit: commit });
+ }
const done = await completeGroup(tx, rows, outcomes);
// Every member is complete in this transaction: the batch's last page re-arms the batch's mention links once.
const last = rows[rows.length - 1]!;
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 82857cdf72..dc1a890fcd 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -46,6 +46,8 @@ export interface FileRecoveryRecord {
after?: string | null;
/** Absent on recovery records created by older binaries. */
staging?: import('./staging.ts').RecoveryStaging;
+ /** G2 (git-door.ts): a strict source's publication, which commits before its database row; the checkout and the HEAD it started from. */
+ door?: { root: string; head: string | null };
}
export interface BundleRecoveryRecord {
version: 2;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 2403634ed6..dab3659b1d 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -18,7 +18,8 @@ import { assertLargePageReplacement } from './large-page-guard.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { CANONICAL_FILE_MISSING } from './publication-failure.ts';
-import { committedPendingImport, pendingImportRefusal, SYNC_HELD } from './pending-import.ts';
+import { committedBlob, committedPendingImport, headBlob, pendingImportRefusal, SYNC_HELD } from './pending-import.ts';
+import { sourceCanonicalGit } from './git-door.ts';
import { readFix } from '../ops/op-fix.ts';
import { isOpPageSlug } from '../ops/context.ts';
import { shellQuote, type Action } from '../agent-output.ts';
@@ -340,6 +341,8 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
// missing still refuses below.
if (publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;
if (options.deleting === true && content === null && !snapshot.page.source_path && !capturedPath) return undefined;
+ // G2: on a strict source a removal Git already holds (a replay after the door commit landed) completes in the database.
+ if (options.deleting === true && content === null && await sourceCanonicalGit(engine, row.source_id) && await headBlob(root, path) === null) return undefined;
// #6696 (A12): tagged, so a producer can refuse this before admission and the receipt says which refusal it was.
throw opError('source_changed', 'The canonical file was removed outside coordinated publication.',
'Import the local deletion or recover the canonical file before editing this page.', { detail: CANONICAL_FILE_MISSING });
@@ -357,6 +360,10 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
// holding content the database never had is an uncoordinated edit and still refuses below.
const staleCache = !matches && before instanceof Buffer && publishesDatabaseOnly(root, row.slug, snapshot)
&& await replaceableFile(engine, row.source_id, row.slug, path).then(check => check.ok && check.expectedFileBytes === before.toString('utf8'));
+ // G2: a strict publication replayed after its door commit landed finds exactly its own bytes, committed, and completes against them.
+ const landed = !matches && !staleCache && content !== null && beforeHash() === fileContentHash(content)
+ && await sourceCanonicalGit(engine, row.source_id) && await committedBlob(root, path) !== null;
+ if (landed) return { path, root, content, expectedBeforeHash: beforeHash() };
if (!matches && !staleCache) {
const held = await heldFileRefusal(engine, row, root, path, 'drift', options.remote === true);
if (held) throw held;
diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.ts
index 6f067a75ad..9c60b9fb44 100644
--- a/src/core/persistence/params.ts
+++ b/src/core/persistence/params.ts
@@ -108,6 +108,7 @@ export const WRITE_RECEIPT_SCHEMA = {
mode: { type: 'string', enum: ['filesystem', 'database'] },
file_written: { type: 'boolean' },
git_state: { type: 'string' },
+ git_commit: { type: 'string' },
},
},
created_at: { type: 'string' },
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index be4e5100ce..7eacb35b4d 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -76,8 +76,8 @@ export async function committedPendingImport(engine: BrainEngine, sourceId: stri
const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
const rel = `./${relative(root, path).split(sep).join('/')}`;
try {
- const head = (await gitRead(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`], signal)).trim();
- if (!head || (await gitRead(root, ['hash-object', '--', rel], signal)).trim() !== head) return false;
+ const head = await committedBlob(root, path, signal);
+ if (!head) return false;
if (!source?.last_commit) return true;
await gitRead(root, ['cat-file', '-e', `${source.last_commit}^{commit}`], signal);
let imported = '';
@@ -92,6 +92,30 @@ export async function committedPendingImport(engine: BrainEngine, sourceId: stri
}
}
+/** The blob id HEAD holds at `path` (inside `root`), or null when HEAD has no entry there or Git cannot read it. Rejects only when `signal` aborts. */
+export async function headBlob(root: string, path: string, signal?: AbortSignal): Promise<string | null> {
+ return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `HEAD:./${relative(root, path).split(sep).join('/')}`], signal), signal);
+}
+
+/**
+ * The blob id HEAD holds at `path` when the working-tree file there is exactly that blob (`hash-object` applies the
+ * path's clean filters, as `git add` would); null when the file differs, is absent, or HEAD has no entry there.
+ */
+export async function committedBlob(root: string, path: string, signal?: AbortSignal): Promise<string | null> {
+ const head = await headBlob(root, path, signal);
+ if (!head) return null;
+ return await quiet(gitRead(root, ['hash-object', '--', `./${relative(root, path).split(sep).join('/')}`], signal), signal) === head ? head : null;
+}
+
+/** The commit HEAD names in `root`, or null on an unborn branch or when Git cannot read it. */
+export async function headCommit(root: string, signal?: AbortSignal): Promise<string | null> {
+ return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], signal), signal);
+}
+
+function quiet(read: Promise<string>, signal?: AbortSignal): Promise<string | null> {
+ return read.then(out => out.trim() || null, error => { if (signal?.aborted) throw error; return null; });
+}
+
/**
* The refusal: nothing was overwritten; a remember waits for its replay, any other write is resubmitted after the next sync.
* GBRA-133: neither fix starts a sync; both read the status, so no caller puts a second sync owner beside a running one.
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 58825e9553..bb1a27aa91 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -52,6 +52,8 @@ export interface WriteReceipt {
mode: 'filesystem' | 'database';
file_written?: boolean;
git_state?: string;
+ /** G2: the commit a strict (canonical: git) source's write was committed in before its row. */
+ git_commit?: string;
};
created_at?: string;
updated_at?: string;
@@ -118,6 +120,7 @@ export function isWriteReceipt(value: unknown): value is WriteReceipt {
if (!isRecord(value.persistence) || !['filesystem', 'database'].includes(String(value.persistence.mode))) return false;
if (value.persistence.file_written !== undefined && typeof value.persistence.file_written !== 'boolean') return false;
if (value.persistence.git_state !== undefined && typeof value.persistence.git_state !== 'string') return false;
+ if (value.persistence.git_commit !== undefined && typeof value.persistence.git_commit !== 'string') return false;
}
return true;
}
@@ -148,6 +151,7 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {
mode: receipt.persistence.mode,
...(receipt.persistence.file_written !== undefined ? { file_written: receipt.persistence.file_written } : {}),
...(receipt.persistence.git_state !== undefined ? { git_state: receipt.persistence.git_state } : {}),
+ ...(receipt.persistence.git_commit !== undefined ? { git_commit: receipt.persistence.git_commit } : {}),
} } : {}),
...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),
...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),
diff --git a/test/git-door-strict-gbra133.test.ts b/test/git-door-strict-gbra133.test.ts
new file mode 100644
index 0000000000..0cc89413f2
--- /dev/null
+++ b/test/git-door-strict-gbra133.test.ts
@@ -0,0 +1,180 @@
+/**
+ * G2, the door (plans/git-canonical-build.md; src/core/persistence/git-door.ts). On a strict source
+ * (`sources.config.canonical = "git"`, default off) a page write is committed to Git before its database row:
+ * - the commit exists at the publication's before_commit seam, inside the transaction, and the receipt names it;
+ * - a publication interrupted after that commit (the before_commit seam, a dropped connection) keeps the committed
+ * file instead of restoring the prior bytes, and its replay completes the row against it: one commit, the one made
+ * before the interruption (forced probe);
+ * - interrupted before the commit (after_publication), recovery restores the prior bytes and the replay commits once;
+ * - the Git effect only pushes: the remote receives the publication's commit and no second commit is made;
+ * - a source without the flag behaves as before: nothing is committed before the row, and the effect commits later.
+ * Runs on PGLite (publishMutation) and, with DATABASE_URL, on Postgres (a single write publishes as a group of one).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const putPage = operations.find(op => op.name === 'put_page')!;
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${body}\n`;
+const interruption = (code: string) => Object.assign(new Error(`database interruption ${code}`), { code });
+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);
+const put = (ctx: OperationContext, slug: string, content: string, requestId = randomUUID(), expectedRevision?: string) =>
+ putPage.handler(ctx, { slug, content, request_id: requestId, wait_ms: 30_000, ...(expectedRevision ? { expected_revision: expectedRevision } : {}) }) as Promise<Record<string, any>>;
+const receipt = async (engine: BrainEngine, requestId: string) => (await engine.executeRaw<{ state: string; outcome: Record<string, any> | null }>(
+ 'SELECT state, outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]!;
+const commitsTouching = (root: string, rel: string) => git(root, 'log', '--format=%H', '--', rel).split('\n').filter(Boolean);
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+
+for (const backend of testBackends()) describe(`[${backend}] G2: a strict source commits before its row`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ afterEach(() => installFaultHook(undefined));
+
+ test('the commit exists at before_commit, inside the transaction, and the receipt names it', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const requestId = randomUUID();
+ const seen: { head?: string; blob?: string } = {};
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:before_commit' || detail.requestId !== requestId) return;
+ seen.head = git(root, 'rev-parse', 'HEAD').trim();
+ seen.blob = git(root, 'show', 'HEAD:notes/door.md');
+ });
+ expect(await put(ctx, 'notes/door', page('Door', 'Committed before indexed.'), requestId)).toMatchObject({ state: 'committed' });
+ expect(seen.blob).toContain('Committed before indexed.');
+ const done = await receipt(engine, requestId);
+ expect(done.state).toBe('committed');
+ expect(done.outcome?.persistence).toMatchObject({ git_state: 'committed', git_commit: seen.head });
+ expect(commitsTouching(root, 'notes/door.md')).toEqual([seen.head!]);
+ expect(git(root, 'status', '--porcelain', '--', 'notes/door.md')).toBe('');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('interrupted after its commit (forced probe): the committed file is kept and the replay completes against it', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const first = await put(ctx, 'notes/kept', page('Kept', 'First revision.'));
+ expect(first).toMatchObject({ state: 'committed' });
+ const requestId = randomUUID();
+ const at: { crash?: string; file?: string } = {};
+ let thrown = 0;
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'publication:before_commit' && !thrown) { thrown++; at.crash = git(root, 'rev-parse', 'HEAD').trim(); throw interruption('CONNECTION_CLOSED'); }
+ if (point === 'publication:prepared' && thrown && at.file === undefined) at.file = readFileSync(join(root, 'notes/kept.md'), 'utf8');
+ });
+ expect(await put(ctx, 'notes/kept', page('Kept', 'Second revision.'), requestId, first.revision)).toMatchObject({ state: 'committed' });
+ expect(thrown).toBe(1);
+ // The interrupted publication's own commit holds the second revision; recovery did not restore the first.
+ expect(git(root, 'show', `${at.crash}:notes/kept.md`)).toContain('Second revision.');
+ expect(at.file).toContain('Second revision.');
+ expect(commitsTouching(root, 'notes/kept.md')[0]).toBe(at.crash!);
+ expect(commitsTouching(root, 'notes/kept.md')).toHaveLength(2);
+ expect(git(root, 'status', '--porcelain', '--', 'notes/kept.md')).toBe('');
+ const done = await receipt(engine, requestId);
+ expect(done.outcome?.persistence).toMatchObject({ git_commit: at.crash });
+ const [row] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id='default' AND slug='notes/kept'");
+ expect(row!.compiled_truth).toContain('Second revision.');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a removal interrupted after its commit is kept, and its replay deletes the row', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const first = await put(ctx, 'notes/removed', page('Removed', 'Soon gone.'));
+ expect(first).toMatchObject({ state: 'committed' });
+ const requestId = randomUUID();
+ let crash = '';
+ installFaultHook(async (point, detail) => {
+ if (point === 'publication:before_commit' && detail.requestId === requestId && !crash) { crash = git(root, 'rev-parse', 'HEAD').trim(); throw interruption('CONNECTION_CLOSED'); }
+ });
+ const deletePage = operations.find(op => op.name === 'delete_page')!;
+ expect(await deletePage.handler(ctx, { slug: 'notes/removed', request_id: requestId, expected_revision: first.revision, wait_ms: 30_000 })).toMatchObject({ state: 'committed' });
+ expect(crash).not.toBe('');
+ expect(commitsTouching(root, 'notes/removed.md')[0]).toBe(crash);
+ expect(existsSync(join(root, 'notes/removed.md'))).toBe(false);
+ const [row] = await engine.executeRaw<{ deleted: boolean }>("SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id='default' AND slug='notes/removed'");
+ expect(row?.deleted).toBe(true);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('interrupted before its commit: the prior bytes are restored and the replay commits once', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const first = await put(ctx, 'notes/restored', page('Restored', 'First revision.'));
+ expect(first).toMatchObject({ state: 'committed' });
+ const requestId = randomUUID();
+ let thrown = 0, file = '';
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'publication:after_publication' && !thrown) { thrown++; throw interruption('CONNECTION_CLOSED'); }
+ if (point === 'publication:prepared' && thrown && !file) file = readFileSync(join(root, 'notes/restored.md'), 'utf8');
+ });
+ expect(await put(ctx, 'notes/restored', page('Restored', 'Second revision.'), requestId, first.revision)).toMatchObject({ state: 'committed' });
+ expect(thrown).toBe(1);
+ expect(file).toContain('First revision.');
+ expect(commitsTouching(root, 'notes/restored.md')).toHaveLength(2);
+ expect(git(root, 'show', 'HEAD:notes/restored.md')).toContain('Second revision.');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('the Git effect only pushes: the remote gets the publication\'s commit and no second commit is made', () => managedBrain(async ({ engine, ctx, root }) => {
+ const remote = join(root, '..', 'remote.git');
+ git(root, 'init', '-q', '--bare', remote);
+ git(root, 'remote', 'add', 'origin', remote);
+ git(root, 'push', '-q', '-u', 'origin', 'HEAD');
+ await strict(engine);
+ const requestId = randomUUID();
+ expect(await put(ctx, 'notes/pushed', page('Pushed', 'Pushed by the effect.'), requestId)).toMatchObject({ state: 'committed' });
+ const head = git(root, 'rev-parse', 'HEAD').trim();
+ await settleManagedGitEffects(engine);
+ expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(head);
+ expect(git(remote, 'rev-parse', 'HEAD').trim()).toBe(head);
+ const [effect] = await engine.executeRaw<{ state: string; data: Record<string, unknown> }>(
+ "SELECT e.state, e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.request_id=$1::uuid AND e.kind='git'", [requestId]);
+ expect(effect).toMatchObject({ state: 'committed', data: { push_only: true } });
+ }, { databaseUrl, setup }), 120_000);
+
+ test('put_pages: every member is committed before its row; a group shares one commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const putPages = operations.find(op => op.name === 'put_pages')!;
+ const slugs = ['notes/g1', 'notes/g2', 'notes/g3', 'notes/g4'];
+ const batch = await putPages.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, pages: slugs.map(slug => ({ slug, content: page(slug, `Body of ${slug}.`) })) }) as Record<string, any>;
+ expect(batch).toMatchObject({ state: 'committed', counts: { committed: slugs.length, failed: 0 } });
+ const rows = await engine.executeRaw<{ slug: string; state: string; outcome: Record<string, any> }>(
+ "SELECT slug, state, outcome FROM persistence_requests WHERE source_id='default' AND slug = ANY($1::text[]) ORDER BY slug", [slugs]);
+ expect(rows.map(row => row.state)).toEqual(slugs.map(() => 'committed'));
+ for (const row of rows) expect(git(root, 'show', `${row.outcome.persistence.git_commit}:${row.slug}.md`)).toContain(`Body of ${row.slug}.`);
+ const commits = new Set(rows.map(row => row.outcome.persistence.git_commit));
+ // Postgres publishes the batch as groups (group-publish.ts): fewer commits than pages; PGLite publishes one at a time.
+ if (backend === 'postgres') expect(commits.size).toBeLessThan(slugs.length);
+ expect(git(root, 'log', '--format=%H', '--', ...slugs.map(slug => `${slug}.md`)).split('\n').filter(Boolean).sort()).toEqual([...commits].sort());
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a commit Git refuses publishes nothing: the write fails and the file is never left behind', () => managedBrain(async ({ engine, ctx, root }) => {
+ writeFileSync(join(root, '.gitignore'), 'notes/ignored.md\n');
+ git(root, 'commit', '-qam', 'ignore one path');
+ await strict(engine);
+ const head = git(root, 'rev-parse', 'HEAD').trim();
+ const result = await put(ctx, 'notes/ignored', page('Ignored', 'Never published.')).then(value => value, (error: { code?: string }) => ({ thrown: error.code }));
+ expect(result).toMatchObject({ thrown: 'git_target_ignored' });
+ expect(existsSync(join(root, 'notes/ignored.md'))).toBe(false);
+ expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(head);
+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug='notes/ignored' AND deleted_at IS NULL")).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('without the flag nothing is committed before the row; the effect commits it later', () => managedBrain(async ({ engine, ctx, root }) => {
+ const requestId = randomUUID();
+ let blob: string | null = 'unread';
+ const initial = git(root, 'rev-parse', 'HEAD').trim();
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:before_commit' || detail.requestId !== requestId) return;
+ blob = git(root, 'rev-parse', 'HEAD').trim() === initial ? null : 'moved';
+ });
+ expect(await put(ctx, 'notes/classic', page('Classic', 'Committed by the effect.'), requestId)).toMatchObject({ state: 'committed' });
+ expect(blob).toBeNull();
+ const done = await receipt(engine, requestId);
+ expect(done.outcome?.persistence?.git_commit).toBeUndefined();
+ expect(done.outcome?.persistence?.git_state).toBe('queued');
+ await settleManagedGitEffects(engine);
+ expect(commitsTouching(root, 'notes/classic.md')).toHaveLength(1);
+ }, { databaseUrl, setup }), 120_000);
+});