Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge capy/cat40-next-part1 (b6607b82) into capy/cat40-next-f5
garrytan333de4047b24
diff --cc docs/architecture/key-files/core-search-2.mdindex c586397b33,a3828eb35c..191873afe3--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@@ -26,7 -26,8 +26,8 @@@ Current behavior and load-bearing invar- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- - `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.-- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.++- `src/core/link-ranking-policy.ts` — the link ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `NON_RANKING_LINK_KINDS` (`owner_phrase`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer; owner-phrase invariance in `test/owner-phrase-pass.test.ts`.+ - `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (FROM source for `cc`, the full-text match, the `modality = 'text'` filter). For excludePrivate callers it puts the match in an `OFFSET 0` subquery the planner plans on its own: the private-visibility subplans otherwise inflate every join plan's cost so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (~1.1 s → ~0.2 s for a common term at 250k chunks). Local callers keep the unfenced join, which can plan in parallel (an OFFSET subquery forbids that). PGLite does not use it. Pinned by `test/search/keyword-arm-ranking.test.ts` and `test/e2e/keyword-arm-ranking-postgres.test.ts`.diff --cc docs/architecture/key-files/entity-recall.mdindex 562a47bdd9,c80c03db27..459c5962c7--- a/docs/architecture/key-files/entity-recall.md+++ b/docs/architecture/key-files/entity-recall.md@@@ -11,14 -11,14 +11,15 @@@ card and `get_backlinks`. Guide: [entit- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. Stored aliases and card identity lines read declarations with `anchored: true` (a cue must attach to the page itself; search's per-result `aliasDeclarations` scan reads them all). `titleSubject` (text after the last `: `), `declarationsIn` (each declaration with its line: prose cues, label and value lines and table rows whose label names an alias field (also a label opening a later sentence of a line, alias noun within its first two words, at most 7 words), the quoted-only "calls it" cue, a quoted defined term right after the page's own name; a capture is a quoted name or a run of up to 4 capitalized or code tokens ending at punctuation, a lowercase word or the line end, rejected on a possessive, a run of only common words or a cue after a relational noun; linear in the line length), `declaredNames` (its post-filtered names, shared with search's `aliasDeclarations`), `deriveEntityAliases(page, {multiword, deny})` (subject `origin='subject'`, declarations `origin='declared'` with their lines, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`; `mentions.alias_deny` and frontmatter `alias_deny` reject as `denied`). `aliasRejection`: under 4 characters (unless a short code the page declares for itself: a declaration marked `selfCode`), a generic word, or the first word of the page's own multi-word name. Rejections are returned with their line for explain. Tests: `test/mentions-policy-aliases.test.ts`.- `src/core/mentions/short-codes.ts` — `isShortCode` (2-3 letters or digits with a capital, not in `SHORT_CODE_STOPLIST` of common capitals and business acronyms, compared upper-cased). `declarationsIn` marks a short code `selfCode` when an alias label or an `also called` / `a.k.a.` / `known as` / `short for` cue declares it in a sentence naming nothing before the cue but the page (empty, a pronoun or an own name); `aliasRejection` lets it through and `by-mention.ts` keeps a `declared`, `case_sensitive` short code in the gazetteer, matched only as written. Leaf module (aliases.ts imports by-mention.ts). Tests: `test/mentions-policy-aliases.test.ts`, `test/mentions-pass.test.ts`.- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list, `mentions.alias_deny`, `mentions.multiword_aliases`, `mentions.sibling_merge`) marks every page due and recounts `pending`; the status row's `policy_fingerprint` carries the extractor versions its count reflects after the hash (`<hash>;v<mention>.<alias>`, `INDEX_VERSION_STAMP`), and a stamp that differs from the binary's recounts `pending` once (version-behind pages are already due, so nothing is invalidated); `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, `pending` (`countIndexDuePages`: mention-due pages plus linkable entity pages whose derived aliases are behind their content or `ALIAS_DERIVATION_VERSION`, counted when the source finishes or the deadline stops it) and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-coverage-version.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.- - `src/core/mentions/owner-phrase/` — owner-phrase resolution with validity windows behind `mentions.owner_phrases` (default off; contract: [owner phrases](../../guides/owner-phrases.md)). `scan.ts` stores per page (`owner_phrase_page_state`, keyed by `knowledge_revision` and `OWNER_PHRASE_SCAN_VERSION`) the cue lines, owner phrases, declared descriptors, the non-fallback page date and the belated-note readings; `dates.ts` parses written dates; `statements.ts` turns cue lines into dated takeover/join/ongoing/end/stint/correction statements (agent-written pages set none); `windows.ts` applies corrections, assembles per-identity-group windows with inclusive bounds and resolves a phrase (temporal candidates first, then ambiguity refusal, readings must agree). `pass.ts` `runOwnerPhrasePass`, called per source from `runMentionPass` after the plain reconcile, rebuilds windows into `owner_phrase_windows` (generation bumps only when the window hash changes; a window whose evidence includes a private page records `private_page_id`) and diffs `link_source='mentions'`, `link_kind='owner_phrase'` links under `pg_advisory_xact_lock`, storing a private evidence page as `origin_page_id`; a page pair another link covers gets none, and a plain mention displaces the row (`mentions/pass.ts`). Key off removes rows, windows, scans and status once. `known-as.ts` is the card's bounded `known_as` read (10 rows plus total, private windows hidden from untrusted readers) and its keyset continuation, served as `get_backlinks` `group: "known_as"` (`ops/backlinks-paged.ts`); `ranking.ts` `rankingLinkSql` keeps owner-phrase links out of the readers that count every link (adjacency boosts, entity anchoring, generated-page demotion). `sample.ts` derives the links the pass would store without writes (in-memory scans fed to `buildOwnerPhraseModel`) and implements sampling rule v1, the labeling TSV and the Wilson bound for `scripts/owner-phrase-sample.ts`. Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/owner-phrase-sample.test.ts`, `test/e2e/owner-phrase-parity.test.ts`.++- `src/core/mentions/owner-phrase/` — owner-phrase resolution with validity windows behind `mentions.owner_phrases` (default off; contract: [owner phrases](../../guides/owner-phrases.md)). `scan.ts` stores per page (`owner_phrase_page_state`, keyed by `knowledge_revision` and `OWNER_PHRASE_SCAN_VERSION`) the cue lines, owner phrases, declared descriptors, the non-fallback page date and the belated-note readings; `dates.ts` parses written dates; `statements.ts` turns cue lines into dated takeover/join/ongoing/end/stint/correction statements (agent-written pages set none); `windows.ts` applies corrections, assembles per-identity-group windows with inclusive bounds and resolves a phrase (temporal candidates first, then ambiguity refusal, readings must agree). `pass.ts` `runOwnerPhrasePass`, called per source from `runMentionPass` after the plain reconcile, rebuilds windows into `owner_phrase_windows` (generation bumps only when the window hash changes; a window whose evidence includes a private page records `private_page_id`) and diffs `link_source='mentions'`, `link_kind='owner_phrase'` links under `pg_advisory_xact_lock`, storing a private evidence page as `origin_page_id`; a page pair another link covers gets none, and a plain mention displaces the row (`mentions/pass.ts`). Key off removes rows, windows, scans and status once. `known-as.ts` is the card's bounded `known_as` read (10 rows plus total, private windows hidden from untrusted readers) and its keyset continuation, served as `get_backlinks` `group: "known_as"` (`ops/backlinks-paged.ts`). Owner-phrase links are non-ranking through `link-ranking-policy.ts` (`NON_RANKING_LINK_KINDS`). `sample.ts` derives the links the pass would store without writes (in-memory scans fed to `buildOwnerPhraseModel`) and implements sampling rule v1, the labeling TSV and the Wilson bound for `scripts/owner-phrase-sample.ts`. Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/owner-phrase-sample.test.ts`, `test/e2e/owner-phrase-parity.test.ts`.- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (index-due pages per source, as `countIndexDuePages` counts them, and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.- - `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).+ - `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. F3: `pageStatusValue` (string, trimmed, at most `PAGE_STATUS_MAX_CHARS` 40) is the one `page_status` rule; `readPageStatusByRef` reads it by `(source_id, slug)` in one statement (private pages hidden from untrusted callers, quarantined pages unless allowed) for `readReferrerPage {pageStatus}`, `get_backlinks` link rows and `context_pack` cards and newer-mention rows. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while index-due pages exist (`previewMentionPass`), including every page behind the binary's mention or alias version on an unchanged brain. Post-upgrade does not run the sweep; autopilot's cycle extract phase continues it on its stale-drain budget (`CYCLE_STALE_DRAIN_BUDGET_MS`).- - `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode filters by referrer type and cuts at `limit` with a `listing_truncated` notice naming the paged call. `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values.+ - `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode filters by referrer type and cuts at `limit` with a `listing_truncated` notice naming the paged call. `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values. F3 (`entity.row_page_status`, default on): `withLinkPageStatus` adds the referring page's `page_status` to link rows, and `group: "page"` rows get it through `readReferrerPage {pageStatus}`; a record type's continuation keeps it through `recordMetadata` when the key is off.- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `denied_by_config`, `not_a_known_name`); only `pending` names a sweep. A slug query also lists each derived name with origin and declaring line, the rejected candidates with reasons, and the sibling decision. Tests: `test/mentions-explain.test.ts`.- - `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` resolves each name through `buildEntityCard` (no references), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; siblings come from `readCardIdentity`. `pageLead` is the body's opening prose from `sanitizeRemoteBody` plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. Tests: `test/entity-names.test.ts`.+ - `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` resolves each name through `buildEntityCard` (no references), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; siblings come from `readCardIdentity`. `pageLead` is the body's opening prose from `sanitizeRemoteBody` plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. `attachReferences` adds `referenced_by_count`, the card `next` and `records` to every found page and sibling from one `readRowReferences` call. Tests: `test/entity-names.test.ts`, `test/entity-records.test.ts`.+ - `src/core/verbs/entity-references.ts` — the F1 reference fields on compact rows: `readRowReferences` (config gate per surface `names` / `pack` / `full_card`, `REFERENCES_DEADLINE_MS` 2 s cooperative deadline, `references_unavailable` marker + degraded notice, per-type `next` to `get_backlinks` returning exactly the rest, `record_types_undeclared` notice), `readPackReferences` (context_pack pull verb only: card page + identity siblings), `renderRecordLines` / `RECORDS_HEADER` (packed text, "page date"). Config: `src/core/entity-references-config.ts` (`entity.names_references` default on, `entity.record_types` default empty). Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.- `src/core/verbs/entity-card-identity.ts` — the `entity` card's `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines of the page and its siblings from `sanitizeRemoteBody`, tiered: declarations, label lines with a name-like value, other label lines, lines with another capitalized run or code; 600 characters per page, 1,200 per card, `identity_excerpt_omitted`), `alias_guidance` (surface-aware) and the `identity_siblings_capped` notice. Tests: `test/mentions-identity-siblings.test.ts`.- `src/core/search/alias-fanout.ts` — search and query's alias fan-out: `resolveQueryEntity` (query n-grams up to 4 tokens through `resolveAliases` and linkable exact titles, longest first, capitalized or code-shaped unless a multi-word n-gram resolves to one page, case-sensitive aliases as written, a tie only when the pages are identity siblings), the names of the entity and its siblings by origin then length, at most `search.alias_fanout_max` (4) keyword queries of 5 rows (`searchAliasRequired`: the name as a required websearch phrase, ranked by the query's other terms through `SearchOpts.rankQuery` on both engines), at most 8 spliced rows with `matched_alias`, and the `fanout` meta (`alias_fanout` notice when capped). Offset 0 only. Tests: `test/search-alias-fanout.test.ts`, `test/search-other-names.test.ts`, `test/e2e/mentions-parity.test.ts`. `wholeQueryEntityNames`: when the whole query is one entity's name or alias, `match: "keyword"` lists pages matching any of its names (one websearch OR of phrases; `match_names` in the meta and the count line; rows found by another name carry `matched_alias`). `resolveQueryEntities` returns every entity a text names.- `src/core/search/entity-facts.ts` — `entitySavedFacts`: when a search names an entity, its newest active saved facts (`factEntitySlugs`, 5) lead the model-visible saved-facts block, then up to 3 facts each of up to 2 entities those facts name (`linked_from`), before the word-overlap matches. Same active, audit-row and visibility rules as recall. Tests: `test/memory-sibling-facts.test.ts`.diff --cc docs/guides/entity-recall.mdindex 5c7859ddf0,5c7859ddf0..2053749e50--- a/docs/guides/entity-recall.md+++ b/docs/guides/entity-recall.md@@@ -187,6 -187,6 +187,7 @@@ with its reason, and the identity-sibli|---|---|---|| `mentions.auto_link` | `true` | `false` removes mention links and derived names on the next sweep; `true` relinks everything on the next sweep. `auto_link=false` also turns it off. || `mentions.newer_on_cards` | `true` | `context_pack` cards list up to 8 pages that mention the entity and are dated after the entity's own page, newest first, each with its date, slug, title and the `referenced_by` preview (2,000 characters per card, 6,000 per pack, under the same read policy as the `entity` card). `false` leaves them off. |++| `mentions.owner_phrases` | `false` | Owner-phrase resolution: the mention pass links a document that says "<owner>'s <descriptor> account" to the account its owner held on the document's date, as `link_kind='owner_phrase'` mention rows, and the `entity` card lists `known_as` windows. Read when the mention pass runs; turning it off removes the rows on the next pass. See [owner phrases](owner-phrases.md). || `mentions.entity_types` | none | `+type` adds a linkable type, `-type` removes one (person, company, organization and entity always stay). || `mentions.ignore` | none | Names never linked, comma-separated or a JSON array. || `mentions.exclude_slugs` | none | Pages never linked by any of their names (title or alias), comma-separated or a JSON array of slugs. Use it for an entity whose name is also a common word, such as a person titled 인하 against "로 인하여" ("due to"). The next sweep removes mention links already written to the page. |diff --cc docs/guides/owner-phrases.mdindex 9130a03233,0000000000..1ab442ad3dmode 100644,000000..100644--- a/docs/guides/owner-phrases.md+++ b/docs/guides/owner-phrases.md@@@ -1,197 -1,0 +1,197 @@@+# Owner phrases: "alice-example's freight account"++Company text often names an account by who owns it: "Alice's freight account",+"the health book Charlie handles". Which account that means depends on the date,+because accounts change hands. With owner phrases on, the mention index works+out each owner's validity window from ownership and handoff statements in page+text. It then links a document that uses an owner phrase to the account its+owner held on the document's date.++**Say to your agent:** *"Turn on owner-phrase linking so notes that say 'Alice's freight account' link to the right account."*+**Say to your agent:** *"Who owned the acme-example account in March, and which phrases point at it?"*++```bash+gbrain config set mentions.owner_phrases true # off by default+gbrain extract --stale --catch-up # builds windows and links+gbrain entity "Acme Example Freight" # the card lists known_as rows+```++`mentions.owner_phrases` takes effect when the mention pass runs: when a brain+or benchmark slot is built, or on the next `gbrain extract --stale`. A read-time+config change does nothing until the pass runs. When the key is on, it is part+of the mention policy fingerprint stored on each source's `mention_index_status`+row (and in slot receipts that copy it). When the key is off, the fingerprint+is the same as on a brain that never had the key. Turning it off removes every+owner-phrase link, window and page state on the next pass.++## What gets linked++A link is stored as an ordinary mention: `link_source='mentions'`,+`link_kind='owner_phrase'`, `link_type='mentions'`, with the phrase as written+in `context`. Owner-phrase links never change search scores. Most ranking+readers already skip mention links (backlink counts, relational chain hops and+typed degree, salience inbound counts). The three that count every link+(adjacency boosts, entity anchoring and generated-page demotion) skip- `link_kind='owner_phrase'` through `rankingLinkSql`- (`src/core/mentions/owner-phrase/ranking.ts`), so a brain's final scores are++`link_kind='owner_phrase'` through the shared ranking policy++(`rankingLinkSql`, `src/core/link-ranking-policy.ts`), so a brain's final scores are+the same with the key on or off. Graph traversal, `get_backlinks` and the entity card's+`referenced_by` see them the same way they see plain mentions. A page pair that+another link already connects gets no owner-phrase link. A plain mention found+later replaces the owner-phrase row.++## Resolution contract (v1, deterministic, no model calls)++The rules below are general to any brain. Each line is covered by a test row in+`test/owner-phrase-*.test.ts`.++1. **Inputs are kept apart.** Ownership statements come from one place, account+ descriptors from another and the document's date from a third. A statement+ never supplies a descriptor, and a phrase never creates a window.+2. **Ownership statements.** Sentences on any page type (not only entity pages)+ in the title, compiled truth or timeline. They have one of these forms:+ - takeover: "B takes over / inherits / picks up / assumes X", "X moves / is+ handed / is reassigned (from A) to B", "A hands X (off) to B", "B replaces A+ on X", "B is now / becomes the owner (lead, AE, CSM) for X", "B will own /+ is going to own / is set to own X", and the label line "Outgoing A,+ incoming B";+ - join: "B joins X", "B has owned X since <date>", "B starts / started /+ began on (with, covering) X". A join adds an owner without ending anyone+ else's stint;+ - ongoing: "B owns / runs / handles / covers / leads X", "B has run / has+ owned / has handled X", "B is the owner of X", "X is owned by B", "X is B's+ account", and on an account page the label lines `Owner:`, `Account+ owner:`, `Account lead:` and the same frontmatter keys;+ - end: "A rolls off / steps away from / leaves / is no longer on X", "A's+ last day on X is <date>";+ - stint: "A ran X from <date> to <date>", "A ran X until <date>";+ - tables whose header names an account column and an owner column, with+ optional start and end columns, or Outgoing / Incoming / Effective+ columns (a handoff). A parenthesized cell is a note, not a value.++ An adverb after the owner ("actually", "officially", "formally", "also",+ "already", "effectively") does not change the form. In a chat line+ ("[09:14] Name: I'm picking up X"), first-person words mean the speaker.++ X is an account: a linkable entity page that is not a person, named by its+ title or alias, by "the <descriptor> account" when exactly one account has+ that descriptor, or implicitly. An implicit account is the page itself on an+ account page, else the one account named on the statement's line, else the+ one account named across the page's ownership lines; with two or more, an+ implicit statement sets nothing. A form that begins with the account ("X+ moves from A to B") never takes the page implicitly. An account named in a+ statement that has no page competes in ambiguity (line 9) but is never+ stored or linked. Negated sentences, questions and hypothetical sentences+ ("might", "if", "considering", "proposed") are not statements.+3. **Statement dates.** A date written in the sentence wins. Cue-led dates+ ("starting", "effective", "as of", "from", "on") come first, then the first+ date after the verb, then the last date before it. A day-month date without+ a year takes the year that puts it nearest the page date. An ongoing+ statement whose date follows a start cue ("since", "starting", "as of",+ "effective", "from") is a join from that date. With no date in the+ sentence, the statement takes the page's own date. Only a non-fallback+ page date counts (`effective_date_source` other than `fallback`). A relative+ date with no written date ("next week", "soon") makes the statement+ undated. An undated statement sets no window.+4. **Agent-written pages are not evidence.** Statements on a page whose type+ has the word `agent`, or whose frontmatter `author_kind`/`written_by` is+ `agent`, set no window. Owner phrases on those pages still resolve.+5. **Corrections void a stint.** A sentence with a correction cue+ ("correction", "was wrong", "actually", "not B", "rather than B", "instead+ of B") that names a wrong owner voids that owner's takeover, join or ongoing+ statements for the account, as recorded up to the correction. If it names the+ right owner, that owner takes over on the voided statement's date (or on+ the date the correction states). The previous owner's end is kept. A+ correction that names no account uses the page's only account.+6. **Window assembly.** Per identity group (an account page and its identity+ siblings, `mentions/siblings.ts`), statements are applied in date order.+ A takeover starts the new owner on day D and ends every other open stint+ (only the named predecessor's for "from A") on D−1. A predecessor named+ by "from A" who had no stint gets one ending on D−1, with an unknown+ start. An end statement ends the stint on its date. Bounds are inclusive+ calendar days. An open end runs until a later statement closes it. An+ ongoing statement on day D with no covering stint opens one with an+ unknown start. The window then begins the day after the latest earlier stint+ on the account ends, or has no lower bound. An ongoing statement that+ contradicts another owner's covering stint is ignored.+7. **Descriptors.** An account's descriptors are the words of its title and+ aliases (without corporate suffixes such as Inc, LLC, Co or Group), plus+ declared descriptors on the account page: "X is our <d> account", "known+ internally as the <d> account", and the `segment`, `industry`, `vertical`,+ `sector`, `category`, `descriptor`, `region` and `territory` labels or+ frontmatter keys. A label counts at the start of a line or after a+ sentence boundary ("Account: X. Industry: food. Region: EMEA.").+8. **Owner phrases.** "<Name>'s <d> account" (also book, client, customer,+ relationship, portfolio, book of business) and "the <d> account (that) <Name>+ runs / handles / owns / manages / covers / leads". The descriptor is the+ whole run between the possessive and the noun, one to three words. It+ matches an account when the run is one of the account's descriptors, or+ when every word of the run is a word of its descriptors ("EMEA software"+ for an account with region EMEA and industry software). A plural noun, a name+ that is itself an account or company, and a sentence about personal or+ benefit accounts (benefits, HSA, FSA, 401k, payroll, bank, login, password)+ are not owner phrases. A one-word name matches an owner by first name, a+ longer name by the full name.+9. **Temporal candidates first, then ambiguity.** For the document's date, the+ candidates are windows whose owner matches, whose account has the+ descriptor and that cover the date. One identity group links. Two or more+ groups are ambiguous and refused. None is unresolved.+10. **Document dates and belated notes.** A document links only with a+ non-fallback page date. When the document also cites another date for+ itself, both readings must resolve to the same account or nothing links.+ The cited dates are a differing frontmatter `event_date` or `date`, a+ leading slug date, a `Date:`/`Sent:`/`Recorded:` label, or "notes from /+ recap of / written on <date>".+11. **Windows are stored apart.** Windows live in `owner_phrase_windows`, never+ in `page_aliases`, the `aka` list or search alias fan-out. Each row keeps+ its evidence (page, line, statement kind, date). Per-page scan results live+ in `owner_phrase_page_state`.+12. **Visibility.** A link whose window evidence includes a private page stores+ that page as `origin_page_id`. Remote and world-scope readers apply the+ link-origin privacy check and do not see the link. Trusted local reads do.+ `known_as` rows on the card follow the same rule. The card shows at most+ 10 `known_as` rows, newest window first, with the `total`. When rows <+ total, `known_as.next` is an executable `get_backlinks` call with+ `group: "known_as"` and a cursor that returns the rest in the same order.+13. **Invalidation.** A page is rescanned when its content revision or the+ owner-phrase version changes. Windows are rebuilt from every page's stored+ statements on each pass, and links are diffed against them. So a window+ change alone relinks exactly the documents it affects, and a deleted or+ edited evidence page withdraws its windows.++Every pass reports `links`, `documents`, `unresolved`, `ambiguous` and+`windows` under `mentions.owner_phrases` in `gbrain extract --stale --json`.++## Precision sample++Before the key's default can change, a labeled sample of derived links from a+real brain must show precision at a Wilson 95% lower bound of 0.85 or more+(at least 57 of 60 correct, or 92 of 100). `scripts/owner-phrase-sample.ts`+draws that sample without writing anything:++- It derives the windows and links the pass would store, inside a `READ ONLY`+ transaction, with no model or network calls. The key can stay off.+- Sampling rule v1, fixed before any sample is drawn: one population row per+ (document, account page) link; rows are ranked by+ sha256(`owner-phrase-sample-v1`, seed, document slug, account slug) and the+ first `--n` (default 100) are taken. The same brain and seed give the same+ sample.+- Fewer than 22 derivable links is a refusal (exit 3); nothing is written.+- The TSV goes only to the path given with `--out` (mode 0600; an existing file+ needs `--force`). Columns: `id`, `doc_slug`, `phrase`, `line_excerpt`,+ `account`, `window`, `evidence_page`, `label`. stdout carries counts only.++From a checkout of the branch, against a copy of a PGLite brain or a live+Postgres brain:++```bash+cd ~/gbrain-f5 && bun install+cp -a "$(jq -r .database_path ~/.gbrain/config.json)" /tmp/brain-f5-copy # PGLite only; copy while nothing writes+bun scripts/owner-phrase-sample.ts --pglite /tmp/brain-f5-copy --source all --seed "<seed>" --n 100 --out ~/f5-sample.tsv+# Postgres brain: omit --pglite; the script reads ~/.gbrain/config.json+# label each row y (the document means that account) or n in the label column, then:+bun scripts/owner-phrase-sample.ts --score ~/f5-sample.tsv+```++`--score` prints the labeled, correct and wrong counts and the Wilson 95%+lower bound. The TSV stays with the owner; only the counts and the bound are+published.diff --cc src/core/config.tsindex 32ff08c483,7159de4d9e..07e07093f5--- a/src/core/config.ts+++ b/src/core/config.ts@@@ -1652,7 -1655,7 +1655,7 @@@ export const KNOWN_CONFIG_KEYS: readonl// Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked, pages never linked (#5829),// aliases never derived, multi-word declared aliases, identity siblings; search's alias fan-out cap and generated-page demotion.'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'mentions.exclude_slugs', 'mentions.alias_deny', 'mentions.multiword_aliases',-- 'mentions.sibling_merge', 'search.alias_fanout_max', 'search.demote_generated',++ 'mentions.sibling_merge', 'search.alias_fanout_max', 'search.demote_generated', 'mentions.owner_phrases',// #4987: the write-path timeline extractor's off switch (read by// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`// works without --force, as the compiled-truth guide documents.diff --cc src/core/link-ranking-policy.tsindex 0000000000,a6db96b20d..6df3ab3d91mode 000000,100644..100644--- a/src/core/link-ranking-policy.ts+++ b/src/core/link-ranking-policy.ts@@@ -1,0 -1,35 +1,43 @@@+ /**+ * Link-type ranking participation: the one policy every reader that turns+ * links into a ranking signal honors.+ *+ * A non-ranking link type records metadata about a page (for example that a+ * record amends another record) without saying the target matters more. Its+ * edges stay ordinary references: get_links, get_backlinks, graph traversal,+ * entity-card edges and backlink_count, and the referrer path still return+ * them. They never feed a ranking signal: the backlink boost, the in-set and+ * cross-source adjacency boosts, relational fanout hops, relational chain+ * hops and the typed (hub) degree, the enrich inbound-link order, the+ * connection count that picks a canonical entity, generated-page demotion and+ * entity anchoring.+ *++ * Owner-phrase links (`link_kind = 'owner_phrase'`, mentions/owner-phrase/)++ * are non-ranking the same way: a brain's final scores are the same with++ * `mentions.owner_phrases` on or off.++ *+ * The policy lives in code, not in a schema pack field, so a pack that+ * declares one of these types loads on any gbrain. Contract:+ * docs/guides/temporal-edges.md ("Amendments: the amends link").+ */++ /** Link types that take no part in ranking. */+ export const NON_RANKING_LINK_TYPES: readonly string[] = Object.freeze(['amends']);+++/** Link kinds that take no part in ranking, whatever their type. */++export const NON_RANKING_LINK_KINDS: readonly string[] = Object.freeze(['owner_phrase']);+++ /** True when edges of this type may feed a ranking signal. */+ export function linkTypeRanks(linkType: string): boolean {+ return !NON_RANKING_LINK_TYPES.includes(linkType);+ }++ /**+ * SQL predicate over a `links` row alias: TRUE when the row may feed a+ * ranking signal. The type names are code constants inlined as literals, so+ * the fragment composes into statements with any parameter numbering.+ */+ export function rankingLinkSql(alias: string): string {- return `${alias}.link_type <> ALL(ARRAY[${NON_RANKING_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`;++ return `(${alias}.link_type <> ALL(ARRAY[${NON_RANKING_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`++ + ` AND COALESCE(${alias}.link_kind, '') <> ALL(ARRAY[${NON_RANKING_LINK_KINDS.map(k => `'${k}'`).join(', ')}]::text[]))`;+ }diff --cc src/core/ops/backlinks-paged.tsindex 453b3170b5,a7352d463b..c40a099f99--- a/src/core/ops/backlinks-paged.ts+++ b/src/core/ops/backlinks-paged.ts@@@ -16,10 -15,10 +16,11 @@@ import type { Link, PageReadPolicy } frimport type { Notice } from '../agent-output.ts';import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';import {- decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,+ canonicalRecordTypes, decodeCursor, readPageStatusByRef, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,} from '../mentions/referrers.ts';import { mentionCoverageNotice, readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';+import { decodeKnownAsCursor, readKnownAsPage, type KnownAsRow } from '../mentions/owner-phrase/known-as.ts';+ import { readEntityReferencesConfig, readRowPageStatus } from '../entity-references-config.ts';export interface BacklinkPage {rows: ReferenceRow[];@@@ -100,31 -98,30 +101,52 @@@ export async function readBacklinkPage(if (!resolved) return { rows: [], total: 0, truncated: false, cursor: null, coverage };const type = typeof p.type === 'string' && p.type ? p.type : undefined;if (type) await assertKnownType(ctx, resolved.scope, type);- return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor }), coverage };+ // F1: a record type's continuation rows carry the same record metadata as the record view (membership unchanged).+ const recordMetadata = type !== undefined && canonicalRecordTypes((await readEntityReferencesConfig(ctx.engine)).recordTypes, resolved.scope.pack)+ .includes(canonicalTypeOf(type, resolved.scope.pack));+ const pageStatus = !recordMetadata && await readRowPageStatus(ctx.engine);+ return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor, recordMetadata, pageStatus }), coverage };+ }++ /**+ * F3 (`entity.row_page_status`, default on): each link row carries its+ * referring page's frontmatter `status` as `page_status` when set. The link's+ * own `status` (the relationship's temporal state) and the `status` input+ * filter are unchanged.+ */+ export async function withLinkPageStatus(ctx: OperationContext, policy: () => Promise<PageReadPolicy>, links: Link[]): Promise<Array<Link & { page_status?: string }>> {+ if (!links.length || !(await readRowPageStatus(ctx.engine))) return links;+ const excludePrivate = (await policy()).excludePrivate === true;+ const status = await readPageStatusByRef(ctx.engine, links.map(l => ({ source_id: l.from_source_id, slug: l.from_slug })), { excludePrivate })+ .catch(() => new Map<string, string>());+ return links.map(l => {+ const value = status.get(`${l.from_source_id}:${l.from_slug}`);+ return value ? { ...l, page_status: value } : l;+ });}+export interface KnownAsPage { rows: KnownAsRow[]; total: number; truncated: boolean; cursor: string | null }++/**+ * `group: "known_as"`: one page of the entity card's owner windows+ * (mentions/owner-phrase/known-as.ts), continuing a card's `known_as.next`.+ * A slug with no live page in scope answers like an empty read.+ */+async function readKnownAsGroup(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<KnownAsPage> {+ if (p.type !== undefined) {+ throw opError('invalid_params', 'get_backlinks: type does not apply to group: "known_as".', 'Omit type with group: "known_as".');+ }+ const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;+ const after = p.cursor === undefined ? null : decodeKnownAsCursor(String(p.cursor));+ if (p.cursor !== undefined && !after) {+ throw opError('invalid_params', 'get_backlinks: cursor is not one this tool returned.', 'Pass the cursor from the previous known_as response unchanged, or omit it to start from the newest window.');+ }+ const sourceId = await targetSource(ctx, String(p.slug), await scopeSources(ctx, policy));+ if (!sourceId) return { rows: [], total: 0, truncated: false, cursor: null };+ const page = await readKnownAsPage(ctx.engine, sourceId, String(p.slug), { excludePrivate: policy.excludePrivate === true, limit, after });+ return { rows: page.rows, total: page.total, truncated: page.cursor !== null, cursor: page.cursor };+}+/*** Array mode with `type` and/or `limit`: today's link rows, filtered by the* referring page's type and cut at `limit` (a cut is reported with adiff --cc src/core/verbs/entity-card.tsindex 97ed7108c0,28cf766ece..568a5b5726--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@@ -37,9 -37,10 +37,11 @@@ import type { NewerMentions } from '../import { loadLinkableTypes } from '../mentions/policy.ts';import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';+ import { readRowReferences, referencesUnavailableNotice, type RecordGroupView, type ReferencesUnavailable, type RowReferences } from './entity-references.ts';+ import type { Notice } from '../agent-output.ts';import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';import { factEntitySlugs } from '../mentions/siblings.ts';+import { readKnownAs, type KnownAs } from '../mentions/owner-phrase/known-as.ts';const EDGE_CAP = 10;const OPEN_THREADS_CAP = 3;@@@ -328,8 -340,8 +343,9 @@@ export async function buildEntityCardconst card = await assembleCard(engine, sourceId, best.row, opts.remote, excludePrivate, opts.eligibility ?? {});if (opts.includeReferences) {Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes),- await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));+ await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }),+ await readKnownAs(engine, sourceId, best.row.slug, { excludePrivate, surfaceCeiling: opts.surfaceCeiling }));+ await attachCardRecords(engine, sourceId, card, opts, excludePrivate);}return {found: true,diff --cc test/amends-link.test.tsindex 0000000000,2d75a6690d..6d669a4c3dmode 000000,100644..100644--- a/test/amends-link.test.ts+++ b/test/amends-link.test.ts@@@ -1,0 -1,65 +1,66 @@@+ /**+ * The non-ranking `amends` link on PGLite (Postgres twin:+ * test/e2e/amends-link-postgres.test.ts): one final-output invariance row per+ * link-counting ranking consumer, amendments versus genuine replacement in+ * final search scores and labels, the example pack's frontmatter mapping and+ * `since`, and the frozen-clock liveness exemption.+ */+ import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, setSystemTime, test } from 'bun:test';+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';+ import { resetPgliteState } from './helpers/reset-pglite.ts';+ import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+ import { setPackRelationSemantics } from '../src/core/link-validity.ts';-import { linkTypeRanks, NON_RANKING_LINK_TYPES, rankingLinkSql } from '../src/core/link-ranking-policy.ts';++import { linkTypeRanks, NON_RANKING_LINK_KINDS, NON_RANKING_LINK_TYPES, rankingLinkSql } from '../src/core/link-ranking-policy.ts';+ import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';+ import { INVARIANCE_ROWS, amendmentsVersusReplacement, databaseToday, frontmatterRecordsSince, futureAmendsStayVisible,+ runInvarianceRow, useExamplePack } from './helpers/amends-ranking-scenarios.ts';++ setDefaultTimeout(60_000);+ let engine: PGLiteEngine;+ let restorePacks: () => void;++ beforeAll(async () => {+ restorePacks = useExamplePack();+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ });+ afterAll(async () => { await engine.disconnect(); resetGateway(); setPackRelationSemantics(new Map()); restorePacks(); });+ beforeEach(async () => { await resetPgliteState(engine); configureGateway({ env: {} } as never); setPackRelationSemantics(new Map()); });++ describe('ranking participation policy', () => {- test('amends is the non-ranking link type; the SQL predicate inlines it', () => {++ test('amends is the non-ranking link type and owner_phrase the non-ranking link kind; the SQL predicate inlines both', () => {+ expect(NON_RANKING_LINK_TYPES).toEqual(['amends']);++ expect(NON_RANKING_LINK_KINDS).toEqual(['owner_phrase']);+ expect(linkTypeRanks('amends')).toBe(false);+ expect(linkTypeRanks('supersedes')).toBe(true);+ expect(linkTypeRanks('mentions')).toBe(true);- expect(rankingLinkSql('l')).toBe(`l.link_type <> ALL(ARRAY['amends']::text[])`);++ expect(rankingLinkSql('l')).toBe(`(l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[]))`);+ });++ test('the bundled example pack is a valid manifest declaring amends as an event mapped from frontmatter', () => {+ const manifest = loadPackFromFile(new URL('../examples/schema-packs/amends-example/pack.yaml', import.meta.url).pathname);+ expect(manifest.link_types).toEqual([{ name: 'amends', temporal: 'event' }, { name: 'supersedes' }]);+ expect(manifest.frontmatter_links).toEqual([+ { page_type: 'contract', fields: ['amends'], link_type: 'amends' },+ { page_type: 'contract', fields: ['supersedes'], link_type: 'supersedes' },+ ]);+ });+ });++ describe('final-output invariance: one row per link-counting ranking consumer', () => {+ for (const row of INVARIANCE_ROWS) {+ test(`${row.consumer} — threshold: ${row.threshold}`, () => runInvarianceRow(engine, row));+ }+ });++ describe('amendments versus replacement', () => {+ test('current and future amendments leave scores and labels unchanged; supersedes halves and labels', () => amendmentsVersusReplacement(engine));+ test('frontmatter amends objects record since as first_start in both scopes, each on its exact target', () => frontmatterRecordsSince(engine));+ });++ describe('liveness exemption (frozen clock)', () => {+ test('a future-since amends edge stays visible in get_backlinks, traverse_graph and card edges', async () => {+ const today = await databaseToday(engine);+ setSystemTime(new Date(`${today}T12:00:00Z`));+ try { await futureAmendsStayVisible(engine, today); } finally { setSystemTime(); }+ });+ });diff --cc test/fixtures/goldens/sql-text/salience.jsonindex aad17489c7,346c3d1604..076824acb7--- a/test/fixtures/goldens/sql-text/salience.json+++ b/test/fixtures/goldens/sql-text/salience.json@@@ -222,8 -222,8 +222,8 @@@"number","number"],- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",- "textSha256": "3338bd2f96f229be17a9f3405af5556f88263be691c24990ac2ae0db4c358661"- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",- "textSha256": "1a1f91975382b6f97f2ba8119b0a344c48a2383f19a21040b553657652875f01"++ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",++ "textSha256": "8f368d9866c4bd7b414151d634cb32c6fed8eabd78b1b6035aceb3b7830874b9"}],"sourceId": [@@@ -235,8 -235,8 +235,8 @@@"string","number"],- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",- "textSha256": "d66d07de0d8a4b29e1a7f730e8bfae4ca1f52e8afc12cf356552eb151d4ddfdb"- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",- "textSha256": "ac911efc9ff41921e9ebdde94bd01d861d022f72ccedac6417eea9de315b2dfc"++ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",++ "textSha256": "fe012403bd78fc3b31f4a2875a65e71043d262483467dbaebbf4d1d612dcdf27"}],"sourceIds+reenrich": [@@@ -249,8 -249,8 +249,8 @@@"string","number"],- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",- "textSha256": "99c6dc60239a138d17df8f52076ceb9020c9404507aa45fa608be039f3b90d4d"- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",- "textSha256": "01b82217b92b0982f9570e78247e7c39ab1925fde627edf063923526b895d9e6"++ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND (l.link_type <> ALL(ARRAY['amends']::text[]) AND COALESCE(l.link_kind, '') <> ALL(ARRAY['owner_phrase']::text[])) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",++ "textSha256": "388baaace733ea685b8b4b0678c589ccdb5e1b8b7618f154bdca53a17381ee8a"}]},