Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Conversation facts keep a name tag for people and companies with no page; held member shares; mention links follow aliases (GBRA-574, GBRA-585, GBRA-621) (#9674)

Garry Tan9b78b02111ce
diff --git a/behavior-changes.d/conversation_name_keys_gbra574.md b/behavior-changes.d/conversation_name_keys_gbra574.md
new file mode 100644
index 0000000000..b207a5dbbd
--- /dev/null
+++ b/behavior-changes.d/conversation_name_keys_gbra574.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+`gbrain extract-conversation-facts` now keeps a name tag on a fact about a person or company that has no page, instead of storing the fact with no entity (the 0.60.162.0 rule, which still applies to every other writer). The tag is the full name in slug form without a folder (Alice Example becomes alice-example); a single word such as a first name or a topic keeps no tag. No page is created, lists of pages never show a tag, and only new extractions get one. A page written later at that file name (people/alice-example) reads the tag's facts, and `gbrain facts relink --conversation --unbacked` (preview with --dry-run) moves them onto the page the name resolves to. Forgetting or purging a fact on a tag now applies to that claim across the whole source (a forget refuses with claim_linked while the same claim is active on another person's or company's fact), and a claim forgotten or purged for anyone never comes back on a tag; facts already stored on a bare slug with no page are treated the same way. Two people with the same full name in one source share a tag until a page or alias separates them (docs/guides/facts-relink.md). Turn tags off with `gbrain config set facts.unbacked_entity_keys false`.
diff --git a/behavior-changes.d/member_share_about_member_held_gst2897.md b/behavior-changes.d/member_share_about_member_held_gst2897.md
new file mode 100644
index 0000000000..dcff576f3b
--- /dev/null
+++ b/behavior-changes.d/member_share_about_member_held_gst2897.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+A member credential's remember with share: true about another enabled member (an entity under people/<member>/ or people/<member>) is now stored private, with a pending proposal the brain owner lists with gbrain trust review and shares with gbrain trust confirm tp<N>, instead of being shared with every reader of the source at once. The reply says visibility "private" and carries a held field naming the proposal and the member. A share about the team's work, about the caller itself, or by the owner's own credential is unchanged. The member a shared fact is about can now withdraw it with forget, where only the brain host could before; it still cannot withdraw a shared fact about anyone else. A member's visibility "world" about another member is refused as before, and the refusal no longer tells the agent to retry with share: true.
diff --git a/behavior-changes.d/mention_links_thin_pages_9675.md b/behavior-changes.d/mention_links_thin_pages_9675.md
new file mode 100644
index 0000000000..0cac108af0
--- /dev/null
+++ b/behavior-changes.d/mention_links_thin_pages_9675.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+Mention links change on the next mention sweep. Text that writes @handle now links to the person whose frontmatter names that X handle. A page that is only titled with a name another page of the same kind claims as a frontmatter alias or handle stops collecting that name, and those mentions move to the claiming page. A one-word person page titled with another person's first name stops collecting bare mentions of that first name. No page is edited; only the mention links move.
diff --git a/changelog.d/capy-mention-links-go-to.md b/changelog.d/capy-mention-links-go-to.md
new file mode 100644
index 0000000000..0340c8a85d
--- /dev/null
+++ b/changelog.d/capy-mention-links-go-to.md
@@ -0,0 +1,8 @@
+**Mention links now go to the person or company a page's frontmatter names, not to a thin page that only carries the name as its title.**
+
+<!-- behavior-change: mention_links_thin_pages_9675 -->
+
+### Fixed
+- A person's X handle in frontmatter (`x_handle`, `twitter`, `twitter_handle` or `x`) now links text that writes `@handle` to that person. Placeholders such as `unknown`, `0`, `true` or `false` are not handles, and a bare word that happens to equal a handle does not link through it.
+- When exactly one page claims a name as a frontmatter alias or handle, a page of the same kind that is only titled with that name stops collecting its mentions, and they link to the claiming page instead. The thin page itself is not changed. If the claiming page's own entry for the name is dropped by another rule, the thin page keeps the name, as before.
+- A one-word person page titled with another person's first name (`Alice` when `Alice Example` exists) no longer collects every bare mention of that first name. A one-word person title that only its own page's longer alias starts with still links.
diff --git a/changelog.d/gbra574-name-keys.md b/changelog.d/gbra574-name-keys.md
new file mode 100644
index 0000000000..73bf8cf4db
--- /dev/null
+++ b/changelog.d/gbra574-name-keys.md
@@ -0,0 +1,13 @@
+**Conversation facts about a person or company with no page keep a name tag, so their history can be grouped without creating pages.**
+
+### Changed
+- `gbrain extract-conversation-facts` keeps a name tag on a fact whose person or company was named in full but has no page. The tag is the name in slug form without a folder (`alice-example`), where the fact used to have no entity at all. A single word (a first name, a topic) keeps no tag. No page is created and page lists never show a tag. The fact also gets a role, employer or city slot from the existing small tagging call. Only new extractions get tags. Off with `gbrain config set facts.unbacked_entity_keys false`.
+- Forgetting or purging a fact on a name tag applies to that claim across the whole source, and a claim forgotten or purged for anyone stays out of a tag, so a page written later or a tag moved onto a page never brings it back (schema migration v321 updates the facts guards). Like a fact with no entity, forgetting a tag fact refuses with `claim_linked` while the same claim is active on another person's or company's fact, and a member forgetting a fact on their own memory page never reaches a tag. Facts already stored on a bare slug with no page (written before 0.60.162.0) are treated the same way.
+- A private page at `<folder>/<tag>` (people, companies, orgs, organizations, funds, hosts, projects or concepts) keeps the tag's facts from every remote caller who cannot read that page.
+- The consolidate phase no longer reads facts whose entity has no page; it skipped them after reading before.
+
+### Added
+- `gbrain facts relink --conversation --unbacked` moves the facts on a name tag onto the page the name now resolves to (its file name, a unique alias, or the same name without a company suffix; a merged page hands them to its target), free, preview first with `--dry-run`. The facts relink guide explains how to separate two people who share a full name.
+- A `query` with a token budget that asks for one person's history in one slot (which job titles, employers or cities, oldest first or over time) gets every value that person or name tag has had in that slot that the caller may read, oldest first, each with its validity window, inside the facts block's existing share. A name tag is found when the question holds its full name and no other tag matches. A failed history read keeps the block and is reported as the degraded stage `facts_history_unavailable`.
+
+<!-- behavior-change: conversation_name_keys_gbra574 -->
diff --git a/changelog.d/gbra585-share-held.md b/changelog.d/gbra585-share-held.md
new file mode 100644
index 0000000000..28f2d13fdd
--- /dev/null
+++ b/changelog.d/gbra585-share-held.md
@@ -0,0 +1,8 @@
+**On a shared brain, a member who shares a fact about another member now waits for the brain owner, and the member it is about can withdraw it.**
+
+### Changed
+- A member's `remember` with `share: true` about another member (`people/<member>`) is stored private with a proposal the owner confirms (`gbrain trust confirm tp<N>`) or drops; until then no other member recalls or reads it. The reply says it is held and for whom. Shares about the team's work, about the caller itself, and by the owner are unchanged.
+- The member a shared fact is about can forget it; before, only the brain host could.
+- A member's `visibility: "world"` about another member is refused without suggesting `share: true`.
+
+<!-- behavior-change: member_share_about_member_held_gst2897 -->
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index fae5ad713e..1bc44455b3 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -486,12 +486,14 @@ updates that row in `facts`, and the write role then needs a permissive `UPDATE`
`facts` covering the row, beside its `SELECT` policy, or the guard refuses the insert with the
same `writer_coordinator_required` error.
-**Check that the upgrade replaced every guard.** Migration v318 can only replace a guard function
-the role running it owns. A guard owned by another role is left as it was, so it still lets a
-scoped writer without ledger policies through, and v318 only names it in one stderr line
-(`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`). After upgrading,
-run this as any role that can read the catalog. Every one of the seven rows must show
-`fails_closed = t`:
+**Check that the upgrade replaced every guard.** Migrations v318 and v321 can only replace a guard
+function the role running them owns. A guard owned by another role is left as it was, and each
+migration only names it in one stderr line. Left by v318, it still lets a scoped writer without
+ledger policies through (`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`).
+Left by v321, a facts guard still lacks the name-tag rule, so a claim forgotten or
+purged under another subject can come back on a name tag (`guards: N purge or withdrawal guard(s)
+keep their body from before name keys ...`). After upgrading, run this as any role that can read
+the catalog. Every one of the seven rows must show `fails_closed = t`:
```sql
SELECT p.proname, pg_get_userbyid(p.proowner) AS owner,
@@ -506,11 +508,14 @@ ORDER BY 1;
For a row with `fails_closed = f`, connect as the role in its `owner` column and run
`ALTER FUNCTION public.<proname>() OWNER TO <the role gbrain migrates as>;`. Then run
`gbrain apply-migrations --yes`, or start gbrain: every migration run re-creates a guard that
-is missing its check, provided the migrating role owns it. You can also run gbrain once as the
-owning role instead. Run the query again to confirm. On Postgres, `gbrain doctor`
-(`guard_ledger_checks`) runs the same check and names each guard left without its ledger check
-with its owner, and the fix: `gbrain apply-migrations --yes` when the doctor's role may re-create
-it, else the `ALTER FUNCTION ... OWNER TO` SQL to run as the owning role first.
+is missing its check or its current body, provided the migrating role owns it. You can also run
+gbrain once as the owning role instead. Run the query again to confirm. The query sees only the
+ledger check, so a facts guard v321 left still shows `fails_closed = t`. On Postgres, `gbrain doctor`
+(`guard_ledger_checks`) runs the same check, also checks the current body of the three facts guards
+(`unbacked_page` in `gbrain_refuse_purged_fact`, `memory/scope` in `gbrain_preserve_fact_withdrawal`
+and `gbrain_guard_inserted_facts`), and names each guard left behind with its owner, and the fix:
+`gbrain apply-migrations --yes` when the doctor's role may re-create it, else the
+`ALTER FUNCTION ... OWNER TO` SQL to run as the owning role first.
The segmented storage recipe above already covers the two derivation purge tables for a
role it applies to. A policy that filters out ledger rows of a source the role writes hides
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 07b6b32b57..974634259f 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -282,7 +282,7 @@ src/core/trust/fence-guard.ts 2 coordinator guardFenceRows detaches and renumber
src/core/trust/held-removals.ts 3 coordinator The owner accept of a held take or timeline removal deletes or re-projects that one row as the page now says, inside withCoordinatedWrite under the page key on a managed brain (withWriteAttribution otherwise), in the transaction that decides the proposal; a refused takes_remove instead reruns as an owner takes_remove through the takes request preparer.
src/core/trust/owner-actions.ts 1 coordinator The owner release of a held fact inserts it database-only at user_confirmed under the promotion capability, in the owner action transaction that decides the hold: withWriteAttribution on an unmanaged brain, and withCoordinatedWrite on a managed brain only for the facts-lane fallback (a hold with no entity slug, or whose page is missing). Every other managed fact release publishes through the trust_release door (trust/release-publish.ts: the fence row in the file first, then the row).
src/core/trust/page-handlers.ts 1 coordinator Owner page confirm/revert: a managed brain admits a journaled owner page mutation (submitOwnerPage); the unmanaged path runs importFromContent inside one attributed transaction that re-checks the previewed revision.
-src/core/trust/supersede-handlers.ts 3 filesystem_guard Trust-guard supersession accept/undo raise or restore only trust_tier on the proposal's facts/takes row through the S9 decide_proposals checked accept/undo path (proposal-supersede.ts): source filesystem and page locks unmanaged, the decide_proposal coordinator mutation managed.
+src/core/trust/supersede-handlers.ts 4 filesystem_guard Trust-guard supersession accept/undo raise or restore only trust_tier on the proposal's facts/takes row through the S9 decide_proposals checked accept/undo path (proposal-supersede.ts): source filesystem and page locks unmanaged, the decide_proposal coordinator mutation managed. GST-2897 B: the owner's accept of a held share sets only the held fact's visibility to the world its fence cell already asks for (or a pageless row), under withCoordinatedWrite on a managed brain; it never changes a claim, a file or a lifecycle.
src/core/trust/timeline-projection.ts 2 engine_guard gbrain extract's timeline projection inserts gate-allowed rows stamped with the page tier inside an attributed maintenanceTransaction; on a managed brain the canonical table trigger refuses it outside the coordinator.
src/eval/brainbench/trust-scenario.ts 2 isolated_eval BrainBench trust suites register their fixture sources in the scenario's own isolated benchmark brain (persistence disabled for the registration, re-enabled after); never opened against the active managed brain.
src/core/oversized-backfill.ts 1 coordinator The oversized-page backfill (gbrain reindex --oversized, the post-upgrade pass) rewrites a size-skipped page without its gate markers through importFromContent on unmanaged brains (assertUnmanagedCanonicalWriter applies) and through submitPageMutation put_page (managed_quarantine_clear, expected_revision) on managed brains; its only direct write is the page_embedding_budget hold row, which is derived spend state, not canonical content.
diff --git a/docs/architecture/coordinated-writes.tsv b/docs/architecture/coordinated-writes.tsv
index fc3ce37ccc..8dfb94f087 100644
--- a/docs/architecture/coordinated-writes.tsv
+++ b/docs/architecture/coordinated-writes.tsv
@@ -45,3 +45,4 @@ src/core/trust/backfill.ts runTrustBackfill 1 metadata Backfills trust tiers com
src/core/trust/held-removals.ts acceptHeldRemoval 1 projection An accepted held removal re-derives the take from its fence row or the timeline row from the page body; the rows follow the text.
src/core/trust/owner-actions.ts publishReleasedFact 1 facts_lane A released held fact with no entity slug, or whose entity page is missing, is inserted database-only (G4, GBRA-190, owns that class); every other managed fact release publishes its fence row through the door as a journaled trust_release request (trust/release-publish.ts).
src/core/trust/page-handlers.ts setRowTier 1 metadata An owner trust decision sets trust_tier and its owner_decision note on a fact, take or page row; trust tier is metadata, page content changes go through trust_owner_page.
+src/core/trust/supersede-handlers.ts accept 1 projection GST-2897 B: the owner's accept of a held share sets the held fact's visibility to the world its page's fence cell already asks for (or a pageless row); the row follows the text, no file or claim changes.
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index 966b8569e9..7ea5bfb3f2 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -7,7 +7,7 @@ Patterns, drift reports and the cycle modules listed after them.
- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still s... (line truncated to 2000 chars) Reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`, so neither carries a facts row other than world or a takes row (test: `test/cycle-world-fence-rows.test.ts`).
- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws. Both publish paths carry the report's derivation (#9208): channel `derive:drift` over the judged pages, whose timeline entries are the judge's evidence, so the report takes their least trusted tier capped at `agent_written`.
-- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically: a fenced member on the entity page is closed in its `## Facts` fence row in the same page publication and its `valid_until` derives from that cell, an unfenced member is closed in the database, and a member fenced on another page stays open (test `test/consolidate-fenced-close-reimport.test.ts`). A member ends at the next member that says something else by claim text and typed value (`consolidationCloses` in `persistence/prepared-maintenance.ts`, both paths), so a restated value stays open from its first statement and every copy ends together when the value changes (test `test/consolidate-restatement.test.ts`). Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)
+- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Its bucket scan lists only entities with a live page in the source (GBRA-574 E1), so a conversation-only brain's name keys cost no per-bucket read (`test/conversation-unbacked-keys-gbra574.test.ts`). `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically: a fenced member on the entity page is closed in its `## Facts` fence row in the same page publication and its `valid_until` derives from that cell, an unfenced member is closed in the database, and a member fenced on another page stays open (test `test/consolidate-fenced-close-reimport.test.ts`). A member ends at the next member that says something else by claim text and typed value (`consolidationCloses` in `persistence/prepared-maintenance.ts`, both paths), so a restated value stays open from its first statement and every copy ends together when the value changes (test `test/consolidate-restatement.test.ts`). Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)
- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding, skipping markdown inline markup (`*`, backticks, `~~`; not `_`), WITH an offset map back to the original string, so every replacement is a verbatim transcript slice; a slice that differs from the quote only by that markup counts exact and is not spliced in) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). A source built with `groundSource(path, content, { tolerant: true })` (think, concepts and patterns; never dream synthesis) also reads markdown link syntax and any other square bracket as plain text (`[Name](target)`, `[Name]` and `Name` match; repairs drop link targets and never carry a `"`), folds `"` to `'`, and counts a quote exact when its words match once the writer's edge punctuation and elision, brackets (including a bracketed letter's case, `[T]he`), editorial insertions in a word (`decide[s]`, `want[ed]`) and inner quote style are set aside. Think also grounds against the user's question. `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. In strict mode (dream synthesis) a quote that misses whole is retried on its core (`quoteCore`: edge elision and closing punctuation set aside) at the exact and normalized rungs; an exact core keeps the writer's quote, a normalized core is replaced by the verbatim source slice. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the... (line truncated to 2000 chars)
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 12e2d8ebb5..76ab295149 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -10,10 +10,10 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs; `submitConversationPages` raises every member's attempt past an id another write holds, or whose receipt lost its intent without committing (#7516: a redacted `purged_content` refusal or a compacted failure takes the attempt history `loadGenerationIndex` reads, so the same id came back on every run as `idempotency_conflict` after a paid extraction; test `test/conversation-facts-redacted-batch-7516.test.ts`, + Postgres arm). The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Rows carry an optional slot (GBRA-574 B2: `dimension`, `value`, `value_hash`, `dim_status 'active'`): `insertableSlots` drops a slot outside the vocabulary, without an entity, or whose unique slot key the page or an earlier row of the batch already holds (the fact stays), and `clearConversationFacts` clears the slot of every row it keeps expired in the same UPDATE. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
- `src/core/facts/slots.ts` — GBRA-574 B2/G4 conversation fact slots: the closed vocabulary (`location`, `employer`, `role`), `normalizeSlot` (entity required, value at most 80 characters), `CHANGE_CUE` and `deriveSlotEnds`, which works out read-time validity ends per (source, entity, dimension): a run of one value is one stint, and the next distinct value ends it at its `valid_from` only when it starts later and comes from a page the stint came from or its fact states a change; otherwise both values stay open. Nothing is written. The ontology keeps its own domain: `getOntology`, `discoverOntologyDimensions`, `findOntologyConflicts`, `mergeOntologyFact` and the ontology-facts repair skip conversation rows (`chronicle/ontology.ts` `NOT_CONVERSATION_SLOT_SQL`), `mergeOntologyFact` and the re-key dedup (`facts/ontology-rekey.ts`, also run by the twin merge) clear the slot of a conversation row that holds an observation's exact stint key instead of dropping either, and windows read conversation rows only. Tests: `test/facts-slot-windows-gbra574.test.ts` (+ Postgres arm), `test/facts/extract-slots.test.ts`, `test/facts/normalize-slot.test.ts`.
-- `src/core/facts/slot-tagging.ts` — GBRA-574 slot tagging: the main extraction call never asks for a slot, so `extractConversationWindow` sends a second small call (`tagSlots`, the facts extraction model, `SLOT_TAG_SYSTEM`, at most 10 facts and 400 output tokens) over the window's `fact` and `event` rows whose entity was named exactly (the extractor's name resolves to the same page through `resolveStrictEntityReference`: exact slug, unique basename or unique alias, never a prefix guess or a near name; or subject inference) and is a live, unretired `person` page; no candidate, no call, and BrainBench's injected extractor skips it. Each reply pair goes through `normalizeSlot`. A failed or unreadable reply keeps the facts without slots and counts `slot_tagging_failed`; abort and `BudgetExhausted` propagate. The per-page cap (`conversation-incremental.ts`) and `conversationRunEstimate` add one tagging call per window at its largest (`SLOT_TAG_INPUT_CHARS`). Tests: `test/facts/slot-tagging.test.ts`, `test/large-pages/conversation-slot-tagging-segmented.test.ts`.
+- `src/core/facts/slot-tagging.ts` — GBRA-574 slot tagging: the main extraction call never asks for a slot, so `extractConversationWindow` sends a second small call (`tagSlots`, the facts extraction model, `SLOT_TAG_SYSTEM`, at most 10 facts and 400 output tokens) over the window's `fact` and `event` rows whose entity was named exactly (the extractor's name resolves to the same page through `resolveStrictEntityReference`: exact slug, unique basename or unique alias, never a prefix guess or a near name; or subject inference) and is a live, unretired `person` page, or whose entity is a name key the window kept for a full name with no page (`unbacked`, bracketed with the extractor's own name text); no candidate, no call, and BrainBench's injected extractor skips it. Each reply pair goes through `normalizeSlot`. A failed or unreadable reply keeps the facts without slots and counts `slot_tagging_failed`; abort and `BudgetExhausted` propagate. The per-page cap (`conversation-incremental.ts`) and `conversationRunEstimate` add one tagging call per window at its largest (`SLOT_TAG_INPUT_CHARS`). Tests: `test/facts/slot-tagging.test.ts`, `test/large-pages/conversation-slot-tagging-segmented.test.ts`. The name keys come from `src/core/entities/resolve-on-save.ts` (GBRA-574 F): conversation extraction alone passes the `unbacked` map while `facts.unbacked_entity_keys` is on (`unbackedEntityKeysEnabled`), and a fallback name of at least two words keeps its bare basename key (`unbackedEntityKey`: `Alice Example`, `alice-example` and `people/alice-example` give `alice-example`) unless a live page sits at that bare slug, counted as `unbacked_key_count`; no page is created and every other writer still stores NULL.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text (lowercase Unicode page-slug letters without combining marks; a literal glued to further letters is not a literal), resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
- `src/core/facts/conversation-subject-infer.ts` — #6764 write-time subject inference for `gbrain extract-conversation-facts` (both the classic and managed branches, trusted local only) and the free conversation relink. `inferConversationSubject` is the per-fact rule (a withdrawn claim misses as `withdrawn`); `inferConversationSubjects(engine, sourceId, visibility, rows)` gives each row the extractor left without an entity the slug `inferFactSubject` proves in `write` mode (mention tier; `excludePrivate` for world rows) plus the `entity inferred from <tier>` context note, unless `facts.entity_inference` is off or the claim was withdrawn. The row stays a derived row of the conversation page (`entity_slug` column only). Test: `test/conversation-facts-unlinked-6764.test.ts`.
-- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model); a row the assistant or a third party said is never linked, never picks a page, and is counted as `not_user_attributed` (#7270). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
+- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model); a row the assistant or a third party said is never linked, never picks a page, and is counted as `not_user_attributed` (#7270). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`. GBRA-574 C1 `--unbacked` (`planUnbackedPages`): rows on an unbacked name key (`withdrawal-schema.ts` `unbackedEntitySql`) re-key onto the page the key's words resolve to through `resolveStrictEntityReference` with `sameName` (exact slug, unique basename, unique alias, same name ignoring corporate suffixes; a retired page answers through its `superseded_by` target; `excludePrivate` for world rows); each planned row carries `from` (the key), the write re-checks the row is still on that key, runs `dropRekeyDuplicates` first so a slot never collides, notes `entity relinked from unbacked` and records a `linked` attempt with tier `unbacked`; misses keep their key and write no memo. Test: `test/conversation-unbacked-keys-gbra574.test.ts` (both engines; Postgres via `test/e2e/conversation-unbacked-keys-gbra574-postgres.test.ts`).
- `src/core/facts/conversation-memo.ts` — #6764 what makes free relink, then paid re-extraction, then linking by hand converge, all in `fact_relink_attempts`: `conversationTriedSql` (a `conversation_unresolved` memo, re-armed for the free relink by any page created in the source after it unless `RELINK_REASONS` memoizes the reason), `conversationPaidSql` and `recordReextractMemo` (tier `paid_reextract`, `target_slug` the page, `reason` its `content_hash`, keyed on the page's completion outcome row; written when an extraction of the page completes, unmanaged in `extract-conversation-facts.ts` and managed in `conversation-publication.ts` `applyEntry`). No schema change. Test: `test/conversation-memo-6764.test.ts`.
- `src/core/facts/conversation-relink-carry.ts` — #6764 how a free conversation relink survives a batch replacement: `clearConversationFacts` (conversation-publication.ts) expires the page's relinked rows (`RELINKED_DERIVED_ROW`: entity set and `entity relinked from` in the context) instead of deleting them, after deleting the previous clear's expired copies, and `inheritRelinkedEntities` gives each inserted row with no entity whose claim matches one of them that entity (live page only) and the relink note, in every insert `publishConversationFacts` makes (managed and unmanaged, replacement or addition) and in `insertGatedFacts`. One active copy, link kept. Test: `test/conversation-relink-6764.test.ts`.
diff --git a/docs/architecture/key-files/core-search-evidence.md b/docs/architecture/key-files/core-search-evidence.md
index 7314f40a1e..be3f957f8e 100644
--- a/docs/architecture/key-files/core-search-evidence.md
+++ b/docs/architecture/key-files/core-search-evidence.md
@@ -6,5 +6,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed YYYY-MM-DD|unknown; valid FROM to UNTIL]` for facts, `observed` from the source page (`source_markdown_slug`) via `factObservationDates` under the caller's page read policy; a failed read renders `unknown` and the caller reports `fact_observed_date_unavailable`), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off) and `evidenceTitlesEnabled` (`search.evidence_titles`, GBRA-205, default off: with the header on, `blockDateHeaders` ends a page block's line with its title via `titledPageHeader`, fact headers unchanged; `evidenceTitle` removes bidi overrides, isolates and marks and blanks angle brackets and C0/C1 controls in both sinks; think's `<page>` tag gets a `title` attribute). Tests: `test/evidence-date-header.test.ts`, `test/search-8k-conversion.test.ts`.
- `src/core/search/evidence-tail-trim.ts` — the protected tail trim (`search.evidence_tail_trim`, default off, GBRA-156). `resolveEvidencePlan` sets `EvidencePlan.tailTrim` only for `unit: auto` with the key on; `deliverEvidence` calls `trimEvidenceTail(results, opts.query)` on the rank-order delivered rows after redaction and before the token totals, and only when `DeliverOptions.query` is set (`search`/`query` pass `p.query`; the library `assembleEvidenceForHits` passes `input.query` and frozen hits may carry `score`; the `assemble_evidence` op passes neither, so the trim never runs there). Rows past `TAIL_TRIM_PROTECTED` = 3 that are whole-conversation blocks (`delivered.reason` `conversation_type`/`conversation_slug`) and score under `TAIL_TRIM_SCORE_FRACTION` = 0.5 of rank one are dropped, unless their `chunk_text` holds at least `TAIL_TRIM_TERM_FRACTION` = 0.8 of rank one's share of the query's terms (`queryTerms`: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. `delivery.tail_trim` is `{ dropped, kept_by_query_terms }`; `dropped_reasons.tail_trim` counts drops. Pinned by `test/evidence-tail-trim.test.ts` (the knowledge-update regression case).
- `src/core/search/transcript-quote.ts` — quotes third-party text on every read that hands it to a model (#7600, #8042). The signal is stored metadata, in one place: `isQuotedPageType` (every concrete type in `facts/conversation-types.ts` `ALLOWED_TYPE_ALIASES` plus `transcript` and `chat`) for page rows, and for fact rows `isQuotedFactSource` (`facts.source` starting `cli:extract-conversation-facts`, the prefix in `facts/audit-sources.ts`) or `factsFromQuotedPages` (one bounded read, same source: the fact's `source_markdown_slug` page, a `derivation_inputs` page edge the backstop and extract_facts already write, or for a `sync:import` / `mcp:put_page` fact the page its `source_session` names (`sync:<slug>`, `put_page:<slug>`, covering facts saved before edges or rebuilt from git) has a quoted type; it writes nothing, and a lookup failure withholds `saved_facts` (stage `saved_facts_withheld`) and remote recall facts (`facts_degraded.reason`) and fails the delta facts arm; the facts arm carries both on `fact_row.source`/`from_quoted_page`, stripped by `factRowOutput`; marker `fact <id>`); nothing reads the text to decide, so other rows come back byte-for-byte unchanged. `quoteLabel` is the row decision. GST-687: for an untrusted (remote, `ctx.remote !== false`) reader the signal also includes the stored trust tier: `quotesTier` (below `OWNER_TIER_FLOOR`, `operator_curated`; a missing tier reads as `unknown`, so it fails closed) and `quotesStored` (page type or tier) quote agent-written, tool-data, external and unverified-origin text. `quoteLabel(row, untrusted)`, `deliveredQuoteText`, `fenceTranscriptRows` and `quoteFacts(engine, facts, untrusted)` take that flag (`quoteFacts` reads each fact's stored tier from `facts`, never from the caller's row); only third-party types get tool calls summarized. `quotePageText` and `pageTypesById` serve reads whose rows name only a page (`get_timeline`, `get_chunks`). Local reads are unchanged. Beyond search: `recall` (remote callers: neutralize + fence its results before packing, `quoteFacts` its facts), think's pages block (`think/gather.ts renderPagesBlockDetailed`: neutralize before the excerpt, fence what it renders, every run), `saved_facts` in search/query meta, remote `delta` facts and `_meta.brain_hot_memory` (`quoteFacts`, which also quotes a representative when a collapsed member qualifies), remote `get_page known_as_of` and `get_versions` bodies and diffs (`ops/known-as-of.ts intervalView`, `ops/admin.ts`), and remote `get_page`/`fetch` (`ops/get-page-projection.ts projectGetPage` `quote`, which `projectFetchText` reuses: compiled_truth, timeline and `content` fenced without the tool-call summary, so text inside stays byte-exact; windows fenced in `get-page-body.ts envelopeText`; `quoted: "transcript"`; `quotesBody(ctx, page, trust)` also quotes a page below the owner's tier, and `neutralizesBody` summarizes tool calls only on a third-party page's reading shapes, never for the thin client, with `include_content` and `view: markdown` keeping the stored bytes inside the fence). Remote `get_timeline`, `get_chunks`, `search_exact`, think's extractive fallback, `context_pack` and `list_write_requests`/`get_write_request` outcome text quote by tier too, and so (#8377) do the `chronicle_*` reads and `volunteer_chronicle`'s timeline (`ops/chronicle.ts remoteTimeline`, each row by its own page; `quoteTimelineRows` fences a row's free-text `source` with summary and detail, #8384, and an event row's `kind` is fenced by its event page's type and tier), its ontology values, `ontology_get`'s and `ontology_conflicts`' (`remoteOntology`, `quoteFacts` by `fact_id`; remote `ontology_propose` drops a fact fence), `takes_list`/`takes_search` (`ops/takes.ts quoteTakes`), a quoted page's title, frontmatter strings and tags (`quotedPageMeta`, also `get_tags`; remote `add_tag`/`remove_tag` drop a fence naming the page; `include_content` and fetch `text` fence the whole serialized markdown), a quoted search/query/assemble_evidence/recall row's title (`deliveredQuoteTitle`, which `capEvidenceToBudget` counts), a `context_pack` card below the owner's tier rendering its title under the card's trust label, the per-turn push hook's hot facts and the pushed context pack (`untrusted: true`); `context_pack` counts entity facts a failed quote lookup withholds in `suppressed`. Remote `remember` drops a fact fence (`unquoteFactText`) and `add_timeline_entry` a fence naming its page, so a copied-back entry keeps its replay key. Remote `put_page` (`ctx.remote !== false`) runs `unquoteTranscriptText` over `content` (`persistence/page-mutations.ts unquotedPutContent`, after the replay check so the request digest covers what the caller sent; slug lowercased as admission does) when the stored page or the incoming frontmatter has a quoted type or the stored page is below the owner's tier (an owner-tier page keeps a fence naming it only when its stored body already holds one), removing only a marker naming that slug and its own fence (lines may end in CRLF), so get → edit → put writes the body and a note's fence-like text is kept (`unclosed`: a fence opening the content, after blank lines at most, whose closing line the edit replaced is removed too, #8377, #8384; `closingLine` takes the first line that is exactly the read's fence outside a code block the text opens itself, so an agent's added block stays whole; every search of one text shares a budget of eight times its length, past which the rest is kept as written, so many unclosed markers stay linear). Remote `put_page` content holding a tool-call summary that a whole read of the stored conversation page never produces, or fewer of a call's summaries than the page holds (`holdsSummarizedToolCalls`), refuses `invalid_params` and stores nothing; only summaries outside the text's own tool-call blocks count, and a named summary the page never wrote is admitted while every stored call stays (#8377). A thin client paging a quoted page (`cli/page-render.ts spoolWholePage`) unquotes each window before checking size and sha256, then prints the page (and `--json` content) inside one quote fence (`transcriptFence`). Trusted local get_page/fetch/put_page, recall and delta are unchanged. `searchOutput` (`ops/search.ts`) runs `neutralizeTranscriptRows` before the snippet and evidence caps and `fenceTranscriptRows` after them, on copies, after ranking and evidence delivery; `assembleEvidenceForHits` (`evidence-delivery.ts`, so the `assemble_evidence` op and gbrain-evals) does the same around `capEvidenceToBudget`. That cap counts a conversation row as delivered, inside its fence (`deliveredQuoteText`, its `quote` flag; deliverEvidence's own cap, which recall uses, counts the text as returned), so an explicit `auto` token budget still holds, `snippet_chars` included (a rank-one row is kept even when its fence alone exceeds a very small budget); a row it cuts is shortened until the fenced text fits, and other rows are cut exactly as before. The neutralizer replaces each tool-call block with `[tool call: <name>, arguments omitted]` (`[tool calls: a, b, …]` for several): an object typed `tool_use`, `server_tool_use`, `mcp_tool_use`, `function_call`, `custom_tool_call`, `tool_call` or `toolCall` (the enclosing object, found by walking back over candidate `{` with a string-aware scan), the value of a `tool_calls` array or a `function_call` or Gemini `functionCall` object (the message object and its `content` or `parts` stay), and an XML-style `function_calls`, `invoke`, `tool_use` or `tool_call` element with its `parameter` children, namespace prefix optional (the name from `invoke name="…"`, a `<name>` child, or the root `name` of the JSON object a `tool_call` opens with; result elements are never matched, and a tag counts as markup only when it ends its line (LF or CRLF) or the text, runs into the next tag, is an `invoke` with a name, or is a `tool_call` followed by `{`; blocks separated only by whitespace merge). The XML pass runs before the JSON pass. Text between evidence omission lines is read separately; a block cut by the end of the text is replaced to the end or the next message anchor line (an open-ended block never swallows a later message), one whose `{` lies before the text from the text start (or the last message anchor) when the type is followed by `,` or `}`, and prose that only names the shape is left alone. An XML block whose close lies past the text runs to the end or the next message anchor line; a closing tag with no opener (or a `parameter` opener outside a call) starts at the text start or the last message anchor. A trailing evidence cut marker and a leading `[observed …]` date header stay outside any block. Message anchor lines may end in CRLF. Scanning is linear: anchors are indexed once, and past a per-text work budget the rest of a message is summarized (fails closed). Names outside `[A-Za-z0-9_.:/-]{1,64}` are dropped. The fence is a marker line naming the slug (`[`, `]`, `;` and line breaks shown as `?`), then a code fence of at least three backticks, one longer than the longest run in the text; the row gets `quoted: "transcript"` (kept in lean rows). `rowPreview` is the CLI human line: `[quoted transcript]` and the start of the fenced text. Stored pages, chunks, ranking and scores are unchanged; delivered `match_spans` are remapped to the returned text, and `tokens`, `tokens_delivered` and `budget_used` count the fenced text (`fenceTranscriptRows` with a recount). Tests: `test/search/transcript-quote.test.ts`, `test/search-transcript-quote.test.ts` (ChatGPT export through the importer, with a JSON and an XML call; remote MCP `search`/`query`/`assemble_evidence` and CLI human/`--json`, both engines), `test/search-transcript-quote-budget.test.ts` (budget, spans and snippet cap through the ops), `test/search-transcript-quote-coverage.test.ts` (#8042 matrix: slack, imessage, email, meeting and conversation pages plus a conversation-extracted fact against a note and a remembered fact, plus backstop facts linked to a synced slack page by a derivation edge or only by their sync session, and one derived from a note, a failed lookup withholding facts, a retried retype put, over remote search, query, saved_facts, assemble_evidence, recall, get_page body/content/window, local get_page, the get→put round trip (a note's fence-like text, a mixed-case slug), thin-client paging of a 12,000-line slack page, fetch, think's prompt, delta, hot memory, and get_page known_as_of / get_versions bodies and diff, both engines), `test/search-transcript-quote-tiers.test.ts` (GST-687: every placement and read surface by tier, both engines) and `test/search-transcript-quote-legacy-claim.test.ts` (a legacy note is quoted, raw again after claim and backfill, both engines), `test/search-transcript-quote-followups.test.ts` (#8377: the chronicle, takes and page title/frontmatter reads, hook-injected facts, and the copied-back writes, red on master, both engines) and `test/trust-keep-maintenance-reimport-8352.test.ts` (#8352: maintenance re-imports keep an owner note's tier, both engines) and `test/search-transcript-quote-8384.test.ts` (#8384: whole-markdown round-trip edges, timeline source, ontology values, the `quoted_unverified_origin` notice from `get-page-projection.ts unverifiedOriginNotice`, both engines) and `test/search-transcript-quote-8384b.test.ts` (#8384 wave 3: CRLF whole-markdown, chronicle `kind`, search row and card titles, tags, a fenced value next to a naive datetime, both engines).
-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Fact reserves: `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default on since the held-out gate passed; `false` or a config read error turns it off): the same facts for every query whose caller passed `token_budget` (the no-budget evidence plan's implicit budget does not run it, #8411), up to 22% of the budget, 40 rows and the caller's `limit`, oldest first ahead of the pages at the top page's score (never above it), adding rows; copies of one claim (`collapseFactReads`, `facts/capture-dedup.ts`) take one row dated as first stated, followed by `(stated N times, last DATE)`; copies are ordered by when each was said (its observed date, else its write date, then id). A shown fact with a conversation slot (`dimension`/`value_hash`, GBRA-574 B2) and no stored `valid_until` (an ended history row keeps its stored one) gets a read-time end: `fact-relevance.readSlotRows` reads the slot's rows under the pool read policy and `facts/slots.ts` `deriveSlotEnds` ends a stint at the next distinct value's `valid_from` only when that value starts later and either comes from a page the stint came from or its fact matches `CHANGE_CUE` (G4); otherwise, and when the read fails, the end reads `unknown`. GBRA-574: on `hasHistoryCue` the pool also takes the named entity's ended facts (`collectFactCandidates` `history`, `ENDED_FACT_SQL`: superseded or past `valid_until`, the most recent first, never withdrawn or from a purged page); `questionDate` adds `; told after DATE` or `; learn date unknown` to each header; `withDecideContested` adds `(contested by #<id>)`, and a failed lookup sets `fact_row.contested_unavailable` (degraded `contested_unavailable`). Tests: `test/facts-block-history-gbra574.test.ts`. B5: a later fact that retracts or calls off a block fact follows it with its own date, inside the same share and row count (`fact-relevance.ts` `laterRetractions`, one read under the pool's read policy, active rows only, newest 50 cue facts per entity): it matches the fixed cue (`saved-facts-match.ts` `RETRACTION` plus rumour/rumor, called off, cancelled/canceled, fell through, not happening, never happened, no longer planned), has the fact's source and entity, a strictly later `valid_from`, no not/never/no/n't a word or two before the cue (a cue that starts with one, "not happening", counts), and either the fact's slot (`dimension`, `value_hash`) or, on content terms other than the entity's name and the cue words, all of its terms (at least one) in the fact or two shared with it; one already in the block moves there, one that fits no budget is left out, and a failed read leaves the block as it was. Tests: `test/facts-block-retractions-gbra574.test.ts`. Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.
+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Fact reserves: `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default on since the held-out gate passed; `false` or a config read error turns it off): the same facts for every query whose caller passed `token_budget` (the no-budget evidence plan's implicit budget does not run it, #8411), up to 22% of the budget, 40 rows and the caller's `limit`, oldest first ahead of the pages at the top page's score (never above it), adding rows; copies of one claim (`collapseFactReads`, `facts/capture-dedup.ts`) take one row dated as first stated, followed by `(stated N times, last DATE)`; copies are ordered by when each was said (its observed date, else its write date, then id). A shown fact with a conversation slot (`dimension`/`value_hash`, GBRA-574 B2) and no stored `valid_until` (an ended history row keeps its stored one) gets a read-time end: `slot-history.ts` `slotWindows` reads the slot's rows under every key of its entity (`fact-relevance.readSlotRows`, the pool read policy) and `facts/slots.ts` `deriveSlotEnds` ends a stint at the next distinct value's `valid_from` only when that value starts later and either comes from a page the stint came from or its fact matches `CHANGE_CUE` (G4); otherwise, and when the read fails, the end reads `unknown`. GBRA-574: on `hasHistoryCue` the pool also takes the named entity's ended facts (`collectFactCandidates` `history`, `ENDED_FACT_SQL`: superseded or past `valid_until`, the most recent first, never withdrawn or from a purged page); `questionDate` adds `; told after DATE` or `; learn date unknown` to each header; `withDecideContested` adds `(contested by #<id>)`, and a failed lookup sets `fact_row.contested_unavailable` (degraded `contested_unavailable`). Tests: `test/facts-block-history-gbra574.test.ts`. B5: a later fact that retracts or calls off a block fact follows it with its own date, inside the same share and row count (`fact-relevance.ts` `laterRetractions`, one read under the pool's read policy, active rows only, newest 50 cue facts per entity): it matches the fixed cue (`saved-facts-match.ts` `RETRACTION` plus rumour/rumor, called off, cancelled/canceled, fell through, not happening, never happened, no longer planned), has the fact's source and entity, a strictly later `valid_from`, no not/never/no/n't a word or two before the cue (a cue that starts with one, "not happening", counts), and either the fact's slot (`dimension`, `value_hash`) or, on content terms other than the entity's name and the cue words, all of its terms (at least one) in the fact or two shared with it; one already in the block moves there, one that fits no budget is left out, and a failed read leaves the block as it was. Tests: `test/facts-block-retractions-gbra574.test.ts`. GBRA-574 F: a history question about one slot dimension of one named entity puts that entity's slot rows first in the block's pool (`slot-history.ts` `readSlotHistory`); a failed read keeps the block and sets `fact_row.history_unavailable` (degraded `facts_history_unavailable`). Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.
+- `src/core/search/slot-history.ts` — GBRA-574 F, the facts block's slot-history arm (`applyFactReserve` on the dated policy). `slotHistoryDimension`: the one slot dimension (`role`, `employer`, `location`; a word list each) a question names, only with a history cue (`hasHistoryCue`, oldest/newest first, held, or the dimension in the plural) and no present-tense cue (now, currently, these days...); none or several: null. The entity: `namedEntity` under the caller's page read scope, else `matchUnbackedKey` (D1): every 2 to 5 word run of the question's last 64 words, slugified, looked up by `fact-relevance.ts` `poolUnbackedKeys` (keys with an active fact in the pool under its read policy and no live page at that slug, at most 8); a key inside a longer matched key is the same mention; exactly one (source, key) pair, else none. `entityKeys`: a bare key the one readable live `<dir>/<key>` page claims reads as that page, else `mentions/siblings.ts` `factEntitySlugs`. `readSlotHistory` reads the entity's slot rows in that dimension across its keys (`readSlotRows`: active conversation slot rows, never withdrawn, superseded or expired) and orders each value's first row newest first, then restatements, so a tight budget keeps the latest values; the block puts them ahead of the admitted facts, inside its own share and row count, and shows them oldest first. `slotWindows` derives every shown slot fact's window across its entity's keys, grouped as one entity. No model call, no writes; read errors throw to the block. Tests: `test/facts-slot-history-gbra574.test.ts` (Postgres through `test/e2e/facts-slot-history-gbra574-postgres.test.ts`).
- `src/core/search/remote-page-cap.ts` — GBRA-156: the default distinct-page cap of a remote `search`/`query` that names no `limit` (and no `offset`). `remotePageCap(ctx, p)` reads `search.remote_page_cap` (default `DEFAULT_REMOTE_PAGE_CAP`, `0` = off; null for trusted local callers and `viaSubagent` host tool calls); `capVectorOnlyPages(rows, cap)` keeps every page with lexical evidence (`keyword_hit`, strict or relaxed, `alias_hit`, `qualified_alias_hit`, `exact_lookup`, `relational_pinned`) and admits vector-only pages, in rank order, only while the result holds fewer than `cap` distinct `(source_id, slug)` pages; it reports `{ cap, kept_pages, dropped_pages }` as `_meta.retrieval.page_cap` when it dropped any. `pageCapLine(retrieval, how)` renders that as the model-visible line dispatch's `retrievalNoticeBlocks` appends after the keyword count line (hosts that show only `content[]` never see `_meta`), and the CLI's `formatResult` writes on stderr with `--limit`. Applied to the hybrid output before alias fan-out (search) and to the first pass and an adopted CRAG re-run (query); keyword-only paths carry no vector-only rows and the image branch is uncapped (`test/search-remote-page-cap.test.ts`). Every vector path (the hybrid vector arm, the embed-failure fallback, the `query` image branch) reads the keyword path's source scope (`test/search-vector-scope-parity.test.ts`).
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 6b8f71100c..fdd5fef978 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -18,7 +18,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `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. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). 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 triggers (per row, or once per statement for the bulk fence insert, v264); they prevent 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 other than the brain owner, `worldOnlyFacts`, GST-2951) 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/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. GBRA-574 A1: a fact on an unbacked name key (`unbackedEntitySql`: a bare slug with no live page at it in the source) counts as subject '*': forgetting or purging it writes '*' (`factWithdrawalSubjectSql`, `planFactPurge`), and the guards (`gbrain_preserve_fact_withdrawal`, `gbrain_guard_inserted_facts`, `gbrain_refuse_purged_fact`, migration v321), the forget-time expiry, the purge plan and the conversation purge pre-filter match such a row under a withdrawal or tombstone of any subject. 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. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). 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 triggers (per row, or once per statement for the bulk fence insert, v264); they prevent 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 other than the brain owner, `worldOnlyFacts`, GST-2951) 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/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 64bc074d89..54a2f709c9 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -341,7 +341,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/trust/fence-guard.ts` (2): the guarded fence re-projection detaches or moves higher-tier fact rows inside the page's coordinated publication.
- `src/core/trust/held-removals.ts` (1): an owner accept of a held take or timeline removal re-projects the row as the page says in a coordinated (managed) or attributed (unmanaged) transaction under the page key.
- `src/core/trust/owner-actions.ts` (1): an owner release inserts the held fact database-only at user_confirmed in an attributed transaction (unmanaged) or, on a managed brain, in a coordinated one only for a hold with no entity slug or whose page is missing; every other managed fact release is a journaled `trust_release` publication (`src/core/trust/release-publish.ts`) that writes the fence row to the file first; an index-existing release binds the cell's previewed fields and refuses `preview_changed` when the cell moved, and the database-only release re-checks the approval on the locked hold.
-- `src/core/trust/supersede-handlers.ts` (3): owner accept/undo of a trust proposal re-tiers the new fact (or take) inside the checked supersede's (or takes publication's) transaction.
+- `src/core/trust/supersede-handlers.ts` (4): owner accept/undo of a trust proposal re-tiers the new fact (or take) inside the checked supersede's (or takes publication's) transaction; the accept of a held share (GST-2897 B) widens the held fact's visibility in its own attributed transaction.
<!-- write-attribution-covered:end -->
Unattributed (on unmanaged brains these would write with `NULL` attribution).
diff --git a/docs/contracts/public-surface.json b/docs/contracts/public-surface.json
index fb8d8c0a96..504ba85479 100644
--- a/docs/contracts/public-surface.json
+++ b/docs/contracts/public-surface.json
@@ -2043,6 +2043,7 @@
"facts.extraction_prompt_appendix",
"facts.page_write_notability_filter",
"facts.supersession_thresholds",
+ "facts.unbacked_entity_keys",
"feedback.alpha",
"feedback.enabled",
"feedback.event_retention_days",
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index b685bd6f3a..0c240d96a4 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -202,7 +202,18 @@ the facts block and the temporal fact reserve work out its end
at read time: the start of the next different value for the same person, when
that value came from the same conversation or its fact says the value changed
(moved, joined, left and similar words). Otherwise both values stay open and
-the end reads `unknown`. Nothing is written. The setting
+the end reads `unknown`. Nothing is written. A question that asks for history
+(a history word, "oldest first", "held", or the slot named in the plural, such
+as job titles, employers or cities) about one slot of one named person or
+company, and not for its current value ("now", "currently", "these days"),
+also gets every value that entity has had in that slot that the caller may
+read, oldest first, each with its own window, inside the block's share and
+row count. The entity is the page the question names or, when no page
+matches, the one name tag (a name of two or more words saved with no page)
+whose words the question holds in order; two candidates match none. A page
+written later at `people/<tag>` takes over the tag's facts on this read. If
+that read fails the block keeps its other rows and the response reports the
+degraded stage `facts_history_unavailable`. The setting
applies to `search`, `query`, `recall`, `think` and `assemble_evidence`.
### Tail trim
diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.md
index 8e20047390..0f1bcc3e2f 100644
--- a/docs/guides/access-designations.md
+++ b/docs/guides/access-designations.md
@@ -187,8 +187,10 @@ for rules in the database (a repo-less brain) and in `access.yml`.
Each fact row has its own visibility. `remember` defaults to `world`, except into a private page or under an
explicit private `facts.default_visibility`. A remote credential bound to a member saves `private` on its own member
-page (`memory/members/<member>`) unless the call passes `share: true`, and its `visibility: "world"` is refused; it
-withdraws only facts on that page, and the brain host withdraws the rest (`gbrain forget <id>`). The owner's own
+page (`memory/members/<member>`) unless the call passes `share: true`, and its `visibility: "world"` is refused; a
+`share: true` fact about another enabled member is held `private` until the brain owner confirms its proposal
+(`gbrain trust review`, `gbrain trust confirm tp<N>`). It withdraws facts on that page and shared facts about
+itself, and the brain host withdraws the rest (`gbrain forget <id>`). The owner's own
credential (or a stdio server started with `--stdio-member <owner>`), speaking for itself (no audience, not a
subagent job, no slug fence), saves like a credential bound to no member: shared on the subject's page, or `private` on its member page when it passes `visibility: "private"` or the
page or `facts.default_visibility` keeps facts private (the reply names the `page` and `visibility`; an explicit
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
index a581a62542..2b33477aae 100644
--- a/docs/guides/entity-recall.md
+++ b/docs/guides/entity-recall.md
@@ -128,12 +128,22 @@ agent never reads a short list as "nothing else exists".
- Put the name in the title, or after a prefix: `CRM record: Acme Example`.
- Declare other names in the body (see [How gbrain learns an alias](#how-gbrain-learns-an-alias)).
- Or list names in frontmatter `aliases: [Acme, Acme Inc]`.
+- Put a person's X handle in frontmatter `x_handle:` (or `twitter:`,
+ `twitter_handle:` or `x:`; an `x.com/<handle>` URL works too): text that
+ writes `@handle` links to that page. `unknown`, `0` and other placeholders
+ are ignored.
+
+A frontmatter alias or handle outranks a page of the same kind that is only
+titled with that name: when `people/alice-example` declares `x_handle:
+alicetweets`, a thin `people/alicetweets` page stops collecting the mentions
+and they link to `people/alice-example`. The thin page itself is not changed.
Names are never linked when they are shorter than 4 characters, a generic word
("Will", "Team"), the first word of a longer entity name ("Quormiro" alone when
-"Quormiro Capital" and "Quormiro Labs" both exist), claimed by two unrelated
-pages, or inside a private facts or takes fence. Contracts and other non-entity
-pages that repeat a code do not claim it.
+"Quormiro Capital" and "Quormiro Labs" both exist; a one-word person page
+titled "Alice" when "Alice Example" exists), claimed by two unrelated pages, or
+inside a private facts or takes fence. Contracts and other non-entity pages
+that repeat a code do not claim it.
## How gbrain learns an alias
diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.md
index e8b401c294..b0e15c81f0 100644
--- a/docs/guides/facts-relink.md
+++ b/docs/guides/facts-relink.md
@@ -146,6 +146,57 @@ re-extraction for it: facts still unlinked there are listed for linking by
hand (forget each one and remember it again with `--entity`). Editing the
page's content offers the re-extraction again.
+### Name tags for people and companies with no page
+
+A brain built only from conversations usually has no person or company pages.
+So that a person's facts can still be grouped (their job titles, employers and
+cities in date order), conversation extraction gives a fact a **name tag** when
+the extractor named someone in full and no page matches: the name in slug form,
+without a folder. "Alice Example", "alice-example" and "people/alice-example"
+all give the tag `alice-example`. A single word ("Alice", "travel") gives no
+tag, and the fact is stored without an entity as before. No page is created,
+lists of pages never show a tag, and a tag is per source. Only new extractions
+get tags; existing facts are not changed. A fact on a tag gets a slot (role,
+employer or city) from the same small tagging call that person pages get.
+
+When you later write a page for that person (`people/alice-example`), reads
+of the page include the tag's facts, because the tag is the page's file name.
+To move them onto the page for good, preview and then run:
+
+```bash
+gbrain facts relink --conversation --unbacked --dry-run # what would move; writes nothing
+gbrain facts relink --conversation --unbacked # move them
+```
+
+A tag moves to the one page its name resolves to: the exact file name in a
+people, companies, hosts, projects or concepts folder, a unique alias, or the
+same name ignoring a company suffix ("Acme Example" and `companies/acme-example-inc`
+titled "Acme Example Inc"). A page that was merged into another
+(`superseded_by`) hands its facts to that page. A world fact never moves onto
+a private page. A tag that still matches no page, or matches two, keeps its
+facts.
+
+Forgetting or purging a fact on a tag applies to that claim across the whole
+source, and a claim forgotten or purged for any person never comes back on a
+tag, so writing a page or moving a tag never brings a forgotten fact back.
+
+Two different people with the same full name in one source share one name tag
+until a page or alias tells them apart. Today their facts share nothing because
+they have no entity at all, so this only matters once both are talked about in
+the same brain, which is rare for full two-word names. When it happens, a
+history question about that name lists both people's values in one timeline,
+and a newer value of one can end the other's stint. To separate them, write a
+page for each (for example `people/alice-example` and `people/alice-example-2`
+with an alias that tells them apart), then run `gbrain facts relink
+--conversation --unbacked` to move the facts whose page resolves; facts that
+still cannot be told apart need `extract-conversation-facts --force` on the
+pages that mention them (paid; preview with `--dry-run`). A page written later
+at the same file name adopts the tag's facts on reads.
+
+Turn name tags off with `gbrain config set facts.unbacked_entity_keys false`.
+New extractions then store such facts without an entity, as before; facts
+already on a tag keep it.
+
Neither relink attaches what the assistant or a named third party said (a
fact saved with `attributed_to` assistant or other) to an entity page. Such a
fact is counted as `not_user_attributed` and left where it was saved: recall
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 528ec58b1a..a33999ff47 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -260,7 +260,9 @@ read back only by that member, written remotely by no one else); an attested cal
`share: true` or `visibility: "world"` is refused (`attested_share_refused`), while a credential
bound to a member may pass `share: true` to save on the subject's page for everyone who reads
the source (refused with `share_target_restricted` on a page whose facts are kept private;
-only the brain host withdraws a shared fact); the reply names the `page` and `visibility`. `delta` cursors, write receipts
+a share about another member is held private until the brain owner confirms it with
+`gbrain trust confirm tp<N>`; only the brain host, or the member a shared fact is about,
+withdraws a shared fact); the reply names the `page` and `visibility`. `delta` cursors, write receipts
(`get_write_request`, `list_write_requests`, `cancel_write_request`) and agent
jobs (`submit_agent`, `get_agent_job`) belong to the person they were made for.
QM's memory pair, `memory_recall` and `memory_write`, reads and saves that
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index 9dc38fd399..44c3c6d7d7 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -188,7 +188,7 @@ The codes in `_meta.degraded.reasons` ([AGENT_OPERATOR_v1.md, Degraded stamp](AG
| Code | Ops | Meaning |
|---|---|---|
-| a retrieval stage: `embed_unavailable`, `embed_timeout`, `expansion_failed`, `expansion_partial`, `rescore_skipped`, `vector_arm_failed`, `keyword_arm_failed`, `title_arm_failed`, `budget_dropped_all`, `budget_truncated`, `keyword_zero`, `cache_prestamp`, `rerank_passthrough`, `rerank_failed`, `keyword_relaxed_carried`, `safe_index_pending`, `vector_candidates_incomplete`, `keyword_candidates_incomplete`, `projection_pending`, `projection_by_design`, `projection_status_unknown`, `keyword_count_unavailable`, `saved_facts_withheld`, `fact_observed_date_unavailable`, `contested_unavailable` (query) | search, query, recall, find_experts; think and synthesize (their page search) | the stage in `_meta.retrieval.degraded` (every stage except the ranking-only `reranker_skipped`; `projection_pending` only when a pending page could match). `embed_unavailable` also covers a keyless brain and recall's keyword-only markers, so a keyless brain stamps every search |
+| a retrieval stage: `embed_unavailable`, `embed_timeout`, `expansion_failed`, `expansion_partial`, `rescore_skipped`, `vector_arm_failed`, `keyword_arm_failed`, `title_arm_failed`, `budget_dropped_all`, `budget_truncated`, `keyword_zero`, `cache_prestamp`, `rerank_passthrough`, `rerank_failed`, `keyword_relaxed_carried`, `safe_index_pending`, `vector_candidates_incomplete`, `keyword_candidates_incomplete`, `projection_pending`, `projection_by_design`, `projection_status_unknown`, `keyword_count_unavailable`, `saved_facts_withheld`, `fact_observed_date_unavailable`, `contested_unavailable`, `facts_history_unavailable` (query) | search, query, recall, find_experts; think and synthesize (their page search) | the stage in `_meta.retrieval.degraded` (every stage except the ranking-only `reranker_skipped`; `projection_pending` only when a pending page could match). `embed_unavailable` also covers a keyless brain and recall's keyword-only markers, so a keyless brain stamps every search |
| `no_query_terms`, `facts_embedding_column_missing`, `facts_read_failed`, `saved_facts_withheld`, `fact_observed_date_unavailable` | recall | `facts_degraded.reason` of a question-ranked recall |
| `facts_unembedded` | recall | some facts in scope could not be compared with the question |
| `deadline`, `server_budget`, `budget_trimmed` | context_pack | `degraded_reason`: the pack is partial |
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 1133a85a95..658440676a 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -304,7 +304,10 @@ Save ONE fact with mandatory attribution.
operator set `facts.default_visibility` to private; a save never lands wider
than the page it is written into. In gbrain, a remote credential bound to
one member saves `private` on its own member page unless it passes
- `share: true`, and its `visibility: "world"` is refused; the brain owner's
+ `share: true`, and its `visibility: "world"` is refused; a `share: true`
+ fact about another enabled member (`people/<member>`) is saved `private` with
+ a pending proposal the brain owner confirms (`gbrain trust confirm tp<N>`),
+ and the reply carries a `held` field naming it; the brain owner's
own credential saves as above (shared by default, `private` on its member
page when it asks or the page or default keeps facts private). The response
names the `page` and `visibility` the fact got. Facts saved `private` before
@@ -788,8 +791,8 @@ says to keep them, or to forget them first to withdraw the claim everywhere.
A forget never withdraws an active fact the caller cannot read; when one
would be reached, the refusal keeps the `claim_linked:` prefix and names no fact.
In gbrain, a credential bound to one member withdraws only facts on its own
-member page (another fact it reads is refused naming the brain host); the
-brain owner's own credential also withdraws a shared fact it reads, and any
+member page, and a shared fact about itself (another fact it reads is refused
+naming the brain host); the brain owner's own credential also withdraws a shared fact it reads, and any
other fact it reads on a page that credential can write, such as a page whose
`readable_by` names the owner.
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 63d03719f8..c8f9b4d5aa 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -175,7 +175,7 @@ gbrain auth rescope --client <client_id> --attest-actor qm # default ops: g
gbrain access member link alice-example --qm U0ALICE # --dry-run previews; unlink and links manage them
```
-Each request then carries `x-qm-actor: U0ALICE`, and each attested operation runs as `alice-example` (page reads, and the person's own memory writes), never reading `visibility: private` pages, whatever the client's own grant says. A fact the person saves (`remember`) goes on their own page `memory/members/<member>`, which names them as its only reader, so another member, the client's bare calls and an unbound credential never recall it, and no one but that member writes under `memory/members/<member>` remotely. A credential bound to a member may save with `share: true` to put the fact on its subject's page for everyone who reads the source, and its `visibility: "world"` is refused (`member_share_required`); the brain owner's own credential saves shared by default instead, unless it passes `visibility: "private"` or the page or `facts.default_visibility` keeps facts private; an attested call (`x-qm-actor`) never shares (`attested_share_refused`). Every `remember` reply names the `page` and `visibility` the fact got; `delta` cursors, write receipts and agent jobs (`submit_agent`, `get_agent_job`) are kept to the person the same way, and `forget` or `forget_fact` withdraws only a fact on the person's own page. QM itself calls `memory_recall` and `memory_write` ([QM guide](../guides/qm.md)). Not attestable yet, because what they read or write is not yet kept to the person: `list_write_conflicts`, `capture`, `extract_facts` and `takes_add|update|resolve|supersede`; every page write (`add_timeline_entry`, `add_link`, `put_page`, `edit_page`, tags, deletes, uploads and the rest) waits for owner-approved proposals. Under the header, `tools/list` lists only the attested operations and `resources/read` is refused. An `acting_user` argument must equal the header and is stripped. A client without the right, an operation outside `--attest-ops`, or an id that is not 1-256 visible ASCII characters refuses `actor_not_attested`; an id with no link to an enabled member refuses `actor_unlinked`. Ids compare exactly, unlink and disable take effect on the next call, and queued writes and jobs re-check the link before they commit or call a tool. Links and the right are database state, so this works the same on a repo-less brain.
+Each request then carries `x-qm-actor: U0ALICE`, and each attested operation runs as `alice-example` (page reads, and the person's own memory writes), never reading `visibility: private` pages, whatever the client's own grant says. A fact the person saves (`remember`) goes on their own page `memory/members/<member>`, which names them as its only reader, so another member, the client's bare calls and an unbound credential never recall it, and no one but that member writes under `memory/members/<member>` remotely. A credential bound to a member may save with `share: true` to put the fact on its subject's page for everyone who reads the source (a fact about another member is held private until the brain owner confirms it with `gbrain trust confirm tp<N>`), and its `visibility: "world"` is refused (`member_share_required`); the brain owner's own credential saves shared by default instead, unless it passes `visibility: "private"` or the page or `facts.default_visibility` keeps facts private; an attested call (`x-qm-actor`) never shares (`attested_share_refused`). Every `remember` reply names the `page` and `visibility` the fact got; `delta` cursors, write receipts and agent jobs (`submit_agent`, `get_agent_job`) are kept to the person the same way, and `forget` or `forget_fact` withdraws only a fact on the person's own page or a shared fact about the person. QM itself calls `memory_recall` and `memory_write` ([QM guide](../guides/qm.md)). Not attestable yet, because what they read or write is not yet kept to the person: `list_write_conflicts`, `capture`, `extract_facts` and `takes_add|update|resolve|supersede`; every page write (`add_timeline_entry`, `add_link`, `put_page`, `edit_page`, tags, deletes, uploads and the rest) waits for owner-approved proposals. Under the header, `tools/list` lists only the attested operations and `resources/read` is refused. An `acting_user` argument must equal the header and is stripped. A client without the right, an operation outside `--attest-ops`, or an id that is not 1-256 visible ASCII characters refuses `actor_not_attested`; an id with no link to an enabled member refuses `actor_unlinked`. Ids compare exactly, unlink and disable take effect on the next call, and queued writes and jobs re-check the link before they commit or call a tool. Links and the right are database state, so this works the same on a repo-less brain.
For most company-brain installs (10+ teammates each with their own AI client), Model A is the right starting point. If you're running the fat-agent-serves-everyone pattern from the personal-brain tutorial, Model B is genuinely simpler. You can also mix: separate sources for the obviously-different ones (customer notes vs internal-only) AND a `partners/<slug>/` convention inside the shared source for per-person workspace.
diff --git a/llms-full.txt b/llms-full.txt
index 24be72a6e8..395edc02d6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5128,12 +5128,14 @@ updates that row in `facts`, and the write role then needs a permissive `UPDATE`
`facts` covering the row, beside its `SELECT` policy, or the guard refuses the insert with the
same `writer_coordinator_required` error.
-**Check that the upgrade replaced every guard.** Migration v318 can only replace a guard function
-the role running it owns. A guard owned by another role is left as it was, so it still lets a
-scoped writer without ledger policies through, and v318 only names it in one stderr line
-(`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`). After upgrading,
-run this as any role that can read the catalog. Every one of the seven rows must show
-`fails_closed = t`:
+**Check that the upgrade replaced every guard.** Migrations v318 and v321 can only replace a guard
+function the role running them owns. A guard owned by another role is left as it was, and each
+migration only names it in one stderr line. Left by v318, it still lets a scoped writer without
+ledger policies through (`guards: N purge or withdrawal guard(s) still read their ledgers as empty ...`).
+Left by v321, a facts guard still lacks the name-tag rule, so a claim forgotten or
+purged under another subject can come back on a name tag (`guards: N purge or withdrawal guard(s)
+keep their body from before name keys ...`). After upgrading, run this as any role that can read
+the catalog. Every one of the seven rows must show `fails_closed = t`:
```sql
SELECT p.proname, pg_get_userbyid(p.proowner) AS owner,
@@ -5148,11 +5150,14 @@ ORDER BY 1;
For a row with `fails_closed = f`, connect as the role in its `owner` column and run
`ALTER FUNCTION public.<proname>() OWNER TO <the role gbrain migrates as>;`. Then run
`gbrain apply-migrations --yes`, or start gbrain: every migration run re-creates a guard that
-is missing its check, provided the migrating role owns it. You can also run gbrain once as the
-owning role instead. Run the query again to confirm. On Postgres, `gbrain doctor`
-(`guard_ledger_checks`) runs the same check and names each guard left without its ledger check
-with its owner, and the fix: `gbrain apply-migrations --yes` when the doctor's role may re-create
-it, else the `ALTER FUNCTION ... OWNER TO` SQL to run as the owning role first.
+is missing its check or its current body, provided the migrating role owns it. You can also run
+gbrain once as the owning role instead. Run the query again to confirm. The query sees only the
+ledger check, so a facts guard v321 left still shows `fails_closed = t`. On Postgres, `gbrain doctor`
+(`guard_ledger_checks`) runs the same check, also checks the current body of the three facts guards
+(`unbacked_page` in `gbrain_refuse_purged_fact`, `memory/scope` in `gbrain_preserve_fact_withdrawal`
+and `gbrain_guard_inserted_facts`), and names each guard left behind with its owner, and the fix:
+`gbrain apply-migrations --yes` when the doctor's role may re-create it, else the
+`ALTER FUNCTION ... OWNER TO` SQL to run as the owning role first.
The segmented storage recipe above already covers the two derivation purge tables for a
role it applies to. A policy that filters out ledger rows of a source the role writes hides
@@ -7990,7 +7995,10 @@ Save ONE fact with mandatory attribution.
operator set `facts.default_visibility` to private; a save never lands wider
than the page it is written into. In gbrain, a remote credential bound to
one member saves `private` on its own member page unless it passes
- `share: true`, and its `visibility: "world"` is refused; the brain owner's
+ `share: true`, and its `visibility: "world"` is refused; a `share: true`
+ fact about another enabled member (`people/<member>`) is saved `private` with
+ a pending proposal the brain owner confirms (`gbrain trust confirm tp<N>`),
+ and the reply carries a `held` field naming it; the brain owner's
own credential saves as above (shared by default, `private` on its member
page when it asks or the page or default keeps facts private). The response
names the `page` and `visibility` the fact got. Facts saved `private` before
@@ -8474,8 +8482,8 @@ says to keep them, or to forget them first to withdraw the claim everywhere.
A forget never withdraws an active fact the caller cannot read; when one
would be reached, the refusal keeps the `claim_linked:` prefix and names no fact.
In gbrain, a credential bound to one member withdraws only facts on its own
-member page (another fact it reads is refused naming the brain host); the
-brain owner's own credential also withdraws a shared fact it reads, and any
+member page, and a shared fact about itself (another fact it reads is refused
+naming the brain host); the brain owner's own credential also withdraws a shared fact it reads, and any
other fact it reads on a page that credential can write, such as a page whose
`readable_by` names the owner.
diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv
index 7354e7dd9f..3d06413ddc 100644
--- a/scripts/engine-raw-sql-baseline.tsv
+++ b/scripts/engine-raw-sql-baseline.tsv
@@ -275,7 +275,7 @@ src/core/access/caller.ts execute_raw 9
src/core/access/federation-exposure.ts execute_raw 1
src/core/access/implicit-placement.ts execute_raw 1 came from master #9625 (shared company brains: owner setup, member keys), which landed after this ratchet was cut
src/core/access/labelled-only.ts execute_raw 4
-src/core/access/member-facts.ts execute_raw 1
+src/core/access/member-facts.ts execute_raw 2 GST-2897 B (#9670, opened before this ratchet): one access_members lookup to see whether the member a share is about is enabled; no typed engine method exists yet
src/core/access/member-sources.ts execute_raw 8
src/core/access/members.ts execute_raw 25
src/core/access/members.ts sql_template 1
@@ -445,6 +445,7 @@ src/core/embedding-restamp.ts execute_raw 2
src/core/embedding-state.ts execute_raw 1
src/core/enrichment-service.ts execute_raw 2
src/core/entities/near-name.ts execute_raw 1
+src/core/entities/resolve-on-save.ts execute_raw 1 GBRA-574 F #9674 (opened before this ratchet): the live-page check before keeping an unbacked name tag
src/core/entities/resolve.ts execute_raw 13
src/core/entity-identity.ts execute_raw 6
src/core/eval-contradictions/cost-prompt.ts execute_raw 1
@@ -471,7 +472,7 @@ src/core/facts/conversation-incremental.ts execute_raw 1
src/core/facts/conversation-memo.ts execute_raw 4
src/core/facts/conversation-publication.ts execute_raw 24
src/core/facts/conversation-relink-carry.ts execute_raw 1
-src/core/facts/conversation-relink.ts execute_raw 6
+src/core/facts/conversation-relink.ts execute_raw 7 GBRA-574 F #9674 (opened before this ratchet): +1 the relink --unbacked read of name-tag rows
src/core/facts/dead-absorb-retry.ts execute_raw 2
src/core/facts/derivation-inputs.ts execute_raw 6
src/core/facts/drain.ts execute_raw 2
@@ -491,7 +492,7 @@ src/core/facts/proposal-supersede.ts execute_raw 4
src/core/facts/purge-overlay.ts execute_raw 3
src/core/facts/purge-reasons.ts execute_raw 8
src/core/facts/purge-verify.ts execute_raw 22
-src/core/facts/purge.ts execute_raw 39
+src/core/facts/purge.ts execute_raw 40 GBRA-574 F #9674 (opened before this ratchet): +1 the purge plan reads whether a fact sits on an unbacked name tag
src/core/facts/question-recall.ts execute_raw 1
src/core/facts/reconcile-watermark.ts execute_raw 6
src/core/facts/relink-publish.ts execute_raw 8
@@ -780,7 +781,7 @@ src/core/persistence/facts-prepare.ts execute_raw 5
src/core/persistence/file-claims.ts execute_raw 2
src/core/persistence/file-repair.ts execute_raw 4
src/core/persistence/filesystem-guard.ts execute_raw 3
-src/core/persistence/forget-prepare.ts execute_raw 6
+src/core/persistence/forget-prepare.ts execute_raw 7 GBRA-574 F #9674 (opened before this ratchet): +1 forget reads whether the claim sits on an unbacked name tag
src/core/persistence/git-conversion.ts execute_raw 16
src/core/persistence/git-declared.ts execute_raw 7
src/core/persistence/git-door.ts execute_raw 1
@@ -824,7 +825,7 @@ src/core/persistence/managed-mode.ts execute_raw 3
src/core/persistence/managed-sources.ts execute_raw 1
src/core/persistence/managed-sync-orphans.ts execute_raw 14
src/core/persistence/manual-links.ts execute_raw 8
-src/core/persistence/memory-mutations.ts execute_raw 5
+src/core/persistence/memory-mutations.ts execute_raw 6 GST-2897 B (#9670, opened before this ratchet): one read of a fact's entity_slug so the member it is about can withdraw it; no typed engine method exists yet
src/core/persistence/memory-prepare.ts execute_raw 4
src/core/persistence/memory-proposals.ts execute_raw 16
src/core/persistence/mirror-read-only.ts execute_raw 4
@@ -1082,7 +1083,7 @@ src/core/search/entity-facts.ts execute_raw 1
src/core/search/evidence-date.ts execute_raw 3
src/core/search/evidence-delivery.ts execute_raw 2
src/core/search/exact-scan.ts execute_raw 2
-src/core/search/fact-relevance.ts execute_raw 13 came from master #9627 (held private facts, database-only untrack), which landed after this ratchet was cut
+src/core/search/fact-relevance.ts execute_raw 14 came from master #9627 (held private facts, database-only untrack), which landed after this ratchet was cut; GBRA-574 F #9674 (opened before this ratchet): +1 poolUnbackedKeys, the name-tag lookup for the slot-history arm
src/core/search/facts-arm.ts execute_raw 3
src/core/search/feedback-boost.ts execute_raw 1
src/core/search/frontmatter-where.ts execute_raw 1
@@ -1101,6 +1102,7 @@ src/core/search/relational-recall.ts execute_raw 3
src/core/search/retrieval-coverage.ts execute_raw 2
src/core/search/safe-chunks.ts execute_raw 2
src/core/search/saved-facts-match.ts execute_raw 2
+src/core/search/slot-history.ts execute_raw 1 GBRA-574 F #9674 (opened before this ratchet): the readable-page lookup that maps a bare name tag to the page later written at <dir>/<tag>
src/core/search/telemetry.ts execute_raw 2
src/core/search/transcript-quote.ts execute_raw 3
src/core/search/two-pass.ts execute_raw 5
@@ -1202,7 +1204,7 @@ src/core/trust/provenance-drift.ts execute_raw 3
src/core/trust/refs.ts execute_raw 1
src/core/trust/release-publish.ts execute_raw 2
src/core/trust/review.ts execute_raw 18
-src/core/trust/supersede-handlers.ts execute_raw 12
+src/core/trust/supersede-handlers.ts execute_raw 14 GST-2897 B (#9670, opened before this ratchet): the held-share accept reads the fact's visibility and widens it; no typed engine method exists yet
src/core/trust/taint.ts execute_raw 5
src/core/trust/timeline-projection.ts execute_raw 2
src/core/uncommitted-deletions.ts execute_raw 1
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index ad33a64e1d..cba64e3fb7 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -352,8 +352,8 @@ export interface ExtractConversationFactsResult {
facts_inserted: number;
/** #7438: extracted claims left out because they match a purge tombstone (the rest of the page still publishes). */
facts_skipped_purged?: number;
- /** Entity values that reached the shipped deterministic fallback slug path. */
- fallback_slugify_count: number;
+ /** Entity values that reached the shipped deterministic fallback slug path; GBRA-574 `unbacked_keys` of them kept a name key with no page. */
+ fallback_slugify_count: number; unbacked_keys?: number;
/** Entity values kept raw after a best-effort resolution failure. */
resolution_errors: number;
/** GBRA-574: windows whose slot-tagging call failed; their facts were kept without slots (--force tags them again). */ slot_tagging_failed?: number;
@@ -997,7 +997,7 @@ async function processPage(
pageRows.push(...window.rows);
rowNum += window.extracted;
mergeSaveTimeResolutionCounts(pageResolution, window.resolution);
- state.result.fallback_slugify_count += window.resolution.fallback_slugify_count;
+ state.result.fallback_slugify_count += window.resolution.fallback_slugify_count; if (window.resolution.unbacked_key_count) state.result.unbacked_keys = (state.result.unbacked_keys ?? 0) + window.resolution.unbacked_key_count;
state.result.resolution_errors += window.resolution.resolution_errors;
newestEnd = seg.endIso;
@@ -1804,7 +1804,7 @@ export async function runExtractConversationFacts(
aggregate.segments_processed += perSource.segments_processed;
aggregate.facts_extracted += perSource.facts_extracted;
aggregate.facts_inserted += perSource.facts_inserted;
- aggregate.fallback_slugify_count += perSource.fallback_slugify_count;
+ aggregate.fallback_slugify_count += perSource.fallback_slugify_count; if (perSource.unbacked_keys) aggregate.unbacked_keys = (aggregate.unbacked_keys ?? 0) + perSource.unbacked_keys;
aggregate.resolution_errors += perSource.resolution_errors;
if (perSource.slot_tagging_failed) aggregate.slot_tagging_failed = (aggregate.slot_tagging_failed ?? 0) + perSource.slot_tagging_failed;
if (perSource.pages_pending) aggregate.pages_pending = (aggregate.pages_pending ?? 0) + perSource.pages_pending;
@@ -1892,7 +1892,7 @@ export async function runExtractConversationFacts(
console.log(` Cleaned ${aggregate.orphan_facts_cleaned} orphan fact(s) from prior partial runs (D11 replay safety).`);
}
if (aggregate.fallback_slugify_count > 0) {
- console.log(` Preserved ${aggregate.fallback_slugify_count} fact(s) without an entity target after unresolved fallback_slugify.`);
+ console.log(` Preserved ${aggregate.fallback_slugify_count - (aggregate.unbacked_keys ?? 0)} fact(s) without an entity target after unresolved fallback_slugify${aggregate.unbacked_keys ? `; kept ${aggregate.unbacked_keys} under a name key with no page (facts.unbacked_entity_keys)` : ''}.`);
}
if (aggregate.resolution_errors > 0) {
console.log(` Preserved ${aggregate.resolution_errors} fact(s) without an entity target after best-effort resolution errors.`);
diff --git a/src/commands/extract-mentions-explain.ts b/src/commands/extract-mentions-explain.ts
index abea297ea5..a30bd21ffe 100644
--- a/src/commands/extract-mentions-explain.ts
+++ b/src/commands/extract-mentions-explain.ts
@@ -76,7 +76,7 @@ export async function explainMention(engine: BrainEngine, query: string, opts: {
const dropped: DroppedName[] = [];
const gazetteer = await buildGazetteer(engine, { policy, dropped });
const all = [...gazetteer.values()].flat().filter(e => e.source_id === sourceId);
- const view = (e: GazetteerEntry) => ({ name: e.caseTokens ? e.caseTokens.join(' ') : e.tokens.join(' '), slug: e.slug, origin: e.origin ?? 'title', case_sensitive: !!e.caseTokens });
+ const view = (e: GazetteerEntry) => ({ name: `${e.atOnly ? '@' : ''}${e.caseTokens ? e.caseTokens.join(' ') : e.tokens.join(' ')}`, slug: e.slug, origin: e.origin ?? 'title', case_sensitive: !!e.caseTokens });
const [asPage] = await engine.executeRaw<{ slug: string; type: string | null; title: string | null }>(
'SELECT slug, type, title FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, query]);
const key = tokenizeTitle(query).join(' ');
diff --git a/src/commands/facts.ts b/src/commands/facts.ts
index dae98f1781..a157e3eeb4 100644
--- a/src/commands/facts.ts
+++ b/src/commands/facts.ts
@@ -32,13 +32,16 @@ gbrain facts relink [flags]
--examples <n> Example facts per outcome (default 3)
--json Machine-readable report (schema_version ${1})
-gbrain facts relink --conversation [--source <id>] [--slugs <a,b>] [--dry-run] [--json]
+gbrain facts relink --conversation [--unbacked] [--source <id>] [--slugs <a,b>] [--dry-run] [--json]
Link the conversation extractor's facts saved without an entity (plain
relink never examines them), free only: a fact naming exactly one entity
page in full is linked, one write per page. Without --slugs, the
${CONVERSATION_RELINK_PAGES} pages with the most untried unlinked facts. Facts it cannot
resolve are recorded, and the report prints the paid re-extraction for
- their pages.
+ their pages. --unbacked moves facts saved under a name tag (a full name
+ with no page, facts.unbacked_entity_keys) onto the page that name now
+ resolves to (exact slug, unique basename, unique alias or the same name);
+ preview with --dry-run first.
Relink never creates pages and never supersedes a fact. Exact duplicates are
retired (expired, kept in history). Linked facts are queued for the System One
@@ -151,7 +154,8 @@ export function formatRelinkReport(report: RelinkReport, args: string[]): string
export function formatConversationRelinkReport(r: ConversationRelinkReport, args: string[]): string {
const lines = [`${r.dry_run ? 'DRY RUN: would link' : 'Linked'} ${r.linked} conversation fact(s) on ${r.pages.length} page(s) in source ${r.source_id}`
- + ` (mention tier, no model call); ${r.unresolved} unresolved${r.changed ? `; ${r.changed} changed before the write (run again)` : ''}.`];
+ + ` (${r.unbacked ? 'name tags moved onto their page' : 'mention tier'}, no model call); ${r.unresolved} ${r.unbacked ? 'still under a name tag with no page' : 'unresolved'}`
+ + `${r.changed ? `; ${r.changed} changed before the write (run again)` : ''}.`];
if (r.not_user_attributed) lines.push(` not_user_attributed: ${r.not_user_attributed}. ${RELINK_REASONS.not_user_attributed.fix}`);
for (const p of r.pages) lines.push(` ${p.slug}: ${p.linked} linked, ${p.unresolved} unresolved`);
if (r.dry_run && r.linked) lines.push(`Apply with:\n gbrain facts relink ${args.filter(a => a !== '--dry-run').join(' ')}`);
@@ -162,9 +166,9 @@ export function formatConversationRelinkReport(r: ConversationRelinkReport, args
return lines.join('\n');
}
-/** `--conversation` flags: --source, --slugs, --dry-run, --json; anything else is a usage error. */
+/** `--conversation` flags: --unbacked, --source, --slugs, --dry-run, --json; anything else is a usage error. */
async function runConversation(engine: BrainEngine, args: string[], config: GBrainConfig, sourceId: string): Promise<number> {
- const opts: { sourceId: string; slugs?: string[]; dryRun?: boolean } = { sourceId };
+ const opts: { sourceId: string; slugs?: string[]; dryRun?: boolean; unbacked?: boolean } = { sourceId };
let json = false;
for (let i = 0; i < args.length; i++) {
const a = args[i]!;
@@ -172,11 +176,12 @@ async function runConversation(engine: BrainEngine, args: string[], config: GBra
if (a === '--conversation') continue;
if (a === '--json') json = true;
else if (a === '--dry-run') opts.dryRun = true;
+ else if (a === '--unbacked') opts.unbacked = true;
else if ((a === '--source' || a === '--slugs') && v !== undefined && !v.startsWith('--')) {
if (a === '--source') opts.sourceId = v; else opts.slugs = v.split(',').map(s => s.trim()).filter(Boolean);
i++;
} else {
- console.error(`gbrain facts relink --conversation: ${a === '--source' || a === '--slugs' ? `${a} requires a value` : `unknown flag ${a} (takes --source, --slugs, --dry-run, --json)`}`);
+ console.error(`gbrain facts relink --conversation: ${a === '--source' || a === '--slugs' ? `${a} requires a value` : `unknown flag ${a} (takes --unbacked, --source, --slugs, --dry-run, --json)`}`);
return 1;
}
}
diff --git a/src/commands/integrity.ts b/src/commands/integrity.ts
index 0136aada32..d09d150176 100644
--- a/src/commands/integrity.ts
+++ b/src/commands/integrity.ts
@@ -44,6 +44,7 @@ import { isSegmentedPage } from '../core/page-body/page-shape.ts';
import type { BodyStorage } from '../core/page-body/types.ts';
import { bodyLines } from '../core/page-body/segment-lines.ts';
import { detachedValue } from '../core/page-body/segment-blocks.ts';
+import { HANDLE_FRONTMATTER_KEYS } from '../core/by-mention.ts';
// ---------------------------------------------------------------------------
// Paths
@@ -833,8 +834,7 @@ function logSkip(args: SkipArgs): void {
export function extractXHandleFromFrontmatter(fm: Record<string, unknown> | undefined): string | null {
if (!fm) return null;
- const keys = ['x_handle', 'twitter', 'twitter_handle', 'x'];
- for (const k of keys) {
+ for (const k of HANDLE_FRONTMATTER_KEYS) {
const v = fm[k];
if (typeof v === 'string' && v.trim().length > 0) {
return v.trim().replace(/^@/, '');
diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.ts
index 8d845e4866..673194f92b 100644
--- a/src/core/access/member-facts.ts
+++ b/src/core/access/member-facts.ts
@@ -14,6 +14,7 @@ import { createHash } from 'node:crypto';
import type { OperationContext } from '../ops/contract.ts';
import { currentCallerAccess, folderRestrictedSql, isDerivationPrivate, privateFactSources, privatePagesFilterForCaller, withFolderRestricted } from '../search/private-visibility.ts';
import { factPagesOpenSql, unpagedFactSql } from '../facts/private-fact-pages.ts';
+import { ownedMemorySubjectSql, unbackedEntitySql } from '../facts/withdrawal-schema.ts';
import type { BrainEngine } from '../engine.ts';
import { ACCESS_ID_RE, MEMBER_PAGE_PREFIX, normalizeReaders, SCOPE_PAGE_SLUG } from './principals.ts';
import { opError, type OperationError } from '../ops/contract.ts';
@@ -35,6 +36,20 @@ export function callerMember(): string | null {
return member && ACCESS_ID_RE.test(member) ? member : null;
}
+/** GST-2897 B: the member a people page names: `people/<member>` or a page under it. */
+export function peoplePageMember(slug: string | null | undefined): string | null {
+ const id = /^people\/([^/]+)/.exec(slug ?? '')?.[1];
+ return id && ACCESS_ID_RE.test(id) ? id : null;
+}
+
+/** GST-2897 B: the enabled member other than the caller whose people page `entitySlug` is, else null. */
+export async function otherMemberSubject(engine: Pick<BrainEngine, 'executeRaw'>, entitySlug: string | null): Promise<string | null> {
+ const id = peoplePageMember(entitySlug);
+ if (!id || id === callerMember()) return null;
+ const rows = await engine.executeRaw('SELECT 1 FROM access_members WHERE id = $1 AND disabled_at IS NULL AND tombstoned_at IS NULL', [id]);
+ return rows.length ? id : null;
+}
+
/**
* The member page a remote memory write goes to, or null when the caller writes as no single member (local or
* unbound). A member id whose page slug a repo brain would rename on sync (`a--b`, `zed-`) is refused: its facts
@@ -190,10 +205,11 @@ export function onOwnedMemoryPageSql(alias: string): string {
/**
* GST-359 D: the withdrawal-ledger subject of a fact, as SQL. A fact on an owned memory page (a member page, GST-1113 a
* scope page) is withdrawn for that page alone (its slug), so forgetting it never reaches another copy of the same claim;
- * any other fact keeps its entity ('*' without one).
+ * any other fact keeps its entity ('*' without one, and GBRA-574 '*' for an unbacked entity).
*/
export function factWithdrawalSubjectSql(alias: string): string {
- return `CASE WHEN ${onOwnedMemoryPageSql(alias)} THEN ${alias}.source_markdown_slug ELSE COALESCE(${alias}.entity_slug, '*') END`;
+ return `CASE WHEN ${onOwnedMemoryPageSql(alias)} THEN ${alias}.source_markdown_slug WHEN ${unbackedEntitySql(alias)} THEN '*'
+ ELSE COALESCE(${alias}.entity_slug, '*') END`;
}
/**
@@ -207,9 +223,9 @@ export function withdrawalCoversFactSql(w: string, f: string): string {
ELSE ${withdrawalReachedFactSql(w, f)} END)`;
}
-/** Whether withdrawal row `w` expired fact `f` when it was made (recordFactWithdrawal's reach), as SQL: every subject ('*'), the fact's entity, or the owned memory page it sits on. */
+/** Whether withdrawal row `w` expired fact `f` when it was made (recordFactWithdrawal's reach), as SQL: every subject ('*'), the fact's entity, any subject but an owned memory page for an unbacked entity, or the owned memory page it sits on. */
export function withdrawalReachedFactSql(w: string, f: string): string {
- return `(${w}.subject = '*' OR ${w}.subject = COALESCE(${f}.entity_slug, '*') OR (${onOwnedMemoryPageSql(f)} AND ${w}.subject = ${f}.source_markdown_slug))`;
+ return `(${w}.subject = '*' OR ${w}.subject = COALESCE(${f}.entity_slug, '*') OR (${unbackedEntitySql(f)} AND NOT ${ownedMemorySubjectSql(`${w}.subject`)}) OR (${onOwnedMemoryPageSql(f)} AND ${w}.subject = ${f}.source_markdown_slug))`;
}
/** The owned memory page a claim is checked on for withdrawals, or null: `slug` when it is one, so a page-scoped withdrawal applies there alone. */
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index ca5fd921c8..9dd3f01ead 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -38,7 +38,7 @@ import { stripCodeBlocks, isCrossSourceLinksEnabled } from './link-extraction.ts
// #4222: shared generic-token reject list — same list gates enrichEntity
// minting and drives the junk_entity_hubs doctor check.
import { isGenericEntityToken } from './entity-name-quality.ts';
-import { ALWAYS_LINKABLE_TYPES, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './mentions/policy.ts';
+import { ALWAYS_LINKABLE_TYPES, canonicalTypeOf, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './mentions/policy.ts';
import { siblingVerdict, type SiblingCandidate } from './mentions/siblings.ts';
import { isShortCode } from './mentions/short-codes.ts';
import { bodyBlocks } from './page-body/segment-blocks.ts';
@@ -104,6 +104,34 @@ export interface GazetteerEntry {
* binds to that canonical twin instead (see findMentionedEntities).
*/
connector_stub?: true;
+ /** An X handle from the page's frontmatter: matches only where the text writes it as `@handle`. */
+ atOnly?: true;
+}
+
+/** Frontmatter keys that hold a person's X handle. */
+export const HANDLE_FRONTMATTER_KEYS = ['x_handle', 'twitter', 'twitter_handle', 'x'] as const;
+
+const HANDLE_RE = /^[A-Za-z0-9_]{1,15}$/;
+/** Values people write in a handle field when they do not know the handle. */
+const PLACEHOLDER_HANDLES = new Set(['unknown', 'none', 'null', 'nil', 'na', 'tbd', 'todo', 'unset', 'undefined', 'private', 'redacted', 'anonymous', 'true', 'false', 'yes', 'no']);
+
+/**
+ * The X handle a frontmatter value names, lowercase without the `@`, or null
+ * for anything that is not a handle: an empty value, a placeholder such as
+ * `unknown`, an all-digit or all-zero value, a list or a longer text. An
+ * `x.com/<handle>` or `twitter.com/<handle>` URL yields its handle.
+ */
+export function frontmatterHandle(value: string | null | undefined): string | null {
+ const raw = value?.trim() ?? '';
+ const url = /^(?:https?:\/\/)?(?:www\.)?(?:x|twitter)\.com\/([^/?#\s]+)/i.exec(raw);
+ const v = (url ? url[1]! : raw).replace(/^@/, '');
+ if (!v || !HANDLE_RE.test(v) || /^[\d_]+$/.test(v) || PLACEHOLDER_HANDLES.has(v.toLowerCase())) return null;
+ return v.toLowerCase();
+}
+
+/** The name an entry is saved and diffed under: its tokens, case-preserved for a case-sensitive entry, `@`-prefixed for a handle. */
+export function entryNameNorm(e: GazetteerEntry): string {
+ return `${e.atOnly ? '@' : ''}${(e.caseTokens ?? e.tokens).join(' ')}`;
}
/**
@@ -124,7 +152,7 @@ export type Gazetteer = Map<string, GazetteerEntry[]>;
export function hashGazetteer(gazetteer: Gazetteer): string {
const entries: string[] = [];
for (const bucket of gazetteer.values()) {
- for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);
+ for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}\0${e.matchText ?? ''}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}${e.atOnly ? '\0@' : ''}`);
}
// Matching semantics are part of the resume identity, not just DB contents.
return createHash('sha256').update('katakana-boundaries-v5\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
@@ -143,8 +171,7 @@ export function gazetteerEntryKeys(gazetteer: Gazetteer): GazetteerEntryKey[] {
const out = new Map<string, GazetteerEntryKey>();
for (const bucket of gazetteer.values()) {
for (const e of bucket) {
- const name_norm = (e.caseTokens ?? e.tokens).join(' ');
- const key: GazetteerEntryKey = { source_id: e.source_id, name_norm, target_slug: e.slug, case_sensitive: !!e.caseTokens };
+ const key: GazetteerEntryKey = { source_id: e.source_id, name_norm: entryNameNorm(e), target_slug: e.slug, case_sensitive: !!e.caseTokens };
out.set(`${key.source_id}\0${key.name_norm}\0${key.target_slug}\0${key.case_sensitive}`, key);
}
}
@@ -497,20 +524,92 @@ export async function buildGazetteer(
}
const allTypes = [...new Set([...typesBySource.values()].flatMap(set => [...set]))];
const linkable = (sourceId: string | null, type: string | null) => !!type && (typesBySource.get(sourceId ?? 'default')?.has(type) ?? false);
- const rows = (await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null; connector_stub: boolean }>(
- `SELECT slug, source_id, title, type, (frontmatter ->> 'google_contact_id') IS NOT NULL AS connector_stub
+ const rows = (await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null; connector_stub: boolean;
+ h1: string | null; h2: string | null; h3: string | null; h4: string | null }>(
+ `SELECT slug, source_id, title, type, (frontmatter ->> 'google_contact_id') IS NOT NULL AS connector_stub,
+ frontmatter ->> $2 AS h1, frontmatter ->> $3 AS h2, frontmatter ->> $4 AS h3, frontmatter ->> $5 AS h4
FROM pages
WHERE type = ANY($1::text[])
AND deleted_at IS NULL`,
- [allTypes],
+ [allTypes, ...HANDLE_FRONTMATTER_KEYS],
)).filter(r => linkable(r.source_id, r.type));
const stubPages = new Set(rows.filter(r => r.connector_stub).map(r => `${r.source_id ?? 'default'}\0${r.slug}`));
const stubFlag = (src: string, slug: string) => stubPages.has(`${src}\0${slug}`) ? { connector_stub: true as const } : {};
+ const kindOf = new Map(rows.map(r => [`${r.source_id ?? 'default'}\0${r.slug}`, canonicalTypeOf(r.type, packBySource.get(r.source_id ?? 'default') ?? null)]));
+ const isPerson = (src: string, slug: string) => kindOf.get(`${src}\0${slug}`) === 'person';
const ignoreSet = new Set<string>(DEFAULT_IGNORE_LIST);
const userIgnore = new Set(policy.ignore.map(n => tokenizeTitle(n).join(' ')).filter(Boolean));
const excludedSlugs = new Set(policy.excludeSlugs);
+ // page_aliases rows joined to LIVE linkable entity pages (read before the
+ // titles: frontmatter aliases are explicit claims a title can yield to).
+ let aliasRows: Array<{ alias_norm: string; slug: string; source_id: string | null; title: string | null; type: string | null;
+ origin: string | null; case_sensitive: boolean | null; alias_text: string | null; identity: unknown }> = [];
+ try {
+ aliasRows = (await engine.executeRaw<typeof aliasRows[number]>(
+ `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title, p.type, pa.origin, pa.case_sensitive, pa.alias_text, p.frontmatter->>'identity' AS identity
+ FROM page_aliases pa
+ JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id
+ WHERE p.type = ANY($1::text[])
+ AND p.deleted_at IS NULL`,
+ [allTypes],
+ )).filter(r => linkable(r.source_id, r.type));
+ } catch (err) {
+ // pre-v110 brains: no page_aliases table — titles-only gazetteer.
+ // Any OTHER failure (connection blip, permission) warns once per process
+ // (adversarial F12): a silently titles-only gazetteer under-links every
+ // page processed until restart, and nobody would know why. A strict
+ // (mention-pass) build throws instead, so nothing is reconciled against
+ // a partial gazetteer.
+ if (opts.strict) throw err;
+ if (!isMissingSchemaObject(err, 'table', 'page_aliases') && !aliasGazetteerWarned) {
+ aliasGazetteerWarned = true;
+ console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
+ // Explicit claims, per source and name: the pages whose frontmatter writes
+ // the name as an alias or as their X handle. A page titled with a name that
+ // exactly one other page of its kind claims, while it claims nothing itself,
+ // is a thin page for that person or company: its title yields the name to
+ // the claimant (a handle mention lands on the person, not on a page whose
+ // slug is the handle) once the claimant's own entry for the name survives
+ // the alias guards below. Two claimants keep the title.
+ const handlesOf = (r: typeof rows[number]) => [...new Set([r.h1, r.h2, r.h3, r.h4].map(frontmatterHandle).filter((h): h is string => !!h))];
+ const explicit = new Map<string, Set<string>>();
+ const claim = (src: string, key: string, slug: string) => {
+ if (!key) return;
+ const k = `${src}\0${key}`;
+ explicit.set(k, (explicit.get(k) ?? new Set<string>()).add(slug));
+ };
+ for (const a of aliasRows) if (a.origin === 'frontmatter' || a.origin === null) claim(a.source_id ?? 'default', tokenizeTitle(a.alias_norm ?? '').join(' '), a.slug);
+ for (const r of rows) for (const h of handlesOf(r)) claim(r.source_id ?? 'default', tokenizeTitle(h).join(' '), r.slug);
+ const claimant = (src: string, key: string, slug: string): string | null => {
+ const slugs = explicit.get(`${src}\0${key}`);
+ if (!slugs || slugs.size !== 1 || slugs.has(slug)) return null;
+ const [other] = slugs;
+ return kindOf.get(`${src}\0${other}`) === kindOf.get(`${src}\0${slug}`) ? other! : null;
+ };
+ /** `source\0name\0claimant` for every title that yields its name to a claimant whose entry survives. */
+ const yielded = new Set<string>();
+ const yielding: Array<{ entry: GazetteerEntry; base: Omit<DroppedName, 'reason'>; key: string }> = [];
+
+ // Per source: the first word of every multi-word person name (titles and
+ // aliases) and the pages that write it. A one-word person title equal to
+ // another page's one is a bare first name: it never links alone, the same
+ // rule single-token aliases follow below.
+ const personFirstWords = new Map<string, Map<string, Set<string>>>();
+ const notePersonName = (src: string, slug: string, name: string | null) => {
+ const tokens = tokenizeTitle(name ?? '');
+ if (tokens.length < 2 || !isPerson(src, slug)) return;
+ const words = personFirstWords.get(src) ?? new Map<string, Set<string>>();
+ words.set(tokens[0]!, (words.get(tokens[0]!) ?? new Set<string>()).add(slug));
+ personFirstWords.set(src, words);
+ };
+ for (const r of rows) notePersonName(r.source_id ?? 'default', r.slug, r.title);
+ for (const a of aliasRows) notePersonName(a.source_id ?? 'default', a.slug, a.alias_norm);
+
const gazetteer: Gazetteer = new Map();
const add = (entry: GazetteerEntry) => {
const key = entry.tokens[0]!;
@@ -555,13 +654,17 @@ export async function buildGazetteer(
// ("Will Smith") are unaffected; aliases of every type are checked below.
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
noteFirstWord(src, tokens);
- add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title', matchText: row.title, ...stubFlag(src, row.slug) });
+ if (tokens.length === 1 && isPerson(src, row.slug) && [...personFirstWords.get(src)?.get(tokens[0]!) ?? []].some(s => s !== row.slug)) { drop({ ...base, reason: 'ambiguous_first_word' }); continue; }
+ const entry: GazetteerEntry = { slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title', matchText: row.title, ...stubFlag(src, row.slug) };
+ const owner = claimant(src, tokens.join(' '), row.slug);
+ if (owner) { const key = `${src}\0${tokens.join(' ')}\0${owner}`; yielded.add(key); yielding.push({ entry, base, key }); continue; }
+ add(entry);
}
// ── Alias entries ────────────────────────────────────────────────────────
- // page_aliases rows joined to LIVE linkable entity pages become additional
- // gazetteer entries, so a body mention of "saoirse" links to
- // people/saoirse-x and "QUCO" links to the account that declares it.
+ // page_aliases rows become additional gazetteer entries, so a body mention
+ // of "saoirse" links to people/saoirse-x and "QUCO" links to the account
+ // that declares it.
// Guards (stricter than titles — aliases are not user-created pages):
// - one row per (source, alias, page) with origin precedence
// frontmatter > declared > subject
@@ -570,36 +673,13 @@ export async function buildGazetteer(
// - an alias claimed by >1 page at its best origin within a source is
// dropped (ambiguous); a lower-precedence claim yields
// - aliases colliding with any existing page TITLE in the SAME source
- // are skipped (the title entry wins; per-source scoping per R2-9)
+ // are skipped (the title entry wins; per-source scoping per R2-9),
+ // unless that title yielded the name to this page's explicit claim
// - MIN_NAME_LENGTH and the generic-token list apply to the alias string
// - a single-token alias equal to the first word of a multi-word entity
// name in the same source is dropped
// - a case-sensitive row (a single-token declared alias) matches only
// the original-case text
- let aliasRows: Array<{ alias_norm: string; slug: string; source_id: string | null; title: string | null; type: string | null;
- origin: string | null; case_sensitive: boolean | null; alias_text: string | null; identity: unknown }> = [];
- try {
- aliasRows = (await engine.executeRaw<typeof aliasRows[number]>(
- `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title, p.type, pa.origin, pa.case_sensitive, pa.alias_text, p.frontmatter->>'identity' AS identity
- FROM page_aliases pa
- JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id
- WHERE p.type = ANY($1::text[])
- AND p.deleted_at IS NULL`,
- [allTypes],
- )).filter(r => linkable(r.source_id, r.type));
- } catch (err) {
- // pre-v110 brains: no page_aliases table — titles-only gazetteer.
- // Any OTHER failure (connection blip, permission) warns once per process
- // (adversarial F12): a silently titles-only gazetteer under-links every
- // page processed until restart, and nobody would know why. A strict
- // (mention-pass) build throws instead, so nothing is reconciled against
- // a partial gazetteer.
- if (opts.strict) throw err;
- if (!isMissingSchemaObject(err, 'table', 'page_aliases') && !aliasGazetteerWarned) {
- aliasGazetteerWarned = true;
- console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);
- }
- }
const ignoreLc = new Set(Array.from(ignoreSet, (n) => n.toLowerCase()));
// Per-source title index for alias-vs-title collision checks.
const titleBySource = new Set<string>();
@@ -645,9 +725,9 @@ export async function buildGazetteer(
if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias) && !shortCode) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (ignoreLc.has(alias.toLowerCase())) { drop({ ...base, reason: 'ignored' }); continue; }
- if (titleBySource.has(`${src} ${alias.toLowerCase()}`)) { drop({ ...base, reason: 'title_wins' }); continue; }
const tokens = tokenizeTitle(alias);
if (tokens.length === 0) continue;
+ if (titleBySource.has(`${src} ${alias.toLowerCase()}`) && !yielded.has(`${src}\0${tokens.join(' ')}\0${a.slug}`)) { drop({ ...base, reason: 'title_wins' }); continue; }
if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1 && !shortCode) { drop({ ...base, reason: 'below_min_length' }); continue; }
if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
@@ -658,20 +738,56 @@ export async function buildGazetteer(
noteFirstWord(src, tokens);
aliasEntries.push({ entry, base });
}
+
+ // ── Handle entries ───────────────────────────────────────────────────────
+ // A frontmatter X handle (x_handle, twitter, twitter_handle, x) links where
+ // the text writes it as @handle. Where a thin page titled with the handle
+ // yielded it above, the bare handle links to the claimant too, as it linked
+ // to the thin page before. Two pages claiming one handle link neither.
+ const aliasKeys = new Set(aliasEntries.map(({ entry }) => `${entry.source_id}\0${entry.tokens.join(' ')}\0${entry.slug}`));
+ for (const row of rows) {
+ if (!row.title) continue;
+ const src = row.source_id ?? 'default';
+ for (const handle of handlesOf(row)) {
+ const tokens = tokenizeTitle(handle);
+ const key = tokens.join(' ');
+ const base = { source_id: src, slug: row.slug, name: `@${handle}`, origin: 'frontmatter' as const };
+ if (tokens.length === 0) continue;
+ if (excludedSlugs.has(row.slug)) { drop({ ...base, reason: 'excluded_slug' }); continue; }
+ if ((explicit.get(`${src}\0${key}`)?.size ?? 0) > 1) { drop({ ...base, reason: 'alias_collision' }); continue; }
+ if (handle.length < MIN_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (ignoreLc.has(handle) || userIgnore.has(key)) { drop({ ...base, reason: 'ignored' }); continue; }
+ if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
+ const entry: GazetteerEntry = { slug: row.slug, source_id: src, title: row.title, tokens, origin: 'frontmatter', matchText: handle, ...stubFlag(src, row.slug) };
+ add({ ...entry, matchText: `@${handle}`, atOnly: true });
+ const k = `${src}\0${key}\0${row.slug}`;
+ if (yielded.has(k) && !aliasKeys.has(k)) { aliasKeys.add(k); aliasEntries.push({ entry, base: { ...base, name: handle } }); }
+ }
+ }
+ const claimed = new Set<string>();
for (const { entry, base } of aliasEntries) {
if (entry.tokens.length === 1 && firstWords.get(entry.source_id)?.has(entry.tokens[0]!)) {
drop({ ...base, reason: 'ambiguous_first_word' });
continue;
}
add(entry);
+ claimed.add(`${entry.source_id}\0${entry.tokens.join(' ')}\0${entry.slug}`);
+ }
+ // A title yields only to a claimant whose entry for the name survived;
+ // otherwise it keeps the name, as it did before the claim.
+ for (const { entry, base, key } of yielding) {
+ if (claimed.has(key)) drop({ ...base, reason: 'alias_collision' });
+ else add(entry);
}
// Sort each bucket by token-count DESC so maximal-munch walks longest-first;
- // ties break on (source_id, slug) so the pick among same-name entries is
- // deterministic instead of following DB row order.
+ // a handle entry comes before a same-length name, so `@name` reaches the
+ // page that claims the handle; ties break on (source_id, slug) so the pick
+ // among same-name entries is deterministic instead of following DB row order.
for (const bucket of gazetteer.values()) {
bucket.sort((a, b) =>
(b.tokens.length - a.tokens.length)
+ || (Number(!!b.atOnly) - Number(!!a.atOnly))
|| a.source_id.localeCompare(b.source_id)
|| a.slug.localeCompare(b.slug));
}
@@ -784,6 +900,8 @@ export function findMentionedEntities(
const tok = tokens[at + k]!;
return stripped.slice(tok.offset, tok.offset + tok.length).normalize('NFC') === t;
});
+ // A handle entry matches only where the text writes it as @handle.
+ const atMatches = (entry: GazetteerEntry, at: number) => !entry.atOnly || stripped[tokens[at]!.offset - 1] === '@';
const out: Mention[] = [];
const seenTargets = new Set<string>();
@@ -806,6 +924,7 @@ export function findMentionedEntities(
if (!hasHangulMatchBoundary(stripped, tokens, i, entry)) continue;
if (!hasKatakanaMatchBoundary(stripped, tokens, i, entry)) continue;
if (!caseMatches(entry, i)) continue;
+ if (!atMatches(entry, i)) continue;
if (entry.tokens.length === 1) {
matched = entry;
matchedTokens = 1;
@@ -839,6 +958,7 @@ export function findMentionedEntities(
e.tokens.length === want.tokens.length
&& e.tokens.every((t, k) => t === want.tokens[k])
&& caseMatches(e, i)
+ && atMatches(e, i)
&& hasHangulMatchBoundary(stripped, tokens, i, e)
&& hasKatakanaMatchBoundary(stripped, tokens, i, e);
if (matched.source_id !== opts.fromSourceId) {
@@ -880,7 +1000,7 @@ export function findMentionedEntities(
const want = matched.tokens;
const group = matched.shared
? bucket.filter(e => e.shared && e.source_id === matched!.source_id && e.tokens.length === want.length
- && e.tokens.every((t, k) => t === want[k]) && caseMatches(e, i))
+ && e.tokens.every((t, k) => t === want[k]) && caseMatches(e, i) && atMatches(e, i))
: [matched];
if (group.length > 1 && group.some(e => e.source_id === opts.fromSourceId && e.slug === opts.fromSlug)) {
i += matchedTokens;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 26253e59b4..015ffbeb2b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -65,7 +65,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'export': ['--accept-pending', '--access-policy', '--as', '--background', '--body', '--brain', '--dir', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--room', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--as', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-schema', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--room', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--as', '--background', '--body', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--grammar', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--room', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
- 'facts': ['--admin-intent', '--after-id', '--all', '--brain', '--clear', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--list', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--reset', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id'],
+ 'facts': ['--admin-intent', '--after-id', '--all', '--brain', '--clear', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--list', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--reset', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id', '--unbacked'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
'files': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--room', '--source', '--timeout', '--timings', '--type', '--wait', '--yes'],
diff --git a/src/core/config.ts b/src/core/config.ts
index 3a3db8dd85..ce2ba45722 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1533,7 +1533,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'facts.default_visibility',
'storage.git_lfs', // G7a: a git-canonical door commit under a Git LFS rule commits the LFS pointer; default off refuses it (persistence/git-declared.ts)
'visibility.honor_aliases', // remote page reads honor `access`/`confidentiality` aliases on pages without `visibility`; default on, false opts out (search/private-visibility.ts)
- 'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)
+ 'facts.entity_inference', 'facts.unbacked_entity_keys', // #5836 subject inference kill switch (subject-infer.ts); GBRA-574 conversation name keys (entities/resolve-on-save.ts)
'facts.candidate_fusion', // C2: 'rrf_free' (default, cosine arm) | 'interleave' (cosine + keyword; facts/single-prepare.ts)
'facts.supersession_thresholds', // JSON {"provider:model@dims": number | "off"} (facts/supersession-threshold.ts)
'facts.page_write_notability_filter', // #6231: tiers page-write extraction keeps (facts/notability-filter.ts)
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 46e5c68b04..9cf5b0f870 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -466,7 +466,7 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: s
return fact && fact.visibility !== 'world' && (f.visibility ?? 'private') === 'world' ? [Number(fact.id)] : [];
});
const heldWidening = new Set(widening.length ? (await db.executeRaw<{ id: number }>(
- `SELECT related_id AS id FROM trust_proposals WHERE source_id = $1 AND action = 'supersede_fact' AND related_table = 'facts'
+ `SELECT related_id AS id FROM trust_proposals WHERE source_id = $1 AND action IN ('supersede_fact', 'confirm') AND related_table = 'facts'
AND related_id = ANY($2::bigint[]) AND status IN ('pending', 'rejected', 'undone') AND before_state->'visibility' IS NOT NULL`,
[sourceId, widening])).map(r => Number(r.id)) : []);
const updates = extracted.map((f): FenceExtractedFact => {
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 4a6e9be180..d3129cb06b 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -200,8 +200,8 @@ export async function runPhaseConsolidate(
// #5575 write gate: unmanaged takes are gated here (managed ones in takes-prepare); read once per run.
let gateConfig: WriteGateConfig | undefined;
- // Pull every (source_id, entity_slug) bucket of unconsolidated facts.
- // Uses the partial idx_facts_unconsolidated index.
+ // Pull every (source_id, entity_slug) bucket of unconsolidated facts whose entity is a live page (a take needs one, and
+ // GBRA-574: an unbacked name key has none, so its bucket is never read). Uses the partial idx_facts_unconsolidated index.
let buckets: Array<{ source_id: string; entity_slug: string; count: number }>;
try {
buckets = await engine.executeRaw<{
@@ -213,6 +213,7 @@ export async function runPhaseConsolidate(
AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until > now())
AND entity_slug IS NOT NULL
+ AND EXISTS (SELECT 1 FROM pages bucket_page WHERE bucket_page.source_id = facts.source_id AND bucket_page.slug = facts.entity_slug AND bucket_page.deleted_at IS NULL)
AND (attributed_to IS NULL OR attributed_to = 'user')
AND ($2::boolean=false OR visibility='world')
AND ($1::text IS NULL OR source_id=$1) AND NOT ${readersSourcedFactSql('facts')}
diff --git a/src/core/eligibility/fence-overlay.ts b/src/core/eligibility/fence-overlay.ts
index 4a1e868b72..650d854557 100644
--- a/src/core/eligibility/fence-overlay.ts
+++ b/src/core/eligibility/fence-overlay.ts
@@ -225,7 +225,7 @@ export function heldRowSql(sourceId: string, slug: string, rowNum: string, claim
const page = (a: string) => `${a}.source_id = ${sourceId} AND ${a}.source_markdown_slug = ${slug} AND ${a}.expired_at IS NULL`;
const granted = (a: string) => `(${grantedPrivateFactSql(a)} AND NOT EXISTS (SELECT 1 FROM trust_proposals hgp
LEFT JOIN facts hgc ON hgp.target_table = 'facts' AND hgc.id = hgp.target_id
- WHERE hgp.related_table = 'facts' AND hgp.related_id = ${a}.id AND hgp.action = 'supersede_fact' AND hgp.before_state->'visibility' IS NOT NULL
+ WHERE hgp.related_table = 'facts' AND hgp.related_id = ${a}.id AND hgp.action IN ('supersede_fact', 'confirm') AND hgp.before_state->'visibility' IS NOT NULL
AND (hgc.id IS NULL OR NOT (${memberFactAdmitSql('hgc')} OR ${grantedPrivateFactSql('hgc')}))))`;
const narrower = (a: string) => `${page(a)} AND ${a}.visibility <> 'world' AND NOT ${memberFactAdmitSql(a)} AND NOT ${granted(a)}`;
const states = (a: string) => `(CASE WHEN ${partial} THEN strpos(${a}.fact, ${claim}) > 0 ELSE ${a}.fact = ${claim} END)`;
diff --git a/src/core/entities/basename-dirs.ts b/src/core/entities/basename-dirs.ts
new file mode 100644
index 0000000000..8ae97ea534
--- /dev/null
+++ b/src/core/entities/basename-dirs.ts
@@ -0,0 +1,11 @@
+// hosts/projects joined people/companies after the 2026-08-06 memory eval: a
+// bare infra token ("hive") fell through to slugify and recall returned
+// nothing while the canonical hosts/<token> page + its facts sat one prefix
+// away. `infra/` is deliberately NOT here — it is a mixed namespace of
+// analysis/runbook documents (`infra/hive-dependency-audit-…`), and any such
+// doc would trip the ambiguity gate and re-break bare-token resolution.
+export const PREFIX_EXPANSION_DIRS = ['people', 'companies', 'hosts', 'projects'] as const;
+/** Directories a bare entity name resolves under (findExactBasenameCandidates); factEntitySlugs reads the same set. */
+export const BASENAME_DIRS = [...PREFIX_EXPANSION_DIRS, 'concepts'] as const;
+/** GBRA-574: directories whose page at <dir>/<key> covers a bare name key's facts for privacy: the basename directories plus the identity directories (resolve.ts IDENTITY_DIRS) a page adopting the key can sit in. */
+export const NAME_KEY_PAGE_DIRS = [...BASENAME_DIRS, 'funds', 'orgs', 'organizations'] as const;
diff --git a/src/core/entities/resolve-on-save.ts b/src/core/entities/resolve-on-save.ts
index f72b4f5e6d..7c0dd9a26c 100644
--- a/src/core/entities/resolve-on-save.ts
+++ b/src/core/entities/resolve-on-save.ts
@@ -31,6 +31,8 @@ export const SAVE_TIME_RESOLUTION_SOURCES = [
export interface SaveTimeResolutionCounts {
counts: Partial<Record<ResolutionSource, number>>;
fallback_slugify_count: number;
+ /** GBRA-574: fallback_slugify resolutions kept as a name key (facts.unbacked_entity_keys) instead of NULL. */
+ unbacked_key_count?: number;
resolution_errors: number;
}
@@ -38,6 +40,23 @@ export function emptySaveTimeResolutionCounts(): SaveTimeResolutionCounts {
return { counts: {}, fallback_slugify_count: 0, resolution_errors: 0 };
}
+/** The setting that keeps a name key on conversation facts whose entity has no page; on unless set to an off value. */
+export const UNBACKED_ENTITY_KEYS_KEY = 'facts.unbacked_entity_keys';
+
+export async function unbackedEntityKeysEnabled(engine: BrainEngine): Promise<boolean> {
+ return !/^(false|off|0|no)$/i.test(((await engine.getConfig(UNBACKED_ENTITY_KEYS_KEY)) ?? '').trim());
+}
+
+/**
+ * GBRA-574 B1: the name key of an extractor entity that resolved only by fallback_slugify: the bare basename slug
+ * (`Alice Example`, `alice-example` and `people/alice-example` all give `alice-example`), kept only for a name of at least
+ * two words. A first name or a topic (`Alice`, `travel`) gives null.
+ */
+export function unbackedEntityKey(fallbackSlug: string): string | null {
+ const key = fallbackSlug.split('/').filter(Boolean).pop() ?? '';
+ return key.split('-').filter(Boolean).length >= 2 ? key : null;
+}
+
export function mergeSaveTimeResolutionCounts(
into: SaveTimeResolutionCounts,
add: SaveTimeResolutionCounts,
@@ -47,6 +66,7 @@ export function mergeSaveTimeResolutionCounts(
into.counts[typed] = (into.counts[typed] ?? 0) + (count ?? 0);
}
into.fallback_slugify_count += add.fallback_slugify_count;
+ if (add.unbacked_key_count) into.unbacked_key_count = (into.unbacked_key_count ?? 0) + add.unbacked_key_count;
into.resolution_errors += add.resolution_errors;
}
@@ -71,14 +91,17 @@ function isAbortError(err: unknown): boolean {
* resolver. Mutates `facts` in place. Sequential so a PGLite-pinned
* transaction sees one alias probe at a time.
*
- * Unresolved references keep the fact unparented. Ordinary resolver failures
- * increment resolution_errors. Abort and BudgetExhausted propagate.
+ * Unresolved references keep the fact unparented, unless `unbacked` is given (conversation extraction with
+ * facts.unbacked_entity_keys on): then a two-word name keeps its name key (unbackedEntityKey) when no page sits at that
+ * key, and `unbacked` records the row index and the extractor's own name text. No page is created. Ordinary resolver
+ * failures increment resolution_errors. Abort and BudgetExhausted propagate.
*/
export async function resolveExtractedEntitiesForSave(
engine: BrainEngine,
sourceId: string,
facts: ExtractedFact[],
onError?: (raw: string, message: string) => void,
+ unbacked?: Map<number, string>,
): Promise<SaveTimeResolutionCounts> {
const stats = emptySaveTimeResolutionCounts();
for (let i = 0; i < facts.length; i++) {
@@ -86,11 +109,18 @@ export async function resolveExtractedEntitiesForSave(
if (raw === null) continue;
try {
const resolved = await resolveEntitySlugWithSource(engine, sourceId, raw);
- facts[i] = { ...facts[i], entity_slug: resolved?.source === 'fallback_slugify' ? null : resolved?.slug ?? null };
+ const key = unbacked && resolved?.source === 'fallback_slugify' ? unbackedEntityKey(resolved.slug) : null;
+ const kept = key && (await engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1',
+ [sourceId, key])).length === 0 ? key : null;
+ facts[i] = { ...facts[i], entity_slug: resolved?.source === 'fallback_slugify' ? kept : resolved?.slug ?? null };
if (!resolved) continue;
stats.counts[resolved.source] = (stats.counts[resolved.source] ?? 0) + 1;
if (resolved.source === 'fallback_slugify') {
stats.fallback_slugify_count++;
+ if (kept) {
+ stats.unbacked_key_count = (stats.unbacked_key_count ?? 0) + 1;
+ unbacked!.set(i, raw.trim());
+ }
}
} catch (err) {
if (isAbortError(err) || err instanceof BudgetExhausted) throw err;
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 3e5b459538..1423517758 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -33,6 +33,7 @@ import { isMissingSchemaObject } from '../utils.ts';
import { privatePagesFilterForCaller, remoteReadFloorSql } from '../search/private-visibility.ts';
import { rankingLinkSql } from '../link-ranking-policy.ts';
import { isHoldingSlug } from '../facts-fence.ts';
+import { BASENAME_DIRS, PREFIX_EXPANSION_DIRS } from './basename-dirs.ts';
/**
* Canonicalize a free-form entity reference to a page slug.
@@ -127,7 +128,7 @@ export async function resolveEntitySlug(
* (`slugifySegment`), so `Мария` lands on `мария`, not `''`. Latin names keep
* the ASCII form (`o-brien`, `soren`). Null when nothing is left.
*/
-function fallbackSlugify(trimmed: string): string | null {
+export function fallbackSlugify(trimmed: string): string | null {
const slug = trimmed.split('/').map(fallbackSegment).filter(Boolean).join('/');
return slug || null;
}
@@ -351,15 +352,7 @@ function isBareName(raw: string): boolean {
return true;
}
-// hosts/projects joined people/companies after the 2026-08-06 memory eval: a
-// bare infra token ("hive") fell through to slugify and recall returned
-// nothing while the canonical hosts/<token> page + its facts sat one prefix
-// away. `infra/` is deliberately NOT here — it is a mixed namespace of
-// analysis/runbook documents (`infra/hive-dependency-audit-…`), and any such
-// doc would trip the ambiguity gate and re-break bare-token resolution.
-const PREFIX_EXPANSION_DIRS = ['people', 'companies', 'hosts', 'projects'] as const;
-/** Directories a bare entity name resolves under (findExactBasenameCandidates); factEntitySlugs reads the same set. */
-export const BASENAME_DIRS = [...PREFIX_EXPANSION_DIRS, 'concepts'] as const;
+export { BASENAME_DIRS };
async function findExactBasenameCandidates(
engine: BrainEngine,
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 09df3cfa1e..baf9395e1c 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -91,6 +91,8 @@ export interface SegmentedConversationCounters {
failed_pages: Array<{ slug: string; error: string }>;
/** GBRA-574: windows whose slot-tagging call failed; their facts were kept without slots. */
slot_tagging_failed?: number;
+ /** GBRA-574: facts kept under a name key with no page (facts.unbacked_entity_keys). */
+ unbacked_keys?: number;
/** Pages held because no format is detected over them yet some format parses a message (a detection_ambiguous receipt). */
pages_detection_ambiguous?: number;
/** --grammar --dry-run: what a run under the chosen format would extract and collect, per page. */
@@ -442,7 +444,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
});
throw error;
} finally {
- result.fallback_slugify_count += resolution.fallback_slugify_count;
+ result.fallback_slugify_count += resolution.fallback_slugify_count; if (resolution.unbacked_key_count) result.unbacked_keys = (result.unbacked_keys ?? 0) + resolution.unbacked_key_count;
result.resolution_errors += resolution.resolution_errors;
}
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 8eac97011f..3dffb85621 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -87,6 +87,7 @@ import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';
import { sourceWindowKey, type SourceWindow } from '../page-body/derivations.ts';
import { findCaptureDuplicate } from './capture-dedup.ts';
import { normalizeSlot } from './slots.ts';
+import { unbackedEntitySql } from './withdrawal-schema.ts';
import { CONVERSATION_SLOT_SQL, valueHash } from '../chronicle/ontology.ts';
export const CONVERSATION_FACTS_INTENT = 'managed_maintenance_conversation_facts';
@@ -567,16 +568,17 @@ export async function replaceConversationFacts(tx: BrainEngine, sourceId: string
/**
* Inserts `rows` numbered above every fact row of the page; a lost insert throws, rolling the publication back.
- * #7438: a row whose claim matches a purge tombstone (under the entity it carries after relink inheritance) is left
- * out and its index returned in `purged`; the facts insert guard would otherwise refuse the whole statement.
+ * #7438: a row whose claim matches a purge tombstone (under the entity it carries after relink inheritance; under any
+ * subject for an unbacked name key, GBRA-574) is left out and its index returned in `purged`; the facts insert guard
+ * would otherwise refuse the whole statement.
* #7778: never the page outcome row, which no tombstone applies to (the guard exempts it too).
*/
async function insertConversationFacts(tx: BrainEngine, sourceId: string, slug: string, rows: UnnumberedFact[]): Promise<{ inserted: number; ids: number[]; purged: Set<number> }> {
if (!rows.length) return { inserted: 0, ids: [], purged: new Set() };
rows = await inheritRelinkedEntities(tx, sourceId, slug, rows);
- const matches = await tx.executeRaw<{ ord: number | string }>(`SELECT n.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[]) WITH ORDINALITY AS n(fact, visibility, subject, source, ord)
- WHERE NOT ${outcomeMarkerSql('n')} AND EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id=$1 AND p.visibility=n.visibility AND p.subject IN ('*', n.subject)
- AND p.fact_hash=gbrain_fact_fingerprint(n.fact))`,
+ const matches = await tx.executeRaw<{ ord: number | string }>(`SELECT n.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[]) WITH ORDINALITY AS n(fact, visibility, entity_slug, source, ord)
+ WHERE NOT ${outcomeMarkerSql('n')} AND EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id=$1 AND p.visibility=n.visibility
+ AND (p.subject IN ('*', n.entity_slug) OR ${unbackedEntitySql('n', '$1')}) AND p.fact_hash=gbrain_fact_fingerprint(n.fact))`,
[sourceId, rows.map(row => ensureWellFormed(row.fact)), rows.map(row => row.visibility ?? 'private'), rows.map(row => row.entity_slug ? ensureWellFormed(row.entity_slug) : null), rows.map(row => row.source ?? null)]);
const purged = new Set(matches.map(match => Number(match.ord) - 1));
rows = await insertableSlots(tx, sourceId, slug, rows.filter((_, i) => !purged.has(i)));
diff --git a/src/core/facts/conversation-relink.ts b/src/core/facts/conversation-relink.ts
index 88f4509ff7..bd38420ea3 100644
--- a/src/core/facts/conversation-relink.ts
+++ b/src/core/facts/conversation-relink.ts
@@ -23,6 +23,14 @@
* re-arms and how the paid attempt is remembered. A row the assistant or a
* third party said is never linked (#7270): it is counted, left unlinked, and
* never picks a page for a run. Trusted local CLI only.
+ *
+ * GBRA-574 C1, `--unbacked`: the same write re-keys a derived row stored on an
+ * unbacked name key (facts.unbacked_entity_keys: a bare slug with no live page,
+ * withdrawal-schema.ts unbackedEntitySql) onto the page that name now resolves
+ * to through resolveStrictEntityReference (exact slug, unique basename, unique
+ * alias, or the same name ignoring corporate suffixes; a retired page answers
+ * through its superseded_by target), private pages excluded for a world row.
+ * A key that resolves to no page, or to two, keeps its rows; no memo is written.
*/
import type { BrainEngine, FactAttribution } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
@@ -43,6 +51,9 @@ import { conversationTriedSql } from './conversation-memo.ts';
import { appendContextNote } from './subject-infer.ts';
import { ENTITY_LINKABLE_SQL, entityLinkable } from './attribution.ts';
import { inferConversationSubject } from './conversation-subject-infer.ts';
+import { unbackedEntitySql } from './withdrawal-schema.ts';
+import { resolveStrictEntityReference } from '../entities/resolve.ts';
+import { dropRekeyDuplicates } from './ontology-rekey.ts';
export const CONVERSATION_RELINK_INTENT = 'managed_maintenance_conversation_relink';
/** The request slug: a dot-led segment no page can hold; the page's own key is locked with it. */
@@ -51,13 +62,19 @@ export const CONVERSATION_RELINK_ANCHOR = '.maintenance/conversation-relink';
export const CONVERSATION_RELINK_PAGES = 50;
/** The SQL predicate (on alias `f`, audit sources as `$audit`) of a conversation extractor's derived fact row. */
export const derivedConversationRow = (audit: string) => `f.source LIKE 'cli:extract-conversation-facts%' AND f.source <> ALL(${audit}::text[])`;
-const ACTIVE = 'f.entity_slug IS NULL AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())';
+const LIVE = 'f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())';
+const ACTIVE = `f.entity_slug IS NULL AND ${LIVE}`;
+/** GBRA-574: a derived row on an unbacked name key (`--unbacked`). */
+const UNBACKED = `${unbackedEntitySql('f')} AND ${LIVE}`;
-export interface ConversationRelinkRow { id: number; fact: string; entity_slug: string; context: string }
+/** A planned link; `from` is the unbacked name key a `--unbacked` row moves off (absent: a row with no entity). */
+export interface ConversationRelinkRow { id: number; fact: string; entity_slug: string; context: string; from?: string }
interface PagePlan { slug: string; link: ConversationRelinkRow[]; misses: Array<{ id: number; reason: string }>; notUserAttributed: number }
export interface ConversationRelinkReport {
source_id: string;
dry_run: boolean;
+ /** GBRA-574: a `--unbacked` run (rows on a name key re-keyed onto the page the name resolves to). */
+ unbacked?: boolean;
pages: Array<{ slug: string; linked: number; unresolved: number; changed: number; not_user_attributed: number }>;
linked: number;
unresolved: number;
@@ -75,16 +92,38 @@ async function hasAttemptsTable(engine: BrainEngine): Promise<boolean> {
}
/** The pages with the most unlinked derived rows not yet tried by this relink, up to `limit`. */
-export async function conversationRelinkPages(engine: BrainEngine, sourceId: string, limit = CONVERSATION_RELINK_PAGES): Promise<string[]> {
- const untried = await hasAttemptsTable(engine)
+export async function conversationRelinkPages(engine: BrainEngine, sourceId: string, limit = CONVERSATION_RELINK_PAGES, unbacked = false): Promise<string[]> {
+ const untried = !unbacked && await hasAttemptsTable(engine)
? `AND NOT ${conversationTriedSql}` : '';
const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT f.source_markdown_slug AS slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NOT NULL AND ${ACTIVE} AND ${ENTITY_LINKABLE_SQL}
+ `SELECT f.source_markdown_slug AS slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NOT NULL AND ${unbacked ? UNBACKED : ACTIVE} AND ${ENTITY_LINKABLE_SQL}
AND ${derivedConversationRow('$2')} ${untried}
GROUP BY f.source_markdown_slug ORDER BY COUNT(*) DESC, f.source_markdown_slug LIMIT $3`, [sourceId, [...AUDIT_ROW_SOURCES], limit]);
return rows.map(r => r.slug);
}
+/** GBRA-574 C1: each page's rows on an unbacked name key, linked when the key now resolves to exactly one readable page. */
+async function planUnbackedPages(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<PagePlan[]> {
+ const rows = await engine.executeRaw<{ id: number | string; fact: string; context: string | null; visibility: FactVisibility; slug: string; attributed_to: FactAttribution | null; entity_slug: string }>(
+ `SELECT f.id, f.fact, f.context, f.visibility, f.source_markdown_slug AS slug, f.attributed_to, f.entity_slug FROM facts f
+ WHERE f.source_id = $1 AND f.source_markdown_slug = ANY($2::text[]) AND ${UNBACKED} AND ${derivedConversationRow('$3')}
+ ORDER BY f.source_markdown_slug, f.id`, [sourceId, slugs, [...AUDIT_ROW_SOURCES]]);
+ const targets = new Map<string, string | null>();
+ const pages = new Map<string, PagePlan>();
+ for (const row of rows) {
+ const page = pages.get(row.slug) ?? { slug: row.slug, link: [], misses: [], notUserAttributed: 0 };
+ pages.set(row.slug, page);
+ if (!entityLinkable(row.attributed_to)) { page.notUserAttributed++; continue; }
+ const cacheKey = `${row.entity_slug}\u0000${row.visibility}`;
+ if (!targets.has(cacheKey)) targets.set(cacheKey, (await resolveStrictEntityReference(engine, sourceId, row.entity_slug.replace(/-/g, ' '),
+ { sameName: true, excludePrivate: row.visibility === 'world' })).slug);
+ const target = targets.get(cacheKey);
+ if (!target) page.misses.push({ id: Number(row.id), reason: 'no_page' });
+ else page.link.push({ id: Number(row.id), fact: row.fact, entity_slug: target, from: row.entity_slug, context: appendContextNote(row.context, 'entity relinked from unbacked') });
+ }
+ return slugs.flatMap(slug => pages.get(slug) ?? []);
+}
+
async function planPages(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<PagePlan[]> {
const rows = await engine.executeRaw<{ id: number | string; fact: string; context: string | null; visibility: FactVisibility; slug: string; attributed_to: FactAttribution | null }>(
`SELECT f.id, f.fact, f.context, f.visibility, f.source_markdown_slug AS slug, f.attributed_to FROM facts f
@@ -107,24 +146,28 @@ async function linkRows(tx: BrainEngine, sourceId: string, slug: string, rows: C
const linked: number[] = [];
const attempts = await hasAttemptsTable(tx);
for (const row of rows) {
+ // A re-keyed row's slot gives way to one its target already holds on the page (facts/ontology-rekey.ts), so the move never collides.
+ if (row.from) await dropRekeyDuplicates(tx, sourceId, { where: `f.id = $2::bigint AND ${UNBACKED}`, entity: '$3::text', sms: 'f.source_markdown_slug',
+ params: [row.id, row.entity_slug] });
const done = await tx.executeRaw<{ id: number | string }>(
`UPDATE facts f SET entity_slug = $4, context = $5 WHERE f.source_id = $1 AND f.id = $2 AND f.source_markdown_slug = $3 AND f.fact = $6
- AND ${ACTIVE} AND ${ENTITY_LINKABLE_SQL} AND ${derivedConversationRow('$7')}
+ AND ${row.from ? `f.entity_slug = $8 AND ${UNBACKED}` : ACTIVE} AND ${ENTITY_LINKABLE_SQL} AND ${derivedConversationRow('$7')}
AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $4 AND p.deleted_at IS NULL) RETURNING f.id`,
- [sourceId, row.id, slug, row.entity_slug, row.context, row.fact, [...AUDIT_ROW_SOURCES]]);
+ [sourceId, row.id, slug, row.entity_slug, row.context, row.fact, [...AUDIT_ROW_SOURCES], ...(row.from ? [row.from] : [])]);
if (!done.length) continue;
linked.push(row.id);
+ const tier = row.from ? 'unbacked' : 'mention';
if (attempts) await tx.executeRaw(
`INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, reason, tier, model, target_slug, run_id, attempted_at)
- VALUES ($1, $2, 'linked', NULL, 'mention', NULL, $3, NULL, now())
- ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = 'linked', reason = NULL, tier = 'mention', model = NULL,
- target_slug = EXCLUDED.target_slug, run_id = NULL, attempted_at = EXCLUDED.attempted_at`, [sourceId, row.id, row.entity_slug]);
+ VALUES ($1, $2, 'linked', NULL, $4, NULL, $3, NULL, now())
+ ON CONFLICT (source_id, fact_id) DO UPDATE SET outcome = 'linked', reason = NULL, tier = EXCLUDED.tier, model = NULL,
+ target_slug = EXCLUDED.target_slug, run_id = NULL, attempted_at = EXCLUDED.attempted_at`, [sourceId, row.id, row.entity_slug, tier]);
}
return linked;
}
function requestIdFor(sourceId: string, slug: string, rows: ConversationRelinkRow[], attempt: number): string {
- const h = digest(['conversation-relink-v1', sourceId, slug, rows.map(r => [r.id, r.entity_slug, r.context]), attempt]);
+ const h = digest(['conversation-relink-v1', sourceId, slug, rows.map(r => [r.id, r.entity_slug, r.context, ...(r.from ? [r.from] : [])]), attempt]);
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
}
@@ -147,12 +190,13 @@ async function publishManaged(engine: BrainEngine, config: GBrainConfig, authori
}
export async function runConversationRelink(engine: BrainEngine, config: GBrainConfig,
- opts: { sourceId: string; slugs?: string[]; dryRun?: boolean }): Promise<ConversationRelinkReport> {
- const slugs = opts.slugs?.length ? opts.slugs : await conversationRelinkPages(engine, opts.sourceId);
- const plans = await planPages(engine, opts.sourceId, slugs);
- const report: ConversationRelinkReport = { source_id: opts.sourceId, dry_run: !!opts.dryRun, pages: [], linked: 0, unresolved: 0, not_user_attributed: 0, changed: 0, reextract_slugs: [] };
+ opts: { sourceId: string; slugs?: string[]; dryRun?: boolean; unbacked?: boolean }): Promise<ConversationRelinkReport> {
+ const slugs = opts.slugs?.length ? opts.slugs : await conversationRelinkPages(engine, opts.sourceId, CONVERSATION_RELINK_PAGES, opts.unbacked);
+ const plans = await (opts.unbacked ? planUnbackedPages : planPages)(engine, opts.sourceId, slugs);
+ const report: ConversationRelinkReport = { source_id: opts.sourceId, dry_run: !!opts.dryRun, ...(opts.unbacked ? { unbacked: true } : {}),
+ pages: [], linked: 0, unresolved: 0, not_user_attributed: 0, changed: 0, reextract_slugs: [] };
const authority = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId);
- const memo = !opts.dryRun && await hasAttemptsTable(engine);
+ const memo = !opts.dryRun && !opts.unbacked && await hasAttemptsTable(engine);
for (const page of plans) {
let linked = page.link.length;
if (!opts.dryRun && page.link.length) {
@@ -181,7 +225,8 @@ export async function prepareConversationRelink(engine: BrainEngine, row: WriteR
const page = intent?.page;
const rows = intent?.rows;
if (row.slug !== CONVERSATION_RELINK_ANCHOR || typeof page !== 'string' || !Array.isArray(rows) || !rows.length
- || rows.some(r => !Number.isSafeInteger(r?.id) || typeof r.fact !== 'string' || typeof r.entity_slug !== 'string' || typeof r.context !== 'string')) {
+ || rows.some(r => !Number.isSafeInteger(r?.id) || typeof r.fact !== 'string' || typeof r.entity_slug !== 'string' || typeof r.context !== 'string'
+ || (r.from !== undefined && typeof r.from !== 'string'))) {
throw opError('invalid_params', 'The conversation relink intent does not name its page and rows.',
`Request ${row.request_id} in source ${row.source_id} does not name the conversation page and the rows it links, so nothing changed. Preview the relink again with gbrain facts relink --conversation --source ${row.source_id} --dry-run.`);
}
diff --git a/src/core/facts/conversation-window-extract.ts b/src/core/facts/conversation-window-extract.ts
index 51e7fc59f2..706f90eed0 100644
--- a/src/core/facts/conversation-window-extract.ts
+++ b/src/core/facts/conversation-window-extract.ts
@@ -11,7 +11,7 @@ import { observationDateFrom, resolveObservationDate, type ObservationDate } fro
import { BudgetExhausted } from '../budget/budget-tracker.ts';
import { deriveDateContext } from '../conversation-parser/parse.ts';
import { resolveStrictEntityReference } from '../entities/resolve.ts';
-import { resolveExtractedEntitiesForSave, type SaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
+import { resolveExtractedEntitiesForSave, unbackedEntityKeysEnabled, type SaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
import { NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from './audit-sources.ts';
import { CONVERSATION_ENTITY_HINTS_CAP } from './conversation-entity-hints.ts';
import { CONVERSATION_FACTS_SOURCE_PREFIX, type ConversationFactRow } from './conversation-publication.ts';
@@ -82,12 +82,14 @@ export async function extractConversationWindow(run: ConversationWindowRun, page
extracted = extraction.facts;
}
// This bulk path bypasses writeSingleFact and writes through insertFacts: every extractor-provided entity goes
- // through the shipped resolver (alias_exact / prefix / fuzzy / slugify) while source scope is known.
+ // through the shipped resolver (alias_exact / prefix / fuzzy / slugify) while source scope is known. GBRA-574: a full
+ // name with no page keeps its name key (facts.unbacked_entity_keys); no page is created.
const raws = extracted.map(fact => fact.entity_slug);
+ const unbacked = await unbackedEntityKeysEnabled(run.engine) ? new Map<number, string>() : undefined;
const resolution = await resolveExtractedEntitiesForSave(run.engine, run.sourceId, extracted, (raw, message) => {
process.stderr.write(`[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} `
+ `entity resolution failed for ${JSON.stringify(raw)}: ${message}; preserving fact without an entity target\n`);
- });
+ }, unbacked);
if (extracted.length === 0) return { extracted: 0, rows: [], resolution };
const visibility = await tightenToStoredPage(run.engine, run.sourceId, run.factVisibility, page);
const rows = await inferConversationSubjects(run.engine, run.sourceId, visibility, extracted.map((fact, i) => ({ // #6764
@@ -100,13 +102,14 @@ export async function extractConversationWindow(run: ConversationWindowRun, page
context: fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,
})));
// GBRA-574: slots come from a second call over facts whose person was named exactly: by identity evidence alone (an
- // exact slug, a unique basename or alias; never a prefix guess or a near name), or by subject inference, which needs
- // one live page named in full. Never on BrainBench's injected extractor.
+ // exact slug, a unique basename or alias; never a prefix guess or a near name), by subject inference, which needs
+ // one live page named in full, or by a name key this window kept (the full name, by construction). Never on
+ // BrainBench's injected extractor.
if (run.extractor) return { extracted: extracted.length, rows, resolution };
const exact: boolean[] = [];
for (const [i, row] of rows.entries()) exact.push(!!row.entity_slug && (!extracted[i]!.entity_slug
|| (await resolveStrictEntityReference(run.engine, run.sourceId, raws[i]!)).slug === row.entity_slug));
- const tagged = await tagSlots(run.engine, run.sourceId, rows, exact, run.signal);
+ const tagged = await tagSlots(run.engine, run.sourceId, rows, exact, run.signal, unbacked);
if (tagged.failed) {
run.result.slot_tagging_failed = (run.result.slot_tagging_failed ?? 0) + 1;
process.stderr.write(`[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso}: slot tagging failed; `
diff --git a/src/core/facts/insert-guard-schema.ts b/src/core/facts/insert-guard-schema.ts
index 03a6bd953a..6bf2e899ac 100644
--- a/src/core/facts/insert-guard-schema.ts
+++ b/src/core/facts/insert-guard-schema.ts
@@ -6,7 +6,8 @@
*
* - Purge refusal (purge-schema.ts `gbrain_refuse_purged_fact`): an inserted
* row whose fingerprint has a fact_purges tombstone for its source,
- * visibility and subject ('*' or its entity_slug) aborts the statement with
+ * visibility and subject ('*' or its entity_slug; any subject for a row on an
+ * unbacked name key, GBRA-574 withdrawal-schema.ts unbackedEntitySql) aborts the statement with
* the same P0001 `purged_content` message and `{table, hash8}` detail,
* whatever its expired_at. When several rows match, the detail names the
* first one in insertion order, as the per-row trigger did.
@@ -16,7 +17,8 @@
* min(withdrawn_at) and valid_until = LEAST(valid_until, withdrawn_at).
* GST-2346: a row on a member page (memory/members/<id>) is stamped only
* by that page's own withdrawals, as in gbrain_preserve_fact_withdrawal
- * (withdrawal-schema.ts).
+ * (withdrawal-schema.ts); GBRA-574: a row on an unbacked name key by a
+ * withdrawal of its claim under any subject.
* By default the per-row BEFORE INSERT trigger facts_preserve_withdrawal_insert
* stamps the row before it is written, so `INSERT ... RETURNING` reads the
* stamp. An insert made under FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING (the
@@ -48,6 +50,7 @@
*/
import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
import { FACT_WITHDRAWAL_STAMP_SETTING } from '../persistence/attribution-schema.ts';
+import { ownedMemorySubjectSql, unbackedEntitySql } from './withdrawal-schema.ts';
export const FACT_INSERT_GUARD_TRIGGER = 'facts_guard_inserted';
/** Transaction-local; 'on' defers the withdrawal stamp of the following inserts to facts_guard_inserted. */
@@ -62,14 +65,14 @@ export const GUARD_OUTCOME_MARKER_SQL = "(i.source IN ('cli:extract-conversation
/** The WITH clause naming, as m, the active inserted facts a withdrawal matches and its earliest withdrawn_at. */
const WITHDRAWN_INSERTS_SQL = `WITH n AS MATERIALIZED (
- SELECT i.id, i.source_id, i.visibility, i.entity_slug, i.source_markdown_slug,
+ SELECT i.id, i.source_id, i.visibility, i.entity_slug, i.source_markdown_slug, ${unbackedEntitySql('i')} AS unbacked,
gbrain_fact_fingerprint(i.fact) AS fact_hash, gbrain_fact_fingerprint_v1(i.fact) AS fact_hash_v1
FROM inserted_facts i WHERE i.expired_at IS NULL),
m AS (
SELECT n.id, min(w.withdrawn_at) AS withdrawn_at FROM n JOIN fact_withdrawals w
ON w.source_id = n.source_id AND w.visibility = n.visibility
- AND w.subject = ANY(CASE WHEN starts_with(COALESCE(n.source_markdown_slug, ''), 'memory/members/') THEN ARRAY[n.source_markdown_slug]
- ELSE ARRAY['*', n.entity_slug] END) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)
+ AND (CASE WHEN starts_with(COALESCE(n.source_markdown_slug, ''), 'memory/members/') THEN w.subject = n.source_markdown_slug
+ ELSE (n.unbacked AND NOT ${ownedMemorySubjectSql('w.subject')}) OR w.subject IN ('*', n.entity_slug) END) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)
GROUP BY n.id)`;
/**
@@ -90,7 +93,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger
FROM inserted_facts i WHERE NOT ${GUARD_OUTCOME_MARKER_SQL})
SELECT n.fact_hash INTO purged FROM n
WHERE EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id = n.source_id AND p.visibility = n.visibility
- AND p.subject IN ('*', n.entity_slug) AND p.fact_hash = n.fact_hash)
+ AND (p.subject IN ('*', n.entity_slug) OR ${unbackedEntitySql('n')}) AND p.fact_hash = n.fact_hash)
ORDER BY n.ord LIMIT 1;
IF purged IS NOT NULL THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
diff --git a/src/core/facts/purge-schema.ts b/src/core/facts/purge-schema.ts
index 856b386f9a..f756278b50 100644
--- a/src/core/facts/purge-schema.ts
+++ b/src/core/facts/purge-schema.ts
@@ -25,6 +25,7 @@
*/
import { requireLedgerPoliciesSql } from '../derived-state-maintainers.ts';
+import { unbackedEntitySql } from './withdrawal-schema.ts';
const RLS = (table: string) => `DO $rls$ BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
@@ -128,7 +129,7 @@ export const REFUSE_PURGED_FACT_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrai
PERFORM id FROM sources WHERE id = NEW.source_id FOR SHARE;
IF EXISTS (SELECT 1 FROM fact_purges
WHERE source_id = NEW.source_id AND visibility = NEW.visibility
- AND (subject = '*' OR subject = NEW.entity_slug)
+ AND (subject = '*' OR subject = NEW.entity_slug OR ${unbackedEntitySql('NEW')})
AND fact_hash = gbrain_fact_fingerprint(NEW.fact)) THEN
RAISE EXCEPTION USING ERRCODE = 'P0001',
MESSAGE = 'purged_content: this claim was purged from this source and cannot be saved again',
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 5a724ac068..ff3b782b7d 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -29,6 +29,7 @@ import { contentHash, rowToPage } from '../utils.ts';
import { rewriteLiveSegmentedFences, rewriteSegmentedGeneration, segmentedBodyContains } from '../page-body/segment-rewrite.ts';
import { continueDerivationPurges, derivationPurgeState, recordDerivationPurge } from '../page-body/segment-derive.ts';
import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
+import { unbackedEntitySql } from './withdrawal-schema.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';
import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';
@@ -167,9 +168,12 @@ export async function stagingsHoldingClaim(engine: BrainEngine, sourceId: string
/** Read-only: everything a purge of `target` would touch. Inside the purge transaction it runs under the source lock. */
export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, allSubjects: boolean): Promise<PurgePlan> {
- const subject = allSubjects ? '*' : target.entity_slug ?? '*';
+ // GBRA-574 A1: a fact on an unbacked name key (no live page) purges source-wide, and every purge of the claim reaches such rows.
+ const unbacked = !allSubjects && !!target.entity_slug && !target.entity_slug.includes('/') && (await engine.executeRaw(
+ 'SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL LIMIT 1', [target.source_id, target.entity_slug])).length === 0;
+ const subject = allSubjects || unbacked ? '*' : target.entity_slug ?? '*';
const facts = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id=$1 AND visibility=$2
- AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) AND NOT ${outcomeMarkerSql('facts')} ORDER BY id`, [target.source_id, target.visibility, target.fact_hash, subject]);
+ AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4 OR ${unbackedEntitySql('facts')}) AND NOT ${outcomeMarkerSql('facts')} ORDER BY id`, [target.source_id, target.visibility, target.fact_hash, subject]);
const factIds = facts.map(f => Number(f.id));
const takes = (await engine.executeRaw<{ id: number; page_id: number }>(`SELECT DISTINCT k.id,k.page_id FROM takes k JOIN pages p ON p.id=k.page_id
WHERE p.source_id=$1 AND (k.id IN (SELECT consolidated_into FROM facts WHERE id=ANY($2::bigint[]) AND consolidated_into IS NOT NULL)
diff --git a/src/core/facts/slot-tagging.ts b/src/core/facts/slot-tagging.ts
index 55190c79db..6f1eb27612 100644
--- a/src/core/facts/slot-tagging.ts
+++ b/src/core/facts/slot-tagging.ts
@@ -1,8 +1,9 @@
/**
* GBRA-574: conversation fact slots, tagged after extraction. The main extraction call never asks for a slot (asking
* cost wishes and preferences); this second, small call reads only the facts the main call produced whose entity is a
- * live person page named exactly (an exact page or alias match, or subject inference), and tags each with at most one
- * slot (facts/slots.ts). A failed call leaves the facts without slots; abort and an exhausted budget propagate.
+ * live person page named exactly (an exact page or alias match, or subject inference) or a name key the window kept
+ * for a full name with no page (facts.unbacked_entity_keys), and tags each with at most one slot (facts/slots.ts). A
+ * failed call leaves the facts without slots; abort and an exhausted budget propagate.
*/
import { chat, isAvailable } from '../ai/gateway.ts';
import { BudgetExhausted } from '../budget/budget-tracker.ts';
@@ -53,23 +54,24 @@ type TaggableRow = { fact: string; kind?: string | null; entity_slug?: string |
/**
* Returns `rows` with a slot on each fact the model tagged (tagged rows are copies). `exact[i]` says row i's entity was
- * named exactly; `called` says a tagging call went out, `failed` that it errored or its reply could not be read.
+ * named exactly; `unbacked` maps a row whose entity is a name key this window kept to the extractor's name for it, which
+ * the call shows in brackets. `called` says a tagging call went out, `failed` that it errored or its reply could not be read.
*/
export async function tagSlots<T extends TaggableRow>(engine: BrainEngine, sourceId: string, rows: T[], exact: readonly boolean[],
- abortSignal?: AbortSignal): Promise<{ rows: T[]; called: boolean; failed: boolean }> {
+ abortSignal?: AbortSignal, unbacked?: ReadonlyMap<number, string>): Promise<{ rows: T[]; called: boolean; failed: boolean }> {
const picked = rows.map((row, i) => ({ row, i }))
- .filter(({ row, i }) => exact[i] && row.entity_slug && SLOT_KINDS.has(row.kind ?? 'fact'))
- .slice(0, SLOT_TAG_MAX_FACTS);
+ .filter(({ row, i }) => (exact[i] || unbacked?.has(i)) && row.entity_slug && SLOT_KINDS.has(row.kind ?? 'fact'));
if (!picked.length) return { rows, called: false, failed: false };
const people = new Map((await engine.executeRaw<{ slug: string; title: string | null }>(
`SELECT slug, title FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = 'person' AND slug = ANY($2::text[]) AND NOT ${retiredPageSql('pages')}`,
[sourceId, [...new Set(picked.map(p => p.row.entity_slug!))]])).map(p => [p.slug, p.title || p.slug]));
- const candidates = picked.filter(p => people.has(p.row.entity_slug!));
+ const named = (p: { row: T; i: number }) => exact[p.i] ? people.get(p.row.entity_slug!) : unbacked?.get(p.i);
+ const candidates = picked.filter(p => named(p)).slice(0, SLOT_TAG_MAX_FACTS);
if (!candidates.length) return { rows, called: false, failed: false };
const model = await getFactsExtractionModel(engine);
if (!isAvailable('chat', model)) return { rows, called: false, failed: false };
- const lines = candidates.map((c, n) => `${n + 1}. [${people.get(c.row.entity_slug!)}] ${c.row.fact.replace(/\s+/g, ' ').slice(0, SLOT_TAG_FACT_CHARS)}`);
+ const lines = candidates.map((c, n) => `${n + 1}. [${named(c)}] ${c.row.fact.replace(/\s+/g, ' ').slice(0, SLOT_TAG_FACT_CHARS)}`);
let text: string;
try {
const result = await chat({ model, system: SLOT_TAG_SYSTEM, messages: [{ role: 'user', content: lines.join('\n') }],
diff --git a/src/core/facts/withdrawal-schema.ts b/src/core/facts/withdrawal-schema.ts
index 5baaf04552..61fd8b600f 100644
--- a/src/core/facts/withdrawal-schema.ts
+++ b/src/core/facts/withdrawal-schema.ts
@@ -49,11 +49,31 @@ export const FACT_FINGERPRINT_FUNCTION_STATEMENTS = [
* ledger rows written earlier carry the exact v1 fingerprint and keep
* matching through gbrain_fact_fingerprint_v1.
*/
+/**
+ * GBRA-574 A1: whether row `r`'s entity is unbacked, as SQL: a bare name key (no directory, the form conversation
+ * extraction keeps for a full name with no page, entities/resolve-on-save.ts) with no live page at that slug in the
+ * row's source (`source`, default `r.source_id`). Withdrawal and purge treat such a fact as subject '*': forgetting or
+ * purging it is source-wide, and a withdrawal or tombstone of its claim under any subject reaches it, so a later page or
+ * re-key never brings a forgotten claim back. Spelled here so the guards import no module outside the schema inputs.
+ */
+export function unbackedEntitySql(r: string, source = `${r}.source_id`): string {
+ return `COALESCE(strpos(${r}.entity_slug, '/') = 0 AND NOT EXISTS (SELECT 1 FROM pages unbacked_page
+ WHERE unbacked_page.source_id = ${source} AND unbacked_page.slug = ${r}.entity_slug AND unbacked_page.deleted_at IS NULL), false)`;
+}
+
+/**
+ * GBRA-574: whether withdrawal subject `subject` (SQL) is an owned memory page (a member page or the scope page). Such a
+ * withdrawal stays on that page (GST-359 D, GST-2346), so it never reaches a row on an unbacked name key.
+ */
+export function ownedMemorySubjectSql(subject: string): string {
+ return `(starts_with(${subject}, 'memory/members/') OR ${subject} = 'memory/scope')`;
+}
+
/**
* The insert and update guard that stamps a row matching a withdrawal as withdrawn. GST-2346: a row on a member page
* (memory/members/<id>) matches only that page's own withdrawals: it is its member's own, a withdrawal made later still expires it, and the member's
* save checks the withdrawals of claims that member reads (facts/single-prepare.ts), so a claim it never read cannot
- * expire the row it saves. #7632/#7659: a writing role that RLS keeps from reading fact_withdrawals is refused
+ * expire the row it saves. GBRA-574: a row on an unbacked name key matches a withdrawal of its claim under any subject but an owned memory page. #7632/#7659: a writing role that RLS keeps from reading fact_withdrawals is refused
* (derived-state-maintainers.ts requireLedgerPoliciesSql) instead of saving the row active. Re-created alone by the
* member_page_withdrawal_scope and guard_ledgers_fail_closed migrations.
*/
@@ -69,7 +89,7 @@ export const FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION
SELECT min(withdrawn_at) INTO withdrawn FROM fact_withdrawals
WHERE source_id = NEW.source_id AND visibility = NEW.visibility
AND (CASE WHEN starts_with(COALESCE(NEW.source_markdown_slug, ''), 'memory/members/') THEN subject = NEW.source_markdown_slug
- ELSE subject = '*' OR subject = NEW.entity_slug END)
+ ELSE subject = '*' OR subject = NEW.entity_slug OR (${unbackedEntitySql('NEW')} AND NOT ${ownedMemorySubjectSql('subject')}) END)
AND fact_hash IN (gbrain_fact_fingerprint(NEW.fact), gbrain_fact_fingerprint_v1(NEW.fact));
IF withdrawn IS NOT NULL THEN
NEW.expired_at := withdrawn;
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index ebd9005de8..be879664e4 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -11,6 +11,7 @@ import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '.
import { createPageVersion } from '../page-state/versions.ts';
import { validateSlug } from '../utils.ts';
import { factWithdrawalSubjectSql, onOwnedMemoryPageSql } from '../access/member-facts.ts';
+import { ownedMemorySubjectSql, unbackedEntitySql } from './withdrawal-schema.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -81,7 +82,7 @@ export async function planFactWithdrawal(engine: BrainEngine, id: number, source
const affected = existing ? [] : await discoverWithdrawalTargets(engine, sourceId, [{ visibility, fact_hash, subject, claim: fact }]).catch(withdrawalDiscoveryFailure);
// The belief ledger's streams of the facts this withdrawal expires (fence pages and database-only subjects), locked with the pages.
const streams = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts
- WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4 OR (${onOwnedMemoryPageSql('facts')} AND source_markdown_slug=$4)) AND expired_at IS NULL
+ WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4 OR (${unbackedEntitySql('facts')} AND NOT ${ownedMemorySubjectSql('$4::text')}) OR (${onOwnedMemoryPageSql('facts')} AND source_markdown_slug=$4)) AND expired_at IS NULL
AND COALESCE(source_markdown_slug, entity_slug) IS NOT NULL`, [sourceId, visibility, fact_hash, subject]))
.map(r => r.slug).filter(slug => { try { validateSlug(slug); return true; } catch { return false; } });
const slugs = [...new Set([...affected.map(page => page.slug), ...streams])].sort();
@@ -133,12 +134,13 @@ export async function recordFactWithdrawal(
return batch(async () => {
// Scoped to the forgotten row's entity: the same claim about another
// entity stays active and rememberable. A subjectless fact withdraws
- // source-wide ('*').
+ // source-wide ('*'), and so does one on an unbacked name key (GBRA-574),
+ // whose rows every withdrawal of the claim reaches, except one on an owned memory page.
const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash,withdrawn_at)
VALUES ($1,$2,$4,gbrain_fact_fingerprint($3),COALESCE($5::timestamptz,now())) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject,opts.publication?.withdrawnAt ?? null]);
const expired = await tx.executeRaw<{ id: number }>(`UPDATE facts SET expired_at=now(),valid_until=LEAST(COALESCE(valid_until,now()),now())
WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
- AND ($4='*' OR entity_slug=$4 OR ${pageScoped}) AND expired_at IS NULL RETURNING id`, [sourceId,row.visibility,row.fact,row.subject]);
+ AND ($4='*' OR entity_slug=$4 OR (${unbackedEntitySql('facts')} AND NOT ${ownedMemorySubjectSql('$4::text')}) OR ${pageScoped}) AND expired_at IS NULL RETURNING id`, [sourceId,row.visibility,row.fact,row.subject]);
noteBelief({ kind: 'withdrawn', factIds: expired.map(r => Number(r.id)) });
if (!inserted.length) return { withdrawn: false, pages: [] };
// Overnight semantic review (decide review lane): queued with the ledger row so a late commit is never skipped.
diff --git a/src/core/guard-ledger-checks.ts b/src/core/guard-ledger-checks.ts
index 4e9dd6be05..7485bd6b34 100644
--- a/src/core/guard-ledger-checks.ts
+++ b/src/core/guard-ledger-checks.ts
@@ -14,40 +14,51 @@ import { REFUSE_PURGED_FACT_FUNCTION_SQL, REFUSE_PURGED_PAGE_FUNCTION_SQL, REFUS
import { FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL } from './facts/withdrawal-schema.ts';
import { DERIVATION_SCOPE_ENTRY_FUNCTION_SQL, REFUSE_PURGING_DERIVATION_FUNCTION_SQL } from './page-body/schema.ts';
-/** Each guard, the ledger whose check marks its current body, and that body. */
-const LEDGER_GUARDS: ReadonlyArray<{ name: string; ledger: string; sql: string }> = [
- { name: 'gbrain_refuse_purged_fact', ledger: 'fact_purges', sql: REFUSE_PURGED_FACT_FUNCTION_SQL },
+/**
+ * Each guard, the ledger whose check marks its current body, that body, and for a guard a later migration changed again
+ * a text only its current body holds (GBRA-574 v321: the facts guards' name-key branch), so the migration run of a role
+ * that owns it re-creates it too.
+ */
+const LEDGER_GUARDS: ReadonlyArray<{ name: string; ledger: string; sql: string; marker?: string }> = [
+ { name: 'gbrain_refuse_purged_fact', ledger: 'fact_purges', sql: REFUSE_PURGED_FACT_FUNCTION_SQL, marker: 'unbacked_page' },
{ name: 'gbrain_refuse_purged_take', ledger: 'take_purges', sql: REFUSE_PURGED_TAKE_FUNCTION_SQL },
{ name: 'gbrain_refuse_purged_page', ledger: 'page_purges', sql: REFUSE_PURGED_PAGE_FUNCTION_SQL },
- { name: 'gbrain_preserve_fact_withdrawal', ledger: 'fact_withdrawals', sql: FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL },
- { name: 'gbrain_guard_inserted_facts', ledger: 'fact_withdrawals', sql: FACT_INSERT_GUARD_FUNCTION_SQL },
+ { name: 'gbrain_preserve_fact_withdrawal', ledger: 'fact_withdrawals', sql: FACT_WITHDRAWAL_PRESERVE_FUNCTION_SQL, marker: 'memory/scope' },
+ { name: 'gbrain_guard_inserted_facts', ledger: 'fact_withdrawals', sql: FACT_INSERT_GUARD_FUNCTION_SQL, marker: 'memory/scope' },
{ name: 'gbrain_mark_derivation_scope_entry', ledger: 'page_segment_derivation_purges', sql: DERIVATION_SCOPE_ENTRY_FUNCTION_SQL },
{ name: 'gbrain_refuse_purging_derivation', ledger: 'page_segment_derivation_purges', sql: REFUSE_PURGING_DERIVATION_FUNCTION_SQL },
];
+/** A guard body without its ledger check, or without its marker. */
+const STALE_GUARD_SQL = `(strpos(p.prosrc, 'row_security_active(''' || g.ledger || ''')') = 0 OR (g.marker <> '' AND strpos(p.prosrc, g.marker) = 0))`;
+
+function guardParams(): [string[], string[], string[]] {
+ return [LEDGER_GUARDS.map(g => g.name), LEDGER_GUARDS.map(g => g.ledger), LEDGER_GUARDS.map(g => g.marker ?? '')];
+}
+
/**
- * Every installed guard whose body lacks its ledger check (regprocedure text and schema-qualified signature), the role
+ * Every installed guard whose body lacks its ledger check or its marker (regprocedure text and schema-qualified signature), the role
* that owns it, whether the current role may re-create it, and the current role. Read-only (doctor guard_ledger_checks).
*/
export async function ledgerGuardsWithoutCheck(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Array<{ sig: string; qualified: string; owner: string; owned: boolean; role: string }>> {
return engine.executeRaw(
`SELECT p.oid::regprocedure::text AS sig, quote_ident(n.nspname) || '.' || quote_ident(p.proname) || '(' || oidvectortypes(p.proargtypes) || ')' AS qualified,
pg_get_userbyid(p.proowner)::text AS owner, pg_has_role(current_user, p.proowner, 'USAGE') AS owned, quote_ident(current_user) AS role
- FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN unnest($1::text[], $2::text[]) AS g(name, ledger) ON g.name = p.proname
- WHERE n.nspname = 'public' AND p.prokind = 'f' AND strpos(p.prosrc, 'row_security_active(''' || g.ledger || ''')') = 0 ORDER BY 1`,
- [LEDGER_GUARDS.map(g => g.name), LEDGER_GUARDS.map(g => g.ledger)]);
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN unnest($1::text[], $2::text[], $3::text[]) AS g(name, ledger, marker) ON g.name = p.proname
+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND ${STALE_GUARD_SQL} ORDER BY 1`,
+ guardParams());
}
/**
- * Re-creates every installed guard whose body lacks its ledger check and that the current role may replace, and returns
- * the ones another role owns (regprocedure text) with the current role, for the message naming them.
+ * Re-creates every installed guard whose body lacks its ledger check or its marker and that the current role may replace,
+ * and returns the ones another role owns (regprocedure text) with the current role, for the message naming them.
*/
export async function failClosedLedgerGuards(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ left: string[]; role: string }> {
const rows = await engine.executeRaw<{ name: string; sig: string; owned: boolean; role: string }>(
`SELECT p.proname AS name, p.oid::regprocedure::text AS sig, pg_has_role(current_user, p.proowner, 'USAGE') AS owned, current_user::text AS role
- FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN unnest($1::text[], $2::text[]) AS g(name, ledger) ON g.name = p.proname
- WHERE n.nspname = 'public' AND p.prokind = 'f' AND strpos(p.prosrc, 'row_security_active(''' || g.ledger || ''')') = 0 ORDER BY 1`,
- [LEDGER_GUARDS.map(g => g.name), LEDGER_GUARDS.map(g => g.ledger)]);
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN unnest($1::text[], $2::text[], $3::text[]) AS g(name, ledger, marker) ON g.name = p.proname
+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND ${STALE_GUARD_SQL} ORDER BY 1`,
+ guardParams());
const left: string[] = [];
for (const row of rows) {
if (!row.owned) { left.push(row.sig); continue; }
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index f6753362d3..6ab1162ba4 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -61,6 +61,7 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidance
saved_facts_withheld: { why: 'saved facts could not be checked for third-party text to quote, so they were withheld; the page results are complete', fix: 'doctor' },
fact_observed_date_unavailable: { why: 'when saved facts were said could not be read, so their date headers show observed unknown; that is not evidence the date is unknown', fix: 'doctor' },
contested_unavailable: { why: 'whether saved facts are disputed by another saved fact could not be checked, so no fact row carries a contested label; that is not evidence none is disputed', fix: 'doctor' },
+ facts_history_unavailable: { why: 'the saved values a history question asks about (every job title, employer or city of the named person or company) could not be read, so the facts block may be missing some; that is not evidence the brain has none', fix: 'doctor' },
deadline: { why: 'the pack hit its time limit and is partial', fix: null },
server_budget: { why: 'the server ran out of time budget for this pack', fix: null },
no_query_terms: { why: 'the question has no searchable words and semantic search did not run, so no saved fact could be ranked against it', fix: 'embeddings' },
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
index 0419dce93f..d9fe833085 100644
--- a/src/core/mentions/pass.ts
+++ b/src/core/mentions/pass.ts
@@ -55,7 +55,7 @@ import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import { pipelined } from '../page-state/transactions.ts';
import { isCrossSourceLinksEnabled } from '../link-extraction.ts';
import {
- buildGazetteer, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,
+ buildGazetteer, entryNameNorm, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,
type FindMentionsOpts, type Gazetteer, type GazetteerEntry, type GazetteerEntryKey, type Mention,
} from '../by-mention.ts';
import { bodyBlocks, detachedValue } from '../page-body/segment-blocks.ts';
@@ -464,7 +464,7 @@ function miniGazetteer(gazetteer: Gazetteer, keys: Set<string>): Gazetteer {
function entryKey(e: GazetteerEntry | GazetteerEntryKey): string {
if ('target_slug' in e) return `${e.source_id}\0${e.name_norm}\0${e.target_slug}\0${e.case_sensitive}`;
- return `${e.source_id}\0${(e.caseTokens ?? e.tokens).join(' ')}\0${e.slug}\0${!!e.caseTokens}`;
+ return `${e.source_id}\0${entryNameNorm(e)}\0${e.slug}\0${!!e.caseTokens}`;
}
/**
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index a704e41f7f..6bed1a8aac 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -497,7 +497,7 @@ async function buildRetrievalResponseMeta(
if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });
if (quotedFacts === null && visible.length) degraded.push({ stage: 'saved_facts_withheld' });
if ((results as SearchResult[]).some(r => r.fact_row?.observed_unavailable)) degraded.push({ stage: 'fact_observed_date_unavailable' });
- if ((results as SearchResult[]).some(r => r.fact_row?.contested_unavailable)) degraded.push({ stage: 'contested_unavailable' });
+ for (const [flag, stage] of [['contested_unavailable', 'contested_unavailable'], ['history_unavailable', 'facts_history_unavailable']] as const) if ((results as SearchResult[]).some(r => r.fact_row?.[flag])) degraded.push({ stage });
if (readiness.status === 'by_design') degraded.push({ stage: 'projection_by_design' });
else if (readiness.status !== 'ready') {
degraded.push({ stage: readiness.status === 'projection_pending' ? 'projection_pending' : 'projection_status_unknown' });
diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.ts
index 64d5744fcb..13333fc85b 100644
--- a/src/core/persistence/forget-prepare.ts
+++ b/src/core/persistence/forget-prepare.ts
@@ -28,6 +28,7 @@ import { materializedPage } from './segmented-apply.ts';
import { prepareFileTarget, snapshotLedger, unreadPageFile } from './page-prepare.ts';
import { pageIdentityError } from './page-identity.ts';
import { MEMBER_PAGE_PREFIX, onOwnedMemoryPageSql } from '../access/member-facts.ts';
+import { unbackedEntitySql } from '../facts/withdrawal-schema.ts';
import { storedOwnerSpeaksForItself } from './page-visibility.ts';
import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';
import type { WriteAuthority, WriteRequest } from './model.ts';
@@ -40,15 +41,18 @@ interface ForgetTarget { id: number; entity_slug: string | null; trust_tier?: st
* A fact saved without an entity says nothing about whom it concerns, so its
* withdrawal reaches the claim under every entity. When that claim is active
* on entity-linked facts, forgetting the unlinked copy would silently withdraw
- * them too, and a withdrawn claim cannot be remembered again; refuse and name them.
+ * them too, and a withdrawn claim cannot be remembered again; refuse and name them. GBRA-574: a fact on an unbacked
+ * name key withdraws source-wide the same way, so it is checked against every other entity's copy.
* A caller that cannot read private pages never withdraws an active copy it
* cannot see: the refusal is then one fixed text that names no fact.
*/
export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId: string, fact: ForgetTarget, remote: boolean, excludePrivate: boolean): Promise<void> {
const id = fact.id;
- if (fact.entity_slug === null) {
+ const unbacked = fact.entity_slug !== null && (await tx.executeRaw<{ unbacked: boolean }>(
+ `SELECT ${unbackedEntitySql('u')} AS unbacked FROM facts u WHERE u.id=$1 AND u.source_id=$2`, [id, sourceId]))[0]?.unbacked === true;
+ if (fact.entity_slug === null || unbacked) {
const linked = await tx.executeRaw<{ id: number; entity_slug: string }>(`SELECT l.id,l.entity_slug FROM facts u
- JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.entity_slug IS NOT NULL AND l.id<>u.id
+ JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.entity_slug IS NOT NULL AND l.entity_slug IS DISTINCT FROM u.entity_slug AND l.id<>u.id
AND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now())
AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(u.fact)
WHERE u.id=$1 AND u.source_id=$2 AND ($3::boolean=false OR l.visibility='world')${excludePrivate ? ` AND ${remoteProvenanceFloorSql('l')}` : ''}
@@ -56,14 +60,14 @@ export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId:
if (linked.length) {
const named = linked.map(row => `#${row.id} (${row.entity_slug})`).join(', ');
throw verbError('invalid_params',
- `claim_linked: fact #${id} was saved without an entity, and the same claim is active as ${named}. Forgetting #${id} would withdraw those facts too, so nothing was forgotten.`,
+ `claim_linked: fact #${id} was saved ${unbacked ? `on the name tag ${fact.entity_slug}, which has no page` : 'without an entity'}, and the same claim is active as ${named}. Forgetting #${id} would withdraw those facts too, so nothing was forgotten.`,
`Keep the linked ${linked.length === 1 ? 'fact' : 'facts'}: the copy without an entity needs no cleanup (remember the claim with entity and replaces: "${id}" retires it). To withdraw the claim everywhere, forget ${linked.map(row => `#${row.id}`).join(', ')} first, then #${id}.`);
}
}
if (!excludePrivate) return;
const hidden = await tx.executeRaw(`SELECT 1 FROM facts u
JOIN facts l ON l.source_id=u.source_id AND l.visibility=u.visibility AND l.id<>u.id
- AND (u.entity_slug IS NULL OR l.entity_slug=u.entity_slug)
+ AND (u.entity_slug IS NULL OR ${unbackedEntitySql('u')} OR l.entity_slug=u.entity_slug)
AND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now())
AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(u.fact)
WHERE u.id=$1 AND u.source_id=$2 AND NOT (${remoteProvenanceFloorSql('l')}) LIMIT 1`, [id, sourceId]);
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index a71d30ecd8..e3a3af441f 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -35,7 +35,7 @@ import { perCallWriteSource } from '../access/attest-sources.ts';
import { isGitCheckoutRoot } from '../git-checkout.ts';
import { entityPageMissingNotice } from '../interop-notices.ts';
-import { ownerSpeaksForItself } from '../access/member-facts.ts';
+import { otherMemberSubject, ownerSpeaksForItself, peoplePageMember } from '../access/member-facts.ts';
import { isDerivationPrivate } from '../search/private-visibility.ts';
import { refuseGuestSourceWrite } from '../guests/admission.ts';
@@ -277,6 +277,8 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
p.share === true ? 'Share it on a page every reader of this source can read, or drop share to keep the fact on your own page.'
: 'Share it on a page every reader of this source can read, or pass visibility "private" to keep the fact on your own page.'), { reason: 'share_target_restricted' });
}
+ // GST-2897 B: a member's share about another enabled member is stored private until the brain owner confirms it.
+ const heldFor = p.share === true && ownPage !== null && !ownerSpeaksForItself(ctx) ? await otherMemberSubject(ctx.engine, entitySlug) : null;
const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility, entity_slug: entitySlug, ...(memberPage ? { page_slug: memberPage } : {}) };
// Fail fast on an invalid target or a withdrawn claim; the coordinator re-checks both under its locks before publishing.
if (p.replaces !== undefined && p.replaces !== null) {
@@ -292,7 +294,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: typeof p.valid_from === 'string' ? new Date(p.valid_from).toISOString() : new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}), ...(scopePage ? { scope_page: true } : memberPage ? { member_page: true } : {}),
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),
- session_id: ctx.sessionId ?? null },
+ session_id: ctx.sessionId ?? null, share_held: heldFor ?? undefined },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null, deferrable: true });
const written = await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs);
const response = throwIfHeld(withRememberTarget(row, () => writeResponse(written)));
@@ -320,7 +322,7 @@ async function rememberLanded<T extends Record<string, unknown>>(ctx: OperationC
ctx.emitNotice?.(entityPageMissingNotice(row.source_id, intent.entity_slug));
}
}
- return { ...response, ...(intent?.fence === true ? { page: row.slug } : {}), ...(intent?.visibility === 'world' || intent?.visibility === 'private' ? { visibility: intent.visibility } : {}) };
+ return { ...response, ...(intent?.fence === true ? { page: row.slug } : {}), ...(response.held ? { visibility: 'private' } : intent?.visibility === 'world' || intent?.visibility === 'private' ? { visibility: intent.visibility } : {}) };
}
/**
@@ -405,7 +407,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
: `Fact #${rawId} is not on your member page ${ownPage}, so this credential cannot withdraw it. Nothing was forgotten.`,
ownerSpeaksForItself(ctx)
? `The brain owner's credential withdraws shared facts, facts on its member page and other facts it reads on pages it can write. The brain host withdraws this one with gbrain forget ${rawId}.`
- : `A member credential withdraws only the facts on its own member page. The brain host withdraws this one with gbrain forget ${rawId}.`);
+ : `A member credential withdraws the facts on its own member page and the shared facts about itself (its people/${member} page). The brain host withdraws this one with gbrain forget ${rawId}.`);
let ownerReach = false;
if (ownPage && !mine) {
// #9101: a fact the caller reads (one it shared, or a teammate's shared fact) is refused by name; a fact it cannot read stays not_found.
@@ -422,7 +424,10 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
ownerReach = ownerSpeaksForItself(ctx) && await ownerReachesFact(ctx.engine, id, sourceId, { identity: access.identity, satisfied: access.satisfiedRuleIds })
&& (reads || await readsUnder(''));
if (!reads && !ownerReach) throw missing();
- if (!ownerReach) throw hostWithdraws();
+ // GST-2897 B: a member withdraws a shared fact it reads about itself (its people page), as any remote caller does.
+ const subject = !ownerReach && reads && peoplePageMember((await ctx.engine.executeRaw<{ entity_slug: string | null }>(
+ 'SELECT entity_slug FROM facts WHERE id=$1 AND source_id=$2', [id, sourceId]))[0]?.entity_slug) === member;
+ if (!ownerReach && !subject) throw hostWithdraws();
ownPage = null;
}
// The owner's withdrawal judged the fact itself (ownerReachesFact) and never reaches a copy on a page kept from remote writers.
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 418cb24ef1..234b3bbbb0 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -16,7 +16,7 @@ import { requestChannelTrust } from '../trust/channel.ts';
import { gateField, gateInput, heldOutcome, loadWriteGateConfig } from '../trust/gate-outcomes.ts';
import { decideFactWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';
import { writeGateRejectedError } from '../write-gate.ts';
-import { lexicalContestCandidate, recordContestedFact, restatedPrivateCopy, supersessionGuarded } from '../trust/supersede-handlers.ts';
+import { lexicalContestCandidate, recordContestedFact, recordHeldShare, restatedPrivateCopy, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { storedTrustTier } from '../trust/tier.ts';
import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';
import { prepareFenceFactAppend, prepareFenceFactCreate, prepareFenceRowRetirement, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';
@@ -129,7 +129,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
// #5575 I3: a lower-tier write never supersedes; it is inserted contested and the owner decides (re-checked under lock by validate).
const writerTier = requestChannelTrust(row)?.tier ?? 'unknown';
const contested = decision.status === 'superseded' && supersessionGuarded(writerTier, decision.candidate!.trust_tier);
- const status = contested ? 'inserted' : decision.status;
+ // GST-2897 B: a member's share about another member (submitRememberMutation records the member) is stored private and
+ // supersedes nothing until the brain owner confirms it.
+ const heldFor = p.share === true && typeof p.share_held === 'string' && input.visibility === 'world' ? p.share_held : null;
+ const status = contested || heldFor ? 'inserted' : decision.status;
// Without a fact vector the slot has no cosine; a lexical same-subject match still contests a more trusted fact (never supersedes).
const lexical = (tx: BrainEngine) => decision.status === 'inserted' && !dedupEmbedding && replaces === null ? lexicalContestCandidate(tx, row.source_id, input, writerTier) : Promise.resolve(null);
const lexicalOld = await lexical(engine);
@@ -137,7 +140,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
// GST-2875: a world write restating a more trusted private claim is stored private; its proposal carries the widening.
const restated = (tx: BrainEngine) => decision.status !== 'duplicate' && input.visibility === 'world' ? restatedPrivateCopy(tx, row.source_id, input.fact, input.entity_slug, writerTier) : Promise.resolve(null);
const restatedOld = await restated(engine);
- const widening = restatedOld ? { from: restatedOld.visibility, to: 'world' } : null;
+ const widening = restatedOld ? { from: restatedOld.visibility, to: 'world' } : heldFor ? { from: 'private', to: 'world' } : null;
const validate = async (tx: BrainEngine) => {
await assertFactNotWithdrawn(tx, row.source_id, input, { excludePrivate, remote: row.authority.remote === true });
if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict(row);
@@ -204,14 +207,16 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const contestedBy = contestedOld ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: contestedOld.id,
oldTier: storedTrustTier(contestedOld.trust_tier), newId: id, newTier: writerTier,
guard: replaces !== null ? 'remember.replaces' : contested ? 'conflict_slot' : 'conflict_slot_lexical',
- ...(widening && restatedOld!.id === contestedOld.id ? { visibility: widening, pageless: !fence } : {}) }) : null;
+ ...(widening && restatedOld?.id === contestedOld.id ? { visibility: widening, pageless: !fence } : {}) }) : null;
const widenedBy = restatedOld && restatedOld.id !== contestedOld?.id ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: restatedOld.id,
oldTier: restatedOld.trust_tier, newId: id, newTier: writerTier, guard: 'remember.restated_private', visibility: widening!, pageless: !fence }) : null;
+ const held = heldFor && !restatedOld ? await recordHeldShare(tx, { sourceId: row.source_id, factId: id, tier: writerTier, member: heldFor, pageless: !fence }) : null;
const flagged = gateField(gate.assessment, `f${id}`, await recordFlaggedRow(tx, gate, { table: 'facts', id, sourceId: row.source_id }));
const superseded = status === 'superseded' ? decision.candidate! : undefined;
return { ...outcome(id, status, input.entity_slug, validUntil, degraded, p, superseded?.id,
superseded !== undefined && superseded.entity_slug == null && input.entity_slug !== null), ...claimColumns(p), ...fence?.fencesNormalized,
...(contestedBy ?? widenedBy ? { contested: contestedBy ?? widenedBy } : {}), ...(flagged ? { gate: flagged } : {}),
+ ...(held ? { status_text: `held as fact #${id}: it is about member ${held.member}, so it stays private until the brain owner shares it (gbrain trust confirm ${held.proposal_ref})`, held } : {}),
...(pageReceipt?.size_state ? { size_state: pageReceipt.size_state } : {}) };
} };
}
diff --git a/src/core/repair/open-facts.ts b/src/core/repair/open-facts.ts
index d2c51c19d0..eabe92f65a 100644
--- a/src/core/repair/open-facts.ts
+++ b/src/core/repair/open-facts.ts
@@ -98,7 +98,7 @@ export function openFactsReasonSql(f: string): string {
OR EXISTS (SELECT 1 FROM fact_purges x WHERE x.source_id = ${f}.source_id AND x.fact_hash = gbrain_fact_fingerprint(${f}.fact)
AND (x.subject = '*' OR x.subject = ${f}.entity_slug)) THEN 'withdrawn'
WHEN EXISTS (SELECT 1 FROM trust_proposals tp WHERE ((tp.target_table = 'facts' AND tp.target_id = ${f}.id) OR (tp.related_table = 'facts' AND tp.related_id = ${f}.id))
- AND (tp.status = 'pending' OR (tp.action = 'supersede_fact' AND tp.status IN ('rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL))) THEN 'contested'
+ AND (tp.status = 'pending' OR (tp.action IN ('supersede_fact', 'confirm') AND tp.status IN ('rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL))) THEN 'contested'
${factPageReasons(f).map(([reason, condition]) => `WHEN ${condition} THEN '${reason}'`).join('\n ')}
ELSE NULL END)`;
}
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 34c82f3732..6b40edfd4c 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 320;
+export const LATEST_SCHEMA_VERSION = 321;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 9b46163728..352f5a4f17 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -321,6 +321,7 @@ import { v317 } from './v317-pages-projection-waiting-index.ts';
import { v318 } from './v318-guard-ledgers-fail-closed.ts';
import { v319 } from './v319-principal-private-facts.ts';
import { v320 } from './v320-owner-only-lineage.ts';
+import { v321 } from './v321-unbacked-entity-keys-guards.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -640,4 +641,5 @@ export const MIGRATIONS: Migration[] = [
v318,
v319,
v320,
+ v321,
];
diff --git a/src/core/schema-migrations/v321-unbacked-entity-keys-guards.ts b/src/core/schema-migrations/v321-unbacked-entity-keys-guards.ts
new file mode 100644
index 0000000000..ef0d142c4a
--- /dev/null
+++ b/src/core/schema-migrations/v321-unbacked-entity-keys-guards.ts
@@ -0,0 +1,27 @@
+import type { Migration } from './types.ts';
+import { failClosedLedgerGuards } from '../guard-ledger-checks.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-574 A1: conversation extraction now keeps a name key (a bare slug such as alice-example, no page) on a fact
+// whose person or company has no page (facts.unbacked_entity_keys). The three facts guards treat a row on such a key
+// (no directory, no live page at that slug in its source) as subject '*': a withdrawal or purge tombstone of its claim
+// under any subject but an owned memory page expires or refuses it, so a claim forgotten under a page that is later
+// deleted, or forgotten under the key before a page was written, never comes back under the key. Rows with a page or no
+// entity match as before. Replaces only the functions: their triggers already call them, and re-creating a trigger would
+// take an ACCESS EXCLUSIVE lock on facts. Like v318, a guard another role owns is left and named on stderr, never an
+// abort; every later migration run re-creates it once a role that owns it runs (failClosedLedgerGuards reads each
+// guard's marker). No row is read or written.
+export const v321: Migration = {
+ version: 321,
+ name: 'unbacked_entity_keys_guards',
+ idempotent: true,
+ sql: '',
+ handler: async engine => {
+ const { left, role } = await failClosedLedgerGuards(engine);
+ if (left.length === 0) return;
+ process.stderr.write(` guards: ${left.length} purge or withdrawal guard(s) keep their body from before name keys (${left.join(', ')}): `
+ + `CREATE OR REPLACE FUNCTION needs the owner. As that role run ALTER FUNCTION public.<name>() OWNER TO ${role}, or connect gbrain as it; the next migration run re-creates them (docs/ENGINES.md#purge-and-withdrawal-guards).\n`);
+ },
+};
diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.ts
index 18a3b5c188..30ed6b0847 100644
--- a/src/core/search/fact-relevance.ts
+++ b/src/core/search/fact-relevance.ts
@@ -363,18 +363,32 @@ export async function countUncomparableFacts(engine: BrainEngine, scope: FactPoo
* the pool's read policy, so a row the caller cannot see never shapes a window the caller sees; ordered by valid_from, id.
* A row whose stored valid_until has passed still ends the value before it; withdrawn and superseded rows never do.
*/
-export async function readSlotRows(engine: BrainEngine, scope: FactPoolScope, slots: ReadonlyArray<{ source_id: string; entity_slug: string; dimension: string }>): Promise<SlotRow[]> {
+export async function readSlotRows(engine: BrainEngine, scope: FactPoolScope, slots: ReadonlyArray<{ source_id: string; entity_slug: string; dimension: string }>): Promise<Array<SlotRow & Omit<FactCandidate, 'entity'>>> {
if (!slots.length) return [];
const { where, params } = poolPredicate(scope, { includeExpired: true });
const n = params.length;
- return engine.executeRaw<SlotRow>(
- `SELECT f.id, f.source_id, f.entity_slug, f.dimension, f.value_hash, f.valid_from, f.source_markdown_slug, f.fact FROM facts f
+ return engine.executeRaw<SlotRow & Omit<FactCandidate, 'entity'>>(
+ `SELECT ${COLS} FROM facts f
WHERE ${where} AND f.expired_at IS NULL AND f.superseded_by IS NULL AND f.dimension IS NOT NULL AND f.value_hash IS NOT NULL AND COALESCE(f.dim_status, 'active') = 'active' AND ${CONVERSATION_SLOT_SQL}
AND (f.source_id, f.entity_slug, f.dimension) IN (SELECT * FROM unnest($${n + 1}::text[], $${n + 2}::text[], $${n + 3}::text[]))
ORDER BY f.valid_from, f.id`,
[...params, slots.map(s => s.source_id), slots.map(s => s.entity_slug), slots.map(s => s.dimension)]);
}
+/**
+ * GBRA-574 F (D1): the distinct (source_id, entity_slug) pairs among `keys` that hold an active fact in the pool under
+ * its read policy and have no live page at that slug (an unbacked name key), at most `limit`, by source then slug.
+ */
+export async function poolUnbackedKeys(engine: BrainEngine, scope: FactPoolScope, keys: readonly string[], limit: number): Promise<Array<{ source_id: string; entity_slug: string }>> {
+ if (!keys.length) return [];
+ const { where, params } = poolPredicate(scope, undefined);
+ const n = params.length;
+ return engine.executeRaw<{ source_id: string; entity_slug: string }>(
+ `SELECT DISTINCT f.source_id, f.entity_slug FROM facts f WHERE ${where} AND f.entity_slug = ANY($${n + 1}::text[])
+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.entity_slug AND p.deleted_at IS NULL)
+ ORDER BY f.source_id, f.entity_slug LIMIT $${n + 2}`, [...params, [...keys], limit]);
+}
+
/** GBRA-574 B5: what marks a later fact as calling an earlier one off: saved-facts-match.ts's RETRACTION plus plain cancellation words. Fixed, never configurable. */
const CALLED_OFF = String.raw`rumour|rumor|called off|cancelled|canceled|fell through|not happening|never happened|no longer planned`;
const CALL_OFF_SQL = String.raw`\m(${RETRACTION}|${CALLED_OFF})\M`;
diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.ts
index fb148b9e13..07d6cd221e 100644
--- a/src/core/search/facts-arm.ts
+++ b/src/core/search/facts-arm.ts
@@ -20,8 +20,8 @@
import type { BrainEngine } from '../engine.ts';
import type { PageReadScope, SearchResult } from '../types.ts';
import { resolveExcludePrivatePages, worldOnlyFacts } from './private-visibility.ts';
-import { admitted, collectFactCandidates, FACTS_ARM_COSINE_MIN, laterRetractions, queryTerms, readSlotRows, scoreFactCandidates, type FactCandidate as PoolCandidate, type FactPoolScope } from './fact-relevance.ts';
-import { deriveSlotEnds } from '../facts/slots.ts';
+import { admitted, collectFactCandidates, FACTS_ARM_COSINE_MIN, laterRetractions, queryTerms, scoreFactCandidates, type FactCandidate as PoolCandidate, type FactPoolScope } from './fact-relevance.ts';
+import { readSlotHistory, slotWindows } from './slot-history.ts';
import { pageReadFilter } from './read-policy-sql.ts';
import { enforceTokenBudget, resultTokens } from './token-budget.ts';
import { configFlagOn, factDateHeader, factObservationDates } from './evidence-date.ts';
@@ -283,9 +283,15 @@ export function applyFactsBlock(engine: BrainEngine, query: string, results: Sea
async function applyFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }, policy: ReservePolicy): Promise<SearchResult[]> {
try {
const scope = await poolScope(engine, opts);
+ const readScope: PageReadScope = opts.readScope ?? { sourceId: opts.sourceId, sourceIds: opts.sourceIds, excludePrivate: scope.excludePrivate };
+ // GBRA-574 F: a history question about one slot dimension of one named entity takes every value it has had, first in line (slot-history.ts).
+ let historyUnavailable = false;
+ const history = policy.dated ? await readSlotHistory(engine, query, scope, readScope).catch(() => { historyUnavailable = true; return null; }) : null;
+ const pinned = new Set((history?.rows ?? []).map(c => Number(c.id)));
const { candidates, stems } = await collectFactCandidates(engine, query, scope, opts.queryEmbedding,
{ depth: { keyword: 50, cosine: 50, entity: policy.maxRows }, cosineForAll: true, history: policy.dated && hasHistoryCue(query) });
- const scored = scoreFactCandidates(query, candidates, queryTerms(query), stems).filter(s => admitted(s, 'reserve')).map(s => s.candidate);
+ const scored = [...(history?.rows ?? []), ...scoreFactCandidates(query, candidates, queryTerms(query), stems)
+ .filter(s => admitted(s, 'reserve') && !pinned.has(Number(s.candidate.id))).map(s => s.candidate)];
if (!scored.length) return results;
const callerRows = (await opts.rowCap?.().catch(() => 0)) ?? 0;
const rowCap = Math.max(results.length, callerRows);
@@ -301,10 +307,9 @@ async function applyFactReserve(engine: BrainEngine, query: string, results: Sea
const said = (c: FactCandidate) => dates?.get(Number(c.id)) ?? day(c.created_at ?? c.valid_from) ?? '';
const groups = members.map(g => g.sort((a, b) => said(a).localeCompare(said(b)) || Number(a.id) - Number(b.id)));
const shown = groups.map(g => g[0]!);
- // GBRA-574 B2/G4: a slot value's window ends at read time, from the slot's rows the caller may read (facts/slots.ts).
- const slots = new Map(shown.flatMap(c => c.entity_slug && c.dimension && c.value_hash
- ? [[[c.source_id, c.entity_slug, c.dimension].join('\u0000'), { source_id: c.source_id, entity_slug: c.entity_slug, dimension: c.dimension }] as const] : []));
- const ends = slots.size ? await readSlotRows(engine, scope, [...slots.values()]).then(deriveSlotEnds).catch(() => new Map<number, Date>()) : new Map<number, Date>();
+ // GBRA-574 B2/G4 and F: a slot value's window ends at read time, from the rows the caller may read under every key of its entity (slot-history.ts).
+ const ends = await slotWindows(engine, scope, readScope, shown, history?.keys ?? null)
+ .catch(() => { historyUnavailable ||= history !== null; return new Map<number, Date>(); });
const pageSlugs = await readableEntityPages(engine, shown, opts.readScope).catch(() => new Set<string>());
const fromQuoted = await factsFromQuotedPages(engine, [...shown, ...retracting].map(c => Number(c.id)));
const asked = policy.dated ? questionDate(query) : null;
@@ -323,6 +328,7 @@ async function applyFactReserve(engine: BrainEngine, query: string, results: Sea
const label = contested.has(Number(c.id)) ? ` (contested by #${contested.get(Number(c.id))})` : '';
row.chunk_text = `${factDateHeader(window, undefined, dates?.get(Number(c.id)), asked)}\n${c.fact}${restated}${label}`;
if (lookup.degraded) row.fact_row = { ...row.fact_row!, contested_unavailable: true };
+ if (historyUnavailable) row.fact_row = { ...row.fact_row!, history_unavailable: true };
return row;
};
type Shown = { c: FactCandidate; row: SearchResult; after: Array<{ c: FactCandidate; row: SearchResult }> };
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index e30e3d37f1..9013d53e5b 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -30,6 +30,7 @@ import { asciiLower, asciiLowerSql, edgeTrimSql } from '../edge-whitespace.ts';
import { ACCESS_ID_RE, hasReaders, MEMBER_PAGE_PREFIX, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';
import { ruleCoversSql, validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';
import { holdingSlugSql } from '../facts-fence.ts';
+import { NAME_KEY_PAGE_DIRS } from '../entities/basename-dirs.ts';
import { atomMovedOriginPrivateSql, atomOriginSlugsSql } from '../persistence/atom-origin.ts';
import { ownerOnlyFactSql, ownerOnlyForm, ownerOnlyPageSql, ownerOnlySourcesPresent } from '../access/owner-only.ts';
@@ -1001,7 +1002,10 @@ export function privateProvenanceFilterUnderPolicy(factAlias: string, perCandida
export function privateEntityFilterForCaller(factAlias: string, perCandidate = false): string {
const entityPolicy = currentCallerAccess().labelledOnly ? withCallerAccess({ labelledOnly: false }, () => privatePagesFilterForCaller('entity_pp')) : privatePagesFilterForCaller('entity_pp');
const held = `CASE WHEN ${factAlias}.entity_slug IS NOT NULL AND ${holdingSlugSql(`${factAlias}.source_markdown_slug`)} THEN ${factAlias}.source_markdown_slug END`;
- return `(NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug IN (${factAlias}.entity_slug, ${held}) AND NOT ${entityPolicy}${perCandidate ? ' OFFSET 0' : ''})${sharedHeldRuledSql(factAlias)})`;
+ // GBRA-574: a bare name key reads as the page later written at <dir>/<key>, so that page's privacy covers it.
+ const keyedSlugs = `ARRAY[${NAME_KEY_PAGE_DIRS.map(dir => `'${dir}/' || ${factAlias}.entity_slug`).join(', ')}]`;
+ const keyed = `CASE WHEN strpos(${factAlias}.entity_slug, '/') = 0 THEN NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug = ANY(${keyedSlugs}) AND NOT ${entityPolicy}${perCandidate ? ' OFFSET 0' : ''}) ELSE TRUE END`;
+ return `(NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug IN (${factAlias}.entity_slug, ${held}) AND NOT ${entityPolicy}${perCandidate ? ' OFFSET 0' : ''}) AND ${keyed}${sharedHeldRuledSql(factAlias)})`;
}
/**
diff --git a/src/core/search/slot-history.ts b/src/core/search/slot-history.ts
new file mode 100644
index 0000000000..16d519bca1
--- /dev/null
+++ b/src/core/search/slot-history.ts
@@ -0,0 +1,136 @@
+/**
+ * GBRA-574 F (part B): the slot-history arm of the query facts block. A question that asks for history (hasHistoryCue,
+ * "oldest first", "held", or a dimension named in the plural) about exactly one slot dimension (facts/slots.ts:
+ * role, employer, location), and not for the current value, gets every readable active slot value of the one entity it
+ * names in that dimension, oldest first, each with its read-time window, inside the block's own row count and token
+ * share. No model call, no writes.
+ *
+ * The entity is the one page the question names (entity-anchor.ts namedEntity, under the caller's page read policy)
+ * or, when none, the one unbacked name key (D1): a bare slug of two or more words with an active fact in the
+ * authorized pool and no live page at it, whose words the question holds as a contiguous run; a key inside a longer
+ * matched key is the same mention, and two candidates (two names, or one name in two sources) match none. Its fact
+ * keys are the page's (mentions/siblings.ts factEntitySlugs: the page, its siblings, its title subject and its
+ * unclaimed basename) or, for a key the one readable live <dir>/<key> page claims, that page's; the read-time windows
+ * (deriveSlotEnds) group every key of one entity as that entity. Rows are read under the pool's read policy
+ * (fact-relevance.ts readSlotRows): withdrawn, superseded and expired rows never show.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PageReadScope } from '../types.ts';
+import { deriveSlotEnds, SLOT_DIMENSIONS } from '../facts/slots.ts';
+import { factEntitySlugs } from '../mentions/siblings.ts';
+import { BASENAME_DIRS, fallbackSlugify } from '../entities/resolve.ts';
+import { namedEntity } from './entity-anchor.ts';
+import { pageReadFilter } from './read-policy-sql.ts';
+import { poolUnbackedKeys, readSlotRows, type FactCandidate, type FactPoolScope } from './fact-relevance.ts';
+import { hasHistoryCue } from './facts-arm.ts';
+
+/** Words of a name key the question may hold, at most. */
+const MAX_KEY_WORDS = 5;
+/** Question words read for name keys, at most (the last ones). */
+const MAX_KEY_SCAN_WORDS = 64;
+/** Unbacked keys read per question, at most; past one the match is ambiguous anyway. */
+const MAX_KEY_MATCHES = 8;
+
+const LIST_CUE = /\b(oldest first|newest first|held)\b/i;
+const CURRENT_CUE = /\b(now|nowadays|currently|current|today|these days|at the moment|at present|presently)\b/i;
+const DIMENSION_CUES: ReadonlyArray<readonly [string, RegExp, RegExp]> = [
+ ['role', /\b(roles?|titles?|jobs?|positions?)\b/i, /\b(roles|titles|jobs|positions)\b/i],
+ ['employer', /\b(employers?|compan(?:y|ies)|work(?:s|ed|ing)? (?:at|for))\b/i, /\b(employers|companies)\b/i],
+ ['location', /\b(cit(?:y|ies)|lived|lives?|living|based in|moved)\b/i, /\b(cities)\b/i],
+];
+
+/**
+ * The one slot dimension a history question asks about, or null: no history cue (hasHistoryCue, "oldest first",
+ * "held", or the dimension named in the plural), a present-tense cue ("now", "currently", "these days"), or no or
+ * several dimensions.
+ */
+export function slotHistoryDimension(query: string, asOf?: string): string | null {
+ if (CURRENT_CUE.test(query)) return null;
+ const named = DIMENSION_CUES.filter(([, cue]) => cue.test(query));
+ if (named.length !== 1) return null;
+ const [dimension, , plural] = named[0]!;
+ if (!SLOT_DIMENSIONS.has(dimension)) return null;
+ return plural.test(query) || LIST_CUE.test(query) || hasHistoryCue(query, asOf) ? dimension : null;
+}
+
+/** The slugs a run of two to MAX_KEY_WORDS question words would carry as a name key. */
+function keyCandidates(query: string): string[] {
+ const words = query.split(/[^\p{L}\p{N}]+/u).filter(Boolean).slice(-MAX_KEY_SCAN_WORDS);
+ const keys = new Set<string>();
+ for (let i = 0; i < words.length; i++) {
+ for (let n = 2; n <= MAX_KEY_WORDS && i + n <= words.length; n++) {
+ const key = fallbackSlugify(words.slice(i, i + n).join(' ')) ?? '';
+ if (key.includes('-')) keys.add(key);
+ }
+ }
+ return [...keys];
+}
+
+/** D1: the one unbacked name key the question names in the authorized pool, or null for none or several. */
+export async function matchUnbackedKey(engine: BrainEngine, query: string, scope: FactPoolScope): Promise<{ source_id: string; entity_slug: string } | null> {
+ const matches = await poolUnbackedKeys(engine, scope, keyCandidates(query), MAX_KEY_MATCHES);
+ const inside = (short: string, long: string) => short.length < long.length && ('-' + long + '-').includes('-' + short + '-');
+ const outer = matches.filter(m => !matches.some(o => inside(m.entity_slug, o.entity_slug)));
+ return outer.length === 1 ? outer[0]! : null;
+}
+
+export interface EntityKeys { source_id: string; canonical: string; slugs: string[] }
+
+/**
+ * One entity's fact keys: a bare key the one readable live <dir>/<key> page claims (its unclaimed basename) reads as
+ * that page; any other slug as factEntitySlugs gives it ([slug] when no page sits there).
+ */
+export async function entityKeys(engine: BrainEngine, sourceId: string, slug: string, readScope: PageReadScope): Promise<EntityKeys> {
+ const excludePrivate = readScope.excludePrivate ?? false;
+ if (!slug.includes('/')) {
+ const params: unknown[] = [sourceId, BASENAME_DIRS.map(dir => dir + '/' + slug)];
+ const filter = pageReadFilter('p', { ...readScope, sourceId: undefined, sourceIds: undefined }, params, true);
+ const pages = await engine.executeRaw<{ slug: string }>('SELECT p.slug FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND ' + filter + ' LIMIT 2', params);
+ if (pages.length === 1) {
+ const slugs = await factEntitySlugs(engine, sourceId, pages[0]!.slug, { excludePrivate });
+ if (slugs.includes(slug)) return { source_id: sourceId, canonical: pages[0]!.slug, slugs };
+ }
+ }
+ return { source_id: sourceId, canonical: slug, slugs: await factEntitySlugs(engine, sourceId, slug, { excludePrivate }) };
+}
+
+export interface SlotHistory { keys: EntityKeys; rows: FactCandidate[] }
+
+/**
+ * The arm's rows for a history question about one slot dimension of one named entity, or null when it does not fire:
+ * the first row of each value's stint newest first, then the restatements newest first, so a tight budget keeps the
+ * latest values (the block shows what it keeps oldest first).
+ * Throws on a read error (the block reports facts_history_unavailable).
+ */
+export async function readSlotHistory(engine: BrainEngine, query: string, scope: FactPoolScope, readScope: PageReadScope): Promise<SlotHistory | null> {
+ const dimension = slotHistoryDimension(query);
+ if (!dimension) return null;
+ const sourceIds = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];
+ const page = await namedEntity(engine, query, { ...readScope, sourceId: undefined, sourceIds });
+ const named = page ? { source_id: page.source_id, entity_slug: page.slug } : await matchUnbackedKey(engine, query, scope);
+ if (!named) return null;
+ const keys = await entityKeys(engine, named.source_id, named.entity_slug, readScope);
+ const rows = await readSlotRows(engine, scope, keys.slugs.map(entity_slug => ({ source_id: keys.source_id, entity_slug, dimension })));
+ const values = rows.map(r => ({ ...r, id: Number(r.id), entity: true }));
+ const heads = values.filter((r, i) => i === 0 || values[i - 1]!.value_hash !== r.value_hash);
+ return { keys, rows: [...heads.reverse(), ...values.filter(r => !heads.includes(r)).reverse()] };
+}
+
+/**
+ * Read-time windows (deriveSlotEnds) for the slot facts shown, by fact id: each fact's slot is read across its entity's
+ * keys (entityKeys; `known` skips the lookup for an entity already resolved), grouped as that one entity.
+ */
+export async function slotWindows(engine: BrainEngine, scope: FactPoolScope, readScope: PageReadScope, facts: readonly FactCandidate[], known: EntityKeys | null): Promise<Map<number, Date>> {
+ const slotted = facts.filter(f => f.entity_slug && f.dimension && f.value_hash);
+ if (!slotted.length) return new Map();
+ const entities = [...new Map(slotted.map(f => [f.source_id + '\u0000' + f.entity_slug, f])).values()];
+ const resolved = await Promise.all(entities.map(f => known && known.source_id === f.source_id && known.slugs.includes(f.entity_slug!)
+ ? known : entityKeys(engine, f.source_id, f.entity_slug!, readScope).catch(() => ({ source_id: f.source_id, canonical: f.entity_slug!, slugs: [f.entity_slug!] }))));
+ const canonical = new Map(resolved.flatMap(k => k.slugs.map(s => [k.source_id + '\u0000' + s, k.canonical] as const)));
+ const slots = new Map(slotted.flatMap(f => {
+ const keys = resolved[entities.findIndex(e => e.source_id === f.source_id && e.entity_slug === f.entity_slug)]!;
+ return keys.slugs.map(entity_slug => [[f.source_id, entity_slug, f.dimension].join('\u0000'), { source_id: f.source_id, entity_slug, dimension: f.dimension! }] as const);
+ }));
+ const rows = await readSlotRows(engine, scope, [...slots.values()]);
+ return deriveSlotEnds(rows.map(r => ({ ...r, entity_slug: canonical.get(r.source_id + '\u0000' + r.entity_slug) ?? r.entity_slug })));
+}
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 8580b4ef4b..f009e039e3 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -63,7 +63,7 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
// GST-2511: a contested row a widening proposal stored narrower (pending, rejected or undone) is held at its visibility
// while the fence still asks for world at its position. GST-2891: whatever the writer's tier: re-deriving the unchanged
// row (a sync after an unrelated edit, a re-put) is not the owner's accept, which alone applies the widening.
- const held = `f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts'
+ const held = `f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action IN ('supersede_fact', 'confirm') AND tp.related_table = 'facts'
AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL)
AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text)
WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')`;
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index 7c838fc642..62ce4bf4ec 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -29,7 +29,7 @@ import { releaseSuppressedFields, suppressedFields } from '../belief/purge.ts';
import { decideTrustProposal } from './decide.ts';
import { heldLabelsText } from './page-write.ts';
import { resolveContestedFactOnConfirm } from './supersede-handlers.ts';
-import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
+import { getTrustProposal, pendingTrustProposalsFor, SHARE_HELD_GUARD, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
import {
confirmPage, latestPageVersionId, lowerPageState, readPageTrustState, readPageVersion, revertLoweredPage, revertPageToVersion,
setRowTier, versionTier, type PageActionResult,
@@ -322,6 +322,11 @@ function proposalSummary(p: TrustProposalRow, verb: 'Accept' | 'Dismiss' | 'Reve
return `Dismiss ${trustProposalRef(p.id)}: ${page} stays "${trustLabel(s.edited_tier)}"${labels ? ' and keeps its privacy labels' : ''}`;
}
const target = `${p.target_table === 'facts' ? 'f' : p.target_table === 'takes' ? 't' : p.target_table === 'timeline_entries' ? 'timeline row ' : ''}${p.target_id}`;
+ // GST-2897 B: a member's share about another member, held private.
+ if (p.before_state.guard === SHARE_HELD_GUARD) {
+ return verb === 'Accept' ? `Accept ${trustProposalRef(p.id)}: share ${target}, a fact about member ${String(p.before_state.member)}, with every reader of source ${p.source_id} (its trust stays as written)`
+ : `Dismiss ${trustProposalRef(p.id)}: keep ${target} private`;
+ }
const related = p.related_id === null ? '' : ` with ${p.related_table === 'facts' ? 'f' : p.related_table === 'takes' ? 't' : ''}${p.related_id}`;
// W1 #6783 §12 (a): a held take or timeline row names what the lower-tier write asked for.
const held = p.action === 'forget' && p.target_table !== 'facts' ? ({ removed: 'remove', replaced: 'replace', deactivated: 'deactivate', detail_changed: 'rewrite' } as Record<string, string>)[String(p.before_state.change)] : undefined;
diff --git a/src/core/trust/proposals.ts b/src/core/trust/proposals.ts
index 87cf046308..16826a69b7 100644
--- a/src/core/trust/proposals.ts
+++ b/src/core/trust/proposals.ts
@@ -54,6 +54,9 @@ export interface TrustProposalRow {
/** The typed CLI ref of a trust proposal. */
export const trustProposalRef = (id: number | string): string => `tp${id}`;
+
+/** GST-2897 B: the guard of a member's share about another member, held private on a confirm proposal for the brain owner. */
+export const SHARE_HELD_GUARD = 'remember.share_held';
/** `tp<id>` (or a bare id) to the proposal id; null when the ref names something else. */
export function parseTrustProposalRef(ref: string): number | null {
const m = /^(?:tp)?(\d{1,18})$/.exec(ref.trim());
diff --git a/src/core/trust/review.ts b/src/core/trust/review.ts
index 97eeddd583..b2addaca6d 100644
--- a/src/core/trust/review.ts
+++ b/src/core/trust/review.ts
@@ -25,7 +25,7 @@
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import { currentHoldStore, trustKillSwitchState } from './owner-actions.ts';
-import { getTrustProposal, listTrustProposals, pendingTrustProposalsFor, trustProposalRef, type TrustProposalAction, type TrustProposalRow } from './proposals.ts';
+import { getTrustProposal, listTrustProposals, pendingTrustProposalsFor, SHARE_HELD_GUARD, trustProposalRef, type TrustProposalAction, type TrustProposalRow } from './proposals.ts';
import { lowerPageState, readPageTrustState } from './page-handlers.ts';
import { heldLabelsText } from './page-write.ts';
import { TRUST_MARKER_REPAIR_COMMAND } from './marker-repair.ts';
@@ -158,6 +158,7 @@ function proposalItem(p: TrustProposalRow, page: string | null, markerRepair = f
const related = rowRef(p.related_table, p.related_id);
const held = p.action === 'forget' ? HELD_VERBS[String(p.before_state.change)] : undefined;
const what = held ? `A lower-trust write would ${held} ${target}` : p.action === 'forget' ? `An agent asked to forget ${target}`
+ : p.before_state.guard === SHARE_HELD_GUARD ? `A member shared ${target} about member ${String(p.before_state.member)}; it stays private until you confirm it`
: `${related || 'A lower-trust write'} would ${p.action === 'confirm' ? 'confirm' : 'supersede'} ${target}`;
return {
ref, kind: 'proposal', detail: p.action, source_id: p.source_id, page, day: day(p.created_at), created_at: p.created_at,
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index 308678bb79..d5b56aa535 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -17,13 +17,13 @@ import { beliefStreamSlugs, beliefTransaction } from '../belief/writers.ts';
import {
applyProposalAction, type PairProposal, type PairProposalStore, type ProposalActionResult,
} from '../facts/proposal-supersede.ts';
-import { currentWriteTrust, withTrustPromotion, withWriteAttribution } from '../persistence/context.ts';
+import { currentWriteTrust, withCoordinatedWrite, withTrustPromotion, withWriteAttribution } from '../persistence/context.ts';
import { normalizeDimension, NOT_CONVERSATION_SLOT_SQL } from '../chronicle/ontology.ts';
import { verbError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import { onOwnedMemoryPageSql } from '../access/member-facts.ts';
import {
- decisionResult, getTrustProposal, insertTrustProposal, pendingTrustProposalsFor, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,
+ decisionResult, getTrustProposal, insertTrustProposal, pendingTrustProposalsFor, registerTrustProposalHandler, SHARE_HELD_GUARD, transitionTrustProposal, trustProposalRef,
type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,
} from './proposals.ts';
import { tierRaiseFix } from './confirm.ts';
@@ -103,6 +103,15 @@ export async function recordContestedFact(tx: BrainEngine, input: { sourceId: st
return { proposal_ref: trustProposalRef(id) };
}
+/** GST-2897 B: the pending confirm proposal holding a member's share about another member private; the owner's accept widens it. */
+export async function recordHeldShare(tx: BrainEngine, input: { sourceId: string; factId: number; tier: TrustTier; member: string; pageless: boolean }): Promise<{ proposal_ref: string; member: string }> {
+ const { id } = await insertTrustProposal(tx, {
+ action: 'confirm', sourceId: input.sourceId, target: { table: 'facts', id: input.factId }, related: { table: 'facts', id: input.factId }, proposer: SHARE_HELD_GUARD,
+ before: { guard: SHARE_HELD_GUARD, member: input.member, new: { id: input.factId, tier: input.tier }, visibility: { from: 'private', to: 'world' }, ...(input.pageless ? { pageless: true } : {}) },
+ });
+ return { proposal_ref: trustProposalRef(id), member: input.member };
+}
+
/** The pending supersede_take proposal for a contested take write. */
export async function recordContestedTake(tx: BrainEngine, input: { sourceId: string; oldId: number; oldTier: TrustTier; newId: number; newTier: TrustTier; guard: string }): Promise<{ proposal_ref: string }> {
const { id } = await insertTrustProposal(tx, {
@@ -292,7 +301,7 @@ function fromPairResult(proposal: TrustProposalRow, decision: TrustDecision, res
}
/** The actions this module registers handlers for. */
-export const SUPERSEDE_HANDLER_ACTIONS: readonly TrustProposalAction[] = ['supersede_fact', 'supersede_take', 'forget'];
+export const SUPERSEDE_HANDLER_ACTIONS: readonly TrustProposalAction[] = ['supersede_fact', 'supersede_take', 'forget', 'confirm'];
registerTrustProposalHandler('supersede_fact', {
async accept(engine, proposal, ctx: TrustDecisionContext) {
@@ -348,6 +357,46 @@ registerTrustProposalHandler('supersede_take', {
},
});
+type ShareOutcome = { status: 'accepted'; visibility: string } | { status: 'refused' | 'superseded'; reason: string };
+
+/**
+ * GST-2897 B: the owner shares a held fact. Its visibility widens when the fence still asks for it (or it has no page);
+ * its tier stays as written, so the member it is about can still withdraw it.
+ */
+registerTrustProposalHandler('confirm', {
+ async accept(engine, proposal, ctx: TrustDecisionContext) {
+ const { maintenanceAttribution, principalAttribution } = await import('../persistence/attribution.ts');
+ const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');
+ const attribution = ctx.decidedBy ? principalAttribution(ctx.decidedBy) : await maintenanceAttribution(engine);
+ const managed = await managedPersistenceEnabled(engine);
+ const outcome = await engine.transaction(tx => {
+ const run = async (): Promise<ShareOutcome> => {
+ const row = await getTrustProposal(tx, proposal.id, true);
+ if (row?.status !== 'pending') return { status: 'refused' as const, reason: row?.status ?? 'not_found' };
+ const requested = await requestedVisibility(tx, proposal.id, proposal.target_id);
+ const [fact] = await tx.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id = $1 AND source_id = $2 AND expired_at IS NULL',
+ [proposal.target_id, proposal.source_id]);
+ if (!requested || !fact) {
+ await transitionTrustProposal(tx, proposal.id, 'pending', 'superseded');
+ return { status: 'superseded' as const, reason: 'fact_missing' };
+ }
+ const widen = fact.visibility === requested.from && await fenceAsks(tx, proposal.target_id, requested.to, requested.pageless);
+ if (widen) {
+ await tx.executeRaw('UPDATE facts SET visibility = $3 WHERE id = $1 AND source_id = $2', [proposal.target_id, proposal.source_id, requested.to]);
+ await queueTierProjection(tx, 'facts', proposal.target_id);
+ }
+ const visibility = widen ? requested.to : fact.visibility;
+ await transitionTrustProposal(tx, proposal.id, 'pending', 'accepted', { decidedBy: ctx.decidedBy, after: { visibility } });
+ return { status: 'accepted' as const, visibility };
+ };
+ return managed ? withCoordinatedWrite(tx, [proposal.source_id], run, attribution) : withWriteAttribution(tx, attribution, run);
+ });
+ return outcome.status === 'accepted'
+ ? decisionResult(proposal, 'accept', 'accepted', { detail: { fact_id: String(proposal.target_id), visibility: outcome.visibility } })
+ : decisionResult(proposal, 'accept', outcome.status, { reason: outcome.reason });
+ },
+});
+
/** The owner applies the forget a remote caller asked for, as a trusted local forget; a held take or timeline row takes the page's text (trust/held-removals.ts). */
registerTrustProposalHandler('forget', {
async accept(engine, proposal, ctx: TrustDecisionContext) {
diff --git a/src/core/types.ts b/src/core/types.ts
index 7d277d7cb8..f420435a13 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1131,8 +1131,8 @@ export interface SearchResult {
* entity's page, or a page that links to it or names it (newest first).
*/
entity_anchored?: 'entity' | 'linked';
- /** Set on a saved-fact row the `search.query_facts_arm` arm added (search/facts-arm.ts); page_id is 0. `observed`: when it was said; `observed_unavailable`: that read failed; `contested_unavailable`: the facts block's contested lookup failed. */
- fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true };
+ /** Set on a saved-fact row the `search.query_facts_arm` arm added (search/facts-arm.ts); page_id is 0. `observed`: when it was said; `observed_unavailable`: that read failed; `contested_unavailable`: the facts block's contested lookup failed; `history_unavailable`: its slot-history read failed. */
+ fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true; history_unavailable?: true };
/** Fact rows only, and what callers see of them: never a page (no slug or id); follow with `follow_up`, read `page_slug` when the entity page exists. */
result_type?: 'fact'; fact_id?: string; page_slug?: string; follow_up?: { op: 'recall'; args: Record<string, string> };
/** #7600, #8042: a row of third-party text (a chat page or a fact saved from one), returned fenced as quoted source material with its tool-call blocks summarized (search/transcript-quote.ts). */
@@ -2107,7 +2107,7 @@ export const DEGRADED_STAGES = [
'keyword_candidates_incomplete',
'projection_pending', 'projection_by_design',
'projection_status_unknown',
- 'keyword_count_unavailable', 'saved_facts_withheld', 'fact_observed_date_unavailable', 'contested_unavailable',
+ 'keyword_count_unavailable', 'saved_facts_withheld', 'fact_observed_date_unavailable', 'contested_unavailable', 'facts_history_unavailable',
] as const;
export type DegradedStage = (typeof DEGRADED_STAGES)[number];
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1e809b34d5..c01d0c2dd6 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -196,6 +196,13 @@ const remember: Operation = {
// GST-2346 D1: the brain owner speaking for itself is not refused; its "world" is saved shared.
if (p.share !== true && p.visibility === 'world' && ctx.attestedOp !== 'memory_write' && memberFacts.memberFactPage(ctx) && !memberFacts.ownerSpeaksForItself(ctx)) {
if (attested) throw memberFacts.attestedShareRefused(verbError);
+ // GST-2897 B: a fact about another member is never pointed at share: true, which holds it for the brain owner.
+ const subject = typeof p.entity === 'string' ? await memberFacts.otherMemberSubject(ctx.engine, p.entity.trim()) : null;
+ if (subject) {
+ throw Object.assign(verbError('invalid_params', 'remember: a member credential cannot save a fact with visibility "world"; nothing was saved.',
+ `${p.entity} is about member ${subject}. Retry with no visibility to keep the fact on your own member page; a shared fact about another member is held private until the brain owner confirms it.`),
+ { reason: 'member_share_required' });
+ }
throw Object.assign(verbError('invalid_params', 'remember: a member credential shares a fact with share: true, not visibility "world"; nothing was saved.',
'Retry the same call with share: true in place of visibility "world" to share a fact about the team\'s work with everyone who reads this source, or with no visibility to keep a fact about a person on your own member page. A member shares only this way: pass share: true, never visibility "world".'),
{ reason: 'member_share_required' });
diff --git a/test/cli-cold-start-registries.test.ts b/test/cli-cold-start-registries.test.ts
index f8640ac313..5a7e778b38 100644
--- a/test/cli-cold-start-registries.test.ts
+++ b/test/cli-cold-start-registries.test.ts
@@ -122,6 +122,6 @@ describe('load-time registries under per-op loading', () => {
};
const alone = probe('');
expect(alone).toEqual(probe("await import('./src/core/operations.ts');"));
- expect(alone).toEqual(['forget', 'lower_page', 'supersede_fact', 'supersede_take']);
+ expect(alone).toEqual(['confirm', 'forget', 'lower_page', 'supersede_fact', 'supersede_take']);
});
});
diff --git a/test/conversation-unbacked-keys-gbra574.test.ts b/test/conversation-unbacked-keys-gbra574.test.ts
new file mode 100644
index 0000000000..9df1ef60e5
--- /dev/null
+++ b/test/conversation-unbacked-keys-gbra574.test.ts
@@ -0,0 +1,311 @@
+/**
+ * GBRA-574 F, part A: conversation facts about a full name with no page keep a name key (facts.unbacked_entity_keys).
+ *
+ * Protects: a two-word name with no page keeps the bare basename key (three spellings collapse; a first name or a topic
+ * keeps none; the setting off keeps today's NULL) and gets a slot from the tagging call; no page is ever created; a page
+ * written later adopts the key's facts on reads, and `gbrain facts relink --conversation --unbacked` moves them durably
+ * (alias, merged and suffix pages; the preview writes nothing; a world fact never lands on a private page); keys stay
+ * per source; a remote caller never reads a private key fact; a forgotten or purged claim never comes back, whether it
+ * was forgotten under the key, source-wide before this change, or under a page that is gone; consolidate never reads a
+ * bucket whose entity has no page.
+ * Seams: injected extractor or the gateway chat transport stub (no provider call); PGLite with no git repository, and
+ * Postgres through test/e2e/conversation-unbacked-keys-gbra574-postgres.test.ts.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { runFactsCommand } from '../src/commands/facts.ts';
+import { __setChatTransportForTests, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { unbackedEntityKey } from '../src/core/entities/resolve-on-save.ts';
+import { runConversationRelink } from '../src/core/facts/conversation-relink.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+import { SLOT_TAG_SYSTEM } from '../src/core/facts/slot-tagging.ts';
+import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';
+import { factEntitySlugs } from '../src/core/mentions/siblings.ts';
+import { operations } from '../src/core/operations.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CONVO = 'conversations/2026-03-10/alice-chat';
+const JOINED = 'Alice Example joined Acme Example as head of design.';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-unbacked-keys-'));
+let engine: BrainEngine;
+
+const fact = (text: string, entity: string | null, kind = 'fact'): ExtractedFact =>
+ ({ fact: text, kind, entity_slug: entity, confidence: 0.9, source: 'test', notability: 'high' }) as ExtractedFact;
+const reply = (text: string): ChatResult => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } }) as ChatResult;
+const body = [
+ '**user** (2026-03-10 9:00 AM): Alice Example joined Acme Example as head of design.',
+ '**assistant** (2026-03-10 9:01 AM): Noted.',
+ '**user** (2026-03-10 9:02 AM): She likes the new studio.',
+].join('\n');
+
+async function conversation(slug = CONVO, sourceId = 'default', frontmatter: Record<string, unknown> = { date: '2026-03-10' }) {
+ await engine.putPage(slug, { type: 'conversation' as never, title: 'Conversation 2026-03-10', compiled_truth: body, timeline: '', frontmatter }, { sourceId });
+}
+async function page(slug: string, type: string, title: string, frontmatter: Record<string, unknown> = {}, sourceId = 'default') {
+ await engine.putPage(slug, { type: type as never, title, compiled_truth: `# ${title}`, timeline: '', frontmatter }, { sourceId });
+}
+async function extract(facts: ExtractedFact[], opts: { slug?: string; sourceId?: string; force?: boolean } = {}) {
+ await disposePersistenceConsumer(engine);
+ const spy = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ return await runExtractConversationFactsCore(engine, { sourceId: opts.sourceId ?? 'default', slugs: [opts.slug ?? CONVO], sleepMs: 0,
+ overrideDisabled: true, workers: 1, force: opts.force, extractor: async () => facts.map(f => ({ ...f })) });
+ } finally { spy.mockRestore(); }
+}
+async function rows(where = "source_markdown_slug = '" + CONVO + "'") {
+ return engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; expired: boolean; dimension: string | null; value: string | null; context: string | null; source_id: string }>(
+ `SELECT id, fact, entity_slug, expired_at IS NOT NULL AS expired, dimension, value, context, source_id FROM facts
+ WHERE ${where} AND source LIKE 'cli:extract-conversation-facts%' AND fact NOT LIKE 'EXTRACTION_%' ORDER BY id`);
+}
+async function active(claim: string, sourceId = 'default') {
+ return (await rows(`source_id = '${sourceId}' AND fact = '${claim.replace(/'/g, "''")}'`)).filter(r => !r.expired);
+}
+const relink = (opts: { dryRun?: boolean; sourceId?: string; slugs?: string[] } = {}) =>
+ runConversationRelink(engine, { engine: engine.kind } as GBrainConfig, { sourceId: opts.sourceId ?? 'default', unbacked: true, dryRun: opts.dryRun, slugs: opts.slugs });
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let pglite: PGLiteEngine | undefined;
+ let template: Awaited<ReturnType<typeof persistencePostgresTemplate>> | undefined;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ else { pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { await template?.dispose(); await pglite?.disconnect(); rmSync(home, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ if (pglite) { engine = pglite; await resetPgliteState(pglite); }
+ else { const c = await template!.clone(); engine = c.engine; close = c.close; }
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('facts.default_visibility', 'world');
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await conversation();
+ }, 60_000);
+ afterEach(async () => {
+ __setChatTransportForTests(null); resetGateway();
+ if (close) { await disposePersistenceConsumer(engine); await close(); close = undefined; }
+ });
+
+ test('a full name with no page keeps its name key and a slot; no page is created', async () => {
+ const seen: ChatOpts[] = [];
+ __setChatTransportForTests(async opts => {
+ seen.push(opts);
+ return opts.system === SLOT_TAG_SYSTEM ? reply('{"slots":[{"i":1,"dimension":"role","value":"head of design"}]}')
+ : reply(JSON.stringify({ facts: [{ fact: JOINED, kind: 'event', entity: 'Alice Example', confidence: 1, notability: 'high' }] }));
+ });
+ const spy = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ let result;
+ try { result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [CONVO], sleepMs: 0, overrideDisabled: true }); }
+ finally { spy.mockRestore(); }
+ expect(result.unbacked_keys).toBe(1);
+ expect((await rows()).map(r => [r.fact, r.entity_slug, r.dimension, r.value])).toEqual([[JOINED, 'alice-example', 'role', 'head of design']]);
+ const tags = seen.filter(o => o.system === SLOT_TAG_SYSTEM);
+ expect(tags).toHaveLength(1);
+ expect(tags[0]!.messages).toEqual([{ role: 'user', content: `1. [Alice Example] ${JOINED}` }]);
+ expect(await engine.executeRaw(`SELECT slug FROM pages WHERE slug LIKE '%alice-example%' OR type IN ('person', 'company')`)).toEqual([]);
+ });
+
+ test('three spellings collapse to one key; a first name and a topic keep none; the setting off keeps NULL', async () => {
+ expect(['Alice Example', 'alice-example', 'people/alice-example', 'Alice', 'travel'].map(n => unbackedEntityKey(n.toLowerCase().replace(/ /g, '-'))))
+ .toEqual(['alice-example', 'alice-example', 'alice-example', null, null]);
+ const facts = [fact('Alice Example moved to Lisbon.', 'Alice Example'), fact('Alice Example likes tea.', 'alice-example'),
+ fact('Alice Example bikes to work.', 'people/alice-example'), fact('Alice called.', 'Alice'), fact('Travel is booked.', 'travel')];
+ await extract(facts);
+ expect((await rows()).map(r => r.entity_slug)).toEqual(['alice-example', 'alice-example', 'alice-example', null, null]);
+ await engine.setConfig('facts.unbacked_entity_keys', 'off');
+ await extract(facts, { force: true });
+ expect((await rows()).filter(r => !r.expired).map(r => r.entity_slug)).toEqual([null, null, null, null, null]);
+ });
+
+ test('a key never lands on an unrelated page that sits at the bare slug', async () => {
+ await page('alice-example', 'note', 'Notes named alice-example');
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')]);
+ expect((await rows()).map(r => r.entity_slug)).toEqual([null]);
+ });
+
+ test('a page written later adopts the key\'s facts on reads; keys stay per source', async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-b', 'source-b') ON CONFLICT (id) DO NOTHING");
+ await conversation(CONVO, 'source-b');
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')]);
+ await extract([fact('Alice Example moved to Porto.', 'Alice Example')], { sourceId: 'source-b' });
+ await page('people/alice-example', 'person', 'Alice Example');
+ expect(await factEntitySlugs(engine, 'default', 'people/alice-example')).toContain('alice-example');
+ const res = await dispatchToolCall(engine, 'recall', { entity: 'people/alice-example', source_id: 'default' }, { remote: false });
+ const facts = (JSON.parse(res.content[0]!.text!) as { facts: Array<{ fact: string }> }).facts.map(f => f.fact);
+ expect(facts).toContain('Alice Example moved to Lisbon.');
+ expect(facts).not.toContain('Alice Example moved to Porto.');
+ expect((await relink()).linked).toBe(1);
+ expect((await active('Alice Example moved to Lisbon.')).map(r => r.entity_slug)).toEqual(['people/alice-example']);
+ expect((await active('Alice Example moved to Porto.', 'source-b')).map(r => r.entity_slug)).toEqual(['alice-example']);
+ });
+
+ test('a remote caller never reads a private key fact', async () => {
+ await engine.setConfig('facts.default_visibility', 'private');
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')]);
+ expect((await rows()).map(r => r.entity_slug)).toEqual(['alice-example']);
+ const read = async (remote: boolean) => (JSON.parse((await dispatchToolCall(engine, 'recall', { entity: 'alice-example' }, { remote })).content[0]!.text!) as
+ { facts?: Array<{ fact: string }> }).facts?.map(f => f.fact) ?? [];
+ expect(await read(false)).toEqual(['Alice Example moved to Lisbon.']);
+ expect(await read(true)).toEqual([]);
+ });
+
+ test('relink --unbacked: the preview writes nothing; alias, merged and suffix pages take their keys; no page keeps the key', async () => {
+ await page('people/alice-q', 'person', 'Alice Q');
+ await engine.setPageAliases('people/alice-q', 'default', ['alice example']);
+ await page('people/bob-example', 'person', 'Bob Example', { superseded_by: 'people/robert-example' });
+ await page('people/robert-example', 'person', 'Robert Example');
+ await page('companies/acme-example-inc', 'company', 'Acme Example Inc');
+ await page('people/dana-example', 'person', 'Dana Example', { visibility: 'private' });
+ // Keys are kept at extraction time, before the pages exist: re-key them as an older extraction left them.
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example'), fact('Bob Example joined Acme Example.', 'Bob Example'),
+ fact('Acme Example raised a round.', 'Acme Example'), fact('Carol Example likes tea.', 'Carol Example'), fact('Dana Example moved to Oslo.', 'Dana Example')]);
+ await engine.executeRaw(`UPDATE facts SET entity_slug = lower(replace(split_part(fact, ' ', 1) || '-' || split_part(fact, ' ', 2), '.', ''))
+ WHERE source_markdown_slug = $1 AND fact NOT LIKE 'EXTRACTION_%'`, [CONVO]);
+ const keyed = (await rows()).map(r => r.entity_slug);
+ expect(keyed).toEqual(['alice-example', 'bob-example', 'acme-example', 'carol-example', 'dana-example']);
+ const preview = await relink({ dryRun: true });
+ expect(preview).toMatchObject({ dry_run: true, unbacked: true, linked: 3, unresolved: 2 });
+ expect((await rows()).map(r => r.entity_slug)).toEqual(keyed);
+ const out: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((line: unknown) => { out.push(String(line)); });
+ try { expect(await runFactsCommand(engine, ['relink', '--conversation', '--unbacked'], { engine: engine.kind } as GBrainConfig, 'default')).toBe(0); }
+ finally { log.mockRestore(); }
+ expect(out.join('\n')).toContain('Linked 3 conversation fact(s)');
+ const after = await rows();
+ expect(after.map(r => r.entity_slug)).toEqual(['people/alice-q', 'people/robert-example', 'companies/acme-example-inc', 'carol-example', 'dana-example']);
+ expect(after[0]!.context).toContain('entity relinked from unbacked');
+ // A re-extraction now resolves the name to the page itself.
+ await extract([fact('Bob Example joined Acme Example.', 'Bob Example')], { force: true });
+ expect((await active('Bob Example joined Acme Example.')).map(r => r.entity_slug)).toEqual(['people/robert-example']);
+ });
+
+ test('a claim forgotten under the key stays forgotten after a page is written and the page is re-extracted', async () => {
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')]);
+ const [row] = await rows();
+ expect(row!.entity_slug).toBe('alice-example');
+ expect((await recordFactWithdrawal(engine, Number(row!.id), 'default')).withdrawn).toBe(true);
+ expect(await engine.executeRaw<{ subject: string }>('SELECT subject FROM fact_withdrawals')).toEqual([{ subject: '*' }]);
+ await page('people/alice-example', 'person', 'Alice Example');
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')], { force: true });
+ expect(await active('Alice Example moved to Lisbon.')).toEqual([]);
+ });
+
+ test('a claim withdrawn source-wide, or under a page that is gone, never comes back under a key', async () => {
+ const visibility = 'world';
+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash) VALUES
+ ('default', $1, '*', gbrain_fact_fingerprint('Alice Example moved to Lisbon.')),
+ ('default', $1, 'people/alice-example', gbrain_fact_fingerprint('Alice Example likes tea.'))`, [visibility]);
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example'), fact('Alice Example likes tea.', 'Alice Example'),
+ fact('Alice Example bikes to work.', 'Alice Example')]);
+ expect((await rows()).map(r => [r.entity_slug, r.expired])).toEqual([['alice-example', true], ['alice-example', true], ['alice-example', false]]);
+ // A page-scoped withdrawal still leaves another page's same claim alone.
+ await page('people/bob-example', 'person', 'Bob Example');
+ await engine.executeRaw(`INSERT INTO facts (source_id, fact, kind, entity_slug, visibility, source, confidence)
+ VALUES ('default', 'Alice Example likes tea.', 'fact', 'people/bob-example', 'world', 'test', 1)`);
+ expect(await engine.executeRaw(`SELECT expired_at IS NOT NULL AS expired FROM facts WHERE entity_slug = 'people/bob-example'`)).toEqual([{ expired: false }]);
+ });
+
+ test('a purged key fact is purged source-wide and stays out of a re-extraction after a page is written', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await registerLocalWriter(engine, 'cli');
+ const ctx = { engine, sourceId: 'default', remote: false, dryRun: false, config: { engine: engine.kind },
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const purge = operations.find(o => o.name === 'purge_fact')!;
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example'), fact('Alice Example likes tea.', 'Alice Example')]);
+ const [row] = await rows();
+ const dry = await purge.handler(ctx, { id: Number(row!.id), dry_run: true }) as Record<string, unknown>;
+ await purge.handler(ctx, { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(await engine.executeRaw<{ subject: string }>('SELECT DISTINCT subject FROM fact_purges')).toEqual([{ subject: '*' }]);
+ // A tombstone under another subject also keeps the claim off a key.
+ await engine.executeRaw(`INSERT INTO fact_purges(source_id, visibility, subject, fact_hash) VALUES ('default', 'world', 'people/bob-example', gbrain_fact_fingerprint('Alice Example likes tea.'))`);
+ await page('people/alice-example', 'person', 'Alice Example');
+ const again = await extract([fact('Alice Example moved to Lisbon.', 'Alice Example'), fact('Alice Example likes tea.', 'Carol Example'),
+ fact('Alice Example bikes to work.', 'Alice Example')], { force: true });
+ expect(again.pages_failed).toBe(0);
+ expect(again.facts_skipped_purged).toBe(2);
+ expect((await rows()).filter(r => !r.expired).map(r => r.fact)).toEqual(['Alice Example bikes to work.']);
+ }));
+
+ test('a member-page forget never reaches a key row, and a later extraction of the claim on a key stays active', async () => {
+ await extract([fact('Likes sushi.', 'Carol Example')]);
+ await page('memory/members/alice-example', 'note', 'Memory of alice-example', { readable_by: ['alice-example'] });
+ const [member] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, fact, kind, visibility, source, confidence, source_markdown_slug)
+ VALUES ('default', 'Likes sushi.', 'fact', 'world', 'test', 1, 'memory/members/alice-example') RETURNING id`);
+ await recordFactWithdrawal(engine, Number(member!.id), 'default', true, { memberPage: 'memory/members/alice-example' });
+ expect(await engine.executeRaw<{ subject: string }>('SELECT subject FROM fact_withdrawals')).toEqual([{ subject: 'memory/members/alice-example' }]);
+ expect((await active('Likes sushi.')).map(r => r.entity_slug)).toEqual(['carol-example']);
+ await extract([fact('Likes sushi.', 'Carol Example')], { force: true });
+ expect((await active('Likes sushi.')).map(r => r.entity_slug)).toEqual(['carol-example']);
+ });
+
+ test('forgetting a key fact refuses while the same claim is active on a page, and withdraws nothing', async () => {
+ await extract([fact('Prefers email over phone.', 'Carol Example')]);
+ const [row] = await rows();
+ await page('people/bob-example', 'person', 'Bob Example');
+ await engine.executeRaw(`INSERT INTO facts (source_id, fact, kind, entity_slug, visibility, source, confidence)
+ VALUES ('default', 'Prefers email over phone.', 'fact', 'people/bob-example', 'world', 'test', 1)`);
+ const out = await dispatchToolCall(engine, 'forget_fact', { id: Number(row!.id) }, { remote: false, sourceId: 'default' });
+ expect(out.isError).toBe(true);
+ expect(out.content.map(c => (c as { text?: string }).text ?? '').join('\n')).toContain('claim_linked: fact #' + row!.id + ' was saved on the name tag carol-example');
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals')).toEqual([]);
+ expect(await engine.executeRaw(`SELECT entity_slug FROM facts WHERE fact = 'Prefers email over phone.' AND expired_at IS NULL ORDER BY entity_slug`))
+ .toEqual([{ entity_slug: 'carol-example' }, { entity_slug: 'people/bob-example' }]);
+ });
+
+ test('an owner-bound caller still reads a key fact after a private people/<key> page is written; a member the page does not name loses it', async () => {
+ await extract([fact('Alice Example moved to Lisbon.', 'Alice Example')]);
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: (fn: never) => engine.transaction(tx => (fn as (s: unknown) => Promise<unknown>)(sqlQueryForEngine(tx))) } as never);
+ for (const id of ['bob-example', 'carol-example']) await addMember(engine, id);
+ await setOwner(engine, 'carol-example');
+ const auths: Record<string, unknown> = {};
+ for (const [name, member] of [['owner', 'carol-example'], ['bob', 'bob-example']] as const) {
+ const c = await provider().registerClientManual('t-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], 'default');
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { member });
+ auths[name] = await provider().verifyAccessToken((await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token);
+ }
+ const recall = async (who: string) => {
+ __resetPrivateVisibilityCacheForTests();
+ const r = await dispatchToolCall(engine, 'recall', { entity: 'alice-example' }, { remote: true, transport: 'http', sourceId: 'default', auth: auths[who] as never,
+ config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } });
+ return r.content.map(c => (c as { text?: string }).text ?? '').join('\n');
+ };
+ expect(await recall('bob')).toContain('moved to Lisbon');
+ await importFromContent(engine, 'people/alice-example', '---\ntype: person\ntitle: Alice Example\nvisibility: private\n---\n# Alice Example\n', { sourceId: 'default' });
+ expect(await recall('owner')).toContain('moved to Lisbon');
+ expect(await recall('bob')).not.toContain('moved to Lisbon');
+ });
+
+ test('consolidate reads no bucket whose entity has no page', async () => {
+ const old = new Date(Date.now() - 10 * 86_400_000);
+ for (let i = 0; i < 4; i++) await engine.executeRaw(`INSERT INTO facts (source_id, fact, kind, entity_slug, visibility, source, confidence, valid_from, source_markdown_slug, row_num)
+ VALUES ('default', $1, 'fact', 'alice-example', 'world', 'cli:extract-conversation-facts:seg', 1, $2, $3, $4)`, [`Alice Example fact ${i}`, old, CONVO, i]);
+ const reads = spyOn(engine, 'listFactsByEntity');
+ try {
+ const result = await runPhaseConsolidate(engine, { minOldestAgeMs: 0 });
+ expect(reads).toHaveBeenCalledTimes(0);
+ expect(result.details).toMatchObject({ buckets_processed: 0 });
+ } finally { reads.mockRestore(); }
+ });
+ });
+}
diff --git a/test/cycle-consolidate.test.ts b/test/cycle-consolidate.test.ts
index fba0053d58..b534e3ba40 100644
--- a/test/cycle-consolidate.test.ts
+++ b/test/cycle-consolidate.test.ts
@@ -166,8 +166,8 @@ describe('runPhaseConsolidate', () => {
);
}
const r = await runPhaseConsolidate(engine, {});
- // Bucket processed (passes count + age gates) but cluster skipped (no page).
- expect(r.details.buckets_processed).toBeGreaterThanOrEqual(1);
+ // GBRA-574 E1: a bucket whose entity has no page is never listed, so it is never read.
+ expect(r.details.buckets_processed).toBe(0);
expect(r.details.facts_consolidated).toBe(0);
expect(r.details.takes_written).toBe(0);
});
diff --git a/test/e2e/conversation-unbacked-keys-gbra574-postgres.test.ts b/test/e2e/conversation-unbacked-keys-gbra574-postgres.test.ts
new file mode 100644
index 0000000000..1c9e0937b3
--- /dev/null
+++ b/test/e2e/conversation-unbacked-keys-gbra574-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../conversation-unbacked-keys-gbra574.test.ts'));
diff --git a/test/e2e/facts-slot-history-gbra574-postgres.test.ts b/test/e2e/facts-slot-history-gbra574-postgres.test.ts
new file mode 100644
index 0000000000..d02d3cc7fb
--- /dev/null
+++ b/test/e2e/facts-slot-history-gbra574-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../facts-slot-history-gbra574.test.ts'));
diff --git a/test/e2e/mentions-thin-person-pages.test.ts b/test/e2e/mentions-thin-person-pages.test.ts
new file mode 100644
index 0000000000..719a1c176d
--- /dev/null
+++ b/test/e2e/mentions-thin-person-pages.test.ts
@@ -0,0 +1,126 @@
+/**
+ * Mention links and thin person pages (a bare first name, an X handle).
+ *
+ * Shape: a person page with a full-name title, a frontmatter alias and an
+ * X handle, beside thin person pages whose slugs are the bare first name, the
+ * handle and the nickname. Before the person page exists the thin pages are
+ * the only candidates and take the links. Once it exists, the next sweep
+ * moves every handle and alias mention onto it, links a bare first name to
+ * nothing, and leaves the thin pages themselves untouched (same title, body,
+ * frontmatter; nothing deleted, merged or renamed); the thin pages titled
+ * with the handle and the nickname gain a mention link to the person page. The second sweep is the
+ * same path an upgrade takes: the gazetteer's saved entry set changes, so the
+ * pages linking to a removed target are re-scanned.
+ *
+ * Regression: a handle mention landing on the page titled with the handle, a
+ * nickname landing on a thin page titled with it while another page declares
+ * it in frontmatter, a bare first name linking to a thin first-name page.
+ *
+ * Runs on PGLite always and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { setCliOptions } from '../../src/core/cli-options.ts';
+import { extractStaleFromDB } from '../../src/commands/extract.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const describePg = hasDatabase() ? describe : describe.skip;
+
+// The import path every write takes (sync, put_page): it also stores the frontmatter aliases. No git repository is involved.
+const put = (engine: BrainEngine, slug: string, type: string, title: string, body: string, frontmatter: Record<string, unknown> = {}) =>
+ importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type: type as never, title, tags: [] }), { noEmbed: true });
+
+async function links(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ f: string; t: string }>(
+ `SELECT f.slug AS f, t.slug AS t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_source = 'mentions' ORDER BY 1, 2`);
+ return rows.map(r => `${r.f} -> ${r.t}`);
+}
+
+async function thinPages(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string; title: string; type: string; compiled_truth: string; frontmatter: unknown; deleted: boolean }>(
+ `SELECT slug, title, type, compiled_truth, frontmatter, deleted_at IS NOT NULL AS deleted FROM pages
+ WHERE slug IN ('people/alice', 'people/alicetweets', 'people/ally') ORDER BY slug`);
+ return rows.map(r => JSON.stringify([r.slug, r.title, r.type, r.compiled_truth, typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter, r.deleted]));
+}
+
+async function sweep(engine: BrainEngine) {
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+ const r = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ return { state: r.mentions?.state, remaining: r.mentions?.remaining };
+}
+
+async function scenario(engine: BrainEngine) {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await put(engine, 'people/alice', 'person', 'Alice', 'Stub.', { x_handle: 'unknown' });
+ await put(engine, 'people/alicetweets', 'person', 'alicetweets', 'Stub.');
+ await put(engine, 'people/ally', 'person', 'Ally', 'Stub.');
+ await put(engine, 'notes/first-name', 'note', 'First name', 'Lunch with Alice today.');
+ await put(engine, 'notes/handle', 'note', 'Handle', 'Reposted a thread from @alicetweets.');
+ await put(engine, 'notes/nickname', 'note', 'Nickname', 'Ally sent the deck.');
+ await put(engine, 'notes/placeholder', 'note', 'Placeholder', 'Owner: @unknown, status unknown.');
+ const before = { sweep: await sweep(engine), links: await links(engine), thin: await thinPages(engine) };
+
+ await put(engine, 'people/alice-example', 'person', 'Alice Example', 'Founder of Acme Example.',
+ { aliases: ['Ally'], x_handle: '@alicetweets' });
+ await put(engine, 'notes/fresh', 'note', 'Fresh', 'Alice said @alicetweets would post it; Ally agreed.');
+ await put(engine, 'notes/full', 'note', 'Full', 'Alice Example joined the call.');
+ const after = { sweep: await sweep(engine), links: await links(engine), thin: await thinPages(engine) };
+ return { before, after };
+}
+
+const expectFixed = (r: Awaited<ReturnType<typeof scenario>>) => {
+ expect(r.before.sweep).toEqual({ state: 'complete', remaining: 0 });
+ // Before the person page exists the thin pages are the only candidates.
+ expect(r.before.links).toEqual([
+ 'notes/first-name -> people/alice',
+ 'notes/handle -> people/alicetweets',
+ 'notes/nickname -> people/ally',
+ ]);
+ expect(r.after.sweep).toEqual({ state: 'complete', remaining: 0 });
+ expect(r.after.links).toEqual([
+ 'notes/fresh -> people/alice-example',
+ 'notes/full -> people/alice-example',
+ 'notes/handle -> people/alice-example',
+ 'notes/nickname -> people/alice-example',
+ // The thin pages titled with the handle and the nickname name the person by them.
+ 'people/alicetweets -> people/alice-example',
+ 'people/ally -> people/alice-example',
+ ]);
+ expect(r.after.thin).toEqual(r.before.thin);
+ expect(r.after.thin).toHaveLength(3);
+};
+
+let pglite: PGLiteEngine;
+let pgliteRun: Awaited<ReturnType<typeof scenario>>;
+beforeAll(async () => {
+ pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ pgliteRun = await scenario(pglite);
+}, 180_000);
+afterAll(async () => { await pglite.disconnect(); });
+
+describe('mentions and thin person pages (PGLite)', () => {
+ test('handle and alias mentions land on the person page, a bare first name links nothing, thin pages stay as they were', () => {
+ expectFixed(pgliteRun);
+ });
+});
+
+describePg('mentions and thin person pages (Postgres)', () => {
+ let pgRun: Awaited<ReturnType<typeof scenario>>;
+ beforeAll(async () => {
+ const pg = await setupDB();
+ for (const table of ['page_aliases', 'page_mention_state', 'mention_gazetteer_entries', 'mention_index_status']) await pg.executeRaw(`DELETE FROM ${table}`);
+ pgRun = await scenario(pg);
+ }, 180_000);
+ afterAll(async () => { await teardownDB(); });
+
+ test('the same outcome on Postgres', () => {
+ expectFixed(pgRun);
+ expect(pgRun).toEqual(pgliteRun);
+ });
+});
diff --git a/test/extract-conversation-facts-entity-resolution.test.ts b/test/extract-conversation-facts-entity-resolution.test.ts
index 060ab258d7..9e3e45b604 100644
--- a/test/extract-conversation-facts-entity-resolution.test.ts
+++ b/test/extract-conversation-facts-entity-resolution.test.ts
@@ -160,12 +160,14 @@ describe('conversation backfill entity resolution', () => {
extractor: extractorFor(extractedFacts),
});
+ // GBRA-574: the unresolved full name keeps its name key (facts.unbacked_entity_keys, on by default).
expect(await dataEntities()).toEqual([
'people/brian-example',
- null,
+ 'unlisted-person',
null,
]);
expect(result.fallback_slugify_count).toBe(1);
+ expect(result.unbacked_keys).toBe(1);
expect(result.resolution_errors).toBe(0);
expect(result.facts_inserted).toBe(3);
expect(await terminalCount()).toBe(1);
diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.ts
index 408f27dfe2..8b8a2b4aa4 100644
--- a/test/extract-conversation-facts.test.ts
+++ b/test/extract-conversation-facts.test.ts
@@ -50,6 +50,7 @@ import { loadOpCheckpoint } from '../src/core/op-checkpoint.ts';
import { runIngestFacts } from '../src/core/transcripts/ingest-facts.ts';
import { runTranscripts } from '../src/commands/transcripts.ts';
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { SLOT_TAG_SYSTEM } from '../src/core/facts/slot-tagging.ts';
// ---------------------------------------------------------------------------
// pageTypesForAllowed — logical→concrete page-type expansion.
@@ -387,6 +388,11 @@ describe('runExtractConversationFactsCore', () => {
providerId: 'stub',
};
}
+ // GBRA-574: the stub's company gets a name key, so each window also makes a slot-tagging call; it tags nothing.
+ if (opts.system === SLOT_TAG_SYSTEM) {
+ return { text: '{"slots":[]}', blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'stub:stub', providerId: 'stub' };
+ }
mainChatCalls++;
if (chatFailure) throw chatFailure;
const hook = chatHook;
diff --git a/test/facts-slot-history-gbra574.test.ts b/test/facts-slot-history-gbra574.test.ts
new file mode 100644
index 0000000000..e962c8cd7b
--- /dev/null
+++ b/test/facts-slot-history-gbra574.test.ts
@@ -0,0 +1,295 @@
+/**
+ * GBRA-574 F (part B): the slot-history arm of the query facts block. Keyless, no network, no model call.
+ *
+ * Protects: a question with a history cue that names one slot dimension (role, employer, location) about one named
+ * entity gets every readable active slot value that entity has had in that dimension, oldest first, each with its date
+ * and read-time window, inside the block's row count and token share; a current-value question, a question with no
+ * dimension or with two gets no arm; the entity is the one page the question names (its fact keys through
+ * factEntitySlugs) or, with no page, the one unbacked name key (a bare two-word slug with no live page) whose words the
+ * question holds as a run, so two candidates match none; a page later written at people/<key> adopts the key's rows,
+ * and a value under the page ends a stint under the key; the same key in two sources stays two people; a remote or
+ * member-scoped caller never sees a value it cannot read (and an unreadable row never ends a readable window), nor the
+ * history of a page it cannot read; withdrawn, superseded and expired rows never show; a failed history read keeps the
+ * block, marks its rows and reports the degraded stage facts_history_unavailable.
+ * PGLite with no git repository (the repo-less brain), and Postgres through
+ * test/e2e/facts-slot-history-gbra574-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { handleToolCall } from '../src/mcp/server.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { valueHash } from '../src/core/chronicle/ontology.ts';
+import { applyFactsBlock, QUERY_FACTS_BLOCK_SHARE } from '../src/core/search/facts-arm.ts';
+import { matchUnbackedKey, slotHistoryDimension } from '../src/core/search/slot-history.ts';
+import { resultTokens } from '../src/core/search/token-budget.ts';
+import { __resetPrivateVisibilityCacheForTests, withCallerAccess } from '../src/core/search/private-visibility.ts';
+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';
+
+type Row = { result_type?: string; chunk_text?: string; fact_row?: { history_unavailable?: true } };
+const CONVERSATION = 'cli:extract-conversation-facts:v1';
+const ROLE_Q = 'In plain words, which job titles has Alice Example held over time?';
+const head = (from: string, until = 'unknown') => '[observed unknown; valid ' + from + ' to ' + until + ']';
+const HISTORY_READ = "COALESCE(f.dim_status, 'active') = 'active'";
+const logger = { info() {}, warn() {}, error() {} };
+
+describe('slotHistoryDimension', () => {
+ test('a history cue plus one dimension fires, with that dimension', () => {
+ expect(slotHistoryDimension(ROLE_Q, '2026-11-17')).toBe('role');
+ expect(slotHistoryDimension("List Alice Example's employers, oldest first.", '2026-11-17')).toBe('employer');
+ expect(slotHistoryDimension('Which cities has Alice Example lived in, in order?', '2026-11-17')).toBe('location');
+ expect(slotHistoryDimension('What companies has Alice Example worked at before?', '2026-11-17')).toBe('employer');
+ });
+ test('a current-value question, no dimension, or two dimensions never fires', () => {
+ expect(slotHistoryDimension('Where does Alice Example live now?', '2026-11-17')).toBeNull();
+ expect(slotHistoryDimension('In plain words, which job title does Alice Example hold at the moment?', '2026-11-17')).toBeNull();
+ expect(slotHistoryDimension('What job titles does Alice Example hold now, after all those roles before?', '2026-11-17')).toBeNull();
+ expect(slotHistoryDimension('What did Alice Example do before?', '2026-11-17')).toBeNull();
+ expect(slotHistoryDimension("List Alice Example's job titles and employers over time.", '2026-11-17')).toBeNull();
+ expect(slotHistoryDimension('Where does Alice Example work?', '2026-11-17')).toBeNull();
+ });
+});
+
+for (const backend of testBackends()) {
+ describe(backend, () => {
+ let engine: BrainEngine;
+ let sourceId: string;
+ let otherSource: string;
+ let close: (() => Promise<void>) | undefined;
+ let dispose: (() => Promise<void>) | undefined;
+ const ids: Record<string, number> = {};
+
+ async function fact(key: string, text: string, entity: string, validFrom: string, slot: [string, string] | null,
+ opts: { visibility?: 'world' | 'private'; page?: string; source?: string } = {}) {
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from, source_markdown_slug, dimension, value, value_hash, dim_status)
+ VALUES ($1, $2, $3, 'fact', $4, $5, 1, $6::timestamptz, $7, $8, $9, $10, $11) RETURNING id`,
+ [opts.source ?? sourceId, entity, text, CONVERSATION, opts.visibility ?? 'world', validFrom + 'T00:00:00Z', opts.page ?? null,
+ slot?.[0] ?? null, slot?.[1] ?? null, slot ? valueHash(slot[1]) : null, slot ? 'active' : null]);
+ ids[key] = Number(row!.id);
+ }
+
+ const local = async (query: string, source = sourceId) =>
+ (await handleToolCall(engine, 'query', { query, expand: false, use_cache: false, source_id: source, limit: 50, token_budget: 5500 }) as Row[])
+ .filter(r => r.result_type === 'fact').map(r => r.chunk_text ?? '');
+ const remote = async (query: string) => {
+ __resetPrivateVisibilityCacheForTests();
+ const auth = { token: 't', clientId: 'slot-history-remote', scopes: ['read'], sourceId, allowedSources: [sourceId] };
+ const r = await dispatchToolCall(engine, 'query', { query, expand: false, use_cache: false, limit: 50, token_budget: 5500 },
+ { remote: true, transport: 'stdio', sourceId, auth, config: { engine: engine.kind } as never, logger });
+ return r.content.map(c => (c as { text?: string }).text ?? '').join('\n');
+ };
+ const asMember = async (member: string, query: string) => {
+ __resetPrivateVisibilityCacheForTests();
+ const rows = await withCallerAccess({ identity: ['member:' + member] }, () => applyFactsBlock(engine, query, [],
+ { sourceIds: [sourceId], remote: true, readScope: { sourceIds: [sourceId], excludePrivate: true }, budget: 5500, tokenBudget: 5500, rowCap: async () => 50 }));
+ return (rows as Row[]).filter(r => r.result_type === 'fact').map(r => r.chunk_text ?? '');
+ };
+ const block = async (query: string, sourceIds: string[], budget = 5500, rowCap = 50, eng: BrainEngine = engine) =>
+ ((await applyFactsBlock(eng, query, [], { sourceIds, remote: false, budget, tokenBudget: budget, rowCap: async () => rowCap })) as Row[])
+ .filter(r => r.result_type === 'fact');
+ const rowOf = (rows: string[], text: string) => rows.find(r => r.includes(text));
+ const headOf = (rows: string[], text: string) => rowOf(rows, text)?.split('\n')[0];
+
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const template = await persistencePostgresTemplate(requirePostgresTestDatabase());
+ const c = await template.clone();
+ engine = c.engine; close = c.close; dispose = template.dispose;
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ }
+ sourceId = await newSource(engine);
+ otherSource = await newSource(engine);
+ await putPage(engine, sourceId, 'people/carol-example', page('person', 'Carol Example', 'Carol Example is in the address book.'));
+ await putPage(engine, sourceId, 'people/erin-example', page('person', 'Erin Example', 'Erin Example is in the address book.', 'visibility: private\n'));
+ await putPage(engine, sourceId, 'memory/members/alice-example', page('note', 'Memory of alice-example', 'Work notes.', 'readable_by: [alice-example]\n'));
+
+ await fact('a_note', 'Alice Example keeps a plain words list of job titles held over time.', 'alice-example', '2020-01-01', null);
+ await fact('a_intern', 'Alice Example started out as a junior intern.', 'alice-example', '2021-02-01', ['role', 'Intern']);
+ await fact('a_acme', 'Alice Example joined Acme Example.', 'alice-example', '2021-02-01', ['employer', 'Acme Example']);
+ await fact('a_analyst', 'Alice Example was promoted to analyst.', 'alice-example', '2022-03-01', ['role', 'Analyst']);
+ await fact('a_manager', 'Alice Example became the team manager.', 'alice-example', '2024-05-01', ['role', 'Manager']);
+ await fact('a_director', 'Alice Example became director.', 'alice-example', '2025-01-01', ['role', 'Director'], { visibility: 'private' });
+ await fact('a_pilot', 'Alice Example flies as a pilot.', 'alice-example', '2023-01-01', ['role', 'Pilot'], { source: otherSource });
+ await fact('aj_guard', 'Alice Example Jr started as a lifeguard.', 'alice-example-jr', '2022-06-01', ['role', 'Lifeguard']);
+
+ await fact('c_cashier', 'Carol Example began as a cashier.', 'people/carol-example', '2020-01-01', ['role', 'Cashier']);
+ await fact('c_lead', 'Carol Example moved up to store lead.', 'people/carol-example', '2022-01-01', ['role', 'Store Lead']);
+
+ await fact('d_night', 'Dana Example worked the night desk.', 'dana-example', '2020-06-01', ['role', 'Night Clerk']);
+
+ await fact('e_courier', 'Erin Example started as a courier.', 'people/erin-example', '2021-01-01', ['role', 'Courier']);
+
+ await fact('g_engineer', 'Gwen Example joined as an engineer.', 'gwen-example', '2021-01-01', ['role', 'Engineer']);
+ await fact('g_staff', 'Gwen Example became staff engineer.', 'gwen-example', '2023-01-01', ['role', 'Staff Engineer'],
+ { visibility: 'private', page: 'memory/members/alice-example' });
+
+ await fact('h_clerk', 'Hal Example works as a clerk.', 'hal-example', '2020-01-01', ['role', 'Clerk']);
+ await fact('h_cook', 'Hal Example works as a cook.', 'hal-example', '2021-01-01', ['role', 'Cook']);
+ await fact('h_baker', 'Hal Example works as a baker.', 'hal-example', '2022-01-01', ['role', 'Baker']);
+ await fact('h_tailor', 'Hal Example works as a tailor.', 'hal-example', '2023-01-01', ['role', 'Tailor']);
+ const forgot = await dispatchToolCall(engine, 'forget_fact', { id: ids.h_cook }, { remote: false, sourceId });
+ expect(forgot.isError).toBeFalsy();
+ await engine.executeRaw('UPDATE facts SET superseded_by = $2, expired_at = now() WHERE id = $1', [ids.h_baker, ids.h_clerk]);
+ await engine.executeRaw('UPDATE facts SET expired_at = now() WHERE id = $1', [ids.h_tailor]);
+ }, 300_000);
+ afterAll(async () => { await close?.(); await dispose?.(); if (backend === 'pglite') await engine?.disconnect(); }, 60_000);
+
+ describe('D1 unbacked-key matcher', () => {
+ const scope = (sourceIds: string[]) => ({ sourceIds, worldOnly: false, excludePrivate: false });
+ test('exactly one key whose words the question holds as a run', async () => {
+ expect(await matchUnbackedKey(engine, ROLE_Q, scope([sourceId]))).toEqual({ source_id: sourceId, entity_slug: 'alice-example' });
+ expect(await matchUnbackedKey(engine, "Alice Example Jr's job titles over time?", scope([sourceId]))).toEqual({ source_id: sourceId, entity_slug: 'alice-example-jr' });
+ });
+ test('two candidates, a single word, a page-backed slug or no key: none', async () => {
+ expect(await matchUnbackedKey(engine, ROLE_Q, scope([sourceId, otherSource]))).toBeNull();
+ expect(await matchUnbackedKey(engine, 'Job titles of Alice Example and Hal Example over time?', scope([sourceId]))).toBeNull();
+ expect(await matchUnbackedKey(engine, 'Which job titles has Alice held over time?', scope([sourceId]))).toBeNull();
+ expect(await matchUnbackedKey(engine, 'Which job titles has Carol Example held over time?', scope([sourceId]))).toBeNull();
+ expect(await matchUnbackedKey(engine, 'Which job titles has Zed Example held over time?', scope([sourceId]))).toBeNull();
+ });
+ });
+
+ describe('the arm in the facts block', () => {
+ test('an unbacked key: every value of the dimension, oldest first, with its window', async () => {
+ const rows = await local(ROLE_Q);
+ const order = ['junior intern', 'promoted to analyst', 'team manager', 'became director'].map(t => rows.findIndex(r => r.includes(t)));
+ expect(order.every(i => i >= 0)).toBe(true);
+ expect([...order].sort((a, b) => a - b)).toEqual(order);
+ expect(headOf(rows, 'junior intern')).toBe(head('2021-02-01', '2022-03-01'));
+ expect(headOf(rows, 'promoted to analyst')).toBe(head('2022-03-01', '2024-05-01'));
+ expect(headOf(rows, 'team manager')).toBe(head('2024-05-01', '2025-01-01'));
+ expect(rows.join('\n')).not.toContain('Acme Example');
+ expect(rows.join('\n')).not.toContain('pilot');
+ expect(rows.join('\n')).not.toContain('lifeguard');
+ });
+ test('a current-value question gets no history', async () => {
+ const text = (await local('In plain words, which job title does Alice Example hold at the moment?')).join('\n');
+ expect(text).not.toContain('junior intern');
+ expect(text).not.toContain('promoted to analyst');
+ });
+ test('the arm stays inside the block row count and token share', async () => {
+ const budget = 1200;
+ const rows = await block(ROLE_Q, [sourceId], budget, 2);
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.length).toBeLessThanOrEqual(2);
+ expect(rows.reduce((n, r) => n + resultTokens(r as never), 0)).toBeLessThanOrEqual(Math.floor(budget * QUERY_FACTS_BLOCK_SHARE));
+ });
+ test('a page-backed entity reads its own facts', async () => {
+ const rows = await local('In plain words, which job titles has Carol Example held over time?');
+ expect(headOf(rows, 'began as a cashier')).toBe(head('2020-01-01', '2022-01-01'));
+ expect(headOf(rows, 'moved up to store lead')).toBe(head('2022-01-01'));
+ });
+ test('the same key in another source is another person', async () => {
+ expect((await local(ROLE_Q)).join('\n')).not.toContain('pilot');
+ const other = (await local(ROLE_Q, otherSource)).join('\n');
+ expect(other).toContain('flies as a pilot');
+ expect(other).not.toContain('junior intern');
+ const both = (await block(ROLE_Q, [sourceId, otherSource])).map(r => r.chunk_text ?? '').join('\n');
+ expect(both).not.toContain('pilot');
+ expect(both).not.toContain('junior intern');
+ });
+ test('withdrawn, superseded and expired rows never show', async () => {
+ const text = (await local('In plain words, which job titles has Hal Example held over time?')).join('\n');
+ expect(text).toContain('works as a clerk');
+ for (const gone of ['cook', 'baker', 'tailor']) expect(text).not.toContain(gone);
+ });
+ test('a page later written at people/<key> adopts the key, and its value ends the key stint', async () => {
+ const Q = 'In plain words, which job titles has Dana Example held over time?';
+ expect(headOf(await local(Q), 'night desk')).toBe(head('2020-06-01'));
+ await putPage(engine, sourceId, 'people/dana-example', page('person', 'Dana Example', 'Dana Example is in the address book.'));
+ await fact('d_head', 'Dana Example became the head of front office.', 'people/dana-example', '2023-06-01', ['role', 'Head of Front Office']);
+ const rows = await local(Q);
+ expect(headOf(rows, 'night desk')).toBe(head('2020-06-01', '2023-06-01'));
+ expect(headOf(rows, 'head of front office')).toBe(head('2023-06-01'));
+ });
+ });
+
+ describe('read policy', () => {
+ test('a remote caller sees no private value, and a private row ends no window it sees', async () => {
+ const text = await remote(ROLE_Q);
+ expect(text).toContain(head('2021-02-01', '2022-03-01'));
+ expect(text).toContain(head('2024-05-01'));
+ expect(text).not.toContain('director');
+ expect(text).not.toContain(head('2024-05-01', '2025-01-01'));
+ });
+ test('a remote caller gets no history of a page it cannot read', async () => {
+ const Q = 'In plain words, which job titles has Erin Example held over time?';
+ expect((await local(Q)).join('\n')).toContain('started as a courier');
+ const text = await remote(Q);
+ expect(text).not.toContain('courier');
+ expect(text).not.toContain('people/erin-example');
+ });
+ test('a private page written later at a name key keeps the key rows from a remote caller', async () => {
+ const Q = 'In plain words, which job titles has Hana Example held over time?';
+ await fact('h_cook', 'Hana Example started as a line cook.', 'hana-example', '2021-01-01', ['role', 'Cook']);
+ expect(await remote(Q)).toContain('line cook');
+ await putPage(engine, sourceId, 'people/hana-example', page('person', 'Hana Example', 'Hana Example is in the address book.', 'visibility: private\n'));
+ expect((await local(Q)).join('\n')).toContain('line cook');
+ expect(await remote(Q)).not.toContain('line cook');
+ });
+ test('a private page written later at orgs/<key> keeps the key rows from a remote caller', async () => {
+ const Q = 'In plain words, which job titles has Kai Example held over time?';
+ await fact('k_cook', 'Kai Example started as a line cook.', 'kai-example', '2021-01-01', ['role', 'Cook']);
+ expect(await remote(Q)).toContain('line cook');
+ await putPage(engine, sourceId, 'orgs/kai-example', page('company', 'Kai Example', 'Kai Example is in the address book.', 'visibility: private\n'));
+ expect((await local(Q)).join('\n')).toContain('line cook');
+ expect(await remote(Q)).not.toContain('line cook');
+ });
+ test('a non-Latin name key matches its history question', async () => {
+ await fact('i_cook', 'Иван Петров started as a line cook.', 'иван-петров', '2021-01-01', ['role', 'Cook']);
+ await fact('i_chef', 'Иван Петров became head chef.', 'иван-петров', '2023-01-01', ['role', 'Head Chef']);
+ const text = (await local('In plain words, which job titles has Иван Петров held over time?')).join('\n');
+ expect(text).toContain('started as a line cook');
+ expect(text).toContain('became head chef');
+ });
+ test('a member-scoped caller sees a value on its own page; another member sees neither it nor its end', async () => {
+ const Q = 'In plain words, which job titles has Gwen Example held over time?';
+ const alice = await asMember('alice-example', Q);
+ expect(headOf(alice, 'joined as an engineer')).toBe(head('2021-01-01', '2023-01-01'));
+ expect(rowOf(alice, 'became staff engineer')).toBeDefined();
+ const bob = await asMember('bob-example', Q);
+ expect(headOf(bob, 'joined as an engineer')).toBe(head('2021-01-01'));
+ expect(bob.join('\n')).not.toContain('staff engineer');
+ });
+ });
+
+ describe('H1 a failed history read', () => {
+ const failing = (base: BrainEngine) => new Proxy(base, { get(target, prop) {
+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => sql.includes(HISTORY_READ)
+ ? Promise.reject(new Error('history read failed')) : target.executeRaw(sql, params);
+ const v = (target as unknown as Record<string, unknown>)[prop as string];
+ return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(target) : v;
+ } }) as BrainEngine;
+ test('keeps the block and marks its rows', async () => {
+ const rows = await block(ROLE_Q, [sourceId], 5500, 50, failing(engine));
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.map(r => r.chunk_text).join('\n')).not.toContain('junior intern');
+ expect(rows.every(r => r.fact_row?.history_unavailable)).toBe(true);
+ expect((await block(ROLE_Q, [sourceId])).some(r => r.fact_row?.history_unavailable)).toBe(false);
+ });
+ test('query reports the degraded stage facts_history_unavailable', async () => {
+ const call = async () => {
+ const r = await dispatchToolCall(engine, 'query', { query: ROLE_Q, expand: false, use_cache: false, source_id: sourceId, limit: 50, token_budget: 5500 },
+ { remote: false, transport: 'stdio', sourceId, config: { engine: engine.kind } as never, logger });
+ return JSON.stringify(r._meta ?? {});
+ };
+ expect(await call()).not.toContain('facts_history_unavailable');
+ const original = engine.executeRaw;
+ engine.executeRaw = (function (this: BrainEngine, sql: string, ...rest: unknown[]) {
+ if (sql.includes(HISTORY_READ)) return Promise.reject(new Error('history read failed'));
+ return (original as (...a: unknown[]) => unknown).call(this, sql, ...rest);
+ }) as typeof engine.executeRaw;
+ try {
+ expect(await call()).toContain('facts_history_unavailable');
+ } finally { engine.executeRaw = original; }
+ }, 60_000);
+ });
+ });
+}
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
index c100f7f7f5..7cd38daeab 100644
--- a/test/fixtures/fold-hook-noop-6712.json
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -34,7 +34,7 @@
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
"UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
"SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action IN ('supersede_fact', 'confirm') AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
@@ -100,7 +100,7 @@
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'",
"WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
"SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) AND NOT (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) ORDER BY f.row_num, f.id",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action = 'supersede_fact' AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier, (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) AS above, (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world')) AS opened FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND ((CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) OR (f.visibility <> 'world' AND EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.action IN ('supersede_fact', 'confirm') AND tp.related_table = 'facts' AND tp.related_id = f.id AND tp.status IN ('pending', 'rejected', 'undone') AND tp.before_state->'visibility' IS NOT NULL) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS w(row_num integer, fact text, visibility text) WHERE w.row_num = f.row_num AND w.fact = f.fact AND w.visibility = 'world')) OR (f.visibility = 'private' AND f.id::text = ANY(string_to_array(COALESCE(current_setting('gbrain.write_open_facts', true), ''), ',')) AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS o(row_num integer, fact text, visibility text) WHERE o.row_num = f.row_num AND o.fact = f.fact AND o.visibility = 'world'))) ORDER BY f.row_num FOR UPDATE",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 10aee69d96..4ef26d2d3b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -651,7 +651,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -659,9 +659,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 3741477cf7..535917dcee 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -651,7 +651,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -659,9 +659,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 52626e4ea2..b013ffd167 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -651,7 +651,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -659,9 +659,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 50096ce2dc..5ecaaf20f9 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -654,7 +654,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -662,9 +662,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index aa3a447e2e..7152c01ad8 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -654,7 +654,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -662,9 +662,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 80626d6620..d831e6b2fe 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -654,7 +654,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -662,9 +662,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index b1848b7c05..13eb5bb0f9 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -498,7 +498,7 @@
"kind": "variable",
"name": "DEGRADED_STAGES",
"signature": [
- "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_by_design\", \"projection_status_unknown\", \"keyword_count_unavailable\", \"saved_facts_withheld\", \"fact_observed_date_unavailable\", \"contested_unavailable\"]"
+ "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_by_design\", \"projection_status_unknown\", \"keyword_count_unavailable\", \"saved_facts_withheld\", \"fact_observed_date_unavailable\", \"contested_unavailable\", \"facts_history_unavailable\"]"
]
},
{
@@ -512,14 +512,14 @@
"kind": "type",
"name": "DegradedStage",
"signature": [
- "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\""
+ "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\""
]
},
{
"kind": "interface",
"members": [
"reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"timeout\" | \"provider_error\" | \"no_provider\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | \"skipped_after_timeout\" | undefined",
- "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\""
+ "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\""
],
"name": "DegradedStageEntry"
},
@@ -1330,7 +1330,7 @@
"kind": "variable",
"name": "RANKING_ONLY_DEGRADED_STAGES",
"signature": [
- "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\">"
+ "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\">"
]
},
{
@@ -1530,7 +1530,7 @@
"exact_lookup?: \"title\" | \"slug\" | \"identifier\" | undefined",
"exact_match_boost?: number | undefined",
"fact_id?: string | undefined",
- "fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true; } | undefined",
+ "fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true; history_unavailable?: true; } | undefined",
"feedback_boost?: number | undefined",
"follow_up?: { op: \"recall\"; args: Record<string, string>; } | undefined",
"fused_score?: number | undefined",
@@ -9618,7 +9618,7 @@
"kind": "variable",
"name": "DEGRADED_STAGES",
"signature": [
- "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_by_design\", \"projection_status_unknown\", \"keyword_count_unavailable\", \"saved_facts_withheld\", \"fact_observed_date_unavailable\", \"contested_unavailable\"]"
+ "readonly [\"embed_unavailable\", \"embed_timeout\", \"expansion_failed\", \"expansion_partial\", \"rescore_skipped\", \"vector_arm_failed\", \"keyword_arm_failed\", \"title_arm_failed\", \"budget_dropped_all\", \"budget_truncated\", \"keyword_zero\", \"cache_prestamp\", \"reranker_skipped\", \"rerank_passthrough\", \"rerank_failed\", \"keyword_relaxed_carried\", \"safe_index_pending\", \"vector_candidates_incomplete\", \"keyword_candidates_incomplete\", \"projection_pending\", \"projection_by_design\", \"projection_status_unknown\", \"keyword_count_unavailable\", \"saved_facts_withheld\", \"fact_observed_date_unavailable\", \"contested_unavailable\", \"facts_history_unavailable\"]"
]
},
{
@@ -9632,14 +9632,14 @@
"kind": "type",
"name": "DegradedStage",
"signature": [
- "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\""
+ "\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\""
]
},
{
"kind": "interface",
"members": [
"reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"timeout\" | \"provider_error\" | \"no_provider\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | \"skipped_after_timeout\" | undefined",
- "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\""
+ "stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\""
],
"name": "DegradedStageEntry"
},
@@ -10192,7 +10192,7 @@
"kind": "variable",
"name": "RANKING_ONLY_DEGRADED_STAGES",
"signature": [
- "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\">"
+ "ReadonlySet<\"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"projection_by_design\" | \"projection_status_unknown\" | \"keyword_count_unavailable\" | \"saved_facts_withheld\" | \"fact_observed_date_unavailable\" | \"contested_unavailable\" | \"facts_history_unavailable\">"
]
},
{
@@ -10392,7 +10392,7 @@
"exact_lookup?: \"title\" | \"slug\" | \"identifier\" | undefined",
"exact_match_boost?: number | undefined",
"fact_id?: string | undefined",
- "fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true; } | undefined",
+ "fact_row?: { id: number; valid_from: string; valid_until: string | null; source?: string; from_quoted_page?: true; observed?: string; observed_unavailable?: true; contested_unavailable?: true; history_unavailable?: true; } | undefined",
"feedback_boost?: number | undefined",
"follow_up?: { op: \"recall\"; args: Record<string, string>; } | undefined",
"fused_score?: number | undefined",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 956e64633e..70427450bb 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 315,
+ "count": 316,
"gaps": [
17,
18,
@@ -70,7 +70,7 @@
"dropInvalidConcurrentIndex": "6864d844b7dfb2fbecdd0fb9c73e06248473376feb794b3fe58f036c70d2d44c",
"enableRlsSql": "b7901b3d5231fcfacd3260ce0f59d4701d8c0bee902808ff48b1d8affbd444b6",
"ensureFactsFtsIndex": "95e723314ac30cea2db48e0e167c554ef1fa06df80cae765faa2a080a3a655c2",
- "failClosedLedgerGuards": "dadd3ceb13286ca7ab969a911a310c87be313de6ec2c2c8e14d3f95b72901481",
+ "failClosedLedgerGuards": "8a095ef92247a83e7d569c0a721facf0bb4c4213bd2ed5149a81947469bbd5e6",
"getFtsLanguage": "0d790b4c4af1f67a2a1bbd59470beb13f434917b381931baf8404a41c5d903db",
"grantFromRow": "d0b537d687ed3f88f61e33b88490c6dcc74b829485b0c2c44d3238d100c4c3a7",
"hardenFunctionSearchPaths": "ca7bce96a087bfb4644268e5c2ad0ace76532905ceffb4efdc69608e0ef11894",
@@ -105,7 +105,7 @@
"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6",
"withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"
},
- "latest": 320,
+ "latest": 321,
"records": [
{
"handler": {
@@ -2260,8 +2260,8 @@
"idempotent": true,
"name": "durable_fact_withdrawals",
"sql": {
- "length": 4502,
- "sha256": "9843f1619915b1e6f507560317c83ea41b6a3f1fe412d3a99bc34d0e37671630"
+ "length": 4814,
+ "sha256": "b8a0ffcde1c3e87b62905a3484441f3f1e9c62e1fcfe5c35c69c50f3c40826c5"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2573,8 +2573,8 @@
"idempotent": true,
"name": "fact_withdrawal_subject",
"sql": {
- "length": 4474,
- "sha256": "e519d7a2cfd55833e8a2578d4a86c7104a6614042dc80523c5d5ec35b1fe60c6"
+ "length": 4786,
+ "sha256": "d079b6bf4b69a408ed990c1c3e6d4d59e8804816d8d40cad7d91e65886901d94"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2657,8 +2657,8 @@
"idempotent": true,
"name": "fact_withdrawal_normalized_fingerprint",
"sql": {
- "length": 5218,
- "sha256": "be030a0bbd1afec71a3055bcdb67d190b26e582e72a6cc256ea9bfbf2a0ca687"
+ "length": 5530,
+ "sha256": "d70fbb448e12f7dc25da530569d7dc31c163ac95de547642eb6b70038d8ddb73"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -3497,8 +3497,8 @@
"idempotent": true,
"name": "memory_purge",
"sql": {
- "length": 10146,
- "sha256": "8e68069899bf4a92a09dd896b3901ee0c72ade2478d721420a9fe0e61fd45c26"
+ "length": 10378,
+ "sha256": "34888d1763251b12c3308416cffa9e361a6d280fc104c0ab8ef08f629d6354c5"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4238,8 +4238,8 @@
"idempotent": true,
"name": "set_based_fact_insert_guards",
"sql": {
- "length": 12894,
- "sha256": "80072441dbeb3a3989bb4471ab7ac624b1aa21c4e9dd9d4e59975700e50abaa3"
+ "length": 13786,
+ "sha256": "5e7c0747a36bb19892fb1a47f0277e5aea1c69e44856704948e625d9f808330b"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4541,8 +4541,8 @@
"idempotent": true,
"name": "outcome_markers_skip_purge_guard",
"sql": {
- "length": 6870,
- "sha256": "30e88e73d6c7c7a7fab54c5884535eb5c2ffa294ade9485801a654afbd1c834d"
+ "length": 7762,
+ "sha256": "197b0509578b229426ccff05a2cd9f8762fd38a5810f7b1f81633b45fd4b1b99"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -4988,8 +4988,8 @@
"idempotent": true,
"name": "member_page_withdrawal_scope",
"sql": {
- "length": 9129,
- "sha256": "97119f853f23194ed6ac926a0a18e2cb6f3e6289a436f1c2c1bf4d61526d1483"
+ "length": 10333,
+ "sha256": "74a59e84662d5fc399f8527d82cd37b3a4e35fbefc02136d017d1782fee3e025"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -5229,6 +5229,25 @@
"transaction": "absent",
"verify": "absent",
"version": 320
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "failClosedLedgerGuards"
+ ],
+ "sha256": "dda05e2e1849dbaac55e036330c44c55c6c701a745e6aa2366c81592434ec01d"
+ },
+ "idempotent": true,
+ "name": "unbacked_entity_keys_guards",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 321
}
],
"versions": [
@@ -5546,7 +5565,8 @@
317,
318,
319,
- 320
+ 320,
+ 321
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index c020f34014..b56b40edea 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -651,7 +651,7 @@
"gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=edf066d51ee76d4037663393271883a12d7fdf4f0f01b7d1faa9e979d552c6c6",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_guest_records()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2d055da8535efc1d03d9e4e1b6ebaff581577f2b20726617821434266fb27597",
- "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fb06847c44335f63ae529f1a561b65c860213e43f95d1cdf4e66f4e936db3ef2",
+ "gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=987e77b02393511a72e1503c3900d5162d90f5473a2c6f83c23cdd5689601856",
"gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
@@ -659,9 +659,9 @@
"gbrain_mark_derivation_scope_entry()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=592e9e3bcab2cf339197544185dc0ae3664698acecaf77cc6a1588c4134d7a93",
"gbrain_owner_only_lineage()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=ab91d9d7e1c492ac608e00b812a621d950f5c693385d5370450fa67f2af02cea",
"gbrain_owner_only_lineage(p_table text, p_id bigint)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=01a7781cebe2d4b6605d0f15937b3c290a2d706469f375b77200036a8bbe5535",
- "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=672d0b6ff2688229b69291156d7ab73216750e2d9e3a0b1c76e493d0072b2d4a",
+ "gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=9969685406ebbe862fd08037eb4a81b31524ae422069c61d442b082369ae920c",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=dc7a279205df83f00b9147adea8e609a410d0484d04648ea3fdb4344a5caf259",
- "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0a55426ae1c7a540b121c0d1a588f7dbcdb8afe60b5e68ee007aad703e8504d",
+ "gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7da3c1a6b9fd96be5ce5b09924815ce140cc2cbb1da0755cffc34706846175b9",
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5a4d7edc34063b61f333fa24f0ce3e632c10d4f4759b023e876ff6624f4180db",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=16445f63258067ff4fe8a723ef5a04605d8c8d22a927b2239774fb5d0d7e3aa5",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4bbe0281b504599ecf7facae1e1d6701d8890b692a1bcb559b8dc3549557e169",
diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.json
index 191d535e61..ab93335b74 100644
--- a/test/fixtures/goldens/sql-text/facts.json
+++ b/test/fixtures/goldens/sql-text/facts.json
@@ -159,8 +159,8 @@
"number",
"array<string>"
],
- "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND COALESCE(source, '') NOT LIKE 'cli:extract-conversation-facts%' AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND ((NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = ANY(ARRAY[(pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=pp.source_id AND renamed.alias_slug=(pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=pp.source_id AND moved.old_slug=(pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND NOT (facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",
- "textSha256": "9b3e993ead0aeb605a16920b58f4cfbe264a2d95c181e528a3d4deb4f17597e1"
+ "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND COALESCE(source, '') NOT LIKE 'cli:extract-conversation-facts%' AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND ((NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = ANY(ARRAY[(pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=pp.source_id AND renamed.alias_slug=(pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=pp.source_id AND moved.old_slug=(pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND CASE WHEN strpos(facts.entity_slug, '/') = 0 THEN NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug = ANY(ARRAY['people/' || facts.entity_slug, 'companies/' || facts.entity_slug, 'hosts/' || facts.entity_slug, 'projects/' || facts.entity_slug, 'concepts/' || facts.entity_slug, 'funds/' || facts.entity_slug, 'orgs/' || facts.entity_slug, 'organizations/' || facts.entity_slug]) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) ELSE TRUE END AND NOT (facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",
+ "textSha256": "480b9db0d01e2bb9e9563cd8979977b59d65aecad1766b85f133101650175b7c"
}
]
},
@@ -253,8 +253,8 @@
"number",
"boolean"
],
- "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND COALESCE(source, '') NOT LIKE 'cli:extract-conversation-facts%' AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND ((NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = ANY(ARRAY[(pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=pp.source_id AND renamed.alias_slug=(pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=pp.source_id AND moved.old_slug=(pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND NOT (facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",
- "textSha256": "71571b9fc082e5012763f105ac18eeb8a26e05956fd8ce051a27d06b10ce0b24"
+ "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND COALESCE(source, '') NOT LIKE 'cli:extract-conversation-facts%' AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND ((NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = ANY(ARRAY[(pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=pp.source_id AND renamed.alias_slug=(pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=pp.source_id AND moved.old_slug=(pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND CASE WHEN strpos(facts.entity_slug, '/') = 0 THEN NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug = ANY(ARRAY['people/' || facts.entity_slug, 'companies/' || facts.entity_slug, 'hosts/' || facts.entity_slug, 'projects/' || facts.entity_slug, 'concepts/' || facts.entity_slug, 'funds/' || facts.entity_slug, 'orgs/' || facts.entity_slug, 'organizations/' || facts.entity_slug]) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter)) AND NOT EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id >= '' AND (read_source.config->>'kind' IN ('imessage') OR read_source.config->>'owner_only' = 'true'))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN (EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = ANY(ARRAY[(entity_pp.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=entity_pp.source_id AND renamed.alias_slug=(entity_pp.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=entity_pp.source_id AND moved.old_slug=(entity_pp.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private')) WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = ANY(ARRAY[(derived_input.frontmatter->>'source_slug'), (SELECT renamed.canonical_slug FROM slug_aliases renamed WHERE renamed.source_id=derived_input.source_id AND renamed.alias_slug=(derived_input.frontmatter->>'source_slug') AND renamed.notes='rename')]) AND derived_input_origin.frontmatter->>'visibility' = 'private') OR EXISTS (SELECT 1 FROM slug_rename_history moved JOIN pages moved_to ON moved_to.source_id=moved.source_id AND moved_to.slug=moved.new_slug WHERE moved.source_id=derived_input.source_id AND moved.old_slug=(derived_input.frontmatter->>'source_slug') AND moved_to.frontmatter->>'visibility'='private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) ELSE TRUE END AND NOT (facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",
+ "textSha256": "5295e79f4ac408effc9ebe3172c16801cdd8b764fc3c166c1db9c83a97a60963"
}
]
},
diff --git a/test/mentions-thin-pages.test.ts b/test/mentions-thin-pages.test.ts
new file mode 100644
index 0000000000..9b0b1b7150
--- /dev/null
+++ b/test/mentions-thin-pages.test.ts
@@ -0,0 +1,126 @@
+/**
+ * Mention resolution against thin pages: frontmatter handles and aliases are
+ * explicit claims, a bare first name never links a person alone.
+ *
+ * Protects: an X handle in frontmatter links only where the text writes
+ * `@handle`; a placeholder handle (`unknown`, `0`) is no handle; a page of
+ * another kind titled with the handle keeps its title; two pages claiming one
+ * handle link neither through it; a one-word person title that is another
+ * person's first name links nothing, while a one-word person title nobody
+ * shares and a one-word company title still link. Regression: a handle or
+ * nickname mention landing on a thin page whose title is the handle or
+ * nickname; a bare first name linking to a thin first-name page.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildGazetteer, findMentionedEntities, frontmatterHandle } from '../src/core/by-mention.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { mentionBrain, resetMentionBrain } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+const put = (slug: string, type: string, title: string, frontmatter: Record<string, unknown> = {}) =>
+ importFromContent(engine, slug, serializeMarkdown(frontmatter, 'Stub.', '', { type: type as never, title, tags: [] }), { noEmbed: true });
+
+async function links(text: string): Promise<string[]> {
+ const gazetteer = await buildGazetteer(engine);
+ return findMentionedEntities(text, gazetteer, { fromSlug: 'notes/x', fromSourceId: 'default' }).map(m => m.slug);
+}
+
+describe('frontmatterHandle', () => {
+ test('reads a handle, an @handle and an X or Twitter profile URL', () => {
+ expect(frontmatterHandle('@AliceTweets')).toBe('alicetweets');
+ expect(frontmatterHandle(' alice_t ')).toBe('alice_t');
+ expect(frontmatterHandle('https://x.com/alicetweets')).toBe('alicetweets');
+ expect(frontmatterHandle('twitter.com/alicetweets?lang=en')).toBe('alicetweets');
+ });
+ test('placeholders, ids and prose are not handles', () => {
+ for (const v of ['unknown', 'Unknown', 'none', 'n/a', '0', '000', '12345', '', ' ', 'Alice Example', 'a-very-long-handle-name', 'true', 'false']) {
+ expect(frontmatterHandle(v)).toBeNull();
+ }
+ expect(frontmatterHandle(null)).toBeNull();
+ });
+});
+
+describe('frontmatter handles', () => {
+ test('a handle links where the text writes @handle, not as a bare word', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { x_handle: 'alicetweets' });
+ expect(await links('A thread from @alicetweets.')).toEqual(['people/alice-example']);
+ expect(await links('alicetweets is a made-up word here.')).toEqual([]);
+ });
+
+ test('a thin person page titled with the handle yields it, @handle or bare', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { twitter: '@alicetweets' });
+ await put('people/alicetweets', 'person', 'alicetweets');
+ expect(await links('A thread from @alicetweets.')).toEqual(['people/alice-example']);
+ expect(await links('Quoted alicetweets again.')).toEqual(['people/alice-example']);
+ });
+
+ test('a placeholder handle is no handle', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { x_handle: 'unknown' });
+ expect(await links('Owner: @unknown.')).toEqual([]);
+ });
+
+ test('a company titled with a person\'s handle keeps its title; @handle reaches the person', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { x_handle: 'quorvex' });
+ await put('companies/quorvex', 'company', 'Quorvex');
+ expect(await links('Quorvex shipped.')).toEqual(['companies/quorvex']);
+ expect(await links('Shipped, says @quorvex.')).toEqual(['people/alice-example']);
+ });
+
+ test('two pages claiming one handle: neither links through it and the thin page keeps its title', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { x_handle: 'sharedhandle' });
+ await put('people/bob-example', 'person', 'Bob Example', { x_handle: 'sharedhandle' });
+ await put('people/sharedhandle', 'person', 'sharedhandle');
+ expect(await links('From @sharedhandle.')).toEqual(['people/sharedhandle']);
+ });
+});
+
+describe('frontmatter aliases and bare first names', () => {
+ test('a thin person page titled with another person\'s frontmatter alias yields it', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { aliases: ['Ally'] });
+ await put('people/ally', 'person', 'Ally');
+ expect(await links('Ally sent the deck.')).toEqual(['people/alice-example']);
+ });
+
+ test('a page claiming its own title keeps it', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { aliases: ['Ally'] });
+ await put('people/ally', 'person', 'Ally', { aliases: ['Ally'] });
+ expect(await links('Ally sent the deck.')).toEqual(['people/ally']);
+ });
+
+ test('a one-word person title that is another person\'s first name links nothing', async () => {
+ await put('people/alice-example', 'person', 'Alice Example');
+ await put('people/alice', 'person', 'Alice');
+ expect(await links('Lunch with Alice.')).toEqual([]);
+ expect(await links('Lunch with Alice Example.')).toEqual(['people/alice-example']);
+ });
+
+ test('a one-word person title nobody shares, and a one-word company title, still link', async () => {
+ await put('people/alice-example', 'person', 'Alice Example');
+ await put('people/zorbinsky', 'person', 'Zorbinsky');
+ await put('companies/alice', 'company', 'Alice');
+ expect(await links('Zorbinsky called.')).toEqual(['people/zorbinsky']);
+ expect(await links('Alice the company called.')).toEqual(['companies/alice']);
+ });
+
+ test('a one-word person title keeps linking when only its own alias starts with it', async () => {
+ await put('people/zorbinsky', 'person', 'Zorbinsky', { aliases: ['Zorbinsky Example'] });
+ expect(await links('Zorbinsky called.')).toEqual(['people/zorbinsky']);
+ });
+
+ test('a thin title keeps its name when the claimant alias is dropped by a later guard', async () => {
+ await put('companies/acme', 'company', 'Acme');
+ await put('companies/acme-holdings', 'company', 'Acme Holdings', { aliases: ['Acme'] });
+ expect(await links('We met Acme today.')).toEqual(['companies/acme']);
+ });
+
+ test('a YAML boolean in a handle field is no handle', async () => {
+ await put('people/alice-example', 'person', 'Alice Example', { x: true });
+ expect(await links('Posted by @true today.')).toEqual([]);
+ });
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 9ed8269d1b..c1d14dd563 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -682,6 +682,7 @@ test/serve-http-access.test.ts
test/serve-http-memory-proposals.test.ts
test/setup-company-access.test.ts
test/setup-serves-several.test.ts
+test/share-about-member-gst2897.test.ts
test/shared-content-freshness.test.ts
test/shared-skills-catalog.test.ts
test/shared-skills-retention-capacity.test.ts
diff --git a/test/private-facts-grant-8194.test.ts b/test/private-facts-grant-8194.test.ts
index 419a0d6e91..908f2279b3 100644
--- a/test/private-facts-grant-8194.test.ts
+++ b/test/private-facts-grant-8194.test.ts
@@ -39,6 +39,7 @@ import { parseAdminGrantRequest } from '../src/commands/serve-http-grants.ts';
import { runAuth } from '../src/commands/auth.ts';
import { runSources } from '../src/commands/sources.ts';
import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
+import { v319 } from '../src/core/schema-migrations/v319-principal-private-facts.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
@@ -48,7 +49,6 @@ import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { withEnv } from './helpers/with-env.ts';
-import { v319 } from '../src/core/schema-migrations/v319-principal-private-facts.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
const GRANTED = 'pf-alpha';
diff --git a/test/receipt-coverage.test.ts b/test/receipt-coverage.test.ts
index 082ec12521..d56a72493b 100644
--- a/test/receipt-coverage.test.ts
+++ b/test/receipt-coverage.test.ts
@@ -44,6 +44,7 @@ const RECEIPT_COVERAGE: Record<string, Coverage> = {
'src/core/bootstrap/verify.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): bootstrap verify deletes its own probe facts without a request; publish the cleanup as a maintenance intent' },
'src/core/trust/held-removals.ts': { sites: 1, tables: ['takes', 'timeline_entries'], todo: 'TODO(receipts): the owner accept of a held take or timeline removal (W1 #6783 §12 (a)) re-projects that row in withCoordinatedWrite as maintenance without a request when the page no longer carries it as stored; publish the accept as an owner request (a fence-carried take already reruns as a receipted takes_remove)' },
'src/core/trust/owner-actions.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): the owner release of a held fact inserts it in withCoordinatedWrite as maintenance without a request; publish the release as an owner request' },
+ 'src/core/trust/supersede-handlers.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): the owner accept of a held share (GST-2897 B) widens the held fact\'s visibility in withCoordinatedWrite as maintenance without a request; publish it as an owner request' },
'src/core/trust/page-handlers.ts': { sites: 1, tables: ['pages', 'facts', 'takes', 'timeline_entries'], todo: 'TODO(receipts): owner tier decisions (confirm/lower) change only trust_tier/write_origin in withCoordinatedWrite as maintenance without a request; publish them as owner requests' },
'src/core/trust/backfill.ts': { sites: 3, tables: ['pages', 'facts', 'takes', 'timeline_entries'], todo: 'TODO(receipts): gbrain trust backfill and claim-sources --relower (#6533) set legacy trust_tier/write_origin (no content column) as attributed coordinated maintenance without a request; publish each batch as a maintenance intent' },
'src/core/repair/frontmatter-keys.ts': { sites: 1, tables: ['pages'], todo: 'TODO(receipts): gbrain repair frontmatter-keys (#6454) strips the four parser-reserved keys from pages.frontmatter (no content column) in withCoordinatedWrite batches as explicit-only maintenance without a request; publish each batch as a maintenance intent' },
@@ -62,7 +63,7 @@ const RECEIPT_COVERAGE: Record<string, Coverage> = {
};
/** Facts/takes writers allowed without a receipt this wave, each with its TODO above. */
-const RECEIPT_EXCEPTIONS = new Set(['src/core/bootstrap/verify.ts', 'src/core/repair/secret-spans.ts', 'src/core/trust/backfill.ts', 'src/core/trust/held-removals.ts', 'src/core/trust/owner-actions.ts', 'src/core/trust/page-handlers.ts']);
+const RECEIPT_EXCEPTIONS = new Set(['src/core/bootstrap/verify.ts', 'src/core/repair/secret-spans.ts', 'src/core/trust/backfill.ts', 'src/core/trust/held-removals.ts', 'src/core/trust/owner-actions.ts', 'src/core/trust/page-handlers.ts', 'src/core/trust/supersede-handlers.ts']);
const ROOT = join(import.meta.dir, '..');
diff --git a/test/share-about-member-gst2897.test.ts b/test/share-about-member-gst2897.test.ts
new file mode 100644
index 0000000000..526c601bee
--- /dev/null
+++ b/test/share-about-member-gst2897.test.ts
@@ -0,0 +1,158 @@
+/**
+ * GST-2897 B: a member's remember with share: true about another member is held for the brain owner, and the member a
+ * shared fact is about can withdraw it.
+ *
+ * 1. Protects: one member cannot publish a fact about another member to every reader of the source on its own say-so;
+ * the fact is stored private with a confirm proposal, and only the owner's accept shares it. The subject member's
+ * forget withdraws a shared fact about itself instead of being told only the brain host can.
+ * 2. Fails when: the share is stored world or recalled by another member before the accept, no proposal is filed, the
+ * accept does not widen it, a share about the team's work or about the caller itself is held, the visibility "world"
+ * refusal still tells the agent to retry with share: true for another member's page, or the subject cannot forget it
+ * (or can forget a fact about someone else).
+ * 3. Existing coverage: test/remember-share-gst2243.test.ts (share: true), test/member-forget-refusal-9101.test.ts
+ * (member forget refusals), test/remember-restated-private-2875.test.ts (the restatement hold this one extends).
+ * 4. Real seams: OAuth client-credentials tokens bound to members and the owner, MCP dispatch as remote callers, a
+ * repo-less brain, managed and unmanaged, PGLite and Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { decideTrustProposal } from '../src/core/trust/decide.ts';
+import { getTrustProposal, parseTrustProposalRef } from '../src/core/trust/proposals.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+
+const SRC = 'source-a';
+const ACME = 'companies/acme-example';
+const BOB = 'people/bob-example';
+const ALICE = 'people/alice-example';
+const owner = { confirmation: { via: 'tty' as const } };
+
+for (const kind of testBackends()) for (const managed of [false, true]) {
+ describe('share: true about another member (' + kind + (managed ? ', managed' : '') + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-share-held-'));
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ async function call(who: string, op: string, params: Record<string, unknown>) {
+ const out = await dispatchToolCall(engine, op, { ...params }, {
+ remote: true, transport: 'http', auth: await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo, sourceId: SRC, takesHoldersAllowList: ['world'],
+ });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+ }
+ const saved = async (who: string, fact: string, entity: string, extra: Record<string, unknown> = {}) => {
+ const out = await call(who, 'remember', { fact, entity, provenance: 'share test', ...extra });
+ expect(out.isError ? out.text : 'ok').toBe('ok');
+ return out.json;
+ };
+ const row = async (id: string) => (await engine.executeRaw<{ visibility: string; trust_tier: string; active: boolean }>(
+ 'SELECT visibility, trust_tier, expired_at IS NULL AS active FROM facts WHERE id = $1', [Number(id)]))[0]!;
+ const recalls = async (who: string, entity: string, claim: string) => (await call(who, 'recall', { entity })).text.includes(claim);
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => new Array<number>(1536).fill(0).map((_, i) => (i === 0 ? 1 : 0))) })) as never);
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ for (const id of ['alice-example', 'bob-example', 'dave-example', 'owner-example']) await addMember(engine, id);
+ await setOwner(engine, 'owner-example');
+ await importFromContent(engine, ACME, '---\ntype: company\ntitle: Acme Example\n---\n# Acme Example\n\nAcme example builds harbor ledgers.', { sourceId: SRC });
+ await importFromContent(engine, BOB, '---\ntype: person\ntitle: Bob Example\n---\n# Bob Example\n\nBob example runs the ledger team.', { sourceId: SRC });
+ await importFromContent(engine, ALICE, '---\ntype: person\ntitle: Alice Example\n---\n# Alice Example\n\nAlice example runs sales.', { sourceId: SRC });
+ for (const [name, member] of [['alice', 'alice-example'], ['bob', 'bob-example'], ['dave', 'dave-example'], ['owner', 'owner-example']] as const) {
+ const c = await provider().registerClientManual('share-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { member });
+ tokens[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;
+ }
+ if (managed) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ }, 120_000);
+
+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await disposePersistenceConsumer(engine); await close?.(); rmSync(home, { recursive: true, force: true }); });
+
+ test("a member's share about another member is held private until the owner's accept shares it", async () => {
+ const out = await saved('alice', 'Bob example is interviewing elsewhere canaryheldshare', BOB, { share: true });
+ expect(out.visibility).toBe('private');
+ expect(out.held).toMatchObject({ member: 'bob-example' });
+ expect(out.status_text).toContain('brain owner');
+ expect(await row(out.id)).toMatchObject({ visibility: 'private', trust_tier: 'agent_written', active: true });
+ expect([await recalls('dave', BOB, 'canaryheldshare'), await recalls('bob', BOB, 'canaryheldshare')]).toEqual([false, false]);
+ expect((await call('dave', 'get_page', { slug: BOB })).text).not.toContain('canaryheldshare');
+ const id = parseTrustProposalRef(out.held.proposal_ref)!;
+ expect(await getTrustProposal(engine, id)).toMatchObject({ action: 'confirm', status: 'pending', target_id: Number(out.id), related_id: Number(out.id) });
+ expect((await decideTrustProposal(engine, id, 'accept', owner)).status).toBe('accepted');
+ expect(await row(out.id)).toMatchObject({ visibility: 'world', trust_tier: 'agent_written' });
+ expect(await recalls('dave', BOB, 'canaryheldshare')).toBe(true);
+ expect((await call('dave', 'get_page', { slug: BOB })).text).toContain('canaryheldshare');
+ const withdrawn = await call('bob', 'forget', { id: out.id });
+ expect(withdrawn.isError ? withdrawn.text : 'ok').toBe('ok');
+ expect((await row(out.id)).active).toBe(false);
+ }, 120_000);
+
+ test('a dropped share stays private', async () => {
+ const out = await saved('alice', 'Bob example asked for a raise canarydroppedshare', BOB, { share: true });
+ const id = parseTrustProposalRef(out.held.proposal_ref)!;
+ expect((await decideTrustProposal(engine, id, 'reject', owner)).status).toBe('rejected');
+ expect(await row(out.id)).toMatchObject({ visibility: 'private', active: true });
+ expect(await recalls('dave', BOB, 'canarydroppedshare')).toBe(false);
+ }, 120_000);
+
+ test("shares about the team's work, about the caller itself, and by the owner are not held", async () => {
+ const team = await saved('alice', 'Acme renewed for 40 seats canaryteamshare', ACME, { share: true });
+ const self = await saved('alice', 'Alice example moved to the Berlin office canaryselfshare', ALICE, { share: true });
+ const byOwner = await saved('owner', 'Bob example leads the Q3 launch canaryownershare', BOB, { share: true });
+ for (const out of [team, self, byOwner]) {
+ expect(out.held).toBeUndefined();
+ expect(out.visibility).toBe('world');
+ expect((await row(out.id)).visibility).toBe('world');
+ }
+ expect([await recalls('dave', ACME, 'canaryteamshare'), await recalls('dave', ALICE, 'canaryselfshare'), await recalls('dave', BOB, 'canaryownershare')])
+ .toEqual([true, true, true]);
+ }, 120_000);
+
+ test('the member a shared fact is about withdraws it; it still cannot withdraw a shared fact about someone else', async () => {
+ const aboutBob = await saved('owner', 'Bob example joined the ledger guild canarybobwithdraws', BOB, { share: true });
+ const aboutAlice = await saved('owner', 'Alice example closed the Acme deal canarynotbobs', ALICE, { share: true });
+ const own = await call('bob', 'forget', { id: aboutBob.id });
+ expect(own.isError ? own.text : 'ok').toBe('ok');
+ expect((await row(aboutBob.id)).active).toBe(false);
+ const other = await call('bob', 'forget', { id: aboutAlice.id });
+ expect([other.isError, other.json.error]).toEqual([true, 'scope_denied']);
+ expect(other.text).toContain('brain host');
+ expect((await row(aboutAlice.id)).active).toBe(true);
+ }, 120_000);
+
+ test('visibility "world" about another member is refused without pointing at share: true', async () => {
+ const other = await call('alice', 'remember', { fact: 'Bob example is out next week canaryworldrefused', entity: BOB, provenance: 'share test', visibility: 'world' });
+ expect([other.isError, other.json.error]).toEqual([true, 'invalid_params']);
+ expect(other.text).toContain('member bob-example');
+ expect(other.text).not.toContain('Retry the same call with share: true');
+ const team = await call('alice', 'remember', { fact: 'Acme moved its HQ canaryworldteam', entity: ACME, provenance: 'share test', visibility: 'world' });
+ expect(team.text).toContain('Retry the same call with share: true');
+ }, 120_000);
+ });
+}