Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
A landed adoption is also proved by the ledger's intent line when its commit line is missing
garrytan56c2b8fca714
diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.tsindex bf7ff167c2..552b5ae154 100644--- a/src/core/persistence/local-edit-adoption.ts+++ b/src/core/persistence/local-edit-adoption.ts@@ -55,8 +55,8 @@ import { declarePersistenceProtocol } from './protocol.ts';import type { WorktreeBinding } from './ownership.ts';import { getWorktreeBinding } from './ownership.ts';import { fileMatchesSnapshot, protectedLocalEdit } from './page-prepare.ts';-import { blobAt, blobText, commitMessage, headBlob, headCommit, landedCommit, operationMarkerPaths, unmergedPath } from './pending-import.ts';-import { ledgerLocation, readLedger } from '../git/commit-ledger.ts';+import { blobAt, blobText, commitMessage, commitParent, headBlob, headCommit, landedCommit, operationMarkerPaths, unmergedPath } from './pending-import.ts';+import { ledgerLocation, messageDigest, readLedger } from '../git/commit-ledger.ts';import { adoptedBy, localEditAdoptionCommit, type GitCommitNote } from './effect-model.ts';import { claimOwner } from './claim-phase.ts';import type { PreparedMutation } from './coordinator.ts';@@ -226,7 +226,9 @@ export async function assertAdoptionCaller(engine: BrainEngine, row: WriteReques/*** #8824: the commit of this adoption when HEAD already holds it: the newest commit on the path is `gbrain: adopt local edit* to <path>` carrying this adoption's `gbrain-adopted:` trailer and commit-ledger line, its parent held the pre-adoption- * blob, and HEAD holds the adopted blob. Null otherwise, on a repo-less brain, or when Git or the ledger cannot be read.+ * blob, and HEAD holds the adopted blob. The ledger's commit line is best-effort (written after `git commit`), so the+ * intent line written before it also proves the commit when its `head_before` is the commit's parent and its message+ * digest is the commit's. Null otherwise, on a repo-less brain, or when Git or the ledger cannot be read.* A replay that finds it publishes whatever became of its caller (the commit is durable), and its receipt names it.*/export async function landedAdoptionCommit(root: string, target: string, adopted: { path: string; blob: string; replaced_revision: string; head: string | null }): Promise<string | null> {@@ -234,13 +236,16 @@ export async function landedAdoptionCommit(root: string, target: string, adoptedconst commit = await landedCommit(root, null, target);if (!commit || await blobAt(root, `${commit}^`, target) !== adopted.head) return null;const note = localEditAdoptionCommit(adopted.path, adopted.blob, adopted.replaced_revision);- const lines = (await commitMessage(root, commit))?.split('\n') ?? [];+ const message = await commitMessage(root, commit);+ const lines = message?.split('\n') ?? [];if (lines[0] !== note.subject || !note.trailers?.every(trailer => lines.includes(trailer))) return null;const [trailer] = adoptedBy(note.trailers);const location = ledgerLocation(root);- try {- return location && readLedger(location.common).some(record => record.e === 'commit' && record.sha === commit && record.adopted?.includes(trailer!)) ? commit : null;- } catch { return null; }+ let records: ReturnType<typeof readLedger>;+ try { records = location ? readLedger(location.common) : []; } catch { return null; }+ if (records.some(record => record.e === 'commit' && record.sha === commit && record.adopted?.includes(trailer!))) return commit;+ const parent = await commitParent(root, commit), digest = messageDigest(message!);+ return parent && records.some(record => record.e === 'intent' && record.head_before === parent && record.msg_sha256 === digest) ? commit : null;}/** #8824/#8767: `landedAdoptionCommit` for an adoption request `row` (any other request answers null), read on `binding`'s checkout. */diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.tsindex 6d9aed1dfe..ef376a569b 100644--- a/src/core/persistence/pending-import.ts+++ b/src/core/persistence/pending-import.ts@@ -157,6 +157,11 @@ export async function commitMessage(root: string, commit: string): Promise<strinreturn gitRead(root, ['log', '-1', '--format=%B', commit]).catch(() => null);}+/** #8824: the first parent of `commit` in `root`'s repository, or null when it has none or Git cannot read it. */+export async function commitParent(root: string, commit: string): Promise<string | null> {+ return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `${commit}^`]));+}+/** #8824: the blob id `rev` holds at `path` (inside `root`), or null when it has no entry there or Git cannot read it. */export async function blobAt(root: string, rev: string, path: string): Promise<string | null> {return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `${rev}:./${relative(root, path).split(sep).join('/')}`]));diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.tsindex b12ab9b4f2..6d2b6fd498 100644--- a/test/adopt-local-edit.test.ts+++ b/test/adopt-local-edit.test.ts@@ -32,7 +32,7 @@ import { submitRememberMutation } from '../src/core/persistence/memory-mutationsimport { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { localHostId } from '../src/core/persistence/identity.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';-import { readLedger } from '../src/core/git/commit-ledger.ts';+import { ledgerFiles, readLedger, recordIntent } from '../src/core/git/commit-ledger.ts';import { isTerminal, requestPrincipal, type WriteRequest } from '../src/core/persistence/model.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -631,6 +631,14 @@ test('#8755 p: a stale editor save matches an earlier revision whose edges holdconst adoptCommit = (f: RefreshFixture, rel: string) => git(f.root, 'log', '--format=%H %s', '--', `alpha/${rel}`).split('\n').filter(line => line.includes(`gbrain: adopt local edit to ${rel}`)).map(line => line.split(' ')[0]!);const statementCancel = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });+/** Drops the commit-ledger lines naming `shas` (a busy ledger lock or a crash after `git commit`); intent lines stay. */+function dropCommitLines(f: RefreshFixture, shas: string[]): number {+ const ledger = ledgerFiles(join(f.root, '.git')).current;+ const lines = readFileSync(ledger, 'utf8').split('\n');+ const kept = lines.filter(line => { try { const r = JSON.parse(line); return !(r.e === 'commit' && shas.includes(r.sha)); } catch { return true; } });+ writeFileSync(ledger, kept.join('\n'));+ return lines.length - kept.length;+}test('#8824: an adoption whose commit landed before its caller\'s claim ended is published by the consumer, naming that commit', () => each(async f => {const { installFaultHook } = await import('../src/core/persistence/fault-points.ts');@@ -696,6 +704,61 @@ test('#8767: a terminal failure after the adoption\'s commit leaves a receipt naexpect((listing as { rows?: Array<{ request_id: string }> }).rows?.map(row => row.request_id)).toContain(done.request_id);}), 180_000);+test('#8824: an adoption whose commit line never reached the ledger is still published, proved by its intent line', () => each(async f => {+ const { installFaultHook } = await import('../src/core/persistence/fault-points.ts');+ const rel = 'people/alice-example.md', slug = 'people/alice-example';+ commitFile(f.root, `alpha/${rel}`, PERSON, 'person page');+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });+ writeFileSync(join(f.root, 'alpha', rel), PERSON.replace('Alice is a person.', `Alice is a person.\n\n${LOCAL}`));+ const blob = blobOf(f, rel), replaced = await revision(f, slug);+ let fired = 0, dropped = 0, cancelled: string | undefined;+ installFaultHook(async (point, detail) => {+ if (detail.operation !== 'put_page' || detail.sourceId !== f.alpha) return;+ if (point === 'publication:before_commit' && fired++ === 0) { dropped = dropCommitLines(f, adoptCommit(f, rel)); throw statementCancel(); }+ if (point === 'persistence:recovery_interruption_charged' && cancelled === undefined) {+ const [caller] = await f.engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE operation='add_timeline_entry' AND source_id=$1 AND state='running' ORDER BY sequence DESC LIMIT 1", [f.alpha]);+ cancelled = (await cancelWriteRequest(f.engine, requestPrincipal(caller!), caller!.request_id))?.state;+ }+ });+ try { await call(f, 'add_timeline_entry', { slug, date: '2026-11-06', summary: 'Entry whose claim ends.' }).catch(() => undefined); } finally { installFaultHook(undefined); }+ expect(fired).toBeGreaterThan(0);+ expect(dropped).toBe(1);+ expect(cancelled).toBe('cancelled');+ const landed = adoptCommit(f, rel);+ expect(landed).toHaveLength(1);+ expect(readLedger(join(f.root, '.git')).some(r => r.e === 'commit' && r.sha === landed[0])).toBe(false);+ const [adoption] = await adoptionRows(f);+ const done = await settled(f.engine, adoption!);+ expect(done).toMatchObject({ state: 'committed' });+ expect((done.outcome as { persistence?: unknown }).persistence).toMatchObject({ git_state: 'committed', git_commit: landed[0], landed_before_row: true });+ expect((done.outcome as { adopted_local_edit?: unknown }).adopted_local_edit).toEqual({ path: rel, blob, replaced_revision: replaced });+ expect((await f.engine.readPageSnapshot(slug, { sourceId: f.alpha }))!.page.compiled_truth).toContain(LOCAL);+}), 180_000);++test('#8824: an intent line proves no landed adoption without its commit, or on another parent, or with another message', () => each(async f => {+ const { landedAdoptionCommit } = await import('../src/core/persistence/local-edit-adoption.ts');+ const { localEditAdoptionCommit } = await import('../src/core/persistence/effect-model.ts');+ const root = join(f.root, 'alpha'), target = join(root, 'one.md'), ledger = ledgerFiles(join(f.root, '.git')).current;+ const parent = head(f), headBlob = git(f.root, 'rev-parse', 'HEAD:alpha/one.md');+ writeFileSync(target, EDITED);+ const blob = blobOf(f, 'one.md'), replaced = await revision(f, 'one');+ const note = localEditAdoptionCommit('one.md', blob, replaced);+ const message = `${note.subject}\n\n${note.trailers!.join('\n')}`;+ const adopted = { path: 'one.md', blob, replaced_revision: replaced, head: headBlob };+ const intent = (headBefore: string, text: string) => recordIntent(f.root, { writer: 'effect', head_before: headBefore, message: text });+ intent(parent, message);+ expect(await landedAdoptionCommit(root, target, adopted)).toBeNull();+ writeFileSync(ledger, '');+ intent(git(f.root, 'rev-parse', 'HEAD~1'), message);+ intent(parent, `${note.subject}\n\nA message that differs.\n\n${note.trailers!.join('\n')}`);+ git(f.root, 'commit', '-q', '-m', note.subject, '-m', note.trailers!.join('\n'), '--', 'alpha/one.md');+ const landed = head(f);+ expect(git(f.root, 'rev-parse', `${landed}^`)).toBe(parent);+ expect(await landedAdoptionCommit(root, target, adopted)).toBeNull();+ intent(parent, message);+ expect(await landedAdoptionCommit(root, target, adopted)).toBe(landed);+}), 180_000);+test('#8826: a cherry-pick -n of another path leaves no marker, and neither the adoption nor its caller commits the picked path', () => each(async f => {const branch = git(f.root, 'symbolic-ref', '--short', 'HEAD');git(f.root, 'checkout', '-q', '-b', 'side-example');