Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: a local edit adoption checks its caller and the index again where it commits

garrytan8c2266807156
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 8aeae54a79..16ee15f1c0 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, adoptedHeadHolds, assertAdoptionCaller, commitAdoptedLocalEdit } from './local-edit-adoption.ts';
+import { ADOPTED_CHANGE_REASON, adoptedHeadHolds, assertAdoptionCaller, commitAdoptedLocalEdit, conflictOrOperation } 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';
@@ -396,6 +396,9 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
{ fix: ownerStatusFix(row.source_id) });
checkFile();
if (adopted && !await adoptedHeadHolds(binding, root, target, adopted.head, adopted.blob)) throw changedSincePreview(row.source_id, p.path, 'git HEAD moved after its local edit was read', kind);
+ // #8755: the caller's claim and the index are read again here, where the adoption commits: a cancel or a conflict may come after preparation.
+ if (adopted) await assertAdoptionCaller(tx, row, adopted.caller, true);
+ if (adopted && adopted.head !== null && await conflictOrOperation(root, target)) throw changedSincePreview(row.source_id, p.path, 'a merge, rebase or conflicted path appeared 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 fda8b9ff8b..f8de5a744d 100644
--- a/src/core/persistence/local-edit-adoption.ts
+++ b/src/core/persistence/local-edit-adoption.ts
@@ -71,7 +71,7 @@ const STALE_REVISIONS = 50;
const ADOPTING_OPERATIONS: readonly string[] = ['remember', 'capture', 'add_timeline_entry'];
/** Test seams: `beforePublish` runs between the adoption's preparation and its publication, with the file's path; `maxWaitMs` lowers the quiet-wait cap. */
-export const localEditAdoptionSeams: { beforePublish?: (path: string) => void; maxWaitMs?: number } = {};
+export const localEditAdoptionSeams: { beforePublish?: (path: string) => void | Promise<void>; maxWaitMs?: number } = {};
/** The drifted file a `file_database_drift` refusal carries (page-prepare.ts compareFileTarget). */
interface LocalEditTarget { root: string; path: string }
@@ -155,8 +155,7 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Lo
if (!commit && insideGitCheckout(binding.local_path!)) return null;
const head = commit ? await headBlob(target.root, target.path) : undefined;
if (head === null) return null;
- // Conflict markers from a merge, stash pop, cherry-pick or rebase are never adopted (`git add` would mark them resolved).
- if (commit && (await unmergedPath(target.root, target.path) !== false || (await operationMarkerPaths(target.root))?.every(marker => !existsSync(marker)) !== true)) return null;
+ if (commit && await conflictOrOperation(target.root, target.path)) return null;
const { prepareRepairPublication, repairScreenConfig } = await import('./file-repair.ts');
const screen = await repairScreenConfig(engine, row.source_id);
// A checkout whose HEAD holds the database's copy: only the worktree file moved. A repo-less brain has no HEAD to ask.
@@ -175,6 +174,15 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Lo
source_id: row.source_id, request_id: adoptionRequestId(row) } };
}
+/**
+ * Conflict markers from a merge, stash pop, cherry-pick or rebase are never adopted (`git add` would mark them resolved):
+ * true when `path` has unmerged stages or an operation is in progress, or when git cannot tell. Checked at admission and
+ * again in the publication transaction, since either can start in between.
+ */
+export async function conflictOrOperation(root: string, path: string): Promise<boolean> {
+ return await unmergedPath(root, path) !== false || (await operationMarkerPaths(root))?.every(marker => !existsSync(marker)) !== true;
+}
+
/** 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`,
@@ -195,11 +203,12 @@ export async function adoptedHeadHolds(binding: WorktreeBinding, root: string, p
/**
* #8755: the claim an adoption is made under (`adoptLocalEdit.caller`) still holds, checked as the adoption prepares: an
* adoption whose caller is gone (cancelled, finished, or reclaimed after a crash between admission and settling)
- * publishes nothing.
+ * publishes nothing. In the publication transaction (`lock`) the caller row is held FOR SHARE, so a cancel waits until it ends.
*/
-export async function assertAdoptionCaller(engine: BrainEngine, row: WriteRequest, caller: { id?: unknown; token?: unknown } | undefined): Promise<void> {
+export async function assertAdoptionCaller(engine: BrainEngine, row: WriteRequest, caller: { id?: unknown; token?: unknown } | undefined, lock = false): Promise<void> {
if (!caller) return;
- const [held] = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE id=$1::uuid AND state='running' AND execution_token=$2::uuid`, [String(caller.id), String(caller.token)]);
+ const [held] = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE id=$1::uuid AND state='running' AND execution_token=$2::uuid${lock ? ' FOR SHARE' : ''}`,
+ [String(caller.id), String(caller.token)]);
if (held) return;
throw opError('write_claim_lost', 'The write this local edit adoption was made for no longer waits on it.',
`Adoption request ${row.request_id} in source ${row.source_id} belongs to a write whose claim ended (it was cancelled, finished, or reclaimed after its process stopped), so the local edit was not adopted and nothing was written.`);
@@ -222,7 +231,7 @@ async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admitt
if (!claimed) return (await getWriteRequestById(engine, row.id))!;
try {
const prepared = await prepareManagedFileRepairMutation(engine, claimed, { engine: engine.kind } as GBrainConfig);
- localEditAdoptionSeams.beforePublish?.(path);
+ await localEditAdoptionSeams.beforePublish?.(path);
row = await publishMutation(engine, claimed, prepared);
} catch (error) { row = await finishUnpublishedFailure(engine, claimed, error, 'preparation'); }
// #8755: any release is retried, a publication recovery requeued after the adoption's commit landed included.
diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.ts
index 6708a5c5ed..2bf6e95138 100644
--- a/test/adopt-local-edit.test.ts
+++ b/test/adopt-local-edit.test.ts
@@ -546,3 +546,51 @@ test('#8755 h: an adoption names its caller\'s claim, and one whose caller no lo
expect(refused?.code).toBe('write_claim_lost');
}), 180_000);
+
+test('#8755 m: a caller cancelled after its adoption prepared has nothing adopted', () => each(async f => {
+ const { localEditAdoptionSeams } = await import('../src/core/persistence/local-edit-adoption.ts');
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ let cancelled: string | undefined;
+ localEditAdoptionSeams.beforePublish = async () => {
+ 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;
+ };
+ await timeline(f)().catch(() => undefined);
+ expect(cancelled).toBe('cancelled');
+ const [adoption] = await adoptionRows(f);
+ expect(adoption).toMatchObject({ state: 'failed', error_code: 'write_claim_lost' });
+ expect(file(f, 'one.md')).toBe(EDITED);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+}), 180_000);
+
+test('#8755 n: a conflict or a merge that starts after the adoption prepared keeps the refusal and the index', () => each(async f => {
+ const { localEditAdoptionSeams } = await import('../src/core/persistence/local-edit-adoption.ts');
+ const base = git(f.root, 'rev-parse', 'HEAD:alpha/one.md');
+ writeFileSync(join(f.root, 'theirs.tmp'), EDITED);
+ const theirs = git(f.root, 'hash-object', '-w', 'theirs.tmp');
+ const stages = `100644 ${base} 1\talpha/one.md\n100644 ${base} 2\talpha/one.md\n100644 ${theirs} 3\talpha/one.md\n`;
+ const refused = async () => {
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ 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(file(f, 'one.md')).toBe(EDITED);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+ };
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ localEditAdoptionSeams.beforePublish = () => {
+ git(f.root, 'update-index', '--force-remove', 'alpha/one.md');
+ execFileSync('git', ['-C', f.root, 'update-index', '--index-info'], { input: stages });
+ };
+ await refused();
+ expect(git(f.root, 'ls-files', '-u', '--', 'alpha/one.md').split('\n')).toHaveLength(3);
+ git(f.root, 'update-index', '--force-remove', 'alpha/one.md');
+ git(f.root, 'update-index', '--add', '--cacheinfo', `100644,${base},alpha/one.md`);
+ localEditAdoptionSeams.beforePublish = () => { writeFileSync(join(f.root, '.git', 'MERGE_HEAD'), `${head(f)}\n`); };
+ try { await refused(); } finally { rmSync(join(f.root, '.git', 'MERGE_HEAD'), { force: true }); }
+}), 180_000);
+