Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (adoption rechecks HEAD under the lock, fails closed on unreadable HEAD, follows the caller's claim)

garrytanb4a93fdb29b4
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 0820090bc7..9cf2017fb3 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -75,7 +75,7 @@ import type { SyncRename } from './sync-discovery.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import { contentRepairCommit, fenceRepairCommit, localEditAdoptionCommit } from './effect-model.ts';
-import { ADOPTED_CHANGE_REASON, commitAdoptedLocalEdit } from './local-edit-adoption.ts';
+import { ADOPTED_CHANGE_REASON, adoptedHeadHolds, commitAdoptedLocalEdit } from './local-edit-adoption.ts';
import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
import type { WriteRequest } from './model.ts';
import { bindOrigin } from './origin-guard.ts';
@@ -105,7 +105,7 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {
/** #6696 C8: the hold observation the repair read; the publication clears the path's hold only while it is that observation (a newer hold stays). */
holdObservedAt?: string;
/** GST-1601: an adopted one-sided local edit (local-edit-adoption.ts): the worktree blob and the revision it replaces. */
- adoptLocalEdit?: { blob: string; replaced_revision: string };
+ adoptLocalEdit?: { blob: string; replaced_revision: string; head: string | null };
}
/** The repair command a refusal names (D6 router): a fence repair's, the content repair's, or the frontmatter repair's. */
@@ -331,7 +331,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const fenceRepair = checkedFenceRepair(p, row.source_id);
const contentRepair = checkedContentRepair(p, row.source_id);
const adopted = p.adoptLocalEdit;
- if (adopted !== undefined && (typeof adopted?.blob !== 'string' || typeof adopted.replaced_revision !== 'string' || p.expected_revision !== adopted.replaced_revision)) {
+ if (adopted !== undefined && (typeof adopted?.blob !== 'string' || typeof adopted.replaced_revision !== 'string' || (typeof adopted.head !== 'string' && adopted.head !== null) || p.expected_revision !== adopted.replaced_revision)) {
throw opError('invalid_params', 'The local edit adoption intent is incomplete.', `Adoption request ${row.request_id} in source ${row.source_id} names no worktree blob or replaced revision, so it published nothing.`);
}
const binding = await getWorktreeBinding(engine, row.source_id);
@@ -394,6 +394,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
`Source ${row.source_id}'s canonical owner changed while repair request ${row.request_id} was prepared, so it published nothing. Check the owner, then preview the repair again.`,
{ fix: ownerStatusFix(row.source_id) });
checkFile();
+ if (adopted && !await adoptedHeadHolds(binding, root, target, adopted.head)) throw changedSincePreview(row.source_id, p.path, 'git HEAD moved after its local edit was read', kind);
if (contentRepair?.declared_alias) await assertDeclaredSlugAbsent(tx, row.source_id, root, p, contentRepair.declared_alias, row.slug, kind);
await assertRenameSource(tx);
await ready.validate(tx);
diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.ts
index eaace60e5d..eb8d13b4e7 100644
--- a/src/core/persistence/local-edit-adoption.ts
+++ b/src/core/persistence/local-edit-adoption.ts
@@ -6,7 +6,8 @@
* The owner publishes the edit first as its own write: a `managed_file_repair` (file-repair.ts) carrying `adoptLocalEdit`,
* admitted under this installation's CLI writer (never the caller's principal) with a request id derived from the
* caller's, so a write adopts at most once. It imports the file's exact bytes under the hash it read (an edit landing
- * before publication ends `raw_file_changed` and nothing is written), archives the replaced revision with change_reason
+ * before publication ends `raw_file_changed` and nothing is written; a commit that moved HEAD or a cancelled caller
+ * adopts nothing), archives the replaced revision with change_reason
* `adopted_local_edit`, and, on a Git-durable checkout, commits only that file before its row commits: subject
* `gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`, a commit-ledger line
* (`adopted`). A repo-less brain records the adoption in the database alone. The caller's claim is then released and its
@@ -18,8 +19,8 @@
* been quiet for `persistence.adopt_quiet_ms` (default 5000); one that is not quiet within three windows keeps the refusal.
*/
import { randomUUID } from 'node:crypto';
-import { readFileSync, statSync } from 'node:fs';
-import { relative, sep } from 'node:path';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError, type OperationContext } from '../ops/contract.ts';
@@ -88,7 +89,10 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Lo
const text = bytes.toString('utf8');
// An edit whose bytes do not decode losslessly would be rewritten by its own adoption, so it keeps the refusal.
if (!Buffer.from(text, 'utf8').equals(bytes)) return null;
- const head = await headCommit(target.root) ? await headBlob(target.root, target.path) : undefined;
+ const commit = await headCommit(target.root);
+ // A checkout whose HEAD git cannot read keeps the refusal; only a brain with no repository has no HEAD to ask.
+ if (!commit && existsSync(join(binding.local_path!, '.git'))) return null;
+ const head = commit ? await headBlob(target.root, target.path) : undefined;
if (head === null) return null;
// A checkout whose HEAD holds the database's copy: only the worktree file moved. A repo-less brain has no HEAD to ask.
const committed = head ? await blobText(target.root, head) : null;
@@ -103,16 +107,28 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Lo
const adopted: AdoptedLocalEdit = { path, blob: gitBlobOid(bytes, head?.length === 64 ? 'sha256' : 'sha1'), replaced_revision: snapshot.revision };
return { adopted, params: { kind: 'managed_file_repair', slug: row.slug, path, sourcePath, content: text, beforeHash: sha256(bytes),
resultDigest: publication.digest, ownerEpoch: String(binding.owner_epoch), expected_revision: snapshot.revision, noEmbed: true,
- adoptLocalEdit: { blob: adopted.blob, replaced_revision: adopted.replaced_revision }, source_id: row.source_id, request_id: adoptionRequestId(row) } };
+ adoptLocalEdit: { blob: adopted.blob, replaced_revision: adopted.replaced_revision, head: head ?? null }, source_id: row.source_id, request_id: adoptionRequestId(row) } };
+}
+
+/** Whether the caller still holds the claim its refusal is being answered under (a cancelled caller adopts nothing). */
+async function callerHolds(engine: BrainEngine, caller: WriteRequest): Promise<boolean> {
+ return (await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE id=$1::uuid AND state='running' AND execution_token=$2::uuid`,
+ [caller.id, caller.execution_token])).length > 0;
+}
+
+/** Publication's recheck (file-repair.ts validate): HEAD still holds the blob the adoption read, so no newer commit is overwritten. */
+export async function adoptedHeadHolds(binding: WorktreeBinding, root: string, path: string, head: string | null): Promise<boolean> {
+ return head === null ? !existsSync(join(binding.local_path!, '.git')) : await headBlob(root, path) === head;
}
/** Claims, prepares and publishes the admitted adoption, retrying while another owner task holds the worktree lock. */
-async function publishAdoption(engine: BrainEngine, admitted: WriteRequest, path: string): Promise<WriteRequest> {
+async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admitted: WriteRequest, path: string): Promise<WriteRequest> {
const { finishUnpublishedFailure, publishMutation } = await import('./coordinator.ts');
const { prepareManagedFileRepairMutation } = await import('./file-repair.ts');
const deadline = Date.now() + LOCK_RETRY_MS;
let row = admitted;
for (;;) {
+ if (!await callerHolds(engine, caller)) return (await getWriteRequestById(engine, row.id))!;
const [claimed] = await engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,
@@ -130,8 +146,8 @@ async function publishAdoption(engine: BrainEngine, admitted: WriteRequest, path
}
/**
- * An adoption `publishAdoption` left unfinished (still blocked on the worktree lock) is cancelled, so a caller that keeps
- * its refusal never has its local edit adopted later; one the resident consumer already took is awaited instead.
+ * An adoption `publishAdoption` left unfinished (still blocked on the worktree lock, or claimed by the resident consumer
+ * before its publication started) is cancelled, so a caller that keeps its refusal never has its local edit adopted later.
*/
async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<WriteRequest> {
if (isTerminal(row)) return row;
@@ -159,7 +175,7 @@ export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, err
let admission: Awaited<ReturnType<typeof adoptionIntent>>;
let admitted: WriteRequest | null;
try {
- if (!await settled(target.path, await quietMs(engine))) return null;
+ if (!await settled(target.path, await quietMs(engine)) || !await callerHolds(engine, row)) return null;
admission = await adoptionIntent(engine, row, target, binding);
if (!admission) return null;
const params = admission.params;
@@ -173,7 +189,7 @@ export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, err
});
} catch { return null; }
if (!admitted) return null;
- const done = await settleAdoption(engine, await publishAdoption(engine, admitted, target.path));
+ const done = await settleAdoption(engine, await publishAdoption(engine, row, admitted, target.path));
if (done.state === 'committed') {
await engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.ts
index bfc2c36c81..527aa6b7eb 100644
--- a/test/adopt-local-edit.test.ts
+++ b/test/adopt-local-edit.test.ts
@@ -31,7 +31,8 @@ import { 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 { isTerminal, type WriteRequest } from '../src/core/persistence/model.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';
import { managedBrain } from './helpers/managed-brain.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -308,6 +309,59 @@ test('an adoption still blocked on the worktree lock when the caller gives up is
expect(await revision(f, 'one')).toBe(before.revision);
}), 180_000);
+test('a commit that moves HEAD past the database before the adoption publishes keeps the refusal and the newer commit', () => each(async f => {
+ const { localEditAdoptionSeams } = await import('../src/core/persistence/local-edit-adoption.ts');
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = await revision(f, 'one');
+ const NEWER = page('Alpha one', 'The first alpha observation.\n\nA newer commit nobody imported yet.');
+ let newer = '';
+ localEditAdoptionSeams.beforePublish = path => { newer = commitFile(f.root, 'alpha/one.md', NEWER); writeFileSync(path, EDITED); };
+ await timeline(f)().catch(() => undefined);
+ const row = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((await adoptionRows(f)).filter(r => r.state === 'committed')).toEqual([]);
+ expect(head(f)).toBe(newer);
+ expect(git(f.root, 'show', 'HEAD:alpha/one.md')).toContain('A newer commit nobody imported yet.');
+ expect(file(f, 'one.md')).toBe(EDITED);
+ expect(await revision(f, 'one')).toBe(before);
+}), 180_000);
+
+test('a checkout whose HEAD git cannot read keeps the refusal instead of adopting as if it had no repository', () => each(async f => {
+ commitFile(f.root, 'alpha/one.md', page('Alpha one', 'The first alpha observation.\n\nA commit the database never imported.'));
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = await revision(f, 'one');
+ const branch = git(f.root, 'symbolic-ref', 'HEAD');
+ git(f.root, 'symbolic-ref', 'HEAD', 'refs/heads/missing-example');
+ try {
+ await timeline(f)().catch(() => undefined);
+ const row = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ } finally { git(f.root, 'symbolic-ref', 'HEAD', branch); }
+ expect((await adoptionRows(f)).filter(r => r.state === 'committed')).toEqual([]);
+ expect(file(f, 'one.md')).toBe(EDITED);
+ expect(await revision(f, 'one')).toBe(before);
+}), 180_000);
+
+test('a caller cancelled while its adoption waits for the file to settle has nothing adopted', () => each(async f => {
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ const pending = timeline(f)().catch(() => undefined);
+ let caller: WriteRequest | undefined;
+ for (let i = 0; i < 100 && !caller; i++) {
+ const [row] = 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]);
+ if (row) caller = row; else await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ expect(caller).toBeDefined();
+ await new Promise(resolve => setTimeout(resolve, 500));
+ expect((await cancelWriteRequest(f.engine, requestPrincipal(caller!), caller!.request_id))?.state).toBe('cancelled');
+ await pending;
+ await new Promise(resolve => setTimeout(resolve, 4000));
+ expect((await adoptionRows(f)).filter(r => r.state === 'committed')).toEqual([]);
+ expect(file(f, 'one.md')).toBe(EDITED);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+}, { quietMs: 2000 }), 180_000);
+
test('doctor local_edit_adoptions reports the adoptions of the last 24 h per source', () => each(async f => {
const { localEditAdoptionsEntry } = await import('../src/commands/doctor/checks/local-edit-adoptions.ts');
const run = async () => (await localEditAdoptionsEntry.run({ engine: f.engine, progress: { heartbeat() {} } } as never) as Array<{ name: string; status: string; message: string; details?: any }>)[0]!;