Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: refuse a mirror file target prepared before mirror-readonly; prefer evidenced duplicates (Codex review)
garrytaneab83fff6e4e
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex f14a77eb4c..a6a281d459 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -23,6 +23,7 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFilimport { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';+import { sourceMirrorReadOnly } from './mirror-read-only.ts';interface PreparedMutationBase {sourceExclusive?: boolean;@@ -209,6 +210,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');}await prepared.validate?.(tx);+ // #5409: a file target prepared before the source became a read-only mirror is never published.+ if (!skill && prepared.file && await sourceMirrorReadOnly(tx, row.source_id, true)) {+ 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.');+ }if (recovery) {const records = recoveryFiles(recovery);for (const record of records) if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) {diff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.tsindex fd3a16603d..57bbc2afcb 100644--- a/src/core/persistence/mirror-read-only.ts+++ b/src/core/persistence/mirror-read-only.ts@@ -8,8 +8,9 @@*/import type { SqlEngine } from './model.ts';-export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string): Promise<boolean> {+/** `lock`: inside a publication, hold the source row so a concurrent mode change waits for this write. */+export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {const [row] = await engine.executeRaw<{ read_only: boolean }>(- "SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1", [sourceId]);+ `SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);return row?.read_only === true;}diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.tsindex 22aed9e3bb..4e8a4ebcf2 100644--- a/src/core/repair/extractor-facts.ts+++ b/src/core/repair/extractor-facts.ts@@ -14,8 +14,9 @@* - excluded (listed, never restored): the page is missing or deleted; the* fact was superseded (`superseded_by`, E-T5); its claim was withdrawn* (`fact_withdrawals`); an active fact with the same text and entity already- * sits on the page (a fence row or another extractor row); or an earlier- * candidate of the page carries the same text and entity.+ * sits on the page (a fence row or another extractor row); or another+ * candidate of the page with the same text and entity is restored instead+ * (the first evidenced one, else the first ambiguous one).* - ambiguous (restored only with `--include-ambiguous` and the hash of that* preview): an unmanaged brain (no receipts); no committed write receipt of* the page completed at the exact expiry instant (`completed_at =@@ -153,12 +154,17 @@ export async function classifyExtractorFacts(db: BrainEngine, sourceIds: string[LEFT JOIN receipts r ON r.source_id=c.source_id AND r.slug=c.slug AND r.completed_at=c.expiredLEFT JOIN fenced ON fenced.source_id=c.source_id AND fenced.slug=c.slugORDER BY c.source_id, c.slug, c.id`, [sourceIds, opts.slug ?? null]);- const seen = new Set<string>();- return rows.map(row => {+ // One representative per (page, visibility, entity, text): the first evidenced row, else the first ambiguous one.+ const key = (row: CandidateRow) => JSON.stringify([row.source_id, row.slug, row.visibility, row.entity_slug, row.fingerprint]);+ const base = rows.map(row => classify(row, false, opts.managed));+ const representative = new Map<string, number>();+ for (const klass of ['evidenced', 'ambiguous'] as const) {+ rows.forEach((row, i) => { if (base[i][0] === klass && !representative.has(key(row))) representative.set(key(row), i); });+ }+ return rows.map((row, i) => {const id = Number(row.id);- const key = JSON.stringify([row.source_id, row.slug, row.visibility, row.entity_slug, row.fingerprint]);- const [klass, reason] = classify(row, seen.has(key), opts.managed);- if (klass !== 'excluded') seen.add(key);+ const duplicate = base[i][0] !== 'excluded' && representative.get(key(row)) !== i;+ const [klass, reason] = duplicate ? classify(row, true, opts.managed) : base[i];return { id, source_id: row.source_id, slug: row.slug, class: klass, reason, expired_at: row.expired_at,receipt: row.receipt, receipt_consumer: row.receipt === null ? null : row.receipt_consumer,fact_hash: digest([row.fact, row.visibility, row.entity_slug]) };@@ -184,7 +190,7 @@ const DETAILS: Record<string, string> = {superseded: 'a newer fact superseded it',withdrawn: 'its claim was withdrawn (forget)',active_duplicate: 'an active fact with the same text and entity is already on the page',- duplicate_candidate: 'an earlier candidate of the page has the same text and entity',+ duplicate_candidate: 'another candidate of the page with the same text and entity is restored instead',unmanaged_brain: 'unmanaged brain: no write receipt can prove the expiry',no_same_transaction_receipt: 'no committed write of the page completed at the exact expiry instant',post_fix_consumer: 'expired by a write published by a fixed consumer (a fence row may have taken its position)',diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.tsindex 3fc2f2cf93..a5b4df526e 100644--- a/test/repair-extractor-facts.test.ts+++ b/test/repair-extractor-facts.test.ts@@ -255,6 +255,23 @@ for (const backend of testBackends()) {}, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/edited', ['Alice sends the deck', 'Alice books the venue'], root); } });}, 120_000);+ test('within a duplicate group the evidenced row is restored, not an older ambiguous one (Codex review)', async () => {+ let ids: number[] = [];+ await managedBrain(async ({ engine, ctx }) => {+ await prefixExpire(engine, ctx, 'conversations/dupes', { transaction: 'separate' });+ const [{ id: later }] = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw<{ id: number }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)+ VALUES ('default', $1, 'Alice sends the deck', 'commitment', 'private', $2, 5, 'conversations/dupes') RETURNING id::int AS id`, [ENTITY, EXTRACTOR])));+ await prefixExpire(engine, ctx, 'conversations/dupes', { ids: [Number(later)] });+ const preview = await repair(engine, null, []);+ expect(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.class])).toEqual([+ [ids[0], 'excluded:duplicate_candidate'], [Number(later), 'evidenced']]);+ const applied = await repair(engine, null, ['--apply', '--expect', hashOf(preview)]);+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });+ expect(await activeIds(engine, [ids[0], Number(later)])).toEqual([Number(later)]);+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/dupes', ['Alice sends the deck'], root); } });+ }, 120_000);+test('crash after a publication, before the cursor: the resumed apply replays its receipt and restores no new candidate (ENG-O8)', async () => {const seeded: Record<string, number[]> = {};await managedBrain(async ({ engine, ctx }) => {diff --git a/test/sources-mirror-read-only.test.ts b/test/sources-mirror-read-only.test.tsindex 86adf94df8..63cd8e1f27 100644--- a/test/sources-mirror-read-only.test.ts+++ b/test/sources-mirror-read-only.test.ts@@ -19,7 +19,11 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { claimNextWrite } from '../src/core/persistence/journal.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';@@ -139,5 +143,26 @@ for (const backend of testBackends()) {}}}), 120_000);++ test('a file target prepared before the source became a read-only mirror is refused at publication (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {+ const m = await mirror(false);+ const binding = (await getWorktreeBinding(engine, m.id))!;+ const lock = (await acquireWorktree(binding, 5000))!;+ try {+ await expect(submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'notes/racing', request_id: randomUUID(),+ content: '---\ntitle: Racing\ntype: note\n---\nPrepared before the flag.\n' } })).rejects.toMatchObject({ code: 'write_pending' });+ await disposePersistenceConsumer(engine);+ } finally { await lock.release(); }+ const row = (await claimNextWrite(engine, localHostId()))!;+ expect(row.slug).toBe('notes/racing');+ const prepared = await preparePageMutation(engine, row, { engine: engine.kind, embedding_disabled: true });+ expect(prepared.file).toBeDefined();+ const outcome = await publishMutation(engine, row, prepared, localHostId(), { boundary: async name => {+ if (name === 'prepared') await cli(['mirror-readonly', m.id]);+ } });+ expect(outcome).toMatchObject({ state: 'conflict', error_code: 'source_changed' });+ expect(existsSync(join(m.root, 'notes/racing.md'))).toBe(false);+ expect(await engine.getPage('notes/racing', { sourceId: m.id })).toBeNull();+ }), 120_000);});}