Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): a fence write never stubs over a DB-only or deleted page (#6398, W13 P1.17)
time-attacke5fe4e1ff57b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ffa6d562fc..dc99fb4991 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -19,7 +19,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`).-- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.+- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims. On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished `source_path` file, or tombstoned), `writeFactsToFence` returns `stubGuardBlocked` with audit reason `db_only_page` and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns `fenceWriteFailed`; the #4872 page mirror runs only for a body read from a real file. Doctor `stub_guard_24h` (`commands/doctor/checks/local-audits.ts`) counts `unprefixed`, `fallback_resolution` and `db_only_page` separately; `db_only_page` never feeds the WARN threshold. Tests: `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`.- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.- `src/core/interaction.ts` — the one interaction primitive (agent operator wave A5). `isInteractive(probe?)` needs two TTYs and no `GBRAIN_NON_INTERACTIVE`, `CI` or agent-process marker (`agentProcessMarker()`: `CLAUDECODE`, `CLAUDE_CODE_ENTRYPOINT`, `CODEX_SANDBOX`, `CODEX_CI`, `OPENCODE`, `OPENCODE_PID`; never `CODEX_HOME`); `GBRAIN_INTERACTIVE=1` overrides on two TTYs only, and a marker or `CI` forcing prompts off prints one stderr line per process naming it and the override. Neither variable implies consent. `readLine` is the prompt read (stderr prompt; EOF/timeout = decline; `{kind:'eof'}` without reading when non-interactive; bytes after the newline are pushed back for the next prompt). `readStdinBounded` is the payload read: 30 s first-byte deadline (`GBRAIN_STDIN_TIMEOUT_MS` overrides; stderr notice at 5 s), 60 s inactivity reset per chunk, no total cap, 5 MB default byte cap; `data`/`empty`/`timeout{phase}`/`cancelled`/`error` are distinct and partial input is never `data`. Every reader removes its listeners and pauses the stream so the process can exit; a failed read of process stdin also destroys it. Also hosts the legacy `promptLine` (now `''` on EOF), `promptLineStderr` and `promptYesNo`, re-exported by `cli-util.ts` / `confirm-prompt.ts` for one release; `src/cli.ts` keeps a legacy `readStdinBounded(): string | null` shim. Pinned by `test/interaction.test.ts` (decision table, injected streams) and `test/interaction-stdin.test.ts` (real stdin, PTY, natural exit).diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 7b9207cf5c..0895e67ba9 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -38,7 +38,9 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {// no live page backs. Fires append per-arm `reason` lines to// ~/.gbrain/audit/stub-guard-YYYY-Www.jsonl (pre-#4108 lines lack one and// count as unprefixed). The v0.36 sunset criterion covers 'unprefixed'- // ONLY; the fallback_resolution arm never sunsets.+ // ONLY; the fallback_resolution arm never sunsets. 'db_only_page' (#6398)+ // records facts routed DB-only for a page with no file; it is counted on+ // its own and never feeds the resolver WARN threshold or the sunset count.//// WARN at >10 fires/24h — at that rate the resolver is probably missing// a case (typo prefix, alias, non-Latin script). Operators should grep@@ -46,9 +48,11 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {// resolver branch or document them as legitimate bare-slug ingestion.try {const { readRecentStubGuardEvents } = await import('../../../core/facts/stub-guard-audit.ts');- const events = readRecentStubGuardEvents({ sinceMs: 24 * 60 * 60 * 1000 });+ const all = readRecentStubGuardEvents({ sinceMs: 24 * 60 * 60 * 1000 });+ const dbOnlyCount = all.filter((e) => e.reason === 'db_only_page').length;+ const events = all.filter((e) => e.reason !== 'db_only_page');const fallbackCount = events.filter((e) => e.reason === 'fallback_resolution').length;- const reasonSplit = `unprefixed=${events.length - fallbackCount}, fallback_resolution=${fallbackCount}`;+ const reasonSplit = `unprefixed=${events.length - fallbackCount}, fallback_resolution=${fallbackCount}, db_only_page=${dbOnlyCount}`;if (events.length > 10) {// Surface the top 3 slugs that hit it so operators have somewhere to start.const slugCounts = new Map<string, number>();@@ -60,16 +64,16 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {name: 'stub_guard_24h',status: 'warn',message:- `Stub guard fired ${events.length}x in last 24h (${reasonSplit}; top: ${topSlugs}). ` ++ `Stub guard fired ${all.length}x in last 24h (${reasonSplit}; top: ${topSlugs}). ` +`If this stays elevated, the prefix-expansion in resolveEntitySlug is ` +`missing a case. Check ~/.gbrain/audit/stub-guard-*.jsonl for the slugs ` +`that hit it.`,});- } else if (events.length > 0) {+ } else if (all.length > 0) {checks.push({name: 'stub_guard_24h',status: 'ok',- message: `Stub guard fired ${events.length}x in last 24h (${reasonSplit}; below WARN threshold of 10).`,+ message: `Stub guard fired ${all.length}x in last 24h (${reasonSplit}; ${events.length} resolver hits, below WARN threshold of 10).`,});}// Zero hits is the goal — emit no check at all so the doctor output stays clean.diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex e440a908e8..79949f76ad 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -364,7 +364,8 @@ export async function writeFactsToFence(// 1. Read existing body or stub-create.let body: string;- if (existsSync(filePath)) {+ const fromFile = existsSync(filePath);+ if (fromFile) {body = readFileSync(filePath, 'utf-8');} else {// Stub-creation guard, two arms:@@ -419,6 +420,23 @@ export async function writeFactsToFence();return { inserted: 0, ids: [], stubGuardBlocked: true, ...withdrawnSkipped };}+ // #6398: no file is not no page. A DB-only page (a row with no file, a+ // row whose recorded source_path file vanished, or a tombstoned row)+ // takes the DB-only route: a stub here would be mirrored over the DB+ // body and timeline, or resurrect a deleted page. An unreadable row+ // writes nothing.+ let live: Awaited<ReturnType<BrainEngine['getPage']>>;+ try {+ live = await engine.getPage(target.slug, { sourceId: target.sourceId, includeDeleted: true });+ } catch (err) {+ console.warn(`[facts.fence] FACTS_PAGE_READ_FAILED: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; nothing written`);+ return { inserted: 0, ids: [], fenceWriteFailed: true, ...withdrawnSkipped };+ }+ if (live) {+ logStubGuardEvent({ slug: target.slug, source_id: target.sourceId, fact_count: facts.length, reason: 'db_only_page' });+ console.warn(`[facts] page ${target.slug} (source ${target.sourceId}) has no file${live.deleted_at ? ' and is deleted' : ''} — routing facts to the legacy DB-only path instead of creating a stub that would overwrite it.`);+ return { inserted: 0, ids: [], stubGuardBlocked: true, ...withdrawnSkipped };+ }// Stub-create the parent directory if it doesn't exist.mkdirSync(dirname(filePath), { recursive: true });const activePack = await loadActivePackBestEffort({ engine } as never);@@ -527,10 +545,11 @@ export async function writeFactsToFence(// blind to the new row forever. Never persist an EMPTY hash: a row// that had none gets a row-shaped hash of its pre-mirror content,// which the rewritten file can't match. Best-effort: the file is- // already committed; a stub page with no DB row is created by sync.+ // already committed; a stub page with no DB row is created by sync, and+ // only a body read from a real file is mirrored (#6398).try {const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);- const existing = await engine.getPage(target.slug, { sourceId: target.sourceId });+ const existing = fromFile ? await engine.getPage(target.slug, { sourceId: target.sourceId }) : null;if (existing) {// #5575 ENG-1: the appended rows carry their own tier; the page keeps its tier.await maintenanceTransaction(engine, tx => withPageTierKept(tx, target, () => tx.refreshPageBody(target.slug, target.sourceId,diff --git a/src/core/facts/stub-guard-audit.ts b/src/core/facts/stub-guard-audit.tsindex 632a8aa50e..7b2925bb22 100644--- a/src/core/facts/stub-guard-audit.ts+++ b/src/core/facts/stub-guard-audit.ts@@ -5,7 +5,10 @@* `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/stub-guard-YYYY-Www.jsonl`* when `writeFactsToFence` refuses to spawn an unprefixed entity page* (reason 'unprefixed') or a page for a fallback-resolved slug (#4108,- * reason 'fallback_resolution'). The audit log is the operator visibility+ * reason 'fallback_resolution'), or routes facts for a page that exists only+ * in the database (a row with no file, or a tombstoned row) to the DB-only path+ * instead of a stub that would overwrite it (#6398, reason 'db_only_page'). The+ * audit log is the operator visibility* surface for the v0.34.5+ stub guard sunset criterion, WHICH APPLIES TO* THE 'unprefixed' REASON ONLY: when unprefixed reads <5 hits/week for 3* consecutive weeks on production brains, that arm can be removed in v0.36@@ -49,8 +52,9 @@ export interface StubGuardEvent {/*** Which guard arm fired (#4108). Optional: pre-#4108 lines have no reason* and are counted as 'unprefixed' (the only arm that existed then).+ * 'db_only_page' (#6398) is a routing record, not a resolver miss.*/- reason?: 'unprefixed' | 'fallback_resolution';+ reason?: 'unprefixed' | 'fallback_resolution' | 'db_only_page';}/**diff --git a/test/doctor-stub-guard.test.ts b/test/doctor-stub-guard.test.tsnew file mode 100644index 0000000000..425062e3d8--- /dev/null+++ b/test/doctor-stub-guard.test.ts@@ -0,0 +1,49 @@+/**+ * #6398 (fix wave 13 P1.17): doctor's `stub_guard_24h` counts each stub-guard+ * reason on its own. `db_only_page` (facts routed DB-only for a page with no+ * file) is a routing record, not a resolver miss: it never feeds the WARN+ * threshold or the unprefixed (sunset) count.+ * Seams: GBRAIN_AUDIT_DIR / GBRAIN_HOME temp dirs; PGLite.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { logStubGuardEvent } from '../src/core/facts/stub-guard-audit.ts';+import { stubGuardEntry } from '../src/commands/doctor/checks/local-audits.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });++async function stubGuardCheck(events: Array<'unprefixed' | 'fallback_resolution' | 'db_only_page' | undefined>) {+ const dir = mkdtempSync(join(tmpdir(), 'doctor-stub-guard-'));+ try {+ return await withEnv({ GBRAIN_AUDIT_DIR: dir, GBRAIN_HOME: dir }, async () => {+ events.forEach((reason, i) => logStubGuardEvent({ slug: `people/p${i}`, source_id: 'default', fact_count: 1, ...(reason ? { reason } : {}) }));+ const checks = await stubGuardEntry.run({ engine, orphanRatioSourceId: null } as unknown as DoctorContext);+ return checks.find(c => c.name === 'stub_guard_24h');+ });+ } finally { rmSync(dir, { recursive: true, force: true }); }+}++test('each reason is counted explicitly; legacy reasonless lines count as unprefixed', async () => {+ const check = await stubGuardCheck(['unprefixed', undefined, 'fallback_resolution', 'db_only_page', 'db_only_page']);+ expect(check?.status).toBe('ok');+ expect(check?.message).toContain('unprefixed=2, fallback_resolution=1, db_only_page=2');+});++test('db_only_page alone never trips the resolver WARN threshold', async () => {+ const check = await stubGuardCheck(Array(12).fill('db_only_page'));+ expect(check?.status).toBe('ok');+ expect(check?.message).toContain('unprefixed=0, fallback_resolution=0, db_only_page=12');+});++test('resolver hits above 10 still WARN', async () => {+ const check = await stubGuardCheck([...Array(11).fill('fallback_resolution'), 'db_only_page']);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('unprefixed=0, fallback_resolution=11, db_only_page=1');+});diff --git a/test/facts-fallback-stub-guard.test.ts b/test/facts-fallback-stub-guard.test.tsindex 6b5853a7e9..74b6ed62cf 100644--- a/test/facts-fallback-stub-guard.test.ts+++ b/test/facts-fallback-stub-guard.test.ts@@ -19,7 +19,7 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';+import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -34,8 +34,10 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();- // Live pages for the resolvable arms of the matrix (no on-disk files —- // the fence write stub-creates them, exercising DB→file drift repair).+ // Live pages for the resolvable arms of the matrix. Each beforeEach also+ // writes their files: since #6398 a page that exists only in the DB takes+ // the DB-only route (test/fence-write-db-only.test.ts) instead of a stub+ // that would overwrite its body.await engine.putPage('companies/acme-example', {type: 'company',title: 'Acme Example',@@ -64,6 +66,10 @@ afterAll(async () => {beforeEach(async () => {// Fresh tree per test so file-existence assertions are hermetic.brainDir = mkdtempSync(join(tmpdir(), 'facts-fallback-stub-guard-'));+ for (const [slug, type, title] of [['companies/acme-example', 'company', 'Acme Example'], ['people/felicia-example', 'person', 'Felicia Example'], ['people/star-example', 'person', 'Star Example']]) {+ mkdirSync(join(brainDir, slug, '..'), { recursive: true });+ writeFileSync(join(brainDir, `${slug}.md`), `---\ntype: ${type}\ntitle: ${title}\n---\n\n# ${title}\n`);+ }// eslint-disable-next-line @typescript-eslint/no-explicit-anyawait (engine as any).db.query('DELETE FROM facts');// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/test/facts-write-path-failures.test.ts b/test/facts-write-path-failures.test.tsindex 463c7286dc..55ed3fc26a 100644--- a/test/facts-write-path-failures.test.ts+++ b/test/facts-write-path-failures.test.ts@@ -12,7 +12,7 @@* Real PGLite; failures injected by wrapping executeRaw / refreshPageBody.*/import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';-import { mkdtempSync } from 'node:fs';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -91,7 +91,11 @@ describe('facts write-path failures (B-21)', () => {});test('a failed page-cache mirror after a fence write is reported', async () => {- await importFromContent(engine, 'people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n', { noEmbed: true });+ const alice = '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n';+ await importFromContent(engine, 'people/alice-example', alice, { noEmbed: true });+ // The page has its file (#6398: a DB-only page is never fenced or mirrored).+ mkdirSync(join(brainDir, 'people'), { recursive: true });+ writeFileSync(join(brainDir, 'people/alice-example.md'), alice);// The mirror runs on the maintenance transaction's engine, so the fault is injected there too.const failing = (base: BrainEngine): BrainEngine => new Proxy(base, {get(target, prop, receiver) {diff --git a/test/fence-write-db-only.test.ts b/test/fence-write-db-only.test.tsnew file mode 100644index 0000000000..6b49447091--- /dev/null+++ b/test/fence-write-db-only.test.ts@@ -0,0 +1,118 @@+/**+ * #6398 (fix wave 13 P1.17, Tier A): a fact fence write on an unmanaged brain+ * treated "no file" as "no page", stub-created the file and the #4872 mirror+ * copied the stub over the DB body and timeline.+ * Protects: a DB-only page (no file; a recorded source_path whose file was+ * deleted; a tombstoned row) takes the stub-guard DB-only route (reason+ * `db_only_page`): body, timeline, tags and frontmatter stay byte-identical, no+ * file is created, the fact lands DB-only with its entity_slug. An absent page+ * still gets a stub; the read is source-scoped (another source's row doesn't+ * count); an unreadable row returns fenceWriteFailed and writes nothing.+ * Seams: an engine proxy whose includeDeleted page read throws.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { writeFactsToFence, type FenceInputFact } from '../src/core/facts/fence-write.ts';+import { readRecentStubGuardEvents } from '../src/core/facts/stub-guard-audit.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let brainDir: string;+let auditDir: string;+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES ('other','other') ON CONFLICT DO NOTHING`);+}, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ brainDir = mkdtempSync(join(tmpdir(), 'fence-db-only-'));+ auditDir = mkdtempSync(join(tmpdir(), 'fence-db-only-audit-'));+ _resetWriteThroughCacheForTest();+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id IN ('default','other')`, [brainDir]);+});++const fact = (overrides: Partial<FenceInputFact> = {}): FenceInputFact => ({ fact: 'Joined Acme-example in 2020', kind: 'fact', notability: 'high',+ source: 'test', visibility: 'world', confidence: 1, validFrom: new Date(Date.UTC(2020, 0, 1)), embedding: null, sessionId: null, ...overrides });++async function dbOnlyPage(slug: string, sourceId = 'default') {+ await engine.putPage(slug, { type: 'person', title: 'Example Person', compiled_truth: 'A long, hand-written body about the person.\n\nSecond paragraph.',+ timeline: '- **2020-01-01** | Joined Acme-example', frontmatter: { role: 'engineer' }, tags: ['team'] }, { sourceId });+ await engine.addTimelineEntry(slug, { date: '2021-05-01', summary: 'Promoted' }, { sourceId });+}+async function shape(slug: string, sourceId = 'default') {+ const p = await engine.getPage(slug, { sourceId, includeDeleted: true });+ return { compiled_truth: p?.compiled_truth, timeline: p?.timeline, frontmatter: p?.frontmatter, deleted: !!p?.deleted_at,+ tags: await engine.getTags(slug, { sourceId }), entries: (await engine.getTimeline(slug, { sourceId })).map(e => e.summary) };+}+const factRows = async () => engine.executeRaw<{ entity_slug: string | null; source_markdown_slug: string | null }>('SELECT entity_slug, source_markdown_slug FROM facts');+const reasons = () => readRecentStubGuardEvents({ sinceMs: 60_000 }).map(e => `${e.slug}:${e.reason}`);++describe('#6398 fence write on a DB-only page', () => {+ test('exact_page through writeSingleFact: page byte-identical, no file, fact DB-only with entity_slug', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await dbOnlyPage('people/example-person');+ const before = await shape('people/example-person');+ const r = await writeSingleFact(engine, 'default', { fact: 'Joined Acme-example in 2020', provenance: 'test', entity: 'people/example-person', visibility: 'world' });+ expect(r.status).toBe('inserted');+ expect(await shape('people/example-person')).toEqual(before);+ expect(existsSync(join(brainDir, 'people/example-person.md'))).toBe(false);+ expect(await factRows()).toEqual([{ entity_slug: 'people/example-person', source_markdown_slug: null }]);+ expect(reasons()).toEqual(['people/example-person:db_only_page']);+ }));++ test('alias_exact provenance takes the same route', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await dbOnlyPage('people/example-person');+ const before = await shape('people/example-person');+ const r = await writeFactsToFence(engine, { sourceId: 'default', localPath: brainDir, slug: 'people/example-person', resolutionSource: 'alias_exact' }, [fact()]);+ expect(r).toMatchObject({ inserted: 0, stubGuardBlocked: true });+ expect(await shape('people/example-person')).toEqual(before);+ expect(existsSync(join(brainDir, 'people/example-person.md'))).toBe(false);+ }));++ test('a recorded source_path whose file was deleted: DB-only, body untouched', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await dbOnlyPage('people/example-person');+ await engine.executeRaw(`UPDATE pages SET source_path = 'People/Example Person.md' WHERE slug = 'people/example-person'`);+ const before = await shape('people/example-person');+ const r = await writeFactsToFence(engine, { sourceId: 'default', localPath: brainDir, slug: 'people/example-person', resolutionSource: 'exact_page' }, [fact()]);+ expect(r).toMatchObject({ inserted: 0, stubGuardBlocked: true });+ expect(await shape('people/example-person')).toEqual(before);+ expect(existsSync(join(brainDir, 'People/Example Person.md'))).toBe(false);+ }));++ test('a tombstoned row: DB-only, no stub resurrects the page', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await dbOnlyPage('people/example-person');+ await engine.softDeletePage('people/example-person', { sourceId: 'default' });+ const r = await writeFactsToFence(engine, { sourceId: 'default', localPath: brainDir, slug: 'people/example-person', resolutionSource: 'exact_page' }, [fact()]);+ expect(r).toMatchObject({ inserted: 0, stubGuardBlocked: true });+ expect((await shape('people/example-person')).deleted).toBe(true);+ expect(existsSync(join(brainDir, 'people/example-person.md'))).toBe(false);+ }));++ test('an absent page still gets a stub; another source\'s row with the same slug does not count', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await dbOnlyPage('people/example-person', 'other');+ const before = await shape('people/example-person', 'other');+ const r = await writeFactsToFence(engine, { sourceId: 'default', localPath: brainDir, slug: 'people/example-person', resolutionSource: 'exact_page' }, [fact()]);+ expect(r.inserted).toBe(1);+ expect(readFileSync(join(brainDir, 'people/example-person.md'), 'utf8')).toContain('Joined Acme-example in 2020');+ expect(await shape('people/example-person', 'other')).toEqual(before);+ expect(reasons()).toEqual([]);+ }));++ test('an unreadable row: fenceWriteFailed, nothing written', () => withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => {+ const failing = new Proxy(engine, { get(t, k, rcv) {+ if (k === 'getPage') return (slug: string, opts?: { includeDeleted?: boolean }) => opts?.includeDeleted ? Promise.reject(new Error('connection reset')) : t.getPage(slug, opts as never);+ const v = Reflect.get(t, k, rcv); return typeof v === 'function' ? v.bind(t) : v;+ } }) as unknown as BrainEngine;+ const r = await writeFactsToFence(failing, { sourceId: 'default', localPath: brainDir, slug: 'people/example-person', resolutionSource: 'exact_page' }, [fact()]);+ expect(r).toMatchObject({ inserted: 0, fenceWriteFailed: true });+ expect(existsSync(join(brainDir, 'people/example-person.md'))).toBe(false);+ expect(await factRows()).toEqual([]);+ }));+});