Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B lane H follow-up: discovery joins facts fences a forced cut split; segmented forget strike matches inline first-fence semantics
garrytan8bab7d2d9bed
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 6bc8b97c5f..a2c5eaee6c 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -17,4 +17,4 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.-- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.+- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 5f02c5d3ec..977d11059b 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -12,13 +12,13 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. The typed-claim examples keep a bare `$` as USD (series compare by `(metric, unit, period)`, so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by `test/facts-extract-currency-examples-6274.test.ts`. Pinned by `test/facts-extract-structured-output.test.ts`.-- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`. A segmented page's row is struck in the segment holding its fence (`rewriteLiveSegmentedFences`, first fence holding the row), on the DB-only and the file-mirror paths.+- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`. A segmented page's row is struck in the segment holding its fence (`rewriteLiveSegmentedFences`), on the DB-only and the file-mirror paths, with `strikeFenceRow`'s whole-string semantics: only the first facts fence is a candidate (of the compiled truth for the DB body, of truth then timeline for the mirror), and a first fence without the row strikes nothing.- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).-- `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 (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; 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`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes (a slot split by a forced cut is left to the chunk scan).+- `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 (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; 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`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.- `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 (per-model 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`). 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.diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex 4b23064dc6..72f308bd0a 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -22,6 +22,7 @@ import { sanitizeText } from '../batch-rows.ts';import { contentHash } from '../utils.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';+import type { BodyRegion } from '../page-body/types.ts';import { recordFactWithdrawal } from './withdrawal.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { withdrawnFact } from './withdrawal-overlay.ts';@@ -179,14 +180,15 @@ export async function forgetFactInFence(// Mirror the retraction in the page body. The withdrawal record protects// active facts even if this best-effort mirror fails or a stale file returns.// Wave B (spec 11): a segmented page's row is struck in the segment holding its fence (a new generation; only the- // rewritten occurrences' chunks are replaced), never by loading the body. The first fence holding the row is struck.- const strikeSegments = async (pageId: number): Promise<void> => {- let struck = false;- await maintenanceTransaction(engine, tx => rewriteLiveSegmentedFences(tx, pageId, async fence => {- const next = struck ? null : strikeFenceRow(fence, row.row_num!, strike);- if (next === null) return fence;- struck = true;- return next;+ // rewritten occurrences' chunks are replaced), never by loading the body. As `strikeFenceRow` on the whole string,+ // only the first facts fence is a candidate: of the compiled truth for the DB body, of truth then timeline for the+ // file mirror (the file holds both); a first fence without the row strikes nothing.+ const strikeSegments = async (pageId: number, regions: readonly BodyRegion[]): Promise<void> => {+ let first = true;+ await maintenanceTransaction(engine, tx => rewriteLiveSegmentedFences(tx, pageId, async (fence, at) => {+ if (!first || !regions.includes(at.region) || !fence.includes(FENCE_BEGIN)) return fence;+ first = false;+ return strikeFenceRow(fence, row.row_num!, strike) ?? fence;}));};const strikeDbBody = async (): Promise<void> => {@@ -194,7 +196,7 @@ export async function forgetFactInFence(const slug = row.source_markdown_slug;const page = await engine.getPage(slug, { sourceId: row.source_id });if (!page) return;- if (isSegmentedPage(page)) return strikeSegments(page.id);+ if (isSegmentedPage(page)) return strikeSegments(page.id, ['truth']);const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, strike);if (struck === null) return;// The FILE was not rewritten on this tier, so the row must NOT keep the@@ -303,7 +305,7 @@ export async function forgetFactInFence(try {const reparsed = parseMarkdown(tmpBody, `${slug}.md`);const page = await engine.getPage(slug, { sourceId: row.source_id });- if (page && isSegmentedPage(page)) await strikeSegments(page.id);+ if (page && isSegmentedPage(page)) await strikeSegments(page.id, ['truth', 'timeline']);else if (page) {await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.tsindex fb0f99d3be..95f122c6be 100644--- a/src/core/facts/withdrawal-discovery.ts+++ b/src/core/facts/withdrawal-discovery.ts@@ -3,6 +3,8 @@ import { OperationError } from '../ops/contract.ts';import { getCode } from '../retry-matcher.ts';import { parseRowCells, isSeparatorRow, stripStrikethrough } from '../fence-shared.ts';import { withdrawalFenceBlocks, ambiguousWithdrawalFenceSegments } from './withdrawal-overlay.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';+import { pageBodySegmentedError } from '../page-body/page-shape.ts';export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;export interface WithdrawalTarget { slug: string; page_id: number; revision: string }@@ -36,6 +38,51 @@ export function ambiguousFenceClaims(body: string): Array<{ claim: string; visibreturn claims;}+/** A fence's claims as discovery matches them: every row of a clean block, and every ambiguous row. */+function fenceClaims(id: number, slug: string, body: string): Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }> {+ return [+ ...withdrawalFenceBlocks(body).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id, slug, claim: f.claim, visibility: f.visibility, ambiguous: false }))),+ ...ambiguousFenceClaims(body).map(f => ({ id, slug, ...f, ambiguous: true })),+ ];+}++/**+ * Wave B (spec 11): every live facts fence of a segmented page that a forced+ * cut split (its slots carry `open_start`), joined from its slots' bytes in+ * segment order and kept when its lowered text holds every token of a claim+ * keyed to the page. Private rows never reach chunks, so this is the only+ * scan that sees them. A fence above PAGE_MAX_BYTES is refused, never+ * skipped. Keyset by (page, region, fence start); one fence in memory.+ */+async function* splitFactsFences(engine: BrainEngine, sourceId: string, keyed: readonly KeyedClaim[], subjects: string[] | null, deadline: number):+ AsyncIterable<{ id: number; slug: string; fence: string }> {+ for (let after: [number, string, number] = [0, '', -1]; ;) {+ if (performance.now() > deadline) refuse();+ const fences = await engine.executeRaw<{ page_id: number; slug: string; region: string; open_start: string; bytes: string }>(`SELECT m.page_id,p.slug,m.region,+ (s->>'open_start')::bigint::text AS open_start,sum((s->>'end')::bigint-(s->>'start')::bigint)::text AS bytes+ FROM page_body_manifest m JOIN pages p ON p.id=m.page_id CROSS JOIN LATERAL jsonb_array_elements(m.facts_slots) s+ WHERE p.source_id=$1 AND p.body_storage='segmented' AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.facts_slots<>'[]'::jsonb AND s ? 'open_start'+ AND ($2::text[] IS NULL OR p.slug=ANY($2::text[])) AND (m.page_id,m.region,(s->>'open_start')::bigint)>($3::int,$4::text,$5::bigint)+ GROUP BY m.page_id,p.slug,m.region,(s->>'open_start')::bigint ORDER BY m.page_id,m.region,(s->>'open_start')::bigint LIMIT $6`,+ [sourceId, subjects, after[0], after[1], after[2], WITHDRAWAL_LIMITS.batch]);+ for (const f of fences) {+ if (performance.now() > deadline) refuse();+ if (Number(f.bytes) > PAGE_MAX_BYTES) throw pageBodySegmentedError({ slug: f.slug, source_id: sourceId }, 'withdrawal discovery of a fence larger than the single-string ceiling');+ const parts = await engine.executeRaw<{ part: Uint8Array }>(`SELECT substring(t.body from (s->>'start')::int + 1 for (s->>'end')::int - (s->>'start')::int) AS part+ FROM page_body_manifest m CROSS JOIN LATERAL jsonb_array_elements(m.facts_slots) s JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256+ WHERE m.page_id=$1 AND m.region=$2 AND m.gen_to IS NULL AND m.staging_id IS NULL AND (s->>'open_start')::bigint=$3::bigint ORDER BY m.seq`, [f.page_id, f.region, f.open_start]);+ const fence = Buffer.concat(parts.map(p => Buffer.from(p.part))).toString('utf8');+ const lowered = fence.toLowerCase();+ if (keyed.some(k => (k.subject === '*' || k.subject === f.slug) && (k.norm ?? '').split(' ').filter(Boolean).every(token => lowered.includes(token)))) {+ yield { id: Number(f.page_id), slug: f.slug, fence };+ }+ }+ if (fences.length < WITHDRAWAL_LIMITS.batch) return;+ const last = fences[fences.length - 1]!;+ after = [Number(last.page_id), last.region, Number(last.open_start)];+ }+}+/*** Claim-keyed discovery. Every fence row, chunk row or whole chunk whose* fingerprint equals the claim contains each of the claim's normalized tokens@@ -89,15 +136,12 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: sAND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,patterns text[])WHERE (k.subject='*' OR k.subject=p.slug) AND ((${shortlist('p.compiled_truth')}) OR (${shortlist('p.timeline')})))ORDER BY p.id LIMIT $4`, [sourceId, keys, after, WITHDRAWAL_LIMITS.batch, subjects]);- await match(pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => [- ...withdrawalFenceBlocks(body).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: page.id, slug: page.slug, claim: f.claim, visibility: f.visibility, ambiguous: false }))),- ...ambiguousFenceClaims(body).map(f => ({ id: page.id, slug: page.slug, ...f, ambiguous: true })),- ])));+ await match(pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => fenceClaims(page.id, page.slug, body))));if (pages.length < WITHDRAWAL_LIMITS.batch) break;after = pages[pages.length - 1].id;}// Wave B (spec 11): a segmented page's fences live in its segments; only live rows flagged with facts slots are- // read, and only each slot's bytes (a fence split by a forced cut is left to the chunk scan below).+ // read, and only each slot's bytes; a fence split by a forced cut is joined across it (splitFactsFences).const slotText = `convert_from(substring(t.body from (s->>'start')::int + 1 for (s->>'end')::int - (s->>'start')::int),'UTF8')`;for (let after = [0, 0]; ;) {if (performance.now() > deadline) refuse();@@ -109,13 +153,11 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: sAND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,patterns text[]), jsonb_array_elements(m.facts_slots) sWHERE (k.subject='*' OR k.subject=p.slug) AND NOT s ? 'open_start' AND ${shortlist(slotText)})ORDER BY m.page_id,m.occurrence_id LIMIT $4`, [sourceId, keys, after[0], WITHDRAWAL_LIMITS.batch, subjects, after[1]]);- await match(rows.flatMap(row => row.fences.flatMap(fence => [- ...withdrawalFenceBlocks(fence).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: row.id, slug: row.slug, claim: f.claim, visibility: f.visibility, ambiguous: false }))),- ...ambiguousFenceClaims(fence).map(f => ({ id: row.id, slug: row.slug, ...f, ambiguous: true })),- ])));+ await match(rows.flatMap(row => row.fences.flatMap(fence => fenceClaims(Number(row.id), row.slug, fence))));if (rows.length < WITHDRAWAL_LIMITS.batch) break;after = [Number(rows[rows.length - 1].id), Number(rows[rows.length - 1].occurrence_id)];}+ for await (const split of splitFactsFences(engine, sourceId, keyed, subjects, deadline)) await match(fenceClaims(split.id, split.slug, split.fence));for (let after = 0; ;) {if (performance.now() > deadline) refuse();const chunks = await engine.executeRaw<{ id: number; page_id: number; slug: string; chunk_text: string }>(`SELECT c.id,c.page_id,p.slug,c.chunk_textdiff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.tsindex 4efe05d015..146262cdeb 100644--- a/src/core/page-body/segment-rewrite.ts+++ b/src/core/page-body/segment-rewrite.ts@@ -24,8 +24,8 @@ import { ContentHashStream } from './content-hash-stream.ts';import type { StoredRegion } from './segmenter.ts';import type { BodyRegion, JsonObject, ManifestRow } from './types.ts';-/** Rewrites one fence (the text of a stored facts or takes region, markers included). */-export type FenceTransform = (fence: string) => Promise<string>;+/** Rewrites one fence (the text of a stored facts or takes region, markers included), given the body region holding it; called in body order. */+export type FenceTransform = (fence: string, at: { region: BodyRegion }) => Promise<string>;/** Rows `from..to` of a generation, replaced by `bytes`. */interface FenceUnit { from: number; to: number; bytes: Uint8Array }@@ -68,7 +68,7 @@ async function changedUnits(engine: BrainEngine, sourceId: string, rows: readonllet cursor = 0, changed = false;for (const r of regions) {const fence = raw.subarray(r.start, r.end).toString('utf8');- const next = await transform(fence);+ const next = await transform(fence, { region: span[0]!.region });parts.push(raw.subarray(cursor, r.start), Buffer.from(next, 'utf8'));cursor = r.end;if (next !== fence) changed = true;diff --git a/test/large-pages/forget-scope.test.ts b/test/large-pages/forget-scope.test.tsindex 5be54ea522..a0cedfd8f9 100644--- a/test/large-pages/forget-scope.test.ts+++ b/test/large-pages/forget-scope.test.ts@@ -28,6 +28,7 @@ import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts'import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';import { withEnv } from '../helpers/with-env.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';const CLAIM = 'Prefers the window seat';const home = mkdtempSync(join(tmpdir(), 'gbrain-forget-scope-'));@@ -139,4 +140,75 @@ describe('forget on segmented pages', () => {expect(targets.map(t => t.slug)).toEqual(['notes/spare-key']);}}), 300_000);++ test('discovery joins a facts fence a forced cut split, finding a private row after the cut, and the withdrawal strikes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const secret = 'Hides the vault code inside the atlas';+ const rows = Array.from({ length: 12_000 }, (_, i) => row(i + 1, `Routine note number ${i + 1} about the weekly planning meeting`));+ rows.push(row(12_001, secret, 'private'));+ const text = `---\ntitle: Ledger\ntype: note\n---\n\n# Ledger\n\n${filler('Part one', 300_000)}## Facts\n\n${fence(rows)}\n\n${filler('Part two', 300_000)}`;+ for (const engine of engines) {+ await importFromContent(engine, 'notes/ledger', text, { noEmbed: true, sourceId: 'default' });+ const page = await segmentedPageRow(engine, 'notes/ledger');+ expect(page.body_storage).toBe('segmented');+ const split = await engine.executeRaw<{ seq: number; holds: boolean; opens: boolean }>(`SELECT m.seq,position(convert_to($2::text,'UTF8') in t.body)>0 AS holds,+ EXISTS (SELECT 1 FROM jsonb_array_elements(m.facts_slots) s WHERE s ? 'open_start' AND NOT s ? 'open_end') AS opens+ FROM page_body_manifest m JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256+ WHERE m.page_id=$1 AND m.gen_to IS NULL AND m.staging_id IS NULL ORDER BY m.seq`, [page.id, secret]);+ const opened = split.findIndex(r => r.opens), holding = split.findIndex(r => r.holds);+ expect(opened).toBeGreaterThanOrEqual(0);+ expect(holding).toBeGreaterThan(opened);+ const [hash] = await engine.executeRaw<{ h: string }>('SELECT gbrain_fact_fingerprint($1) AS h', [secret]);+ expect((await discoverWithdrawalTargets(engine, 'default', [{ visibility: 'private', fact_hash: hash!.h, claim: secret }])).map(t => t.slug)).toEqual(['notes/ledger']);++ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source)+ VALUES ('default',$1,NULL,'private','test') RETURNING id`, [secret]));+ const result = await coordinated(engine, tx => recordFactWithdrawal(tx, Number(fact!.id), 'default'));+ expect(result.pages.map(p => p.slug)).toEqual(['notes/ledger']);+ expect((await segmentedPageRow(engine, 'notes/ledger')).body_generation).toBe(page.body_generation + 1);+ const { body: stored } = await reconstructedPage(engine, 'notes/ledger');+ expect(stored.compiled_truth).toContain(`| 12001 | ~~${secret}~~ |`);+ expect(stored.compiled_truth).toContain(row(12_000, 'Routine note number 12000 about the weekly planning meeting'));+ // A split fence above the single-string ceiling is refused, never skipped (its slot extent stretched past it here).+ await coordinated(engine, tx => tx.executeRaw(`UPDATE page_body_manifest SET facts_slots=jsonb_set(facts_slots,'{0,end}',to_jsonb($2::bigint))+ WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL AND facts_slots->0 ? 'open_start'`, [page.id, PAGE_MAX_BYTES + 1]));+ const refused = await discoverWithdrawalTargets(engine, 'default', [{ visibility: 'private', fact_hash: hash!.h, claim: secret }]).then(() => 'ok', (e: { code?: string }) => e.code);+ expect(refused).toBe('page_body_segmented');+ }+ }), 300_000);++ test('with two facts fences carrying the same row number, the segmented strike matches the inline one exactly', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ // A second fence whose header orders its columns differently: import cannot merge it into the first (both stay).+ const reordered = (rows: string[]) => `<!--- gbrain:facts:begin -->+| # | kind | claim | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|------|-------|------------|------------|------------|------------|-------------|--------|---------|+${rows.join('\n')}+<!--- gbrain:facts:end -->`;+ const fences = (big: boolean) => {+ const pad = (tag: string) => big ? filler(tag, 700_000) : '';+ return {+ both: `# Twins\n\n${pad('One')}## First\n\n${fence([row(1, 'Alpha twin claim'), row(2, 'Alpha second claim')])}\n\n${pad('Two')}## Second\n\n${reordered([`| 1 | preference | Beta twin claim | 1.0 | world | medium | 2026-01-01 | | chat | |`, `| 3 | preference | Beta third claim | 1.0 | world | medium | 2026-01-01 | | chat | |`])}\n`,+ timelineOnly: `# Twins\n\n${pad('One')}No fence in the truth.\n\n<!-- timeline -->\n\n${pad('Two')}${fence([row(1, 'Gamma timeline claim')])}\n`,+ };+ };+ const cases = [{ name: 'both', rowNum: 1 }, { name: 'both', rowNum: 3 }, { name: 'timelineOnly', rowNum: 1 }] as const;+ const blocks = (text: string) => text.match(/<!--- gbrain:facts:begin -->[\s\S]*?<!--- gbrain:facts:end -->/g) ?? [];+ for (const engine of engines) {+ for (const [n, c] of cases.entries()) {+ const results: string[][] = [];+ for (const big of [false, true]) {+ const slug = `notes/twins-${n}-${big ? 'segmented' : 'inline'}`;+ await importFromContent(engine, slug, `---\ntitle: Twins\ntype: note\n---\n\n${fences(big)[c.name]}`, { noEmbed: true, sourceId: 'default' });+ expect((await segmentedPageRow(engine, slug)).body_storage).toBe(big ? 'segmented' : 'inline');+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)+ VALUES ('default','Twin row claim',NULL,'world','test',$1,$2) RETURNING id`, [slug, c.rowNum]));+ await withCoordinatedWrite(engine, ['default'], () => forgetFactInFence(engine, Number(fact!.id), { supersededBy: { rowNum: 9 } }), TEST_WRITE_ATTRIBUTION);+ const body = big ? (await reconstructedPage(engine, slug)).body : (await engine.getPage(slug, { sourceId: 'default' }))!;+ results.push([...blocks(body.compiled_truth ?? ''), '<timeline>', ...blocks(body.timeline ?? '')]);+ }+ expect(results[1]).toEqual(results[0]!);+ expect(results[0]!.indexOf('<timeline>')).toBe(c.name === 'both' ? 2 : 0);+ expect(results[0]!.join('\n').includes('superseded by #9')).toBe(c.name === 'both' && c.rowNum === 1);+ }+ }+ }), 300_000);});