Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes

garrytane6ba5fdc24a6
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 2122c2e53c..c3c9996b79 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -14,6 +14,7 @@ import { preparationBudgetMs } from './preparation-budget.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT, ownerExceptionHint, unknownOriginHint } from './connector-errors.ts';
import { readQueuedHeadBlockers } from './head-blocker.ts';
+import { SOURCE_CHANGED_ORIGINS } from './publication-failure.ts';
export const WRITER_NEXT_ACTIONS: Record<string, string> = {
unexpected_staging_bytes: 'Keep the worktree blocked and retain its staging files and recovery capacity. Compare the recorded staging size and hash, then reconcile unexpected bytes explicitly before retrying; never discard unverified staging files.',
@@ -175,7 +176,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
const failures = await engine.executeRaw<{ request_id: string; operation: string; source_id: string; state: WriteRequestState;
error_code: string | null; error_detail: Record<string, unknown>; completed_at: Date | string | null }>(
`SELECT request_id,operation,source_id,state,error_code,error_detail,completed_at FROM persistence_requests
- WHERE error_detail IS NOT NULL AND COALESCE(error_detail->>'origin','')<>'fence' ORDER BY sequence DESC LIMIT 20`);
+ WHERE error_detail IS NOT NULL AND NOT COALESCE(error_detail->>'origin','')=ANY($1::text[]) ORDER BY sequence DESC LIMIT 20`, [['fence', ...SOURCE_CHANGED_ORIGINS]]);
const limits = await readJournalLimits(engine);
// #6278: the budgets, ceiling, attempt limit and switch in effect, next to every running blocker's step age.
const snapshot = await readWriteSwitchSnapshot(engine).catch(() => null);
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 9d3686b7c4..0820090bc7 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -342,6 +342,8 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const adoptNote = adopted ? localEditAdoptionCommit(p.path, adopted.blob, adopted.replaced_revision) : undefined;
const bytes = Buffer.from(p.content, 'utf8');
const fileChanges = sha256(bytes) !== p.beforeHash;
+ if (adopted && fileChanges) throw opError('invalid_params', 'A local edit adoption may not rewrite the file it adopts.',
+ `Adoption request ${row.request_id} in source ${row.source_id} would change ${p.path} instead of recording it as it is, so it published nothing.`);
const checkFile = () => {
const target = confinedRepairTarget(root, p.path, row.source_id, kind);
if (fileSha256(target) !== p.beforeHash) throw changedSincePreview(row.source_id, p.path, 'the file bytes differ from the previewed hash', kind);
diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.ts
index fa4c5ced66..eaace60e5d 100644
--- a/src/core/persistence/local-edit-adoption.ts
+++ b/src/core/persistence/local-edit-adoption.ts
@@ -29,7 +29,7 @@ import { sourceCanonicalGit } from './git-door.ts';
import { gitDurabilityPolicy } from './git-durability-policy.ts';
import { withRegisteredLocalWriter } from './identity.ts';
import { admitWrite, getWriteRequest, getWriteRequestById, publicationGroupKey, releaseUnpublishedClaim } from './journal.ts';
-import { isTerminal, type WriteRequest } from './model.ts';
+import { isTerminal, requestPrincipal, type WriteRequest } from './model.ts';
import { declarePersistenceProtocol } from './protocol.ts';
import type { WorktreeBinding } from './ownership.ts';
import { getWorktreeBinding } from './ownership.ts';
@@ -86,6 +86,8 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Lo
if (!snapshot || !sourcePath || snapshot.page.deleted_at) return null;
const bytes = readFileSync(target.path);
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;
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.
@@ -127,6 +129,21 @@ 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.
+ */
+async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<WriteRequest> {
+ if (isTerminal(row)) return row;
+ const { cancelWriteRequest } = await import('./control.ts');
+ const deadline = Date.now() + LOCK_RETRY_MS;
+ for (;;) {
+ const current = await cancelWriteRequest(engine, requestPrincipal(row), row.request_id) ?? row;
+ if (isTerminal(current) || Date.now() > deadline) return current;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+}
+
/**
* The owner's answer to a drift refusal of `row` (coordinator.ts finishUnpublishedFailure): `released` once the local edit
* is adopted and the write queued to prepare again, `error` when the adoption found the file changed under it (the
@@ -156,7 +173,7 @@ export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, err
});
} catch { return null; }
if (!admitted) return null;
- const done = await publishAdoption(engine, admitted, target.path);
+ const done = await settleAdoption(engine, await publishAdoption(engine, 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 d921d90771..bfc2c36c81 100644
--- a/test/adopt-local-edit.test.ts
+++ b/test/adopt-local-edit.test.ts
@@ -19,6 +19,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
@@ -275,6 +276,38 @@ test('a file changed between the adoption\'s preparation and publication ends ra
expect(await revision(f, 'one')).toBe(before.revision);
}), 180_000);
+test('a local edit that is not valid UTF-8 keeps the refusal and its exact bytes', () => each(async f => {
+ const bytes = Buffer.concat([Buffer.from(EDITED.replace(LOCAL, 'Bytes no decoder reads: ')), Buffer.from([0xff, 0xfe, 0x0a])]);
+ writeFileSync(join(f.root, 'alpha', 'one.md'), bytes);
+ 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(readFileSync(join(f.root, 'alpha', 'one.md')).equals(bytes)).toBe(true);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+ expect((await adoptionRows(f)).filter(r => r.state === 'committed')).toEqual([]);
+}), 180_000);
+
+test('an adoption still blocked on the worktree lock when the caller gives up is cancelled, never published later', () => each(async f => {
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ const lock = (await acquireWorktree((await getWorktreeBinding(f.engine, f.alpha))!, 0, undefined, f.engine))!;
+ expect(lock).not.toBeNull();
+ 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 { await lock.release(); }
+ await new Promise(resolve => setTimeout(resolve, 2000));
+ const adoptions = await adoptionRows(f);
+ expect(adoptions.length).toBe(1);
+ expect(adoptions[0]!.state).toBe('cancelled');
+ expect(file(f, 'one.md')).toBe(EDITED);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+}), 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]!;
diff --git a/test/remember-pending-import.test.ts b/test/remember-pending-import.test.ts
index 154c770839..dce68a5772 100644
--- a/test/remember-pending-import.test.ts
+++ b/test/remember-pending-import.test.ts
@@ -11,6 +11,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { performSync } from '../src/commands/sync.ts';
import { parseFactsFence } from '../src/core/facts-fence.ts';
+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
import { lostCallerWrites, replayImportedRemembers } from '../src/core/repair/failed-writes.ts';
@@ -132,6 +133,8 @@ describe('#6693 remember onto a page whose file awaits import', () => {
expect((await lastReceipt(engine, 'put_page')).error_detail?.origin).toBe('canonical_path_occupied');
expect(readFileSync(file(root), 'utf8')).toContain('A hand edit nobody committed.');
expect(readFileSync(join(root, 'people', 'unindexed-example.md'), 'utf8')).toContain('Never imported.');
+ // Routine drift refusals keep out of writer status's recent database refusals.
+ expect((await readWriterDiagnostics(engine)).recent_failures.map(row => row.error_detail?.origin)).not.toContain('file_database_drift');
}, { setup }), 120_000);
test('a put_page refused the same way is classified but not replayed', () => managedBrain(async ({ engine, ctx, root }) => {