Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): retain authorized subjects on drift fallback
garrytancd57bc07ef24
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 8c76735ea6..9e832869a8 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -1040,7 +1040,7 @@ async function runPipelineBodyInner(// didn't (null-localPath echo, or the write_through flag flipped// mid-pipeline across the config-cache TTL). Route the group to the// legacy DB-only path — never drop facts.- if (result.databaseOnlyReason !== 'url_clone') warnOnce(+ if (result.databaseOnlyReason !== 'url_clone' && result.databaseOnlyReason !== 'file_database_drift') warnOnce('facts:fence-write-unexpected-fallback',`[facts] writeFactsToFence returned legacyFallback for slug=${slug} despite localPath being set — routing to DB-only inserts.`,);@@ -1048,7 +1048,7 @@ async function runPipelineBodyInner(const newFact: NewFact = {fact: f.fact,kind: f.kind,- entity_slug: f.entity_inferred ? null : slug,+ entity_slug: f.entity_inferred && result.databaseOnlyReason !== 'file_database_drift' ? null : slug,visibility,notability: f.notability,source: f.source,@@ -1058,7 +1058,7 @@ async function runPipelineBodyInner(embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,// #4206: caller event-time fallback + provenance context.valid_from: factEventTime(f, ctx),- context: ctx.sourceSlug ?? input.pageSlug ?? null,+ context: result.databaseOnlyReason === 'file_database_drift' ? annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, groupResolutionSource, f.entity_inferred) : ctx.sourceSlug ?? input.pageSlug ?? null,};await insertDerivedFact(newFact); // DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)}diff --git a/test/facts-backstop-entity-inference.test.ts b/test/facts-backstop-entity-inference.test.tsindex 2c76744e7b..39d5b5002d 100644--- a/test/facts-backstop-entity-inference.test.ts+++ b/test/facts-backstop-entity-inference.test.ts@@ -64,8 +64,9 @@ beforeEach(async () => {dir = mkdtempSync(join(tmpdir(), 'backstop-infer-'));// The pages have their files, as a local_path brain's pages do (#6398: a DB-only page takes the DB-only fact route).for (const p of pages) {+ const snapshot = (await engine.readPageSnapshot(p.slug, { sourceId: 'default' }))!;mkdirSync(join(dir, p.slug, '..'), { recursive: true });- writeFileSync(join(dir, `${p.slug}.md`), serializePageToMarkdown(p, []));+ writeFileSync(join(dir, `${p.slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));}await engine.executeRaw(`UPDATE sources SET local_path=$1 WHERE id='default'`, [dir]);_resetWriteThroughCacheForTest();diff --git a/test/pathological/d2-fence-write-overwrite.test.ts b/test/pathological/d2-fence-write-overwrite.test.tsindex 8be00b3a05..bf9ce00620 100644--- a/test/pathological/d2-fence-write-overwrite.test.ts+++ b/test/pathological/d2-fence-write-overwrite.test.ts@@ -4,14 +4,21 @@* fallback, and writeSingleFact records the unfenced fact. Agreeing copies still append with history.* Fails when: the pre-fix whole-file mirror overwrites the DB after publishing the file.* Existing coverage checks missing files, not divergent live copies or publication races.+ * Inferred subjects keep their authorized attribution and provenance while drift holds their page out of+ * destructive reconciliation; existing inference coverage does not assert preservation of either body.* Seams: engine proxy injects a real edit before the prepared fence transaction; no production-only hook.*/-import { describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, test } from 'bun:test';+import { __setChatTransportForTests, resetGateway } from '../../src/core/ai/gateway.ts';+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';+import { runFactsPipeline } from '../../src/core/facts/backstop.ts';import { writeSingleFact } from '../../src/core/facts/write-single.ts';import { parseFactsFence } from '../../src/core/facts-fence.ts';import { pathologicalArms } from './harness.ts';import { CLAIM, EDIT, SLUG, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';+afterEach(() => { __setChatTransportForTests(null); resetGateway(); });+for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-2 fence writes (${backend})`, () => {for (const mode of ['database', 'file', 'late-database', 'late-file'] as const) test(`${mode} edit preserves both copies and falls back`, async () => {await withFactsBrain(databaseUrl, async b => {@@ -40,4 +47,30 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-2 fence wexpect(await b.engine.executeRaw('SELECT compiled_truth FROM page_versions WHERE compiled_truth = $1', [before])).toHaveLength(1);});}, 180_000);++ for (const mode of ['database', 'file'] as const) test(`${mode} drift keeps an authorized inferred subject and both bodies`, async () => {+ await withFactsBrain(databaseUrl, async b => {+ if (mode === 'database') await b.dbEdit();+ else b.fileEdit();+ const before = { file: b.bytes(), body: await b.body() };+ __setChatTransportForTests(async () => ({+ text: JSON.stringify({ facts: [{ fact: CLAIM, entity: null, kind: 'fact', confidence: 1, notability: 'high' }] }),+ blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ }));+ const result = await runFactsPipeline('turn', { engine: b.engine, sourceId: 'default', sessionId: null,+ source: 'mcp:extract_facts', sourceSlug: SLUG, mode: 'inline', visibility: 'world', remote: false });+ expect(result.inserted).toBe(1);+ expect(await b.engine.executeRaw('SELECT entity_slug, row_num, context FROM facts WHERE id = $1', [result.fact_ids[0]]))+ .toEqual([{ entity_slug: SLUG, row_num: null, context: `${SLUG} — entity inferred from page` }]);+ const reconcile = await runExtractFacts(b.engine, { sourceId: 'default' });+ expect(reconcile.legacyRowsPending).toBe(1);+ expect(reconcile.guardTriggered).toBe(true);+ expect(reconcile.legacyPages).toEqual([SLUG]);+ expect(reconcile.warnings.some(w => w.includes(`${SLUG} (file_database_drift`))).toBe(true);+ expect({ file: b.bytes(), body: await b.body() }).toEqual(before);+ expect(await b.engine.executeRaw('SELECT entity_slug, row_num FROM facts WHERE expired_at IS NULL'))+ .toEqual([{ entity_slug: SLUG, row_num: null }]);+ });+ }, 180_000);});