Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): remember surfaces the typed fence refusal; the backstop counts fence_refused
time-attack5059afc61f43
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex cdf97b4d80..40c9768999 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. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed `fenceRefusal` (`invalid_fence` / `target_fence_malformed`).- `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/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex f0716eba3b..310c61fac4 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -27,7 +27,7 @@- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver.+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them).- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 37f05b9b75..1671bace2a 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -168,6 +168,8 @@ export type FactsBackstopResult =skipped_reason?: import('./extract.ts').ExtractFailureReason;/** #5575 B3: rows the write gate flagged, held or rejected (unmanaged path). */write_gate?: GateTally;+ /** Entity groups held because the page's facts fence does not parse cleanly (nothing written). */+ fence_refused?: number;};/** One pipeline run's input: the turn text plus its page provenance and observation date. */@@ -529,6 +531,8 @@ export async function runFactsPipeline(write_requests?: WriteReceipt[];/** #5575 B3: rows the write gate flagged, held or rejected (unmanaged path). */write_gate?: GateTally;+ /** Entity groups held because the page's facts fence does not parse cleanly (nothing written). */+ fence_refused?: number;}> {return runPipelineWithBody({turnText,@@ -550,7 +554,7 @@ async function runPipeline(parsedPage: ParsedPageInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {return runPipelineWithBody({turnText: parsedPage.compiled_truth,@@ -597,7 +601,7 @@ async function runPipelineWithBody(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {// #4210: outside a withBudgetTracker scope (extract_facts op, sweep,// put_page backstop, checkpoint harvest, file/code import) the gateway's// chat/embed calls were budget no-ops — real spend, zero audit rows.@@ -660,7 +664,7 @@ async function runPipelineBodyInner(input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally }> {+): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number }> {const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');@@ -749,6 +753,7 @@ async function runPipelineBodyInner(const { insertDerivedFact, write_gate } = writer;// Cathedral 5: slugs whose fence-write actually inserted a fact this run.const fencedSlugs = new Set<string>();+ let fenceRefused = 0;// Phase 1: per-fact filter + dedup. Surviving facts (no dedup hit)// get grouped by entity_slug for the fence-write phase below.@@ -937,6 +942,7 @@ async function runPipelineBodyInner(// every fact in this entity group as not-inserted (no fact_id// returned). Do NOT fall through to legacy DB-only — that// would write rows to a DB index whose fence is broken.+ if (result.fenceRefusal) fenceRefused++;continue;}if (result.stubGuardBlocked || result.targetUnresolvable) {@@ -1005,5 +1011,5 @@ async function runPipelineBodyInner(if (result.inserted > 0) fencedSlugs.add(slug);}- return { ...counts, entity_slugs: [...fencedSlugs], write_gate };+ return { ...counts, entity_slugs: [...fencedSlugs], write_gate, ...(fenceRefused ? { fence_refused: fenceRefused } : {}) };}diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex c7969b1279..6269c611cf 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -227,6 +227,7 @@ export async function writeSingleFact();if (result.fenceWriteFailed) {+ if (result.fenceRefusal) throw result.fenceRefusal;// Parse-validate rejected the .tmp (quarantined). Hard failure — do NOT// fall through to a DB row whose fence is broken (pipeline policy).throw new Error(diff --git a/test/fence-rewrite-refuses-malformed.test.ts b/test/fence-rewrite-refuses-malformed.test.tsindex ad12cc63cf..d2fda5e96d 100644--- a/test/fence-rewrite-refuses-malformed.test.ts+++ b/test/fence-rewrite-refuses-malformed.test.ts@@ -21,6 +21,8 @@ import { mergePhantomFenceRows, phantomHasResidue, tryRedirectPhantom } from '..import { redirectManagedPhantom } from '../src/core/cycle/phantom-redirect-managed.ts';import { writeFactsToFence, type FenceInputFact } from '../src/core/facts/fence-write.ts';import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { runFactsPipeline } from '../src/core/facts/backstop.ts';+import { __setChatTransportForTests, resetGateway } from '../src/core/ai/gateway.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';import { operations } from '../src/core/operations.ts';import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';@@ -129,7 +131,23 @@ describe('classic file writers keep the bytes, the stored facts and the row numbawait engine.putPage(slug, { type: 'person', title: 'Alice', compiled_truth: '# Alice', timeline: '', frontmatter: {} });writeMd(slug, MALFORMED);await expect(writeSingleFact(engine, 'default', { fact: 'Alice lives in Paris', entity: slug, provenance: 'manual', visibility: 'world' }))- .rejects.toThrow(/facts fence write failed for people\/alice-example/);+ .rejects.toMatchObject({ canonicalCode: 'invalid_fence', reason: 'target_fence_malformed' });+ expect(readFileSync(file(slug), 'utf8')).toBe(MALFORMED);+ expect(await factRows(slug)).toEqual([]);+ }));++ test('the facts backstop counts a group held on a fence that does not parse (fence_refused)', () => withEnv({ GBRAIN_HOME: brainDir }, async () => {+ const slug = 'people/alice-example';+ await engine.putPage(slug, { type: 'person', title: 'Alice', compiled_truth: '# Alice', timeline: '', frontmatter: {} });+ writeMd(slug, MALFORMED);+ const text = JSON.stringify({ facts: [{ fact: 'Alice lives in Paris', kind: 'fact', entity: slug, confidence: 1, notability: 'medium' }] });+ __setChatTransportForTests(async () => ({ text, blocks: [], stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' }));+ try {+ const r = await runFactsPipeline('Alice said she lives in Paris now.', { engine, sourceId: 'default', sessionId: 'fence-refused', source: 'mcp:extract_facts' });+ expect(r.fence_refused).toBe(1);+ expect(r.inserted).toBe(0);+ } finally { __setChatTransportForTests(null); resetGateway(); }expect(readFileSync(file(slug), 'utf8')).toBe(MALFORMED);expect(await factRows(slug)).toEqual([]);}));