Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mentions): every name an entity goes by (alias grammar, identity siblings, excerpt, fan-out)

garrytan6adbec76acc7
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 1fb4cd15f9..36e576e513 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -5,16 +5,19 @@ subject, frontmatter alias or declared code) to that entity page, keeps the
links current from `gbrain extract --stale`, and serves them on the `entity`
card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
-- `src/core/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names, reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code with `stripCodeBlocks`, then picks the longest matching entry at each token (maximal munch), first mention per target only, skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
-- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` and `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.
-- `src/core/mentions/aliases.ts` — derived names of an entity page. `titleSubject` (text after the last `: `), `declaredNames` (the `account code` / `also known as` / `a.k.a.` / `aka` / `short name` / `ticker` / `code name` parser shared with search's `aliasDeclarations`), `deriveEntityAliases` (subject `origin='subject'`, declarations `origin='declared'`, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`). `aliasRejection`: under 4 characters, a generic word, or the first word of the page's own multi-word name. Rejections are returned for explain. Tests: `test/mentions-policy-aliases.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) marks every page due; `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 count 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-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.
-- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (due pages 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`). `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/by-mention.ts` — the pure mention matcher plus its gazetteer. `buildGazetteer(engine, opts)` loads linkable entity titles and aliases per source (drops below-minimum, generic, ambiguous-first-word and colliding names (a name claimed at one origin by an identity-sibling group stays, marked `shared`), reported as `DroppedName`), keyed by lowercase first token and sorted longest-first. `findMentionedEntities(text, gazetteer, opts)` masks code with `stripCodeBlocks`, then picks the longest matching entry at each token (maximal munch), first mention per target only (a `shared` match links every sibling with those tokens, unless the scanning page is one of them), skipping self-links and other sources unless `allowCrossSource` (an own-source twin wins). Word-run scripts match whole tokens; Han and Kana match character substrings. A Hangul name must start a word, keep its written spacing, and end at a non-Hangul character or an attached title/particle/copula suffix (`HANGUL_NAME_SUFFIX_RE`), so 지원에게 matches and 지원하는 does not ([measurement](../../designs/hangul-mention-boundaries.md)). A matcher change bumps `MENTION_EXTRACTOR_VERSION` (`mentions/pass.ts`, every page rescans once) and the semantics tag inside `hashGazetteer` (the `extract links --by-mention` resume checkpoint). `scanStaleMentions` is the read-only doctor scan for mention rows the current gazetteer no longer produces.
+- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore`, `mentions.exclude_slugs` (#5829: listed pages get no gazetteer entry by title or alias, dropped as `excluded_slug`; JSON array or comma list, `parseNameList`), `mentions.alias_deny`, `mentions.multiword_aliases` and `mentions.sibling_merge` (both default on). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.
+- `src/core/mentions/siblings.ts` — identity siblings: pages in one source naming the same normalized title subject under pairwise different prefixes, all linkable entities of one canonical type other than `person`, none excluded or `identity: separate`, at most `SIBLING_GROUP_CAP` (3; a larger group is `capped`). `siblingVerdict` is the one rule (card, search fan-out, gazetteer); `readIdentitySiblings` reads a page's group with the private-page predicate for untrusted callers. Nothing is written to `entity_identities` and nothing is unioned. Tests: `test/mentions-identity-siblings.test.ts`.
+- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. `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, 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, 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/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/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. Tests: `test/mentions-card-backlinks.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).
-- `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 mention-due pages exist.
+- `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/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`, `not_a_known_name`); only `pending` names a sweep. Tests: `test/mentions-explain.test.ts`.
+- `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-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`.
- `src/core/schema-migrations/v206-entity-mention-index.ts` — additive: `page_aliases.origin` (`frontmatter` default, `declared`, `subject`), `case_sensitive`, `alias_text`, unique key `(source_id, alias_norm, slug, origin)`; tables `page_mention_state`, `mention_gazetteer_entries`, `mention_index_status` (RLS on when the role bypasses RLS). `GUARDED_TABLE_COLUMNS` lists the new `page_aliases` columns.
-Alias readers apply precedence frontmatter > declared > subject per source, and a derived alias never answers for another live page's exact title (`readAliases` in `src/core/search/read-enrichment.ts`, shared by both engines' `resolveAliases`), so `resolveEntitySlug`, the retrieval reflex, the alias hop, intent weights and `search-diagnose` rank an exact title first. `buildGazetteer` (`src/core/by-mention.ts`) applies the same precedence, drops an alias claimed by two pages at its best origin, yields to a same-source title, drops a single-word alias equal to the first word of another multi-word entity name, applies the generic-word list to every single-word name, and carries `caseTokens` for case-sensitive entries; `opts.dropped` records every dropped name with its reason.
+Alias readers apply precedence frontmatter > declared > subject per source, and a derived alias never answers for another live page's exact title (`readAliases` in `src/core/search/read-enrichment.ts`, shared by both engines' `resolveAliases`), so `resolveEntitySlug`, the retrieval reflex, the alias hop, intent weights and `search-diagnose` rank an exact title first. `buildGazetteer` (`src/core/by-mention.ts`) applies the same precedence, drops an alias claimed by two pages at its best origin (unless the claimants are identity siblings, which all keep it), yields to a same-source title, drops a single-word alias equal to the first word of another multi-word entity name, applies the generic-word list to every single-word name, and carries `caseTokens` for case-sensitive entries; `opts.dropped` records every dropped name with its reason.
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
index 32c4ec8015..6e2ddf12c3 100644
--- a/docs/guides/entity-recall.md
+++ b/docs/guides/entity-recall.md
@@ -124,16 +124,40 @@ agent never reads a short list as "nothing else exists".
(alias `crm`), `organization` and `entity`. Other packs add their own
`primitive: entity` types.
- Put the name in the title, or after a prefix: `CRM record: Acme Example`.
-- Declare codes in the body: `Account code: ACMX`, `also known as`, `aka`,
- `short name`, `ticker`, `code name`. A one-word code links only as written
- (`ACMX`, not `acmx`).
+- 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]`.
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 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), 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
+
+**Say to your agent:** *"Make sure gbrain knows every name the Acme account goes by."*
+
+```markdown
+Acme Example (formerly Gearbox Labs), also known as Blue Harbor, goes by ACMX.
+Internal nickname: Copper Fox
+| Former legal name | Gearbox Labs Inc |
+```
+
+gbrain reads prose cues (`also known as`, `aka`, `nicknamed`, `goes by`,
+`formerly`, `doing business as`, ...), label lines and table rows whose label
+names an alias field (`nickname`, `alias`, `trading name`, `account code`, ...),
+and a quoted defined term after the page's own name. A name is a quoted name or
+up to 4 capitalized or code words; lowercase words, possessives, common words
+(`the Board`, `Q3 Plan`) and names after `competitor`/`partner`/... are
+rejected. The full list is the [alias conventions spec](../designs/ALIAS_CONVENTIONS.md).
+`mentions.alias_deny` (or frontmatter `alias_deny:`) drops a name. The card's
+`identity_excerpt` shows other name-like lines verbatim.
+
+**Identity siblings.** `Account sheet: Acme Example` and `CRM record: Acme
+Example` are shown together (`identity_siblings`, never merged); a document
+naming only "Acme Example" links to both. People are never siblings; frontmatter
+`identity: separate` keeps a page out. **Search** also searches up to 4 other
+names of the entity a query names; those rows carry `matched_alias`.
## When a name does not link
@@ -150,8 +174,12 @@ acmx (source default): case_mismatch
The reason codes are `ambiguous_first_word`, `below_min_length`,
`generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`,
-`linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config` and
-`not_a_known_name`. Only `pending` is fixed by running `gbrain extract --stale`.
+`linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`,
+`excluded_by_config`, `denied_by_config` and `not_a_known_name`. Only `pending`
+is fixed by running `gbrain extract --stale`. Given a slug
+(`gbrain extract mentions --explain crm/acme-example`), it also lists every name
+the page derives with its origin and declaring line, each rejected candidate
+with its reason, and the identity-sibling decision.
## Settings
@@ -162,6 +190,10 @@ The reason codes are `ambiguous_first_word`, `below_min_length`,
| `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. |
| frontmatter `mention_ignore: [names]` | none | Names not linked from that one page. |
+| `mentions.alias_deny` | none | Names never derived as an alias (comma list or JSON array); frontmatter `alias_deny:` does the same for one page. |
+| `mentions.multiword_aliases` | `true` | `false` derives one-word declared aliases only. |
+| `mentions.sibling_merge` | `true` | `false` stops showing identity siblings and linking a shared name to each sibling; frontmatter `identity: separate` does it for one page. |
+| `search.alias_fanout_max` | `4` | Other names search and query also search per call; `0` turns the fan-out off. |
Mention links written inside a longer Hangul word, or across a space, by a
matcher older than the Hangul boundary rule (#5829) are stale:
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index f88ee76196..bfc1e48b07 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -387,6 +387,17 @@ The `entity` verb adds three optional card fields (ambient callers,
- `open_threads` (best-effort in v1): active commitment-kind facts + timeline
entries from the last 90 days, capped at 3.
+#### entity identity fields (additive)
+
+The `entity` verb also adds: `aka_sources[]` (`{ origin, slug }` per `aka`
+entry; `aka` is unchanged and never claims completeness); `identity_siblings`
+(`{ pages[{ slug, title, type, aka[] }], capped }`: same subject under another
+title prefix, shown, never merged; more than 3 is `capped` with an
+`identity_siblings_capped` notice); `identity_excerpt[]` (`{ slug, line }`,
+verbatim name-like lines from the remote-sanitized body, 600 characters per
+page and 1,200 per card, `identity_excerpt_omitted[]`); `alias_guidance`
+(`{ text, requires_surface? }`).
+
#### entity open_threads loop backing (additive)
On brains running the open-loop engine, `open_threads` entries may
diff --git a/llms-full.txt b/llms-full.txt
index b6eee70b16..70f5f1e1a8 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5804,186 +5804,6 @@ Note: there is no SQLite engine. PGLite uses the same SQL as Postgres, so no sep
---
-## docs/what-schemas-unlock.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/what-schemas-unlock.md
-
-# What schemas unlock
-
-Most note-taking apps treat every page the same. You write something, it goes in a pile, you search the pile with text matching. Tags help, but tags are flat. After a few thousand pages, the pile gets noisy and the search gets stupid.
-
-Schemas are how gbrain stops being a pile of notes and becomes something with structure. A schema declares what KINDS of things live in your brain (`person`, `company`, `meeting`, `researcher`, `case`, `lab-result`), what they link to (`attended`, `authored`, `prescribed-by`), what facts the system should extract automatically (`mrr=50000`, `damages=5000000`), and which types route through expert search vs general search.
-
-The default schema (`gbrain-base`) ships with 22 page types covering the universal shapes — people, companies, meetings, notes, daily, calendar events. That's enough to start. But your brain is yours, and your brain's shape is not the default shape. A research brain needs `researcher` and `paper` as first-class types. A founder brain needs `lead`, `investor`, `portco`, `deal-stage`. A lawyer brain needs `case`, `motion`, `deposition`, `precedent`. Same engine, totally different shape.
-
-AGENTS can author that shape for you. Not just "the user manually edits YAML in `~/.gbrain/schema-packs/mine/pack.yaml`" but "your agent sees the corpus, proposes a type, asks for approval, applies it atomically with a full audit trail, then backfills 4000 existing pages with one chunked SQL command."
-
-This doc is the WHY. The [tutorial](schema-author-tutorial.md) is the HOW.
-
-## Killer use cases
-
-### 1. The 4000 invisible pages
-
-You have 4000 markdown files under `meetings/` going back two years. The default schema doesn't have a `meeting` type, so all 4000 are typed `note` (the catchall). When you run:
-
-```bash
-gbrain whoknows "Q3 roadmap discussion"
-```
-
-You get the top 10 text matches, ranked by raw relevance. The brain has no idea these are meetings. It can't route to attendees. It can't pull dates. It can't surface "this conversation came up again with the same people three weeks later."
-
-Add a `meeting` type:
-
-```bash
-gbrain schema add-type meeting --primitive temporal --prefix meetings/ --extractable
-gbrain schema sync --apply
-```
-
-The sync backfills `page.type = 'meeting'` on all 4000 pages in 1000-row batches. Now:
-
-- `gbrain whoknows "Q3 roadmap discussion"` routes through the meeting type, ranking by `expert_routing` signal (attendees, recency, salience) instead of raw text.
-- The `extract_facts` cycle runs on every meeting page automatically (because `extractable: true`), pulling typed facts like `attended_by=alice-example`, `date=2026-05-23`.
-- The downstream `think` skill can now answer "what did we decide about pricing in the last three roadmap meetings" by querying the meeting graph instead of grep'ing 4000 files.
-
-One command. 4000 pages went from invisible to queryable. The content didn't change. The structure did.
-
-### 2. The founder ops brain
-
-You're a founder or investor with ~500 markdown files mixing leads, portfolio companies, deal notes, intros, and follow-ups. You've been writing freely; you have no system. Your queries are all "wait, who introduced me to that fintech founder again?" and you scroll Notion for 20 minutes.
-
-Add the founder shape:
-
-```bash
-gbrain schema fork gbrain-base mine
-gbrain schema use mine
-
-# Types
-gbrain schema add-type lead --primitive entity --prefix people/leads/ --expert
-gbrain schema add-type investor --primitive entity --prefix people/investors/ --expert --extractable
-gbrain schema add-type portco --primitive entity --prefix companies/portco/ --expert --extractable
-gbrain schema add-type deal --primitive entity --prefix companies/deals/ --extractable
-
-# Link verbs
-gbrain schema add-link-type invested-in --page-type investor --target-type portco
-gbrain schema add-link-type intro-from --page-type lead --target-type lead
-gbrain schema add-link-type passed-on --page-type investor --target-type deal
-gbrain schema add-link-type led-by --page-type deal --target-type investor
-
-gbrain schema sync --apply
-```
-
-Now `gbrain whoknows "Series A SaaS"` routes through `investor` and `portco` types specifically, not the noisy general type set. `gbrain graph-query alice-example --type intro-from --depth 2` walks two hops of intros to surface "Alice introduced you to Bob who introduced you to Charlie." The `extract_facts` cycle starts producing typed claims from the fence in your deal pages: `(deals/acme-seed, raise=2000000, valuation=15000000, lead=widget-vc, closed_at=2026-05-23)`.
-
-The CRM you've been promising yourself you'll set up next quarter? You just shipped it in 4 commands. It's downstream of your notes, not parallel to them.
-
-### 3. The research brain
-
-Replace "founder" with "PhD student" and the same pattern applies with different types: `researcher`, `paper`, `lab`, `grant`, `dataset` + `authored`, `cites`, `funded-by`, `uses-dataset`.
-
-```bash
-gbrain schema add-type paper --primitive annotation --prefix research/papers/ --extractable
-gbrain schema add-link-type authored --page-type researcher --target-type paper
-gbrain schema add-link-type cites --page-type paper --target-type paper
-gbrain schema add-link-type uses --page-type paper --target-type dataset
-```
-
-Suddenly "show me papers that cite this work AND use the same dataset" is a `gbrain graph-query` traversal, not 30 minutes in Google Scholar. The fact extraction picks up `arxiv_id=2402.04253`, `cited_by_count=140`, `published_date=2026-02-15` automatically. Your reading-list-as-markdown turns into a queryable research graph that knows who works on what and what's connected to what.
-
-### 4. The legal brain (or any domain where claims have numbers)
-
-Lawyers, medical providers, accountants, anyone working in a domain where the meaning of a number depends on its type. A "judgment of $5M" against a "$2M case strategy threshold" is a comparison the brain can do — but only if both numbers are typed.
-
-```bash
-gbrain schema add-type case --primitive entity --prefix legal/cases/ --extractable --expert
-gbrain schema add-type motion --primitive annotation --prefix legal/motions/ --extractable
-gbrain schema add-type deposition --primitive annotation --prefix legal/depositions/ --extractable
-gbrain schema add-link-type filed-in --page-type motion --target-type case
-gbrain schema add-link-type cites --page-type motion --target-type precedent
-```
-
-Now `## Facts` fences in your case notes can carry typed claims (`damages=5000000`, `filed_date=2026-05-23`, `judge=jane-doe`) that gbrain stores as first-class columns. `gbrain eval trajectory legal/cases/acme-v-widget` prints the case history with regressions flagged. `gbrain founder scorecard` (renamed for legal: roll up plaintiff success rate, average damages, settlement-vs-trial ratio) gives you a structured view of how your practice is performing.
-
-This isn't possible without typed page kinds. You can write the same prose in any note-taking app. Only gbrain treats the numbers as comparable across pages of the same type.
-
-### 5. The team brain
-
-`gbrain mounts add` lets you stack additional brains alongside your personal one. Each mounted brain has its OWN schema pack. The eng team's brain has `incident`, `runbook`, `service`, `oncall-rotation`. The design team's brain has `component`, `experiment`, `ab-test`, `figma-link`. The legal team's brain has cases and depositions.
-
-When you query, the schema pack governs how each source's content is routed. An eng query against the mounted eng brain knows that `incidents/2026-05-23-db-outage.md` is an `incident` page with `severity=p0`, `mttr=47min`, `on_call=alice-example` — extractable typed facts. Your personal query against the same brain still works, but the routing is sharper because the eng team has invested in their ontology.
-
-The schema is the team's tribal knowledge made explicit. Two engineers on different teams searching the same brain get DIFFERENT routing because their personal packs declare different expert types.
-
-### 6. The "agent co-curates your ontology" pattern
-
-Your OpenClaw (or any agent connected to your brain over HTTPS MCP with admin scope) watches your ingestion stream. After a week of you dumping notes under `companies/yc-w24/`, the agent runs `gbrain schema detect` periodically, sees that prefix accumulating, and proposes:
-
-> You have 47 pages under `companies/yc-w24/` typed as `company` (generic). They share a structural pattern (founder names, raise amounts, batch tag). Should I add a `yc-w24-company` type with `extractable: true` and the existing aliases pointing back to `company`? I'd backfill the 47 pages and add `cohort=W24` as a typed fact extracted from each page.
-
-You approve once. The agent calls `schema_apply_mutations` over MCP with a batch:
-
-```json
-{
- "pack": "mine",
- "mutations": [
- {"op": "add_type", "name": "yc-w24-company", "primitive": "entity", "prefix": "companies/yc-w24/", "extractable": true, "expert_routing": true},
- {"op": "add_alias", "type": "yc-w24-company", "alias": "company"}
- ]
-}
-```
-
-All inside ONE `withPackLock` scope, atomic, audited (the agent's `client_id` captured in the audit log as `actor: mcp:<clientId8>`). Cache invalidated cross-process. Sync backfills the 47 pages. The brain learned a new category of thing without you having to think about it.
-
-The next time you query "YC W24 companies in fintech", the brain routes through the new type. Six months later when you forget the pattern entirely, the agent reminds you it's there and offers to consolidate it with the W25 batch.
-
-The brain learns. The agent is the curator. You approve, the agent does the work.
-
-### 7. The before-vs-after benchmark
-
-If you want to FEEL the difference without buying the pitch:
-
-Pick a real corpus you have. Run `gbrain whoknows` on a topic that should match. Note the top-3 results.
-
-Then run `gbrain schema review-orphans --json` and look at the untyped pages. If 10+ of them share an obvious prefix that should be a real type, add the type + sync.
-
-Re-run the same `whoknows` query. Top-3 should shift, because the new type is now routing through expert ranking instead of being lumped into the catchall. The numerical delta IS the win. You can run a tutorial in 5 minutes; this experiment proves it matters on your actual content.
-
-## Why this matters
-
-Three things gbrain does that generic note systems can't:
-
-**1. The brain knows the difference between a person and an idea.** Page-type matters at query time. `gbrain whoknows` only considers `expert_routing: true` types. The `extract_facts` cycle only runs on `extractable: true` types. `gbrain graph-query` walks declared link verbs. None of that works on a flat tag system because tags don't have semantics — they're labels. Types are first-class citizens with rules attached.
-
-**2. Untyped content is invisible content.** If your meetings are typed as `note`, expert routing skips them, facts extraction ignores them, link inference doesn't fire. They exist on disk and they're indexed for text search, but the structural surfaces (whoknows, find_experts, recall, think) treat them as second-class. Adding a type isn't cosmetic; it's structural promotion.
-
-**3. The schema is queryable AND mutable AND auditable.** You can ask the brain what its schema looks like (`gbrain schema graph`), evolve it through atomic CLI verbs + MCP ops (`gbrain schema --help` for the full surface) with full lock + audit semantics, and recover from any mistake (every primitive has an inverse, plus `gbrain schema downgrade` restores the previous active pack). This isn't "vibes-based knowledge management." It's a production system with structural integrity guarantees.
-
-## What makes agent authoring safe
-
-Forking the bundled pack and editing `pack.yaml` by hand is the manual path. Letting an agent author the pack safely takes more machinery: atomic file locks, an audit log, MCP exposure, and pack-aware wiring in the query path. gbrain ships all of it:
-
-- **`withMutation` skeleton** wraps every primitive in 8 ordered safety steps (bundled-guard → lock → read → mutate → validate → atomic write → audit → invalidate). The pack file on disk is never partial. Two concurrent agents can't race.
-- **Per-pack `O_CREAT|O_EXCL` atomic lock** (deliberately NOT the TOCTOU-prone `existsSync+writeFileSync` pattern). TTL refresh every 10s while a mutation runs; `--force` means "steal stale lock" not "skip locking."
-- **Privacy-redacted audit log** at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Type names sha8-hashed, prefixes truncated to first segment only. A leaked screenshot of the audit can't reveal sensitive taxonomy like `personal/oncology/` or `legal/depositions/`.
-- **Schema MCP ops** including the batched `schema_apply_mutations` (admin scope, NOT localOnly — your OpenClaw and any remote agent author packs over normal HTTPS MCP, with `client_id` captured as `actor: mcp:<clientId8>`).
-- **Pack-aware expert routing** in `whoknows` and `find_experts`: a custom `researcher` type marked `--expert` surfaces in query results because the query path reads the active pack's `expert_routing: true` types rather than a hardcoded `['person', 'company']` list.
-- **Cross-process invalidation** via stat-mtime TTL gate inside `loadActivePack`. Operator runs `gbrain schema add-type` from a terminal; the autopilot daemon picks up the new type within 1 second without a restart.
-
-The cumulative effect: an agent can safely co-curate your ontology with a complete forensic trail.
-
-## Where to start
-
-- **Want to see it work in 5 minutes?** Run the [tutorial](schema-author-tutorial.md). Forks the bundled pack, adds a researcher type, proves the wiring end-to-end.
-- **Want the agent recipe?** Read [`skills/schema-author/SKILL.md`](../skills/schema-author/SKILL.md). 7-phase workflow agents follow when they detect a schema-evolution opportunity.
-- **Want the rules of thumb?** Read [`skills/conventions/schema-evolution.md`](../skills/conventions/schema-evolution.md). Decision tree for when to add a type vs alias vs prefix. <20 pages don't pack-codify. 100+ pages need first-class types.
-- **Want the architecture?** The "Schema packs: mutation surface" section in `docs/architecture/KEY_FILES.md` has the module-by-module breakdown.
-- **Want to set up an agent that co-curates your brain?** Run `gbrain auth register-client my-agent --scopes admin` to mint an OAuth client your remote agent can use to call `schema_apply_mutations` over MCP. The agent then runs detect → suggest → apply on its own cadence and asks you to approve substantive changes.
-
-The killer feature isn't "schemas." Personal knowledge systems have had schemas forever. The killer feature is that your AGENT can shape them safely on your behalf, with structural integrity guarantees that match what you'd expect from a database, not a notes app.
-
-That's what we built. Try it on a corpus you actually have and the numbers go up.
-
----
-
## docs/schema-author-tutorial.md
Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/schema-author-tutorial.md
@@ -9250,6 +9070,17 @@ The `entity` verb adds three optional card fields (ambient callers,
- `open_threads` (best-effort in v1): active commitment-kind facts + timeline
entries from the last 90 days, capped at 3.
+#### entity identity fields (additive)
+
+The `entity` verb also adds: `aka_sources[]` (`{ origin, slug }` per `aka`
+entry; `aka` is unchanged and never claims completeness); `identity_siblings`
+(`{ pages[{ slug, title, type, aka[] }], capped }`: same subject under another
+title prefix, shown, never merged; more than 3 is `capped` with an
+`identity_siblings_capped` notice); `identity_excerpt[]` (`{ slug, line }`,
+verbatim name-like lines from the remote-sanitized body, 600 characters per
+page and 1,200 per card, `identity_excerpt_omitted[]`); `alias_guidance`
+(`{ text, requires_surface? }`).
+
#### entity open_threads loop backing (additive)
On brains running the open-loop engine, `open_threads` entries may
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index a1d093d386..d5d7289265 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -134,13 +134,13 @@ export const SECTIONS: DocSection[] = [
includeInFull: false,
},
{
- // Re-inlined: the CLAUDE.md resolver restructure (per-file index moved to
- // docs/architecture/KEY_FILES.md, link-only) freed ~530KB of bundle
- // headroom, so this value-explainer rides the single-fetch bundle again.
+ // Link-only: the bundle reached FULL_SIZE_BUDGET; this value-explainer is
+ // the least operational inlined doc, so it gives way to protocol docs.
title: "docs/what-schemas-unlock.md",
description:
"Why schemas matter: 7 killer use cases (4000 invisible meetings, founder ops brain, research brain, legal brain, team brain, agent-as-co-curator) + the structural argument for typed page kinds. Read this before pitching schema authoring.",
path: "docs/what-schemas-unlock.md",
+ includeInFull: false,
},
{
title: "docs/schema-author-tutorial.md",
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8e178b0c1b..b999517cfa 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,10 +20,10 @@ src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
-src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
-src/core/postgres-engine.ts 2941 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts)
+src/core/pglite-engine.ts 2997 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out)
+src/core/postgres-engine.ts 2942 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
-src/core/types.ts 2232 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
+src/core/types.ts 2236 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +3 cat40 hard wave F1.6: SearchOpts.rankQuery and SearchResult.matched_alias
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1916 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1898 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows
+src/core/config.ts 1900 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +2 cat40 hard wave F1: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated key rows
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
diff --git a/src/commands/extract-mentions-explain.ts b/src/commands/extract-mentions-explain.ts
index e8569d0e3b..312a09d5e3 100644
--- a/src/commands/extract-mentions-explain.ts
+++ b/src/commands/extract-mentions-explain.ts
@@ -7,7 +7,9 @@
* `ambiguous_first_word`, `below_min_length`, `generic_token`,
* `alias_collision`, `case_mismatch`, `type_not_linkable`,
* `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`,
- * `excluded_by_config`, `not_a_known_name`. Only `pending` suggests a sweep; a policy rejection
+ * `excluded_by_config`, `denied_by_config`, `not_a_known_name`. With a slug it also lists every
+ * name the page derives (origin and declaring line), the rejected candidates
+ * with their reasons, and the identity-sibling decision. Only `pending` suggests a sweep; a policy rejection
* names the setting or the page text that would change it.
*/
@@ -15,11 +17,13 @@ import type { BrainEngine } from '../core/engine.ts';
import { buildGazetteer, findMentionedEntities, tokenizeTitle, type DroppedName, type GazetteerEntry } from '../core/by-mention.ts';
import { isCrossSourceLinksEnabled } from '../core/link-extraction.ts';
import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy } from '../core/mentions/policy.ts';
-import { deriveEntityAliases } from '../core/mentions/aliases.ts';
+import { deriveEntityAliases, type RejectedAlias } from '../core/mentions/aliases.ts';
+import { aliasOptsOf } from '../core/mentions/pass.ts';
+import { readIdentitySiblings } from '../core/mentions/siblings.ts';
import { MENTION_EXTRACTOR_VERSION } from '../core/mentions/pass.ts';
export type ExplainReason = 'ambiguous_first_word' | 'below_min_length' | 'generic_token' | 'alias_collision' | 'case_mismatch'
- | 'type_not_linkable' | 'linking_disabled' | 'pending' | 'ignored_by_page' | 'ignored_by_config' | 'excluded_by_config' | 'not_a_known_name';
+ | 'type_not_linkable' | 'linking_disabled' | 'pending' | 'ignored_by_page' | 'ignored_by_config' | 'excluded_by_config' | 'denied_by_config' | 'not_a_known_name';
export interface MentionExplanation {
query: string;
@@ -31,6 +35,12 @@ export interface MentionExplanation {
message: string;
page?: { slug: string; linked: boolean };
next?: string;
+ /** With a slug: every name the page's text derives, with its origin and declaring line. */
+ aliases?: Array<{ alias: string; origin: string; line?: string }>;
+ /** With a slug: candidate names the derivation rejected, with the reason and line. */
+ rejected?: RejectedAlias[];
+ /** With a slug: the identity-sibling decision (mentions/siblings.ts). */
+ siblings?: { pages: string[]; capped: boolean; verdict: string };
}
const DROP_REASON: Record<DroppedName['reason'], ExplainReason> = {
@@ -50,6 +60,7 @@ const MESSAGES: Record<ExplainReason, string> = {
ignored_by_page: 'The page lists this name in its frontmatter `mention_ignore`.',
ignored_by_config: 'The name is on an ignore list (`mentions.ignore` or the built-in ambiguous-brand list).',
excluded_by_config: 'The page is listed in `mentions.exclude_slugs`, so none of its names link.',
+ denied_by_config: 'The name is on `mentions.alias_deny` or the page\'s frontmatter `alias_deny`, so it is never derived as an alias.',
not_a_known_name: 'No linkable entity page has this title, title subject or alias in this source.',
};
@@ -75,6 +86,7 @@ export async function explainMention(engine: BrainEngine, query: string, opts: {
if (!types.includes(asPage.type ?? '')) return done(base, 'type_not_linkable');
}
base.entries = entries.map(view);
+ if (asPage) Object.assign(base, await pageNames(engine, sourceId, asPage.slug, policy));
if (!entries.length) {
const drop = dropped.find(d => d.source_id === sourceId && (asPage ? d.slug === asPage.slug : tokenizeTitle(d.name).join(' ') === key));
if (drop) return done(base, DROP_REASON[drop.reason]);
@@ -116,15 +128,33 @@ export async function explainMention(engine: BrainEngine, query: string, opts: {
: 'The page text does not contain this name.');
}
+/** Every name a page derives (with origin and declaring line), the rejected candidates and the sibling decision. */
+async function pageNames(engine: BrainEngine, sourceId: string, slug: string, policy: Awaited<ReturnType<typeof readMentionPolicy>>):
+ Promise<Pick<MentionExplanation, 'aliases' | 'rejected' | 'siblings'>> {
+ const [p] = await engine.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null; frontmatter: Record<string, unknown> | null }>(
+ 'SELECT title, compiled_truth, timeline, frontmatter FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]);
+ if (!p) return {};
+ const derived = deriveEntityAliases(p, aliasOptsOf(policy));
+ const fm = await engine.executeRaw<{ alias_norm: string }>(
+ `SELECT alias_norm FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin = 'frontmatter' ORDER BY alias_norm`, [sourceId, slug]).catch(() => []);
+ const sib = await readIdentitySiblings(engine, sourceId, { slug, title: p.title }, { excludePrivate: false, policy });
+ return {
+ aliases: [...fm.map(r => ({ alias: r.alias_norm, origin: 'frontmatter' })),
+ ...derived.aliases.map(a => ({ alias: a.alias_text, origin: a.origin, ...(derived.lines.has(a.alias_norm) ? { line: derived.lines.get(a.alias_norm) } : {}) }))],
+ rejected: derived.rejected,
+ siblings: { pages: sib.pages.map(s => s.slug), capped: sib.capped, verdict: sib.pages.length ? 'group' : sib.verdict ?? 'none' },
+ };
+}
+
/** A declaration the alias derivation rejected (e.g. a 3-character code), found on a linkable entity page. */
async function rejectedDeclaration(engine: BrainEngine, sourceId: string, name: string, policy: Awaited<ReturnType<typeof readMentionPolicy>>): Promise<ExplainReason | null> {
const types = linkableTypesFor(await loadSourcePack(engine, sourceId), policy);
- const pages = await engine.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null }>(
- `SELECT title, compiled_truth, timeline FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
+ const pages = await engine.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null; frontmatter: Record<string, unknown> | null }>(
+ `SELECT title, compiled_truth, timeline, frontmatter FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
AND (compiled_truth ILIKE $3 OR title ILIKE $3) LIMIT 50`, [sourceId, types, `%${name.replace(/[\\%_]/g, m => `\\${m}`)}%`]);
for (const p of pages) {
- const hit = deriveEntityAliases(p).rejected.find(r => r.alias.toLowerCase() === name.toLowerCase());
- if (hit) return hit.reason;
+ const hit = deriveEntityAliases(p, aliasOptsOf(policy)).rejected.find(r => r.alias.toLowerCase() === name.toLowerCase());
+ if (hit) return hit.reason === 'denied' ? 'denied_by_config' : hit.reason;
}
return null;
}
@@ -142,6 +172,9 @@ export async function runExtractMentionsExplain(engine: BrainEngine, args: strin
console.log(`${r.query} (source ${r.source_id}): ${r.reason ?? 'links'}`);
for (const e of r.entries) console.log(` entry: "${e.name}" → ${e.slug} (${e.origin}${e.case_sensitive ? ', case-sensitive' : ''})`);
if (r.page) console.log(` page ${r.page.slug}: ${r.page.linked ? 'linked' : 'not linked'}`);
+ for (const a of r.aliases ?? []) console.log(` alias: "${a.alias}" (${a.origin})${a.line ? ` from "${a.line}"` : ''}`);
+ for (const x of r.rejected ?? []) console.log(` rejected: "${x.alias}" (${x.origin}): ${x.reason}${x.line ? ` from "${x.line}"` : ''}`);
+ if (r.siblings) console.log(` identity siblings: ${r.siblings.pages.length ? r.siblings.pages.join(', ') : 'none'} (${r.siblings.capped ? 'capped: more than 3 pages share the subject' : r.siblings.verdict})`);
console.log(` ${r.message}`);
if (r.next) console.log(` next: ${r.next}`);
}
diff --git a/src/commands/reindex-aliases.ts b/src/commands/reindex-aliases.ts
index 90737e942d..bfb250ccc4 100644
--- a/src/commands/reindex-aliases.ts
+++ b/src/commands/reindex-aliases.ts
@@ -74,7 +74,7 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Pr
try {
if (aliasNorms.length) await engine.setPageAliases(ref.slug, ref.source_id, aliasNorms);
const derived = await derivedWrite(ref.source_id, tx => writeDerivedAliases(tx, ref.source_id,
- { slug: ref.slug, title: page.title, type: page.type, compiled_truth: page.compiled_truth, timeline: page.timeline }, { policy: mentionPolicy }));
+ { slug: ref.slug, title: page.title, type: page.type, compiled_truth: page.compiled_truth, timeline: page.timeline, frontmatter: page.frontmatter as Record<string, unknown> | undefined }, { policy: mentionPolicy }));
if (aliasNorms.length || derived) pagesWithAliases++;
aliasesWritten += aliasNorms.length + derived;
} catch (e) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 6aa95c9d43..c01deba2bd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -261,6 +261,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.100.0', text: '`gbrain doctor` has a new `fence_integrity` check: it counts malformed facts and takes fences still waiting (held files, stored pages, unsynced checkout files) by the tier that would fix them, and warns when a source had 20 or more fences normalized in 7 days. Each doctor run scans stored pages and source checkouts for up to 10 seconds (`GBRAIN_DOCTOR_FENCE_TIMEOUT_MS`) and resumes where it stopped; until a scan finishes the check reports partial instead of ok. New settings `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00) cap model fence repair.' },
{ since: '0.60.102.0', text: `Malformed facts and takes fences are now repaired automatically: the maintenance run repairs held files and stored pages on the owner host, and its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files (\`gbrain doctor --only fence_integrity\` counts them; \`gbrain repair fences\` previews the plan). A fence only a rewrite can realign sends just its header and those rows, never the rest of the page, to the repair model, within $0.30 per page and $1.00 per day (\`fences.repair.max_usd_per_page\`, \`fences.repair.max_usd_per_day\`); every rewrite passes validation gates before it is written. With \`models.fence_repair\` unset, the repair model is the first model the fence-repair eval measured as accurate enough that has a provider key on the brain host (\`gbrain models\` names it); with none, model repair stays off until the user sets \`models.fence_repair\`. ${FENCE_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` keeps fence rows away from the model; \`gbrain config set fences.repair.enabled false\` pauses automatic repair. On a managed source each repaired file is committed, so \`git revert\` undoes it (page history keeps the earlier version); turning these settings off stops future repairs and does not undo past ones.` },
{ since: '0.60.104.0', text: '`remember` of a claim that was forgotten is now refused before it is accepted, with `invalid_params` and the message prefix `fact_withdrawn` (it used to be accepted and then fail with "The write did not commit"); a claim forgotten without an entity stays withdrawn for every entity. `replaces` now accepts a fact saved without an entity, so `remember` with `entity` and `replaces` links that fact instead of forgetting it. A failed write receipt names its cause instead of "Inspect its durable request on the source host".' },
+ { since: '0.60.104.0', text: 'gbrain learns more of the names an entity goes by: declared aliases now cover common prose cues ("also known as", "goes by", "formerly", "doing business as"), alias label lines and table rows ("Internal nickname: Copper Fox"), and multi-word names. Every brain re-derives aliases and rescans mentions once on its next `gbrain extract --stale` (autopilot runs it); `gbrain config set mentions.multiword_aliases false` keeps one-word aliases only and `mentions.alias_deny` drops a name.' },
+ { since: '0.60.104.0', text: 'Pages that name the same subject under different title prefixes ("Account sheet: X" and "CRM record: X") are shown as identity siblings on the entity card, never merged; a name both claim now links mentions to each of them instead of to neither. Frontmatter `identity: separate` or `gbrain config set mentions.sibling_merge false` keeps pages apart.' },
+ { since: '0.60.104.0', text: 'The entity card gains `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines that may name the entity otherwise) and `alias_guidance`; `aka` is unchanged. search and query also search every other name of the entity a query names (up to 4, keyword-only, rows marked `matched_alias`); `gbrain config set search.alias_fanout_max 0` turns that off.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index c181546a43..a7ba7a685c 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -38,7 +38,8 @@ 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 } from './mentions/policy.ts';
+import { ALWAYS_LINKABLE_TYPES, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './mentions/policy.ts';
+import { siblingVerdict, type SiblingCandidate } from './mentions/siblings.ts';
/**
* The four types that are always linkable, whatever the schema pack says. The
@@ -88,6 +89,11 @@ export interface GazetteerEntry {
caseTokens?: string[];
/** Spelling being matched (the alias, not the display title, for aliases). */
matchText?: string;
+ /**
+ * Set on a name two or three identity siblings claim (mentions/siblings.ts):
+ * a match links to every sibling with the same tokens instead of one.
+ */
+ shared?: true;
}
/**
@@ -111,7 +117,7 @@ export function hashGazetteer(gazetteer: Gazetteer): string {
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(' ')}` : ''}`);
}
// Matching semantics are part of the resume identity, not just DB contents.
- return createHash('sha256').update('hangul-boundaries-v2\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
+ return createHash('sha256').update('shared-sibling-names-v3\n').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
}
/** One row of the saved entry set the mention pass diffs (mention_gazetteer_entries). */
@@ -473,8 +479,10 @@ export async function buildGazetteer(
const drop = (d: DroppedName) => { dropped?.push(d); };
const sources = await engine.executeRaw<{ id: string }>('SELECT DISTINCT source_id AS id FROM pages WHERE deleted_at IS NULL', []);
const typesBySource = new Map<string, Set<string>>();
+ const packBySource = new Map<string, PackTypes | null>();
for (const { id } of sources) {
const pack = await loadSourcePack(engine, id, { strict: opts.strict });
+ packBySource.set(id, pack);
typesBySource.set(id, new Set(linkableTypesFor(pack, policy)));
}
const allTypes = [...new Set([...typesBySource.values()].flatMap(set => [...set]))];
@@ -557,10 +565,10 @@ export async function buildGazetteer(
// - 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 }> = [];
+ 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
+ `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[])
@@ -594,13 +602,19 @@ export async function buildGazetteer(
const prev = bestPerPage.get(k);
if (!prev || rank(a.origin) < rank(prev.origin)) bestPerPage.set(k, a);
}
- const claims = new Map<string, { rank: number; slugs: Set<string> }>();
+ const claims = new Map<string, { rank: number; slugs: Set<string>; pages: SiblingCandidate[]; shared?: boolean }>();
for (const a of bestPerPage.values()) {
const k = `${a.source_id ?? 'default'} ${a.alias_norm}`;
const r = rank(a.origin);
const c = claims.get(k);
- if (!c || r < c.rank) claims.set(k, { rank: r, slugs: new Set([a.slug]) });
- else if (r === c.rank) c.slugs.add(a.slug);
+ const page = { slug: a.slug, title: a.title, type: a.type, identity: a.identity };
+ if (!c || r < c.rank) claims.set(k, { rank: r, slugs: new Set([a.slug]), pages: [page] });
+ else if (r === c.rank && !c.slugs.has(a.slug)) { c.slugs.add(a.slug); c.pages.push(page); }
+ }
+ // A name identity siblings share (the subject of "Account sheet: X" and
+ // "CRM record: X", or a code both declare) links to every sibling.
+ for (const [k, c] of claims) {
+ if (c.slugs.size > 1) c.shared = siblingVerdict(c.pages, packBySource.get(k.slice(0, k.indexOf(' '))) ?? null, policy) === 'group';
}
const aliasEntries: Array<{ entry: GazetteerEntry; base: Omit<DroppedName, 'reason'> }> = [];
for (const a of bestPerPage.values()) {
@@ -613,7 +627,7 @@ export async function buildGazetteer(
const claim = claims.get(`${src} ${alias}`)!;
if (rank(a.origin) > claim.rank) continue;
if (excludedSlugs.has(a.slug)) { drop({ ...base, reason: 'excluded_slug' }); continue; }
- if (claim.slugs.size > 1) { drop({ ...base, reason: 'alias_collision' }); continue; }
+ if (claim.slugs.size > 1 && !claim.shared) { drop({ ...base, reason: 'alias_collision' }); continue; }
if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) { 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; }
@@ -625,7 +639,7 @@ export async function buildGazetteer(
if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
const caseTokens = a.case_sensitive && a.alias_text ? caseTokensOf(a.alias_text) : undefined;
const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, origin, matchText: alias,
- ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}) };
+ ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}), ...(claim.shared ? { shared: true as const } : {}) };
noteFirstWord(src, tokens);
aliasEntries.push({ entry, base });
}
@@ -812,13 +826,22 @@ export function findMentionedEntities(
continue;
}
- out.push({
- slug: matched.slug,
- source_id: matched.source_id,
- name: matched.title,
- offset: head.offset,
- });
- seenTargets.add(target);
+ // A shared sibling name links every sibling, unless the scanning page is one of them.
+ 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))
+ : [matched];
+ if (group.length > 1 && group.some(e => e.source_id === opts.fromSourceId && e.slug === opts.fromSlug)) {
+ i += matchedTokens;
+ continue;
+ }
+ for (const e of group) {
+ const key = `${e.source_id}\0${e.slug}`;
+ if (seenTargets.has(key)) continue;
+ out.push({ slug: e.slug, source_id: e.source_id, name: e.title, offset: head.offset });
+ seenTargets.add(key);
+ }
i += matchedTokens;
}
diff --git a/src/core/config.ts b/src/core/config.ts
index b03362291a..c5bc03cacb 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1600,8 +1600,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// reconcile-links, and sweep. The documented off-switch is `gbrain config
// set auto_link false` — same unregistered-key class as auto_chronicle.
'auto_link',
- // Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked, pages never linked (#5829).
- 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'mentions.exclude_slugs',
+ // 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',
// #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 --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 639fac931c..6dcb691996 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -378,6 +378,8 @@ export const NOTICE_CODES = {
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },
former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },
+ identity_siblings_capped: { kind: 'info', summary: 'More than three pages share an entity\'s title subject, so the card shows no identity siblings; the fix (for the user) lists them with `gbrain extract mentions --explain`.' },
+ alias_fanout: { kind: 'info', summary: 'search fanned out over an entity\'s other names and stopped at the per-call cap; the skipped names are listed and can be searched directly.' },
mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },
degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },
source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
diff --git a/src/core/mentions/aliases.ts b/src/core/mentions/aliases.ts
index 7691070417..5a6df69391 100644
--- a/src/core/mentions/aliases.ts
+++ b/src/core/mentions/aliases.ts
@@ -1,17 +1,30 @@
/**
* Derived names of an entity page: its title subject and the aliases its body
- * declares. Search's declared-name fan-out (`aliasDeclarations`, ops/search.ts)
- * and the mention pass's alias refresh share `declaredNames`, so both read the
- * same declarations with the same post-filters.
+ * declares. Search's declared-name fan-out (`aliasDeclarations`, ops/search.ts),
+ * the mention pass's alias refresh, the entity card's identity excerpt and
+ * `extract mentions --explain` share `declarationsIn`, so they read the same
+ * declarations with the same post-filters.
*
* - Title subject: for a title with a prefix ending in `: ` ("CRM record:
* Acme Example"), the text after the last `: `. Stored with
* `origin='subject'`; an exact page title in the same source outranks it.
- * - Declarations: `account code`, `also known as`, `a.k.a.`, `aka`, `short
- * name`, `ticker`, `code name`, read from the body with private takes and
- * facts fences stripped, so a private code never becomes a public name.
- * Stored with `origin='declared'`. A single-token declaration matches only
- * as written (`case_sensitive`), so "aka Mark" never links lowercase "mark".
+ * - Declarations: the conventions in docs/designs/ALIAS_CONVENTIONS.md, read
+ * from the body with private takes and facts fences stripped, so a private
+ * code never becomes a public name: prose cues ("also known as", "goes by",
+ * "formerly", "doing business as", ...), label and value lines whose label
+ * names an alias field ("Internal nickname: X", a Markdown table row, a bold
+ * key-value line), and a quoted defined term right after the page's own name
+ * (`Widget Co ("Widget")`). A capture is a quoted name or a run of up to 4
+ * capitalized or code tokens; it ends at punctuation, a lowercase word or the
+ * line end, and a possessive or a run of only common capitalized words
+ * rejects it. A cue after a relational noun ("our competitor, also known as
+ * ...") declares another entity's name and is skipped. Stored with
+ * `origin='declared'`. A single-token declaration matches only as written
+ * (`case_sensitive`), so "aka Mark" never links lowercase "mark".
+ * - Escape hatches: `mentions.alias_deny` and frontmatter `alias_deny:` drop a
+ * derived name; `mentions.multiword_aliases=false` keeps one-token captures.
+ *
+ * Parsing is linear in the line length (no backtracking regex over values).
*/
import { normalizeAlias } from '../search/alias-normalize.ts';
@@ -20,13 +33,149 @@ import { stripFactsFence } from '../facts-fence.ts';
import { isGenericEntityToken } from '../entity-name-quality.ts';
import { hasCJK, tokenizeTitle } from '../by-mention.ts';
-export const ALIAS_DECLARATION = /\b(?:account code|also known as|a\.k\.a\.|aka|short name|ticker|code name)\b\s*[:(]?\s*["\u201c']?([A-Z0-9][A-Za-z0-9&.-]{1,24})/gi;
-/** Every ALIAS_DECLARATION keyword, lowercased: a text containing none of them cannot match the regex. */
-export const DECLARATION_KEYWORDS = ['account code', 'also known as', 'a.k.a', 'aka', 'short name', 'ticker', 'code name'];
+const CUES = [
+ 'also known as', 'a\\.k\\.a\\.?', 'aka', 'known internally as', 'internally known as', 'known to the team as', 'better known as',
+ 'widely known as', 'known as', 'nicknamed', 'nicknames?', 'goes by', 'went by', 'going by', 'also called', 'sometimes called',
+ 'often called', 'commonly called', 'is called', 'commonly referred to as', 'often referred to as', 'referred to as',
+ 'formerly known as', 'previously known as', 'formerly', 'f/k/a', 'fka', 'n\u00e9e', 'trading as', 't/a', 'doing business as',
+ 'd/b/a', 'dba', 'short name', 'short for', 'abbreviated as', 'abbreviated', 'code ?name', 'account code', 'customer code',
+ 'account id', 'ticker', 'alias(?:es)?',
+];
+const CUE_RE = new RegExp(`(?<![A-Za-z0-9])(?:${CUES.join('|')})(?![A-Za-z0-9])`, 'gi');
+const LABEL_NOUN_RE = /(?<![a-z])(?:nicknames?|alias(?:es)?|aka|a\.k\.a\.?|also known as|short name|trading name|trade name|brand name|former (?:legal )?name|previous name|legal name|display name|dba|d\/b\/a|code ?name|account code|customer code|ticker)(?![a-z])/i;
+const RELATIONAL_NOUN_RE = /\b(?:competitors?|rivals?|partners?|parent(?: company)?|subsidiar(?:y|ies)|affiliates?|vendors?|suppliers?|customers?|clients?|acquirers?|investors?)\b/i;
+const QUOTES: Record<string, string> = { '"': '"', '\u201c': '\u201d', "'": "'", '\u2018': '\u2019' };
+const COMMON_WORDS = new Set([
+ 'the', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'january', 'february', 'march', 'april', 'may',
+ 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'board', 'finance', 'legal', 'sales', 'marketing',
+ 'engineering', 'operations', 'support', 'hr', 'it', 'plan', 'report', 'team', 'project', 'update', 'review', 'company',
+]);
+const CORPORATE_SUFFIX = '(?:,?\\s+(?:Inc|LLC|Ltd|Limited|Corp|Corporation|Co|GmbH|PLC|plc|LP|LLP|Holdings|S\\.A)\\.?)*';
+const PAREN_TERM_RE = /\(\s*(?:the\s+)?["\u201c']([^"\u201d'()\n]{1,60})["\u201d']\s*\)/g;
+const MAX_NAME_TOKENS = 4;
/** Below this many characters a (non-CJK) name is never linked or stored as a derived alias. */
export const MIN_ALIAS_LENGTH = 4;
+export interface DeclarationOpts {
+ /** Allow captures of more than one token (`mentions.multiword_aliases`, default on). */
+ multiword?: boolean;
+ /** Other names of the page (frontmatter aliases) that may introduce a parenthetical defined term. */
+ ownNames?: string[];
+}
+
+/** One declared name with the line that declares it (0-based line index into the scanned text). */
+export interface Declaration { alias: string; line: number }
+
+const isQuarter = (t: string) => /^(?:q[1-4]|h[12]|fy\d{2,4})$/i.test(t);
+const isCommon = (t: string) => COMMON_WORDS.has(t.toLowerCase()) || isQuarter(t);
+const isNameToken = (t: string) => /^[A-Z][A-Za-z0-9&.\u2019'-]*$/.test(t) || (/^[0-9][A-Za-z0-9&.-]*$/.test(t) && /[A-Z]/.test(t));
+const POSSESSIVE_RE = /['\u2019]s$/;
+
+/**
+ * The name at the start of `rest` (after a cue or a label): a quoted name of up
+ * to 4 words, or a run of up to 4 capitalized or code tokens. Null when there
+ * is none or the capture is rejected (possessive, too long, only common words).
+ */
+export function captureName(rest: string, opts: { multiword?: boolean } = {}): string | null {
+ let s = rest.replace(/^[\s:,(\-\u2013\u2014]+/, '');
+ const multiword = opts.multiword !== false;
+ const close = QUOTES[s[0] ?? ''];
+ if (close) {
+ const end = s.indexOf(close, 1);
+ if (end < 0 || end > 80) return null;
+ const words = s.slice(1, end).trim().split(/\s+/).filter(Boolean);
+ if (!words.length || words.length > MAX_NAME_TOKENS || (!multiword && words.length > 1)) return null;
+ if (/^['\u2019]s\b/.test(s.slice(end + 1))) return null;
+ return finish(words);
+ }
+ s = s.replace(/^(?:the|a|an)\s+/i, '');
+ const words: string[] = [];
+ for (const raw of s.split(/\s+/)) {
+ const core = raw.replace(/[.,;:!?)\]"\u201d]+$/, '');
+ if (POSSESSIVE_RE.test(core)) return null;
+ if (!core || !isNameToken(core)) break;
+ words.push(core);
+ if (words.length > MAX_NAME_TOKENS) return null;
+ if (core !== raw) break;
+ }
+ if (!words.length || (!multiword && words.length > 1)) return null;
+ return finish(words);
+}
+
+function finish(words: string[]): string | null {
+ const name = words.join(' ').replace(/[.,;]+$/, '');
+ const tokens = name.split(/\s+/).filter(w => !/^the$/i.test(w));
+ if (!tokens.length || tokens.every(isCommon)) return null;
+ if (!/[A-Z0-9]/.test(name)) return null;
+ return name;
+}
+
+/** Split a label's value into its listed names (`,`, `;`, ` / `, ` or `). */
+function labelValues(value: string, multiword: boolean): string[] {
+ const out: string[] = [];
+ for (const part of value.split(/\s*[,;]\s*|\s+\/\s+|\s+or\s+/)) {
+ const name = captureName(part, { multiword });
+ if (name) out.push(name);
+ }
+ return out;
+}
+
+const stripLineMarkup = (line: string) => line.replace(/^\s*(?:[-*+>]|\d+[.)])\s+/, '').replace(/\*\*|__/g, '').trim();
+const isTableSeparator = (line: string | undefined) => !!line && /^\s*\|?\s*:?-{2,}/.test(line);
+const isLabel = (label: string) => label.split(/\s+/).length <= 6 && LABEL_NOUN_RE.test(label);
+
+/** Every declaration in `text` with its line, in line order, deduped by alias (first line wins). Not post-filtered. */
+export function declarationsIn(text: string, opts: DeclarationOpts = {}): Declaration[] {
+ const multiword = opts.multiword !== false;
+ const lines = (text ?? '').split('\n');
+ const out: Declaration[] = [];
+ const push = (alias: string | null, line: number) => { if (alias && !out.some(d => d.alias === alias)) out.push({ alias, line }); };
+ const ownNames = (opts.ownNames ?? []).filter(Boolean);
+ const parenOwner = ownNames.length
+ ? new RegExp(`(?:${ownNames.map(n => n.replace(/[.*+?^\${}()|[\]\\]/g, '\\$&')).join('|')})${CORPORATE_SUFFIX},?\\s*$`, 'i')
+ : null;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.length > 2000) continue;
+ const trimmed = line.trim();
+ if (trimmed.startsWith('|')) {
+ const cells = trimmed.replace(/^\||\|$/g, '').split('|').map(c => stripLineMarkup(c));
+ if (cells.length >= 2 && !isTableSeparator(trimmed) && !isTableSeparator(lines[i + 1]) && isLabel(cells[0]!.replace(/:$/, ''))) {
+ for (const name of labelValues(cells[1]!, multiword)) push(name, i);
+ }
+ continue;
+ }
+ const plain = stripLineMarkup(line);
+ const colon = plain.indexOf(':');
+ if (colon > 0 && colon <= 60 && isLabel(plain.slice(0, colon))) {
+ for (const name of labelValues(plain.slice(colon + 1), multiword)) push(name, i);
+ }
+ CUE_RE.lastIndex = 0;
+ for (const m of plain.matchAll(CUE_RE)) {
+ const before = plain.slice(0, m.index);
+ const sentence = before.slice(Math.max(before.lastIndexOf('. '), before.lastIndexOf('; '), -1) + 1);
+ if (RELATIONAL_NOUN_RE.test(sentence)) continue;
+ push(captureName(plain.slice(m.index! + m[0].length), { multiword }), i);
+ }
+ if (parenOwner) {
+ for (const m of plain.matchAll(PAREN_TERM_RE)) {
+ if (!parenOwner.test(plain.slice(0, m.index))) continue;
+ push(captureName(`"${m[1]}"`, { multiword }), i);
+ }
+ }
+ }
+ return out;
+}
+
+/** Names `text` declares for the entity called `name`, post-filtered (an uppercase letter or digit, differs from the name). */
+export function declaredNames(text: string, name: string, opts: DeclarationOpts = {}): string[] {
+ const own = name.toLowerCase();
+ return declarationsIn(text, { ...opts, ownNames: [name, ...(opts.ownNames ?? [])] })
+ .map(d => d.alias)
+ .filter(alias => alias.toLowerCase() !== own);
+}
+
/** The text after the last `: ` of a title, or the whole title when it has no such prefix. */
export function titleName(title: string): string {
return (title ?? '').split(':').pop()!.trim();
@@ -41,19 +190,6 @@ export function titleSubject(title: string | null | undefined): string | null {
return subject && subject !== t ? subject : null;
}
-/** Names `text` declares for the entity called `name`, post-filtered (punctuation trimmed, an uppercase letter or digit, differs from the name). */
-export function declaredNames(text: string, name: string): string[] {
- const lower = text.toLowerCase();
- if (!DECLARATION_KEYWORDS.some(k => lower.includes(k))) return [];
- const out: string[] = [];
- for (const m of text.matchAll(ALIAS_DECLARATION)) {
- const alias = m[1].replace(/[.,;]+$/, '');
- if (!/[A-Z0-9]/.test(alias) || alias.toLowerCase() === name.toLowerCase()) continue;
- if (!out.includes(alias)) out.push(alias);
- }
- return out;
-}
-
export type AliasOrigin = 'frontmatter' | 'declared' | 'subject';
export const ALIAS_ORIGIN_RANK: Record<AliasOrigin, number> = { frontmatter: 0, declared: 1, subject: 2 };
@@ -65,7 +201,9 @@ export interface DerivedAlias {
case_sensitive: boolean;
}
-export type AliasRejection = 'below_min_length' | 'generic_token' | 'ambiguous_first_word';
+export type AliasRejection = 'below_min_length' | 'generic_token' | 'ambiguous_first_word' | 'denied';
+
+export interface RejectedAlias { alias: string; origin: 'declared' | 'subject'; reason: AliasRejection; line?: string }
/** Private takes and facts fences removed: the text a world reader may see. */
export function publicBody(body: string): string {
@@ -82,30 +220,54 @@ export function aliasRejection(alias: string, ownName: string): AliasRejection |
return null;
}
+/** A frontmatter list value (`alias_deny:`, `aliases:`) as strings. */
+function frontmatterList(value: unknown): string[] {
+ if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string');
+ return typeof value === 'string' && value.trim() ? value.split(',').map(v => v.trim()) : [];
+}
+
+export interface DeriveAliasOpts {
+ /** `mentions.multiword_aliases` (default on). */
+ multiword?: boolean;
+ /** `mentions.alias_deny`: names never derived for any page. */
+ deny?: readonly string[];
+}
+
/**
* The derived alias rows of one entity page: its title subject and its body
* declarations, deduped by normalized form (subject first). Rejected names
- * are returned beside the kept ones for `extract mentions --explain`.
+ * are returned beside the kept ones (with the declaring line) for
+ * `extract mentions --explain`.
*/
-export function deriveEntityAliases(page: { title: string | null; compiled_truth: string | null; timeline?: string | null }): {
- aliases: DerivedAlias[]; rejected: Array<{ alias: string; origin: 'declared' | 'subject'; reason: AliasRejection }>;
-} {
+export function deriveEntityAliases(
+ page: { title: string | null; compiled_truth: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null },
+ opts: DeriveAliasOpts = {},
+): { aliases: DerivedAlias[]; rejected: RejectedAlias[]; lines: Map<string, string> } {
const title = page.title ?? '';
const name = titleName(title);
const aliases: DerivedAlias[] = [];
- const rejected: Array<{ alias: string; origin: 'declared' | 'subject'; reason: AliasRejection }> = [];
+ const rejected: RejectedAlias[] = [];
+ const lines = new Map<string, string>();
+ const deny = new Set([...(opts.deny ?? []), ...frontmatterList(page.frontmatter?.alias_deny)].map(normalizeAlias).filter(Boolean));
const seen = new Set<string>([normalizeAlias(title)]);
- const push = (alias: string, origin: 'declared' | 'subject', caseSensitive: boolean) => {
+ const push = (alias: string, origin: 'declared' | 'subject', caseSensitive: boolean, line?: string) => {
const norm = normalizeAlias(alias);
if (!norm || seen.has(norm)) return;
- const reason = aliasRejection(alias, name);
- if (reason) { rejected.push({ alias, origin, reason }); return; }
+ const reason = deny.has(norm) ? 'denied' : aliasRejection(alias, name);
+ if (reason) { rejected.push({ alias, origin, reason, ...(line !== undefined ? { line } : {}) }); return; }
seen.add(norm);
+ if (line !== undefined) lines.set(norm, line);
aliases.push({ alias_norm: norm, alias_text: alias, origin, case_sensitive: caseSensitive });
};
const subject = titleSubject(title);
if (subject) push(subject, 'subject', false);
const text = publicBody(`${page.compiled_truth ?? ''}\n\n${page.timeline ?? ''}`);
- for (const alias of declaredNames(text, name)) push(alias, 'declared', tokenizeTitle(alias).length === 1);
- return { aliases, rejected };
+ const textLines = text.split('\n');
+ const ownNames = frontmatterList(page.frontmatter?.aliases);
+ const own = name.toLowerCase();
+ for (const d of declarationsIn(text, { multiword: opts.multiword, ownNames: [name, ...ownNames] })) {
+ if (d.alias.toLowerCase() === own) continue;
+ push(d.alias, 'declared', tokenizeTitle(d.alias).length === 1, textLines[d.line]?.trim());
+ }
+ return { aliases, rejected, lines };
}
diff --git a/src/core/mentions/coverage.ts b/src/core/mentions/coverage.ts
index bef641ae04..24b6d7f91a 100644
--- a/src/core/mentions/coverage.ts
+++ b/src/core/mentions/coverage.ts
@@ -4,10 +4,14 @@
* names. Read from the per-source status row the mention pass maintains plus
* the due pages written since its last count (an indexed read over recent
* pages per source), never a whole-brain scan, and never another source's
- * state.
+ * state. A row counted by a binary with other extractor versions (its
+ * version stamp differs) is recounted once and the count saved on the row,
+ * so a version bump shows every version-behind page as pending, whatever its
+ * `updated_at`, until the sweep reaches it.
*
* States: `complete`; `pending` (pages written or invalidated since the last
- * pass, or no pass yet); `disabled` (auto_link or mentions.auto_link is off);
+ * pass, pages behind the binary's mention or alias version, or no pass yet);
+ * `disabled` (auto_link or mentions.auto_link is off);
* `type_not_linkable` (cards only: nothing links to this page type by
* mention); `failed` (the last pass could not build the index). Any state but
* `complete` carries `degraded: true` and a `[gbrain notice mention_index]`.
@@ -15,8 +19,8 @@
import type { BrainEngine } from '../engine.ts';
import type { Notice } from '../agent-output.ts';
-import { readMentionPolicy } from './policy.ts';
-import { MENTION_EXTRACTOR_VERSION } from './pass.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from './policy.ts';
+import { INDEX_VERSION_STAMP, MENTION_EXTRACTOR_VERSION, countIndexDuePages, splitStoredFingerprint } from './pass.ts';
export type CoverageState = 'complete' | 'pending' | 'disabled' | 'type_not_linkable' | 'failed';
@@ -36,8 +40,8 @@ const toIso = (v: unknown): string | null => {
/** Coverage over `sourceIds` (the caller's permitted sources). */
export async function readMentionCoverage(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceIds: string[]): Promise<MentionCoverage> {
const policy = await readMentionPolicy(engine);
- const rows = await engine.executeRaw<{ source_id: string; state: string; pending: number; counted_at: unknown; last_pass_at: unknown }>(
- `SELECT source_id, state, pending, counted_at, last_pass_at FROM mention_index_status WHERE source_id = ANY($1::text[])`, [sourceIds]);
+ const rows = await engine.executeRaw<{ source_id: string; state: string; pending: number; counted_at: unknown; last_pass_at: unknown; policy_fingerprint: string | null }>(
+ `SELECT source_id, state, pending, counted_at, last_pass_at, policy_fingerprint FROM mention_index_status WHERE source_id = ANY($1::text[])`, [sourceIds]);
const bySource = new Map(rows.map(r => [r.source_id, r]));
let pending = 0;
let failed = false;
@@ -53,6 +57,18 @@ export async function readMentionCoverage(engine: Pick<BrainEngine, 'executeRaw'
continue;
}
if (row.state === 'failed') failed = true;
+ const stored = splitStoredFingerprint(row.policy_fingerprint);
+ if (stored.versions !== INDEX_VERSION_STAMP) {
+ // Counted by another binary: recount once (pages behind this binary's versions are due whatever their updated_at) and save it.
+ const due = await countIndexDuePages(engine, sourceId, linkableTypesFor(await loadSourcePack(engine, sourceId), policy));
+ await engine.executeRaw(
+ `UPDATE mention_index_status SET pending = $2, counted_at = now(), policy_fingerprint = $3, updated_at = now(),
+ state = CASE WHEN state = 'complete' AND $2::int > 0 THEN 'pending' ELSE state END
+ WHERE source_id = $1 AND policy_fingerprint IS NOT DISTINCT FROM $4`,
+ [sourceId, due, `${stored.hash ?? ''};${INDEX_VERSION_STAMP}`, row.policy_fingerprint]).catch(() => undefined);
+ pending += due;
+ continue;
+ }
// Pages written at or after the last count that are not scanned at their current content (the index on updated_at keeps it small).
const [since] = await engine.executeRaw<{ n: number }>(
`SELECT count(*)::int AS n FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
index 8e1081ae7e..f811531191 100644
--- a/src/core/mentions/pass.ts
+++ b/src/core/mentions/pass.ts
@@ -7,8 +7,11 @@
* One pass, per source in scope:
* 1. Policy. `auto_link=false` or `mentions.auto_link=false` removes plain
* mention links and derived alias rows once and records `disabled`;
- * re-enabling makes every page due. A change of the linkable type set,
- * cross-source policy or ignore list makes every page due once.
+ * re-enabling makes every page due. A change of the policy fingerprint
+ * (linkable type set, cross-source policy, ignore list, alias deny list,
+ * multi-word aliases, sibling merge) makes every page due once. The
+ * status row records the extractor versions its count reflects; when
+ * they differ from this binary's, `pending` is recounted once.
* 2. Alias refresh: linkable entity pages whose derived aliases were
* refreshed at another content revision (or alias version) get their
* `declared` and `subject` rows rewritten; pages that stopped being
@@ -28,8 +31,10 @@
* scan read them (conditional publish), so an edit or a gazetteer change
* during the scan leaves the page due. Only plain mention rows are
* touched; `typed_ner` rows stay.
- * 6. Status row: state, pending pages, last pass, generation. `coverage`
- * on entity cards and get_backlinks reads it.
+ * 6. Status row: state, pending pages (mention-due pages plus linkable
+ * entity pages with stale derived aliases, counted when the pass ends
+ * or its deadline stops it), last pass, generation. `coverage` on
+ * entity cards and get_backlinks reads it.
*
* MENTION_EXTRACTOR_VERSION is separate from LINK_EXTRACTOR_VERSION_TS, so a
* gazetteer change never reruns link or timeline extraction.
@@ -50,9 +55,9 @@ import { maintenanceAttribution } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
/** Bump to rescan every page's mentions once (gazetteer or scanner behavior change). */
-export const MENTION_EXTRACTOR_VERSION = 2;
+export const MENTION_EXTRACTOR_VERSION = 3;
/** Bump to re-derive every entity page's declared aliases and title subject once. */
-export const ALIAS_DERIVATION_VERSION = 1;
+export const ALIAS_DERIVATION_VERSION = 2;
const RECONCILE_BATCH = 200;
const ALIAS_BATCH = 200;
@@ -95,6 +100,34 @@ export async function countMentionDuePages(engine: Pick<BrainEngine, 'executeRaw
return Number(rows[0]?.n ?? 0);
}
+/**
+ * Index-due live pages of one source: mention-due pages plus linkable entity
+ * pages (`types`) whose derived aliases are behind their content or
+ * ALIAS_DERIVATION_VERSION. The status row's `pending` holds this count.
+ */
+export async function countIndexDuePages(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, types: string[]): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.deleted_at IS NULL AND p.source_id = $1 AND (${DUE_PREDICATE}
+ OR (p.type = ANY($3::text[]) AND (s.alias_revision IS DISTINCT FROM p.knowledge_revision OR s.alias_version IS DISTINCT FROM $4)))`,
+ [sourceId, MENTION_EXTRACTOR_VERSION, types, ALIAS_DERIVATION_VERSION]);
+ return Number(rows[0]?.n ?? 0);
+}
+
+/**
+ * The extractor versions a status row's `pending` count reflects, stored after
+ * the policy hash in `mention_index_status.policy_fingerprint`
+ * (`<hash>;v<mention>.<alias>`). A row without it, or with other versions,
+ * was counted by another binary.
+ */
+export const INDEX_VERSION_STAMP = `v${MENTION_EXTRACTOR_VERSION}.${ALIAS_DERIVATION_VERSION}`;
+
+export function splitStoredFingerprint(stored: string | null | undefined): { hash: string | null; versions: string | null } {
+ if (!stored) return { hash: null, versions: null };
+ const at = stored.indexOf(';');
+ return at < 0 ? { hash: stored, versions: null } : { hash: stored.slice(0, at), versions: stored.slice(at + 1) };
+}
+
async function sourcesInScope(engine: BrainEngine, sourceId?: string): Promise<string[]> {
if (sourceId) return [sourceId];
const rows = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id');
@@ -104,6 +137,7 @@ async function sourcesInScope(engine: BrainEngine, sourceId?: string): Promise<s
function policyFingerprint(types: string[], crossSource: boolean, policy: MentionPolicy): string {
return createHash('sha256').update(JSON.stringify({
types, crossSource, ignore: [...policy.ignore].map(n => n.toLowerCase()).sort(),
+ aliasDeny: [...policy.aliasDeny].map(n => n.toLowerCase()).sort(), multiword: policy.multiwordAliases, siblings: policy.siblingMerge,
})).digest('hex').slice(0, 16);
}
@@ -141,13 +175,13 @@ async function aliasWrite<T>(engine: BrainEngine, managed: boolean, sourceId: st
* leaves no derived rows. Frontmatter rows are untouched.
*/
export async function writeDerivedAliases(tx: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceId: string,
- page: { slug: string; title: string | null; type: string | null; compiled_truth: string | null; timeline?: string | null },
+ page: { slug: string; title: string | null; type: string | null; compiled_truth: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null },
opts: { pack?: PackTypes | null; policy?: MentionPolicy | null } = {}): Promise<number> {
// A config read that fails (null policy) leaves the rows for the next sweep rather than failing the caller's write.
const policy = opts.policy !== undefined ? opts.policy : await readMentionPolicy(tx).catch(() => null);
if (!policy) return 0;
const types = policy.enabled ? linkableTypesFor(opts.pack !== undefined ? opts.pack : await loadSourcePack(tx, sourceId), policy) : [];
- const aliases = types.includes(page.type ?? '') ? deriveEntityAliases(page).aliases : [];
+ const aliases = types.includes(page.type ?? '') ? deriveEntityAliases(page, aliasOptsOf(policy)).aliases : [];
await tx.executeRaw(`DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')`, [sourceId, page.slug]);
if (aliases.length) {
await tx.executeRaw(
@@ -190,10 +224,15 @@ async function disableSource(engine: BrainEngine, managed: boolean, sourceId: st
}
interface DuePage { id: number; slug: string; source_id: string; revision: string; title: string | null; type: string | null;
- compiled_truth: string | null; timeline: string | null; mention_ignore: unknown }
+ compiled_truth: string | null; timeline: string | null; mention_ignore: unknown; frontmatter?: Record<string, unknown> | null }
+
+/** Alias derivation options from the mention policy (`mentions.alias_deny`, `mentions.multiword_aliases`). */
+export function aliasOptsOf(policy: Pick<MentionPolicy, 'aliasDeny' | 'multiwordAliases'>): { deny: string[]; multiword: boolean } {
+ return { deny: policy.aliasDeny, multiword: policy.multiwordAliases };
+}
/** Refresh derived alias rows of due entity pages in one source; returns pages whose rows changed. */
-async function refreshAliases(engine: BrainEngine, managed: boolean, sourceId: string, types: string[], deadline: number): Promise<number> {
+async function refreshAliases(engine: BrainEngine, managed: boolean, sourceId: string, types: string[], deadline: number, policy: MentionPolicy): Promise<number> {
let changed = 0;
// Pages that stopped being linkable entities (retype, pack change, deletion) lose their derived rows.
const stale = await engine.executeRaw<{ slug: string }>(
@@ -211,14 +250,14 @@ async function refreshAliases(engine: BrainEngine, managed: boolean, sourceId: s
for (;;) {
if (Date.now() > deadline) break;
const pages = await engine.executeRaw<DuePage>(
- `SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline, NULL AS mention_ignore
+ `SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline, NULL AS mention_ignore, p.frontmatter
FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.type = ANY($2::text[]) AND p.id > $3
AND (s.page_id IS NULL OR s.alias_revision IS DISTINCT FROM p.knowledge_revision OR s.alias_version IS DISTINCT FROM $4)
ORDER BY p.id LIMIT $5`, [sourceId, types, after, ALIAS_DERIVATION_VERSION, ALIAS_BATCH]);
if (!pages.length) break;
after = pages[pages.length - 1]!.id;
- const desired = new Map(pages.map(p => [p.slug, deriveEntityAliases(p).aliases]));
+ const desired = new Map(pages.map(p => [p.slug, deriveEntityAliases(p, aliasOptsOf(policy)).aliases]));
const existing = await engine.executeRaw<{ slug: string; alias_norm: string; origin: string; case_sensitive: boolean; alias_text: string | null }>(
`SELECT slug, alias_norm, origin, case_sensitive, alias_text FROM page_aliases
WHERE source_id = $1 AND slug = ANY($2::text[]) AND origin IN ('declared','subject')`, [sourceId, pages.map(p => p.slug)]);
@@ -479,16 +518,20 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts
const stored = new Map((await engine.executeRaw<{ source_id: string; policy_fingerprint: string | null }>(
'SELECT source_id, policy_fingerprint FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources]))
.map(r => [r.source_id, r.policy_fingerprint]));
+ // A changed policy makes every page due; a binary with other extractor versions only recounts (version-behind pages are already due).
for (const sourceId of sources) {
- if (stored.get(sourceId) === fingerprints.get(sourceId)) continue;
+ const { hash, versions } = splitStoredFingerprint(stored.get(sourceId));
+ const policyChanged = hash !== fingerprints.get(sourceId);
+ if (!policyChanged && versions === INDEX_VERSION_STAMP) continue;
await engine.transaction(async tx => {
- await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL, alias_revision = NULL WHERE source_id = $1', [sourceId]);
- await writeStatus(tx, sourceId, { state: 'pending', bumpGeneration: true, fingerprint: fingerprints.get(sourceId)! });
+ if (policyChanged) await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL, alias_revision = NULL WHERE source_id = $1', [sourceId]);
+ await writeStatus(tx, sourceId, { state: 'pending', bumpGeneration: policyChanged, pending: await countIndexDuePages(tx, sourceId, types.get(sourceId)!),
+ fingerprint: `${fingerprints.get(sourceId)!};${INDEX_VERSION_STAMP}` });
});
}
for (const sourceId of sources) {
if (Date.now() > deadline) break;
- result.aliasPages += await refreshAliases(engine, managed, sourceId, types.get(sourceId)!, deadline);
+ result.aliasPages += await refreshAliases(engine, managed, sourceId, types.get(sourceId)!, deadline, policy);
}
// Aliases may have changed: the gazetteer the reconcile uses is built after the refresh.
if (result.aliasPages > 0) {
@@ -504,7 +547,7 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts
}
for (const sourceId of sources) {
await reconcileSource(engine, sourceId, gazetteer, allowCrossSource ? allSources : [sourceId], allowCrossSource, opts, deadline, result);
- const pending = await countMentionDuePages(engine, sourceId);
+ const pending = await countIndexDuePages(engine, sourceId, types.get(sourceId)!);
result.remaining += pending;
await writeStatus(engine, sourceId, { state: pending > 0 ? 'pending' : 'complete', pending, error: null, lastPassAt: passStart });
}
diff --git a/src/core/mentions/policy.ts b/src/core/mentions/policy.ts
index a32355d3b6..99eb2cac15 100644
--- a/src/core/mentions/policy.ts
+++ b/src/core/mentions/policy.ts
@@ -13,7 +13,9 @@
*
* Off switches: `auto_link=false` (global) or `mentions.auto_link=false`.
* `mentions.exclude_slugs` keeps named pages out of the gazetteer entirely
- * (#5829: an entity whose name is also a common word).
+ * (#5829: an entity whose name is also a common word). `mentions.alias_deny`
+ * and `mentions.multiword_aliases` shape alias derivation (aliases.ts);
+ * `mentions.sibling_merge` turns identity siblings off (siblings.ts).
*/
import type { BrainEngine } from '../engine.ts';
@@ -36,6 +38,12 @@ export interface MentionPolicy {
ignore: string[];
/** Page slugs that get no gazetteer entry, by title or alias (`mentions.exclude_slugs`, #5829). */
excludeSlugs: string[];
+ /** Names never derived as an alias for any page (`mentions.alias_deny`). */
+ aliasDeny: string[];
+ /** Derive multi-word declared aliases (`mentions.multiword_aliases`, default on). */
+ multiwordAliases: boolean;
+ /** Show same-subject pages as identity siblings on cards and in search (`mentions.sibling_merge`, default on). */
+ siblingMerge: boolean;
}
const FALSE_VALUES = new Set(['false', '0', 'no', 'off']);
@@ -56,10 +64,11 @@ export function parseNameList(value: unknown): string[] {
}
export async function readMentionPolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<MentionPolicy> {
- const [global, own, types, ignore, excludeSlugs] = await Promise.all([
+ const [global, own, types, ignore, excludeSlugs, aliasDeny, multiword, siblings] = await Promise.all([
engine.getConfig('auto_link'), engine.getConfig('mentions.auto_link'),
engine.getConfig('mentions.entity_types'), engine.getConfig('mentions.ignore'),
- engine.getConfig('mentions.exclude_slugs'),
+ engine.getConfig('mentions.exclude_slugs'), engine.getConfig('mentions.alias_deny'),
+ engine.getConfig('mentions.multiword_aliases'), engine.getConfig('mentions.sibling_merge'),
]);
const typeAdds: string[] = [];
const typeRemoves: string[] = [];
@@ -69,7 +78,7 @@ export async function readMentionPolicy(engine: Pick<BrainEngine, 'getConfig'>):
}
const disabledBy = isOff(global) ? 'auto_link' : isOff(own) ? 'mentions.auto_link' : null;
return { enabled: disabledBy === null, disabledBy, typeAdds: typeAdds.filter(Boolean), typeRemoves: typeRemoves.filter(Boolean), ignore: parseNameList(ignore),
- excludeSlugs: parseNameList(excludeSlugs) };
+ excludeSlugs: parseNameList(excludeSlugs), aliasDeny: parseNameList(aliasDeny), multiwordAliases: !isOff(multiword), siblingMerge: !isOff(siblings) };
}
/** Linkable entity types for one pack (null = no pack resolved), sorted. */
diff --git a/src/core/mentions/siblings.ts b/src/core/mentions/siblings.ts
new file mode 100644
index 0000000000..52cc39de82
--- /dev/null
+++ b/src/core/mentions/siblings.ts
@@ -0,0 +1,92 @@
+/**
+ * Identity siblings: pages in one source whose titles name the same subject
+ * under different prefixes ("Account sheet: Widget Co" and "CRM record:
+ * Widget Co"). gbrain never treats them as one identity on the title alone
+ * (no `entity_identities` row, no union of aliases or references). It shows
+ * them side by side instead: the entity card lists them with their own aliases
+ * and identity lines, search's alias fan-out also searches their names (each
+ * spliced row names the alias and page that found it), and the gazetteer links
+ * a name both pages claim to every candidate instead of dropping it.
+ *
+ * One rule decides a group, shared by the card, the fan-out and the
+ * gazetteer: same source, the same normalized title subject, pairwise
+ * different title prefixes, every page a linkable entity of one canonical
+ * type that is not `person`, none in `mentions.exclude_slugs`, none with
+ * frontmatter `identity: separate`, and at most SIBLING_GROUP_CAP pages (a
+ * larger group is `capped` and groups nothing). `mentions.sibling_merge=false`
+ * turns the rule off. Untrusted callers never see a private page as a sibling.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { normalizeAlias } from '../search/alias-normalize.ts';
+import { canonicalTypeOf, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './policy.ts';
+import { titleName } from './aliases.ts';
+
+export const SIBLING_GROUP_CAP = 3;
+
+export interface SiblingCandidate { slug: string; title: string | null; type: string | null; identity?: unknown }
+
+export type SiblingVerdict = 'group' | 'disabled' | 'capped' | 'person' | 'type_mismatch' | 'separate' | 'excluded' | 'same_prefix' | 'subject_mismatch';
+
+/** The prefix of a title before its last `: ` (empty for an unprefixed title), normalized. */
+function titlePrefix(title: string | null): string {
+ const t = (title ?? '').trim();
+ const at = t.lastIndexOf(': ');
+ return at < 0 ? '' : normalizeAlias(t.slice(0, at));
+}
+
+/** Whether `pages` (two or more) form one identity-sibling group under the rule above. */
+export function siblingVerdict(pages: SiblingCandidate[], pack: PackTypes | null, policy: Pick<MentionPolicy, 'siblingMerge' | 'excludeSlugs'>): SiblingVerdict {
+ if (!policy.siblingMerge) return 'disabled';
+ if (pages.length > SIBLING_GROUP_CAP) return 'capped';
+ const types = new Set(pages.map(p => canonicalTypeOf(p.type, pack)));
+ if (types.has('person')) return 'person';
+ if (types.size > 1) return 'type_mismatch';
+ if (pages.some(p => String(p.identity ?? '').trim().toLowerCase() === 'separate')) return 'separate';
+ if (pages.some(p => policy.excludeSlugs.includes(p.slug))) return 'excluded';
+ if (new Set(pages.map(p => normalizeAlias(titleName(p.title ?? '')))).size > 1) return 'subject_mismatch';
+ if (new Set(pages.map(p => titlePrefix(p.title))).size < pages.length) return 'same_prefix';
+ return 'group';
+}
+
+export interface IdentitySiblings {
+ /** The other pages of the group (the asked page excluded), by slug. */
+ pages: Array<{ slug: string; title: string; type: string | null }>;
+ /** True when more than SIBLING_GROUP_CAP pages share the subject, so none are shown. */
+ capped: boolean;
+ /** Why no group formed, for `extract mentions --explain`; absent when `pages` is non-empty. */
+ verdict?: SiblingVerdict;
+}
+
+/**
+ * The identity siblings of one page. Fail-soft: a read error returns no
+ * siblings. `excludePrivate` applies the private-page predicate to every
+ * candidate (untrusted callers).
+ */
+export async function readIdentitySiblings(engine: BrainEngine, sourceId: string, page: { slug: string; title: string | null },
+ opts: { excludePrivate: boolean; policy?: MentionPolicy; pack?: PackTypes | null }): Promise<IdentitySiblings> {
+ const subject = normalizeAlias(titleName(page.title ?? ''));
+ if (!subject) return { pages: [], capped: false, verdict: 'subject_mismatch' };
+ try {
+ const policy = opts.policy ?? await readMentionPolicy(engine);
+ if (!policy.siblingMerge) return { pages: [], capped: false, verdict: 'disabled' };
+ const pack = opts.pack !== undefined ? opts.pack : await loadSourcePack(engine, sourceId);
+ const types = linkableTypesFor(pack, policy);
+ const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '';
+ const like = `%: ${subject.replace(/[\\%_]/g, m => `\\${m}`)}`;
+ const rows = await engine.executeRaw<{ slug: string; title: string | null; type: string | null; identity: unknown }>(
+ `SELECT slug, title, type, frontmatter->>'identity' AS identity FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
+ AND (lower(title) = $3 OR lower(title) LIKE $4)${privacy}
+ ORDER BY slug LIMIT ${SIBLING_GROUP_CAP + 2}`,
+ [sourceId, types, subject, like]);
+ const members = rows.filter(r => normalizeAlias(titleName(r.title ?? '')) === subject);
+ if (!members.some(r => r.slug === page.slug) || members.length < 2) return { pages: [], capped: false };
+ const verdict = siblingVerdict(members, pack, policy);
+ if (verdict !== 'group') return { pages: [], capped: verdict === 'capped', verdict };
+ return { pages: members.filter(r => r.slug !== page.slug).map(r => ({ slug: r.slug, title: r.title ?? r.slug, type: r.type })), capped: false };
+ } catch {
+ return { pages: [], capped: false };
+ }
+}
diff --git a/src/core/mentions/stale.ts b/src/core/mentions/stale.ts
index 268c1704f5..c152beee9f 100644
--- a/src/core/mentions/stale.ts
+++ b/src/core/mentions/stale.ts
@@ -5,8 +5,8 @@
*/
import type { BrainEngine } from '../engine.ts';
-import { countMentionDuePages, type MentionPassResult } from './pass.ts';
-import { readMentionPolicy } from './policy.ts';
+import { countIndexDuePages, countMentionDuePages, type MentionPassResult } from './pass.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from './policy.ts';
export interface MentionPreview {
due: number;
@@ -14,13 +14,22 @@ export interface MentionPreview {
enabled: boolean;
}
-/** Mention-due pages and the newest pass time, for `extract --stale --dry-run` and post-upgrade. */
+/**
+ * Index-due pages (mention-due pages plus linkable entity pages with stale
+ * derived aliases) and the newest pass time, for `extract --stale --dry-run`,
+ * doctor and post-upgrade.
+ */
export async function previewMentionPass(engine: BrainEngine, sourceId?: string): Promise<MentionPreview> {
const policy = await readMentionPolicy(engine);
const [row] = await engine.executeRaw<{ last: string | null }>(
`SELECT to_char(max(last_pass_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS last FROM mention_index_status
WHERE ($1::text IS NULL OR source_id = $1)`, [sourceId ?? null]);
- return { due: policy.enabled ? await countMentionDuePages(engine, sourceId) : 0, last_pass_at: row?.last ?? null, enabled: policy.enabled };
+ let due = 0;
+ if (policy.enabled) {
+ const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id);
+ for (const id of sources) due += await countIndexDuePages(engine, id, linkableTypesFor(await loadSourcePack(engine, id), policy));
+ }
+ return { due, last_pass_at: row?.last ?? null, enabled: policy.enabled };
}
/**
diff --git a/src/core/mentions/upgrade-notice.ts b/src/core/mentions/upgrade-notice.ts
index 7f81874242..332fa1431b 100644
--- a/src/core/mentions/upgrade-notice.ts
+++ b/src/core/mentions/upgrade-notice.ts
@@ -1,7 +1,9 @@
/**
- * `gbrain post-upgrade`: while mention-due pages exist, an `[AGENT]` block
- * names the catch-up sweep and how long it takes, so an upgraded brain gets
- * its entity mention index without waiting for autopilot cycles.
+ * `gbrain post-upgrade`: while index-due pages exist (including every page
+ * behind the binary's mention or alias version on an otherwise unchanged
+ * brain), an `[AGENT]` block names the catch-up sweep and how long it takes,
+ * so an upgraded brain gets its entity mention index without waiting for
+ * autopilot cycles (each cycle's extract phase also continues the sweep).
*/
import type { BrainEngine } from '../engine.ts';
@@ -25,7 +27,7 @@ export async function mentionIndexUpgradeNotice(engine: BrainEngine): Promise<st
return [
'',
agentBlock({
- why: `${preview.due} page(s) have not been scanned for entity names. Until they are, entity cards list only explicit links ` +
+ why: `${preview.due} page(s) have not been scanned for entity names by this version. Until they are, entity cards list only explicit links ` +
'(coverage: pending) and documents that name an account, person or company by name or code are not linked to it.',
consent: 'none (free: no model calls, no egress)',
actor: 'agent',
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index 6e9ecb5f9b..5cf57bea46 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -23,7 +23,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;
/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */
/** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */
export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);
-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete']);
+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout']);
export interface NoticeAudience {
transport: Transport;
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index bf010a07ab..6685b80b4e 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -41,6 +41,8 @@ import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts'
import { pageReadFilter } from '../search/read-policy-sql.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
import { declaredNames, titleName } from '../mentions/aliases.ts';
+import { withAliasFanOut, type FanoutMeta } from '../search/alias-fanout.ts';
+import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';
import { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';
import { opError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
@@ -302,28 +304,22 @@ export class DeclarationMemo {
}
/**
- * When the evidence declares another name for the entity the query names,
- * also search under that name and splice the new pages in after the top two
- * results, so documents that use only the other name are not left for the
- * agent to discover (most agents did not act on the notice alone). Nothing is
- * dropped: cutting the tail to make room lost the page that answered
- * (gbrain-evals Cat 40, family B).
+ * Notices for an alias fan-out: the model-visible line when it stopped at its
+ * cap (the skipped names can be searched directly), and the `mention_index`
+ * notice when the resolved entity's source is not fully indexed yet (its
+ * aliases may be incomplete until the catch-up sweep finishes).
*/
-async function withDeclaredNameFanOut(results: SearchResult[], queryText: string, memo: DeclarationMemo,
- run: (query: string, limit: number) => Promise<SearchResult[]>): Promise<SearchResult[]> {
- const [first] = memo.scan(results, queryText);
- if (!first) return results;
- const nameAt = indexOfName(queryText, first.name, false);
- const [from, to, at] = nameAt >= 0
- ? [first.name, first.alias, nameAt]
- : [first.alias, first.name, indexOfName(queryText, first.alias, true)];
- const alt = queryText.slice(0, at) + to + queryText.slice(at + from.length);
- let extra: SearchResult[];
- try { extra = await run(alt, 5); } catch { return results; }
- const seen = new Set(results.map(r => `${r.source_id ?? ''}\u0000${r.slug}`));
- const fresh = extra.filter(r => !seen.has(`${r.source_id ?? ''}\u0000${r.slug}`));
- if (fresh.length === 0) return results;
- return [...results.slice(0, 2), ...fresh, ...results.slice(2)];
+async function emitFanoutNotices(ctx: OperationContext, fanout: FanoutMeta | undefined, scope: SourceScope): Promise<void> {
+ if (!fanout) return;
+ if (fanout.truncated) {
+ const notice: Notice = { code: 'alias_fanout', kind: 'info',
+ why: `Also searched ${fanout.aliases_searched.map(a => `"${a.alias}"`).join(', ')}; not searched (cap reached): ${fanout.aliases_skipped.map(a => `"${a}"`).join(', ')}. Search those names directly before a history or as-of answer.` };
+ ctx.emitNotice?.(notice);
+ }
+ if (!fanout.resolved_entity) return;
+ const coverage = await readMentionCoverage(ctx.engine, scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default']).catch(() => null);
+ const notice = coverage ? mentionCoverageNotice(coverage) : null;
+ if (notice) ctx.emitNotice?.(notice);
}
export interface SavedFactMatch { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string }
@@ -729,15 +725,19 @@ const search: Operation = {
...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,
});
const declarations = new DeclarationMemo();
- const results = (await withDeclaredNameFanOut(primary, queryText, declarations,
- (alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 }))).map(r => ({ ...r }));
+ const fanned = offset === 0
+ ? await withAliasFanOut(ctx.engine, primary, queryText, { ...scope, excludePrivate },
+ { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...scope }, () => declarations.scan(primary, queryText))
+ : { results: primary };
+ const results = fanned.results.map(r => ({ ...r }));
+ await emitFanoutNotices(ctx, fanned.fanout, scope);
stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
- async rows => withExplainTarget(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' }), finishExplainTarget(ctx, p, explainPrep, results, 'search')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')));
},
scope: 'read', mutating: false,
cliHints: { name: 'search', positional: ['query'] },
@@ -972,10 +972,11 @@ const query: Operation = {
explain: p.explain === true, explainTarget: explainPrep?.trace,
});
const declarations = new DeclarationMemo();
- results = await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
- limit: altLimit, excludePrivate, requireSafeChunks: ctx.remote !== false, takesHoldersAllowList: readHolders(ctx),
- expansion: false, types, ...querySourceScope,
- }));
+ const primaryRows = results;
+ const fanned = await withAliasFanOut(ctx.engine, primaryRows, queryText, { ...querySourceScope, excludePrivate },
+ { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...querySourceScope }, () => declarations.scan(primaryRows, queryText));
+ results = fanned.results;
+ await emitFanoutNotices(ctx, fanned.fanout, querySourceScope);
// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;
// reads the stamped honesty signals: evidence, exact_lookup, rerank
// score), attach grade + query shape to the retrieval meta on EVERY call,
@@ -1135,7 +1136,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 9a4156b3bd..ef25f5f7c0 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1461,6 +1461,7 @@ export class PGLiteEngine implements BrainEngine {
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
+ const rankParam = opts?.rankQuery ? `$${params.push(opts.rankQuery)}` : '$1';
const keywordSql =
`WITH ranked AS (
@@ -1472,7 +1473,7 @@ export class PGLiteEngine implements BrainEngine {
CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,
+ ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', ${rankParam})) * ${sourceFactorCase} AS score,
CASE WHEN p.updated_at < (
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
) THEN true ELSE false END AS stale
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 9bbfc2836f..ef45bb6545 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1026,6 +1026,7 @@ export class PostgresEngine implements BrainEngine {
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
+ const rankParam = opts?.rankQuery ? `$${params.push(opts.rankQuery)}` : '$1';
const rawQuery = `
WITH ranked_chunks AS (
@@ -1037,7 +1038,7 @@ export class PostgresEngine implements BrainEngine {
CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score
+ ts_rank(cc.search_vector, websearch_to_tsquery('${ftsLang}', ${rankParam})) * ${sourceFactorCase} AS score
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
diff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.ts
new file mode 100644
index 0000000000..3bc4f1834e
--- /dev/null
+++ b/src/core/search/alias-fanout.ts
@@ -0,0 +1,214 @@
+/**
+ * Alias fan-out for `search` and `query`: when the query names an entity,
+ * also search under every other name it goes by, so records filed under a
+ * nickname or a code are not left for the agent to discover.
+ *
+ * Resolution: the query's word n-grams (up to 4 tokens, longest first; a
+ * shorter n-gram inside a resolved longer one is dropped) go through
+ * `resolveAliases` and an exact-title lookup over linkable entity pages. Only
+ * capitalized or code-shaped n-grams count, or a multi-word n-gram that
+ * resolves to exactly one page, so a lowercase common word never fans out. A
+ * case-sensitive alias matches only as written. Several pages for one n-gram
+ * resolve only when they are identity siblings (mentions/siblings.ts);
+ * otherwise the n-gram is skipped. With no entity resolved, the names the top
+ * rows declare (`fallback`) are used, as before.
+ *
+ * Fan-out: the names of the resolved page and its identity siblings
+ * (frontmatter, declared and subject aliases, codes included) that the query
+ * does not already use, ordered by origin (frontmatter, declared, subject)
+ * and then longest first, capped at `search.alias_fanout_max` (default 4; 0
+ * turns fan-out off). Each runs as a keyword-only query that requires the
+ * name as a phrase and ranks by the query's other content terms (no embedding
+ * or rerank call), 5 rows each; at most 8 new pages are spliced after the top
+ * two results, each carrying `matched_alias`. Fan-out never changes offsets
+ * or counts. The `fanout` meta says what was searched and skipped.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { SearchOpts, SearchResult } from '../types.ts';
+import { normalizeAlias } from './alias-normalize.ts';
+import { ALIAS_ORIGIN_RANK, titleName, type AliasOrigin } from '../mentions/aliases.ts';
+import { readIdentitySiblings } from '../mentions/siblings.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../mentions/policy.ts';
+
+export const DEFAULT_ALIAS_FANOUT_MAX = 4;
+export const FANOUT_ROWS_PER_ALIAS = 5;
+export const FANOUT_SPLICE_CAP = 8;
+const MAX_NGRAM = 4;
+const STOPWORDS = new Set(['the', 'and', 'for', 'who', 'what', 'when', 'where', 'which', 'with', 'from', 'that', 'this', 'are', 'was', 'were',
+ 'our', 'your', 'their', 'does', 'did', 'has', 'have', 'how', 'any', 'all', 'about', 'into', 'its', 'is', 'of', 'to', 'in', 'on', 'a', 'an', 'at', 'by']);
+
+export interface FanoutMeta {
+ resolved_entity: string | null;
+ aliases_searched: Array<{ alias: string; page: string; hits: number; truncated: boolean }>;
+ aliases_skipped: string[];
+ truncated: boolean;
+}
+
+interface Token { text: string; start: number; end: number }
+
+function queryTokens(query: string): Token[] {
+ const out: Token[] = [];
+ for (const m of query.matchAll(/[\p{L}\p{N}][\p{L}\p{N}&'’.-]*/gu)) {
+ const text = m[0].replace(/['’]s$/, '').replace(/[.'’-]+$/, '');
+ if (text) out.push({ text, start: m.index!, end: m.index! + text.length });
+ }
+ return out;
+}
+
+const shaped = (t: string) => /^[A-Z0-9]/.test(t);
+
+/** A name as a websearch phrase: quotes and websearch operators removed, so codes and punctuation stay literal. */
+export function aliasPhrase(alias: string): string {
+ const clean = alias.replace(/["\\]/g, ' ').replace(/\s+/g, ' ').trim();
+ return clean ? `"${clean}"` : '';
+}
+
+/** The ranking query: the phrase OR each other content term. */
+export function aliasRankQuery(phrase: string, terms: string[]): string {
+ return [phrase, ...terms.map(t => t.replace(/["\\-]/g, ''))].filter(Boolean).join(' OR ');
+}
+
+/** Keyword rows that contain `alias` (required phrase), ranked by `terms`. */
+export async function searchAliasRequired(engine: BrainEngine, alias: string, terms: string[], opts: SearchOpts): Promise<SearchResult[]> {
+ const phrase = aliasPhrase(alias);
+ if (!phrase) return [];
+ return engine.searchKeyword(phrase, { ...opts, orFallback: false, offset: 0, rankQuery: aliasRankQuery(phrase, terms) });
+}
+
+interface Scope { sourceId?: string; sourceIds?: string[]; excludePrivate: boolean }
+
+/** The entity the query names: its pages (one, or an identity-sibling group) and the n-gram that named it. */
+export async function resolveQueryEntity(engine: BrainEngine, query: string, scope: Scope):
+ Promise<{ pages: Array<{ slug: string; source_id: string }>; tokens: [number, number] } | null> {
+ const tokens = queryTokens(query);
+ if (!tokens.length) return null;
+ const grams: Array<{ text: string; norm: string; from: number; to: number }> = [];
+ for (let n = Math.min(MAX_NGRAM, tokens.length); n >= 1; n--) {
+ for (let i = 0; i + n <= tokens.length; i++) {
+ const text = query.slice(tokens[i]!.start, tokens[i + n - 1]!.end);
+ grams.push({ text, norm: normalizeAlias(text), from: i, to: i + n - 1 });
+ }
+ }
+ const norms = [...new Set(grams.map(g => g.norm))];
+ const aliasHits = await engine.resolveAliases(norms, scope).catch(() => new Map<string, Array<{ slug: string; source_id: string }>>());
+ const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];
+ const policy = await readMentionPolicy(engine);
+ const types = [...new Set((await Promise.all(sources.map(async s => linkableTypesFor(await loadSourcePack(engine, s), policy)))).flat())];
+ const { privatePagesFilterFragment } = await import('./private-visibility.ts');
+ const titleRows = await engine.executeRaw<{ slug: string; source_id: string; t: string }>(
+ `SELECT slug, source_id, lower(title) AS t FROM pages
+ WHERE lower(title) = ANY($1::text[]) AND source_id = ANY($2::text[]) AND type = ANY($3::text[]) AND deleted_at IS NULL
+ ${scope.excludePrivate ? `AND ${privatePagesFilterFragment('pages')}` : ''}`, [norms, sources, types]).catch(() => []);
+ const caseRows = await engine.executeRaw<{ slug: string; alias_norm: string; alias_text: string | null }>(
+ `SELECT slug, alias_norm, alias_text FROM page_aliases WHERE alias_norm = ANY($1::text[]) AND case_sensitive AND source_id = ANY($2::text[])`,
+ [norms, sources]).catch(() => []);
+ const covered = new Set<number>();
+ for (const g of grams) {
+ if ([...Array(g.to - g.from + 1).keys()].some(k => covered.has(g.from + k))) continue;
+ const titled = titleRows.filter(r => r.t === g.norm).map(r => ({ slug: r.slug, source_id: r.source_id }));
+ const aliased = (aliasHits.get(g.norm) ?? []).filter(h => !caseRows.some(c => c.slug === h.slug && c.alias_norm === g.norm && c.alias_text !== g.text));
+ const hits = titled.length ? titled : aliased;
+ if (!hits.length) continue;
+ const gramTokens = tokens.slice(g.from, g.to + 1).map(t => t.text);
+ if (!(shaped(gramTokens[0]!) && shaped(gramTokens[gramTokens.length - 1]!)) && !(gramTokens.length > 1 && hits.length === 1)) continue;
+ covered.add(g.from);
+ for (let k = g.from; k <= g.to; k++) covered.add(k);
+ if (hits.length === 1) return { pages: hits, tokens: [g.from, g.to] };
+ const [first] = hits;
+ const sib = await readIdentitySiblings(engine, first!.source_id, { slug: first!.slug, title: await titleOf(engine, first!) }, { excludePrivate: scope.excludePrivate });
+ const group = new Set([first!.slug, ...sib.pages.map(p => p.slug)]);
+ if (hits.every(h => h.source_id === first!.source_id && group.has(h.slug))) return { pages: hits, tokens: [g.from, g.to] };
+ }
+ return null;
+}
+
+async function titleOf(engine: BrainEngine, ref: { slug: string; source_id: string }): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ title: string | null }>('SELECT title FROM pages WHERE source_id = $1 AND slug = $2', [ref.source_id, ref.slug]).catch(() => []);
+ return row?.title ?? null;
+}
+
+/** The names to fan out over: every alias of `pages` and their identity siblings, ordered by origin then length. */
+async function namesOf(engine: BrainEngine, pages: Array<{ slug: string; source_id: string }>, scope: Scope): Promise<Array<{ alias: string; page: string; origin: string }>> {
+ const all = new Map<string, { slug: string; source_id: string; title: string | null }>();
+ for (const p of pages) {
+ const title = await titleOf(engine, p);
+ all.set(`${p.source_id}\0${p.slug}`, { ...p, title });
+ const sib = await readIdentitySiblings(engine, p.source_id, { slug: p.slug, title }, { excludePrivate: scope.excludePrivate });
+ for (const s of sib.pages) all.set(`${p.source_id}\0${s.slug}`, { slug: s.slug, source_id: p.source_id, title: s.title });
+ }
+ const refs = [...all.values()];
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; alias_norm: string; alias_text: string | null; origin: string | null }>(
+ `SELECT slug, source_id, alias_norm, alias_text, origin FROM page_aliases
+ WHERE source_id = ANY($1::text[]) AND slug = ANY($2::text[])`, [[...new Set(refs.map(r => r.source_id))], refs.map(r => r.slug)]).catch(() => []);
+ const names = new Map<string, { alias: string; page: string; origin: string; rank: number }>();
+ const add = (alias: string, page: string, origin: string) => {
+ const norm = normalizeAlias(alias);
+ const rank = ALIAS_ORIGIN_RANK[origin as AliasOrigin] ?? 3;
+ const prev = names.get(norm);
+ if (norm && (!prev || rank < prev.rank)) names.set(norm, { alias, page, origin, rank });
+ };
+ for (const r of rows) add(r.alias_text ?? r.alias_norm, r.slug, r.origin ?? 'frontmatter');
+ for (const r of refs) if (r.title) add(titleName(r.title), r.slug, 'title');
+ return [...names.values()].sort((a, b) => a.rank - b.rank || b.alias.length - a.alias.length);
+}
+
+export async function aliasFanoutMax(engine: BrainEngine): Promise<number> {
+ const raw = await engine.getConfig('search.alias_fanout_max').catch(() => null);
+ const n = raw == null || raw === '' ? DEFAULT_ALIAS_FANOUT_MAX : Number(raw);
+ return Number.isInteger(n) && n >= 0 ? Math.min(n, 16) : DEFAULT_ALIAS_FANOUT_MAX;
+}
+
+/**
+ * Splice rows found under the entity's other names into `results`. `fallback`
+ * supplies (name, alias) pairs the top rows declare, used when no entity
+ * resolves. Fail-soft: any error returns `results` unchanged.
+ */
+export async function withAliasFanOut(engine: BrainEngine, results: SearchResult[], queryText: string, scope: Scope, searchOpts: SearchOpts,
+ fallback: () => Array<{ name: string; alias: string; slug: string }>): Promise<{ results: SearchResult[]; fanout?: FanoutMeta }> {
+ try {
+ const max = await aliasFanoutMax(engine);
+ if (max === 0) return { results };
+ const queryLc = ` ${queryText.toLowerCase()} `;
+ const inQuery = (name: string) => new RegExp(`(?<![\\p{L}\\p{N}])${normalizeAlias(name).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}])`, 'u').test(normalizeAlias(queryLc));
+ const resolved = await resolveQueryEntity(engine, queryText, scope);
+ let names: Array<{ alias: string; page: string }>;
+ let usedTokens: [number, number] | null = null;
+ if (resolved) {
+ names = (await namesOf(engine, resolved.pages, scope)).filter(n => !inQuery(n.alias));
+ usedTokens = resolved.tokens;
+ } else {
+ names = fallback().map(d => inQuery(d.name) ? { alias: d.alias, page: d.slug } : { alias: d.name, page: d.slug }).filter(n => !inQuery(n.alias));
+ }
+ const seenNames = new Set<string>();
+ names = names.filter(n => { const k = normalizeAlias(n.alias); if (seenNames.has(k)) return false; seenNames.add(k); return true; });
+ if (!names.length) return { results };
+ const tokens = queryTokens(queryText);
+ const terms = tokens.filter((_, i) => !usedTokens || i < usedTokens[0] || i > usedTokens[1]).map(t => t.text)
+ .filter(t => !STOPWORDS.has(t.toLowerCase()) && t.length >= 2 && !names.some(n => normalizeAlias(n.alias).split(' ').includes(t.toLowerCase())));
+ const searched = names.slice(0, max);
+ const skipped = names.slice(max).map(n => n.alias);
+ const found = await Promise.all(searched.map(n => searchAliasRequired(engine, n.alias, terms, { ...searchOpts, limit: FANOUT_ROWS_PER_ALIAS })
+ .catch(() => [] as SearchResult[])));
+ const seen = new Set(results.map(r => `${r.source_id ?? ''}\0${r.slug}`));
+ const fresh: SearchResult[] = [];
+ searched.forEach((n, i) => {
+ for (const r of found[i]!) {
+ const key = `${r.source_id ?? ''}\0${r.slug}`;
+ if (seen.has(key) || fresh.length >= FANOUT_SPLICE_CAP) continue;
+ seen.add(key);
+ fresh.push({ ...r, matched_alias: n.alias });
+ }
+ });
+ const fanout: FanoutMeta = {
+ resolved_entity: resolved ? resolved.pages[0]!.slug : null,
+ aliases_searched: searched.map((n, i) => ({ alias: n.alias, page: n.page, hits: found[i]!.length, truncated: found[i]!.length >= FANOUT_ROWS_PER_ALIAS })),
+ aliases_skipped: skipped,
+ truncated: skipped.length > 0,
+ };
+ if (!fresh.length) return { results, fanout };
+ return { results: [...results.slice(0, 2), ...fresh, ...results.slice(2)], fanout };
+ } catch {
+ return { results };
+ }
+}
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
index 920b2333e2..33e7cd51c4 100644
--- a/src/core/search/lean-rows.ts
+++ b/src/core/search/lean-rows.ts
@@ -12,7 +12,8 @@
* - the duplicate-page guard: evidence and create_safety;
* - safety and provenance markers whenever present: injection_suspected,
* injection_p, unverified, content_flag, status, superseded, superseded_by,
- * message_id, thread_id, source_subject; modality when not text; stale
+ * message_id, thread_id, source_subject, matched_alias (the other name the
+ * alias fan-out searched); modality when not text; stale
* only when set (true, or the held-file object from #5988);
* - `delivered: { truncated: true }` whenever evidence delivery truncated.
* `fields: "full"`, the `mcp.result_rows: full` host config and gbrain's own
@@ -27,7 +28,7 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set([
'id', 'slug', 'title', 'type', 'chunk_text', 'score', 'effective_date', 'source_id', 'chunk_id',
'evidence', 'create_safety',
'injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',
- 'message_id', 'thread_id', 'source_subject', 'relational',
+ 'message_id', 'thread_id', 'source_subject', 'relational', 'matched_alias',
// Present only when the caller asked for `explain: true`.
'score_details',
]);
diff --git a/src/core/types.ts b/src/core/types.ts
index 8825448b89..df9954a920 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -844,6 +844,8 @@ export interface SearchResult {
* strict-match rows.
*/
keyword_relaxed?: boolean;
+ /** Set on rows search's alias fan-out spliced in: the entity's other name that found this page (search/alias-fanout.ts). */
+ matched_alias?: string;
/**
* Extraction quarantine lane (issue #160): true when the result's page is
* an unverified auto-extracted entity stub (frontmatter
@@ -1278,6 +1280,8 @@ export interface SearchOpts extends PageReadPolicy {
* ignores this flag.
*/
orFallback?: boolean;
+ /** Keyword `score` query (websearch syntax) while `query` decides the matches (alias fan-out); ignored on the CJK path. */
+ rankQuery?: string;
/**
* v0.27.1 / v0.36 (D11): target column for vector search. Two shapes:
*
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 5eb48e95f7..f3c9dc73f0 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -224,6 +224,10 @@ const entity: Operation = {
const notice = mentionCoverageNotice(coverage, result.card?.entity.type);
if (notice) ctx.emitNotice?.(notice);
}
+ if (result.card?.identity_siblings?.capped) {
+ const { siblingsCappedNotice } = await import('./verbs/entity-card-identity.ts');
+ ctx.emitNotice?.(siblingsCappedNotice(result.card.entity.slug));
+ }
return {
protocol_version: MEMORY_VERBS_VERSION,
found: result.found,
diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.ts
new file mode 100644
index 0000000000..9c1d309df8
--- /dev/null
+++ b/src/core/verbs/entity-card-identity.ts
@@ -0,0 +1,154 @@
+/**
+ * The `entity` card's identity fields: where each `aka` entry came from
+ * (`aka_sources`), the identity siblings (mentions/siblings.ts) with their own
+ * aliases, an `identity_excerpt` of verbatim lines that may carry other names
+ * the alias grammar does not parse, and guidance on what `aka` covers.
+ *
+ * The excerpt is phrasing-independent: a line qualifies without naming the
+ * subject when it matches the alias grammar, has a label and value shape
+ * (`Label: value`, a table row), or holds a capitalized multi-word run or an
+ * all-caps code token other than the subject's own name. Tiers, each in page
+ * order: grammar matches; label and value lines whose value is name-like;
+ * other label and value lines; the rest. Lines are cut from the remote-
+ * sanitized body (private takes and facts fences, forgotten facts and
+ * malformed fences removed) for every caller, at most EXCERPT_PAGE_CHARS per
+ * page and EXCERPT_CARD_CHARS per card; a page that did not fit is listed in
+ * `identity_excerpt_omitted`. The excerpt adds nothing to the mention index.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { sanitizeRemoteBody } from '../remote-body.ts';
+import { ALIAS_ORIGIN_RANK, declarationsIn, titleName, type AliasOrigin } from '../mentions/aliases.ts';
+import { readIdentitySiblings, SIBLING_GROUP_CAP } from '../mentions/siblings.ts';
+import type { Notice } from '../agent-output.ts';
+
+export const EXCERPT_PAGE_CHARS = 600;
+export const EXCERPT_CARD_CHARS = 1200;
+const EXCERPT_LINE_CHARS = 300;
+const NOT_NAMES = new Set(['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'ARR', 'MRR', 'TBD', 'N/A', 'NA', 'CEO', 'CFO', 'CTO', 'COO', 'VP', 'UTC', 'PST', 'PDT', 'EST', 'ID']);
+const NAME_RUN_RE = /\b[A-Z][\p{L}\p{N}&'’-]*(?:\s+[A-Z][\p{L}\p{N}&'’-]*)+/gu;
+const CODE_RE = /\b(?=[A-Z0-9-]*[A-Z])[A-Z0-9][A-Z0-9-]{2,}\b/g;
+
+export interface IdentityExcerptLine { slug: string; line: string }
+
+/** Whether `text` holds a name other than `subject`: a capitalized multi-word run or a code token. */
+export function hasOtherName(text: string, subject: string): boolean {
+ const own = subject.toLowerCase();
+ const stripped = own ? text.replace(new RegExp(own.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), ' ') : text;
+ for (const m of stripped.matchAll(NAME_RUN_RE)) if (m[0].toLowerCase() !== own) return true;
+ for (const m of stripped.matchAll(CODE_RE)) if (!NOT_NAMES.has(m[0]) && !/^\d[\d-]*$/.test(m[0])) return true;
+ return false;
+}
+
+/** The label/value split of a line (`Label: value`, `| label | value |`), or null. */
+function labelValue(line: string, next: string | undefined): { label: string; value: string } | null {
+ const t = line.trim();
+ if (t.startsWith('|')) {
+ if (/^\|?\s*:?-{2,}/.test(t) || (next && /^\s*\|?\s*:?-{2,}/.test(next))) return null;
+ const cells = t.replace(/^\||\|$/g, '').split('|').map(c => c.trim());
+ return cells.length >= 2 && cells[0] ? { label: cells[0], value: cells.slice(1).join(' | ') } : null;
+ }
+ const plain = t.replace(/^(?:[-*+>]|\d+[.)])\s+/, '').replace(/\*\*|__/g, '');
+ const colon = plain.indexOf(':');
+ if (colon <= 0 || colon > 60 || plain.slice(0, colon).split(/\s+/).length > 6) return null;
+ const value = plain.slice(colon + 1).trim();
+ return value ? { label: plain.slice(0, colon).trim(), value } : null;
+}
+
+/** One page's qualifying lines, tiered and capped at `budget` characters. */
+export function excerptLines(body: string, title: string, budget = EXCERPT_PAGE_CHARS): string[] {
+ const subject = titleName(title);
+ const lines = body.split('\n');
+ const declared = new Set(declarationsIn(body, { ownNames: [subject] }).map(d => d.line));
+ const tiers: Array<Array<{ i: number; text: string }>> = [[], [], [], []];
+ for (let i = 0; i < lines.length; i++) {
+ const text = lines[i]!.trim();
+ if (!text || /^#+\s/.test(text) || /^\|?\s*:?-{2,}/.test(text)) continue;
+ const lv = labelValue(text, lines[i + 1]);
+ const tier = declared.has(i) ? 0
+ : lv && hasOtherName(lv.value, subject) && !/^[\d\s$€£.,:%/-]+$/.test(lv.value) ? 1
+ : lv ? 2
+ : hasOtherName(text, subject) ? 3 : -1;
+ if (tier >= 0) tiers[tier]!.push({ i, text: text.length > EXCERPT_LINE_CHARS ? `${text.slice(0, EXCERPT_LINE_CHARS - 1)}…` : text });
+ }
+ const out: string[] = [];
+ let used = 0;
+ for (const tier of tiers) {
+ for (const { text } of tier) {
+ if (used + text.length > budget) return out;
+ out.push(text);
+ used += text.length;
+ }
+ }
+ return out;
+}
+
+export interface CardIdentity {
+ aka_sources: Array<{ origin: string; slug: string }>;
+ identity_siblings?: { pages: Array<{ slug: string; title: string; type: string | null; aka: string[] }>; capped: boolean };
+ identity_excerpt?: IdentityExcerptLine[];
+ identity_excerpt_omitted?: string[];
+ alias_guidance?: { text: string; requires_surface?: 'starter' };
+}
+
+const GUIDANCE = 'aka lists names gbrain recognized as declared on this page (aka_sources says where); it is not proof the list is complete. '
+ + 'search already queries these names and the identity siblings\' names (rows found that way carry matched_alias), which is not proof every record was retrieved. '
+ + 'Before a history or as-of answer, also search any other name shown in identity_excerpt or in a search response\'s fanout.aliases_skipped.';
+const GUIDANCE_VERBS = 'aka lists names gbrain recognized as declared on this page (aka_sources says where); it is not proof the list is complete. '
+ + 'Before a history or as-of answer, also look for records under every name shown in aka, identity_siblings and identity_excerpt; searching needs the search tool on the starter surface.';
+
+/** The card's identity fields for `row`. Fail-soft: a failed read leaves the field out. */
+export async function readCardIdentity(engine: BrainEngine, sourceId: string,
+ row: { slug: string; title: string | null; compiled_truth: string | null },
+ opts: { excludePrivate: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full'; aka: string[] }): Promise<CardIdentity> {
+ const siblings = await readIdentitySiblings(engine, sourceId, row, { excludePrivate: opts.excludePrivate });
+ const slugs = [row.slug, ...siblings.pages.map(p => p.slug)];
+ const aliasRows = await engine.executeRaw<{ slug: string; alias_norm: string; origin: string | null; alias_text: string | null }>(
+ `SELECT slug, alias_norm, origin, alias_text FROM page_aliases WHERE source_id = $1 AND slug = ANY($2::text[]) ORDER BY alias_norm`,
+ [sourceId, slugs]).catch(() => []);
+ const own = aliasRows.filter(a => a.slug === row.slug);
+ const bestOrigin = (norm: string) => own.filter(a => a.alias_norm === norm).map(a => a.origin ?? 'frontmatter')
+ .sort((x, y) => (ALIAS_ORIGIN_RANK[x as AliasOrigin] ?? 0) - (ALIAS_ORIGIN_RANK[y as AliasOrigin] ?? 0))[0] ?? 'frontmatter';
+ const aka_sources = opts.aka.map(norm => ({ origin: bestOrigin(norm), slug: row.slug }));
+ const out: CardIdentity = { aka_sources };
+ if (siblings.pages.length || siblings.capped) {
+ out.identity_siblings = {
+ pages: siblings.pages.map(p => ({ ...p, aka: [...new Set(aliasRows.filter(a => a.slug === p.slug).map(a => a.alias_text ?? a.alias_norm))] })),
+ capped: siblings.capped,
+ };
+ }
+ const bodies = new Map<string, { title: string; body: string }>([[row.slug, { title: row.title ?? row.slug, body: row.compiled_truth ?? '' }]]);
+ if (siblings.pages.length) {
+ const rows = await engine.executeRaw<{ slug: string; title: string | null; compiled_truth: string | null }>(
+ `SELECT slug, title, compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,
+ [sourceId, siblings.pages.map(p => p.slug)]).catch(() => []);
+ for (const r of rows) bodies.set(r.slug, { title: r.title ?? r.slug, body: r.compiled_truth ?? '' });
+ }
+ const excerpt: IdentityExcerptLine[] = [];
+ const omitted: string[] = [];
+ let used = 0;
+ for (const slug of slugs) {
+ const page = bodies.get(slug);
+ if (!page) continue;
+ const lines = excerptLines(sanitizeRemoteBody(page.body), page.title, Math.min(EXCERPT_PAGE_CHARS, EXCERPT_CARD_CHARS - used));
+ const full = excerptLines(sanitizeRemoteBody(page.body), page.title, EXCERPT_PAGE_CHARS);
+ if (lines.length < full.length) omitted.push(slug);
+ for (const line of lines) { excerpt.push({ slug, line }); used += line.length; }
+ }
+ if (excerpt.length) out.identity_excerpt = excerpt;
+ if (omitted.length) out.identity_excerpt_omitted = omitted;
+ if (opts.aka.length || siblings.pages.length || excerpt.length) {
+ out.alias_guidance = opts.surfaceCeiling === 'verbs' ? { text: GUIDANCE_VERBS, requires_surface: 'starter' } : { text: GUIDANCE };
+ }
+ return out;
+}
+
+/** The notice for a sibling group too large to show (more than SIBLING_GROUP_CAP pages share the subject). */
+export function siblingsCappedNotice(slug: string): Notice {
+ return {
+ code: 'identity_siblings_capped', kind: 'info',
+ why: `More than ${SIBLING_GROUP_CAP} pages share this entity's title subject, so none are shown as identity siblings.`,
+ fix: { argv: ['gbrain', 'extract', 'mentions', '--explain', slug], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Lists the pages that share the subject and the sibling decision; the user can mark unrelated pages `identity: separate`.' },
+ };
+}
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index c0e4af5d4e..6dfa87c169 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -31,6 +31,7 @@ import type { Link, SearchResult } from '../types.ts';
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 { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';
const EDGE_CAP = 10;
const OPEN_THREADS_CAP = 3;
@@ -97,6 +98,16 @@ export interface EntityCard {
referenced_by?: ReferenceGroupView[];
/** Whether every page in this source has been scanned for this entity's names. `entity` verb only. */
coverage?: MentionCoverage;
+ /** Parallel to `aka`: each entry's origin (frontmatter, declared, subject) and the page that declares it. `entity` verb only. */
+ aka_sources?: CardIdentity['aka_sources'];
+ /** Pages naming the same subject under another title prefix, with their own aliases; never merged into this card. `entity` verb only. */
+ identity_siblings?: CardIdentity['identity_siblings'];
+ /** Verbatim lines of this page and its siblings that may carry other names (label lines, codes, declarations), with the page slug. `entity` verb only. */
+ identity_excerpt?: CardIdentity['identity_excerpt'];
+ /** Pages whose qualifying lines did not fit the excerpt budget. */
+ identity_excerpt_omitted?: string[];
+ /** What `aka` covers and which names to search before a history or as-of answer. `entity` verb only. */
+ alias_guidance?: CardIdentity['alias_guidance'];
}
export interface ReferenceGroupView {
@@ -269,7 +280,10 @@ export async function buildEntityCard(
}));
const card = await assembleCard(engine, sourceId, best.row, opts.remote, excludePrivate);
- if (opts.includeReferences) Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes));
+ if (opts.includeReferences) {
+ Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes),
+ await readCardIdentity(engine, sourceId, best.row, { excludePrivate, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));
+ }
return {
found: true,
card,
diff --git a/test/e2e/mentions-parity.test.ts b/test/e2e/mentions-parity.test.ts
index 11bb97f9ca..6b3305bd2f 100644
--- a/test/e2e/mentions-parity.test.ts
+++ b/test/e2e/mentions-parity.test.ts
@@ -19,6 +19,9 @@ import { extractStaleFromDB } from '../../src/commands/extract.ts';
import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';
import { readReferrerPage } from '../../src/core/mentions/referrers.ts';
import { loadSourcePack } from '../../src/core/mentions/policy.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
+import { resolveQueryEntity, searchAliasRequired } from '../../src/core/search/alias-fanout.ts';
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
const SKIP_PG = !hasDatabase();
@@ -34,6 +37,12 @@ async function seed(engine: BrainEngine): Promise<void> {
for (let i = 0; i < 14; i++) await put(`tickets/t${String(i).padStart(2, '0')}`, 'ticket', `Ticket ${i}`, `Customer: QUCO\nStatus: ${i === 3 ? 'Open' : 'Closed'}`);
await put('meetings/m1', 'meeting', 'Meeting: QULA renewal prep', 'Quormiro asked about Dana Example.');
await put('notes/lower', 'note', 'Lowercase', 'quco is not a code here');
+ // Identity siblings: the account sheet declares a nickname; a note names only the shared subject.
+ await put('accounts/quormiro-capital', 'account', 'Account sheet: Quormiro Capital', 'Internal nickname: Copper Fox');
+ await put('notes/subject-only', 'note', 'Renewal call', 'Quormiro Capital called about the renewal.');
+ const doc = (slug: string, body: string) => importFromContent(engine, slug, serializeMarkdown({}, body, '', { type: 'note', title: slug, tags: [] }), { noEmbed: true, forceRechunk: true });
+ await doc('docs/cf1', 'Copper Fox renewal slipped; refund pending.');
+ await doc('docs/cf2', 'Copper Fox renewal closed on time.');
// Distinct referrer dates: both engines order the newest-first page identically,
// independent of how many writes share one clock tick.
await engine.executeRaw(
@@ -63,6 +72,10 @@ async function snapshot(engine: BrainEngine) {
coverage: card.coverage!.state },
page: { total: first.total, truncated: first.truncated, rows: first.rows.map(r => r.slug) },
columns: columns.map(r => r.column_name),
+ siblings: card.identity_siblings?.pages.map(p => `${p.slug}:${p.aka.join('|')}`),
+ excerpt: card.identity_excerpt?.map(l => `${l.slug}:${l.line}`),
+ fanout: (await searchAliasRequired(engine, 'Copper Fox', ['refund'], { sourceId: 'default', limit: 5 })).map(r => r.slug),
+ resolved: (await resolveQueryEntity(engine, 'Quormiro Capital renewal', { sourceId: 'default', excludePrivate: true }))?.pages.map(p => p.slug).sort(),
};
}
@@ -82,7 +95,12 @@ describe('entity mention index (PGLite half)', () => {
expect(pgliteSnap.mentions).toEqual({ state: 'complete', remaining: 0 });
expect(pgliteSnap.links).toContain('meetings/m1->crm/124');
expect(pgliteSnap.links).not.toContain('notes/lower->crm/123');
- expect(pgliteSnap.card).toEqual({ slug: 'crm/123', count: 14, groups: ['ticket:14:10'], coverage: 'complete' });
+ expect(pgliteSnap.card).toEqual({ slug: 'crm/123', count: 15, groups: ['note:1:1', 'ticket:14:10'], coverage: 'complete' });
+ expect(pgliteSnap.links).toEqual(expect.arrayContaining(['notes/subject-only->crm/123', 'notes/subject-only->accounts/quormiro-capital']));
+ expect(pgliteSnap.siblings).toEqual(['accounts/quormiro-capital:Copper Fox|Quormiro Capital']);
+ expect(pgliteSnap.excerpt).toContain('accounts/quormiro-capital:Internal nickname: Copper Fox');
+ expect(pgliteSnap.fanout).toEqual(['docs/cf1', 'docs/cf2']);
+ expect(pgliteSnap.resolved).toEqual(['accounts/quormiro-capital', 'crm/123']);
expect(pgliteSnap.page).toMatchObject({ total: 14, truncated: true });
expect(pgliteSnap.columns).toEqual(expect.arrayContaining(['origin', 'case_sensitive', 'alias_text']));
});
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index c21f49470b..9ae2ae5dae 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1345,6 +1345,7 @@
"offset?: number | undefined",
"onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined",
"orFallback?: boolean | undefined",
+ "rankQuery?: string | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
"relationalChainSlots?: number | undefined",
@@ -1408,6 +1409,7 @@
"injection_suspected?: true | undefined",
"keyword_hit?: boolean | undefined",
"keyword_relaxed?: boolean | undefined",
+ "matched_alias?: string | undefined",
"message_id?: string | undefined",
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
@@ -6996,6 +6998,7 @@
"onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined",
"orFallback?: boolean | undefined",
"queryEmbedFn?: ((text: string) => Float32Array | Promise<Float32Array>) | undefined",
+ "rankQuery?: string | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
"relationalChainSlots?: number | undefined",
@@ -8469,6 +8472,7 @@
"offset?: number | undefined",
"onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined",
"orFallback?: boolean | undefined",
+ "rankQuery?: string | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
"relationalChainSlots?: number | undefined",
@@ -8532,6 +8536,7 @@
"injection_suspected?: true | undefined",
"keyword_hit?: boolean | undefined",
"keyword_relaxed?: boolean | undefined",
+ "matched_alias?: string | undefined",
"message_id?: string | undefined",
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
diff --git a/test/fixtures/goldens/search-c5/notices.json b/test/fixtures/goldens/search-c5/notices.json
index b7a4c52336..fac4c93a18 100644
--- a/test/fixtures/goldens/search-c5/notices.json
+++ b/test/fixtures/goldens/search-c5/notices.json
@@ -2,13 +2,13 @@
"with": {
"search NULA billing contact": {
"content": [
- "[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.9836065573770493,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4838709677419355,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"matched_alias\":\"Numbat Labs\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"}]",
"Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in contracts/numbat-labs-msa).",
"Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]",
"[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
],
"retrieval": {
- "returned_count": 4,
+ "returned_count": 3,
"retrieved_count": 2,
"vector_enabled": false,
"expansion_applied": false,
@@ -46,12 +46,25 @@
"slug": "contracts/numbat-labs-msa"
}
],
+ "fanout": {
+ "resolved_entity": null,
+ "aliases_searched": [
+ {
+ "alias": "Numbat Labs",
+ "page": "crm/numbat-labs",
+ "hits": 1,
+ "truncated": false
+ }
+ ],
+ "aliases_skipped": [],
+ "truncated": false
+ },
"rows": "lean"
}
},
"search Numbat Labs payment terms": {
"content": [
- "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"matched_alias\":\"NULA\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
"Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs).",
"[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
],
@@ -84,6 +97,19 @@
"slug": "crm/numbat-labs"
}
],
+ "fanout": {
+ "resolved_entity": null,
+ "aliases_searched": [
+ {
+ "alias": "NULA",
+ "page": "crm/numbat-labs",
+ "hits": 3,
+ "truncated": false
+ }
+ ],
+ "aliases_skipped": [],
+ "truncated": false
+ },
"rows": "lean"
}
},
@@ -133,6 +159,19 @@
"slug": "crm/ocelot-freight"
}
],
+ "fanout": {
+ "resolved_entity": null,
+ "aliases_searched": [
+ {
+ "alias": "Ocelot Freight",
+ "page": "crm/ocelot-freight",
+ "hits": 1,
+ "truncated": false
+ }
+ ],
+ "aliases_skipped": [],
+ "truncated": false
+ },
"rows": "lean"
}
},
@@ -168,7 +207,7 @@
},
"query Numbat Labs payment terms": {
"content": [
- "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":0.14590249955654144,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"matched_alias\":\"NULA\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
"Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs).",
"[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
],
@@ -206,6 +245,19 @@
"reason": "keyword_exact_top",
"query_shape": "factual"
},
+ "fanout": {
+ "resolved_entity": null,
+ "aliases_searched": [
+ {
+ "alias": "NULA",
+ "page": "crm/numbat-labs",
+ "hits": 3,
+ "truncated": false
+ }
+ ],
+ "aliases_skipped": [],
+ "truncated": false
+ },
"rows": "lean"
}
},
@@ -249,6 +301,19 @@
"reason": "keyword_exact_top",
"query_shape": "factual"
},
+ "fanout": {
+ "resolved_entity": null,
+ "aliases_searched": [
+ {
+ "alias": "Ocelot Freight",
+ "page": "crm/ocelot-freight",
+ "hits": 1,
+ "truncated": false
+ }
+ ],
+ "aliases_skipped": [],
+ "truncated": false
+ },
"rows": "lean"
}
}
diff --git a/test/helpers/mention-brain.ts b/test/helpers/mention-brain.ts
index 517d501249..a11b04fc7f 100644
--- a/test/helpers/mention-brain.ts
+++ b/test/helpers/mention-brain.ts
@@ -26,7 +26,8 @@ export async function resetMentionBrain(engine: BrainEngine): Promise<void> {
await engine.executeRaw('DELETE FROM mention_gazetteer_entries');
await engine.executeRaw('DELETE FROM mention_index_status');
await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
- for (const key of ['auto_link', 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'link_resolution.cross_source', 'entity_identity.union']) {
+ for (const key of ['auto_link', 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'link_resolution.cross_source', 'entity_identity.union',
+ 'mentions.exclude_slugs', 'mentions.alias_deny', 'mentions.multiword_aliases', 'mentions.sibling_merge', 'search.alias_fanout_max', 'search.demote_generated']) {
await engine.unsetConfig(key);
}
}
diff --git a/test/mentions-coverage-version.test.ts b/test/mentions-coverage-version.test.ts
new file mode 100644
index 0000000000..b09af1fba9
--- /dev/null
+++ b/test/mentions-coverage-version.test.ts
@@ -0,0 +1,238 @@
+/**
+ * Entity mention index, version-aware coverage and invalidation
+ * (mentions/coverage.ts, mentions/pass.ts, mentions/upgrade-notice.ts) on
+ * PGLite.
+ *
+ * Protects: a binary whose MENTION_EXTRACTOR_VERSION or
+ * ALIAS_DERIVATION_VERSION is ahead of the stored page state reports every
+ * version-behind page as pending on an unchanged brain (whatever its
+ * updated_at), on the card, get_backlinks and post-upgrade, until the sweep
+ * finishes; the recount happens once and later coverage reads stay O(1);
+ * an interrupted (deadline) sweep leaves an exact remaining count and the
+ * next sweep finishes it; one cycle-budget sweep on a brain built at the
+ * previous versions derives the new grammar's aliases and links; alias
+ * staleness counts only linkable entity pages; changing
+ * mentions.alias_deny, mentions.multiword_aliases or mentions.sibling_merge
+ * marks pages due on an indexed brain; a denied alias comes back when the
+ * deny is removed. Regression: coverage that reads `complete` after an
+ * upgrade because no page was written since the last count.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import {
+ ALIAS_DERIVATION_VERSION, INDEX_VERSION_STAMP, MENTION_EXTRACTOR_VERSION, countMentionDuePages, runMentionPass,
+} from '../src/core/mentions/pass.ts';
+import { mentionCoverageNotice, readMentionCoverage } from '../src/core/mentions/coverage.ts';
+import { mentionIndexUpgradeNotice } from '../src/core/mentions/upgrade-notice.ts';
+import { deriveEntityAliases } from '../src/core/mentions/aliases.ts';
+import { CYCLE_STALE_DRAIN_BUDGET_MS } from '../src/core/cycle.ts';
+import { derivedAliases, mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+const config = { engine: 'pglite' } as never;
+const remote = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };
+
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function call(op: string, args: Record<string, unknown>) {
+ const r = await dispatchToolCall(engine, op, args, remote as never);
+ return { json: r.isError ? null : JSON.parse(r.content[0].text), notices: r.content.slice(1).map(c => c.text) };
+}
+
+const ACCOUNT_BODY = 'Account code: QUCO\nInternal nickname: Copper Fox\nOwner: Dana Example';
+const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', ACCOUNT_BODY);
+
+/**
+ * The page state and status row the previous binary left: page versions one
+ * behind, and a status row counted without this binary's version stamp
+ * (`aliasOnly`: only the alias version behind, stamped with it).
+ */
+async function asPreviousRelease(opts: { aliasOnly?: boolean } = {}) {
+ if (!opts.aliasOnly) await engine.executeRaw('UPDATE page_mention_state SET mention_version = $1', [MENTION_EXTRACTOR_VERSION - 1]);
+ await engine.executeRaw('UPDATE page_mention_state SET alias_version = $1 WHERE alias_version IS NOT NULL', [ALIAS_DERIVATION_VERSION - 1]);
+ await engine.executeRaw(
+ `UPDATE mention_index_status SET policy_fingerprint = split_part(policy_fingerprint, ';', 1) || $1`,
+ [opts.aliasOnly ? `;v${MENTION_EXTRACTOR_VERSION}.${ALIAS_DERIVATION_VERSION - 1}` : '']);
+}
+
+async function statusRow() {
+ const [row] = await engine.executeRaw<{ state: string; pending: number; policy_fingerprint: string | null }>(
+ "SELECT state, pending, policy_fingerprint FROM mention_index_status WHERE source_id = 'default'");
+ return row!;
+}
+
+/** Wraps `engine` so every SQL statement it runs is recorded. */
+function recording(target: BrainEngine, sqls: string[]): BrainEngine {
+ return new Proxy(target, {
+ get(t, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[]) => { sqls.push(sql); return t.executeRaw(sql, params as never); };
+ const value = Reflect.get(t, key, t);
+ return typeof value === 'function' ? value.bind(t) : value;
+ },
+ });
+}
+
+describe('coverage after a version bump on an unchanged brain', () => {
+ test('every version-behind page is pending at once; card, get_backlinks and post-upgrade carry it until the sweep finishes', async () => {
+ await account();
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ for (let i = 0; i < 4; i++) await page(engine, `tickets/t${i}`, 'ticket', `Ticket ${i}`, 'Customer: QUCO');
+ await sweep(engine);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ const linksBefore = await mentionLinks(engine);
+
+ await asPreviousRelease();
+ const [written] = await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM pages p, mention_index_status m WHERE m.source_id = 'default' AND p.updated_at >= m.counted_at");
+ expect(written!.n).toBe(0);
+
+ const coverage = await readMentionCoverage(engine, ['default']);
+ expect(coverage).toMatchObject({ state: 'pending', pending_pages: 6, degraded: true });
+ expect(mentionCoverageNotice(coverage)?.fix?.argv).toEqual(['gbrain', 'extract', '--stale', '--catch-up']);
+ // The recount is saved once on the status row with this binary's stamp.
+ expect(await statusRow()).toMatchObject({ state: 'pending', pending: 6 });
+ expect((await statusRow()).policy_fingerprint).toEndWith(`;${INDEX_VERSION_STAMP}`);
+ const sqls: string[] = [];
+ expect(await readMentionCoverage(recording(engine, sqls), ['default'])).toMatchObject({ state: 'pending', pending_pages: 6 });
+ expect(sqls.some(s => s.includes('alias_version'))).toBe(false);
+
+ const card = await call('entity', { name: 'QUCO' });
+ expect(card.json.card.coverage).toMatchObject({ state: 'pending', pending_pages: 6, degraded: true });
+ expect(card.notices.join('\n')).toContain('[gbrain notice mention_index');
+ const backlinks = await call('get_backlinks', { slug: 'crm/123', group: 'page' });
+ expect(backlinks.json.coverage).toMatchObject({ state: 'pending', pending_pages: 6 });
+ expect(backlinks.notices.join('\n')).toContain('[gbrain notice mention_index');
+ const notice = (await mentionIndexUpgradeNotice(engine))?.join('\n') ?? '';
+ expect(notice).toContain('[AGENT]');
+ expect(notice).toContain('gbrain extract --stale --catch-up');
+ expect(notice).toContain('6 page(s)');
+
+ await sweep(engine);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ expect(await statusRow()).toMatchObject({ state: 'complete', pending: 0 });
+ expect(await mentionLinks(engine)).toEqual(linksBefore);
+ expect(await mentionIndexUpgradeNotice(engine)).toBeNull();
+ expect((await call('entity', { name: 'QUCO' })).notices.join('\n')).not.toContain('mention_index');
+ });
+
+ test('an interrupted sweep (deadline) leaves the exact remaining count; the next sweep finishes it', async () => {
+ await account();
+ for (let i = 0; i < 450; i++) await page(engine, `mail/m${i}`, 'email', `Mail ${i}`, i % 50 === 0 ? 'Re: QUCO renewal' : 'Weekly digest');
+ await sweep(engine);
+ const linksBefore = await mentionLinks(engine);
+ expect(linksBefore.length).toBe(9);
+ await asPreviousRelease();
+
+ const realNow = Date.now;
+ let during: Awaited<ReturnType<typeof readMentionCoverage>> | null = null;
+ let interrupted;
+ try {
+ interrupted = await runMentionPass(engine, {
+ deadline: realNow() + 60_000,
+ beforePublish: async () => {
+ if (during) return;
+ during = await readMentionCoverage(engine, ['default']);
+ // The deadline passes while the first batch publishes.
+ Date.now = () => realNow() + 3_600_000;
+ },
+ });
+ } finally {
+ Date.now = realNow;
+ }
+ expect(during).toMatchObject({ state: 'pending', pending_pages: 451, degraded: true });
+ expect(interrupted).toMatchObject({ state: 'pending', pages: 200, remaining: 251 });
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'pending', pending_pages: 251, degraded: true });
+ expect((await call('entity', { name: 'QUCO' })).notices.join('\n')).toContain('[gbrain notice mention_index');
+ expect((await mentionIndexUpgradeNotice(engine))?.join('\n')).toContain('251 page(s)');
+
+ const resumed = await sweep(engine);
+ expect(resumed.mentions).toMatchObject({ state: 'complete', pages: 251, remaining: 0 });
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ expect(await mentionLinks(engine)).toEqual(linksBefore);
+ }, 180_000);
+
+ test('alias staleness counts only linkable entity pages', async () => {
+ await account();
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ for (let i = 0; i < 3; i++) await page(engine, `tickets/t${i}`, 'ticket', `Ticket ${i}`, 'Customer: QUCO');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Nothing relevant.');
+ await sweep(engine);
+ await asPreviousRelease({ aliasOnly: true });
+ expect(await countMentionDuePages(engine)).toBe(0);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'pending', pending_pages: 2 });
+ expect((await mentionIndexUpgradeNotice(engine))?.join('\n')).toContain('2 page(s)');
+ await sweep(engine);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ });
+});
+
+describe('upgrade from a brain built at the previous versions', () => {
+ test('one cycle-budget sweep (no manual catch-up) derives the new grammar\'s multi-word alias and links it', async () => {
+ await account();
+ await page(engine, 'notes/n1', 'note', 'n1', 'Copper Fox renewal call next week.');
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ expect(deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: ACCOUNT_BODY }).aliases.map(a => a.alias_norm))
+ .toContain('copper fox');
+ await sweep(engine);
+ // What the previous grammar left: no multi-word declared alias, so no saved entry and no link from the note.
+ await engine.executeRaw("DELETE FROM page_aliases WHERE alias_norm = 'copper fox'");
+ await engine.executeRaw("DELETE FROM mention_gazetteer_entries WHERE name_norm = 'copper fox'");
+ await engine.executeRaw(
+ "DELETE FROM links l USING pages f WHERE f.id = l.from_page_id AND f.slug = 'notes/n1' AND l.link_source = 'mentions'");
+ await asPreviousRelease();
+ expect(await derivedAliases(engine, 'crm/123')).not.toContain('declared:copper fox');
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'pending', pending_pages: 3 });
+
+ await sweep(engine, { timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS });
+ expect(await derivedAliases(engine, 'crm/123')).toContain('declared:copper fox');
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> crm/123', 'tickets/t1 -> crm/123']);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ expect(await mentionIndexUpgradeNotice(engine)).toBeNull();
+ });
+});
+
+describe('derivation settings on an indexed brain', () => {
+ const indexed = async () => {
+ await account();
+ await page(engine, 'notes/n1', 'note', 'n1', 'Copper Fox renewal call next week.');
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> crm/123', 'tickets/t1 -> crm/123']);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete' });
+ };
+
+ test.each([
+ ['mentions.multiword_aliases', 'false', false],
+ ['mentions.alias_deny', 'Copper Fox', false],
+ ['mentions.sibling_merge', 'false', true],
+ ])('changing %s marks the pages due; the next pass applies it', async (key, value, keepsAlias) => {
+ await indexed();
+ await engine.setConfig(key, value);
+ // A pass stopped before any batch: the fingerprint change alone marks every page due.
+ expect(await runMentionPass(engine, { deadline: Date.now() - 1 })).toMatchObject({ state: 'pending', remaining: 3 });
+ expect(await countMentionDuePages(engine)).toBe(3);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'pending', pending_pages: 3, degraded: true });
+ expect(await runMentionPass(engine)).toMatchObject({ state: 'complete', remaining: 0 });
+ expect((await derivedAliases(engine, 'crm/123')).includes('declared:copper fox')).toBe(keepsAlias);
+ expect(await mentionLinks(engine)).toEqual(keepsAlias ? ['notes/n1 -> crm/123', 'tickets/t1 -> crm/123'] : ['tickets/t1 -> crm/123']);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ });
+
+ test('a denied alias comes back when mentions.alias_deny no longer names it', async () => {
+ await indexed();
+ await engine.setConfig('mentions.alias_deny', 'Copper Fox');
+ await runMentionPass(engine);
+ expect(await derivedAliases(engine, 'crm/123')).not.toContain('declared:copper fox');
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ await engine.unsetConfig('mentions.alias_deny');
+ expect(await runMentionPass(engine)).toMatchObject({ state: 'complete', remaining: 0 });
+ expect(await derivedAliases(engine, 'crm/123')).toContain('declared:copper fox');
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> crm/123', 'tickets/t1 -> crm/123']);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ });
+});
diff --git a/test/mentions-explain.test.ts b/test/mentions-explain.test.ts
index 2896193798..5a0882d597 100644
--- a/test/mentions-explain.test.ts
+++ b/test/mentions-explain.test.ts
@@ -104,3 +104,39 @@ describe('extract mentions --explain reason codes', () => {
expect(JSON.parse(out.join('\n'))).toMatchObject({ schema_version: 1, kind: 'atoms' });
});
});
+
+describe('extract mentions --explain <slug>: names, rejections and the sibling decision', () => {
+ test('lists each derived alias with its origin and line, each rejected candidate with its reason', async () => {
+ await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. Ticker: QCO.\nInternal nickname: Copper Fox\nShort name: Quormiro');
+ await sweep(engine);
+ const r = await explainMention(engine, 'crm/123');
+ expect(r.aliases).toEqual(expect.arrayContaining([
+ { alias: 'Quormiro Capital', origin: 'subject' },
+ { alias: 'QUCO', origin: 'declared', line: 'Account code: QUCO. Ticker: QCO.' },
+ { alias: 'Copper Fox', origin: 'declared', line: 'Internal nickname: Copper Fox' },
+ ]));
+ expect(r.rejected).toEqual(expect.arrayContaining([
+ { alias: 'QCO', origin: 'declared', reason: 'below_min_length', line: 'Account code: QUCO. Ticker: QCO.' },
+ { alias: 'Quormiro', origin: 'declared', reason: 'ambiguous_first_word', line: 'Short name: Quormiro' },
+ ]));
+ expect(r.siblings).toEqual({ pages: [], capped: false, verdict: 'none' });
+ });
+
+ test('a denied alias explains as denied_by_config', async () => {
+ await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Internal nickname: Copper Fox');
+ await engine.setConfig('mentions.alias_deny', 'Copper Fox');
+ await sweep(engine);
+ expect((await explainMention(engine, 'Copper Fox')).reason).toBe('denied_by_config');
+ });
+
+ test('a capped sibling group and a formed one', async () => {
+ await page(engine, 'crm/a', 'crm', 'CRM record: Widget Co', 'x');
+ await page(engine, 'accounts/a', 'account', 'Account sheet: Widget Co', 'y');
+ await sweep(engine);
+ expect((await explainMention(engine, 'crm/a')).siblings).toEqual({ pages: ['accounts/a'], capped: false, verdict: 'group' });
+ await page(engine, 'billing/a', 'account', 'Billing record: Widget Co', 'z');
+ await page(engine, 'support/a', 'account', 'Support record: Widget Co', 'w');
+ await sweep(engine);
+ expect((await explainMention(engine, 'crm/a')).siblings).toEqual({ pages: [], capped: true, verdict: 'capped' });
+ });
+});
diff --git a/test/mentions-identity-siblings.test.ts b/test/mentions-identity-siblings.test.ts
new file mode 100644
index 0000000000..b6acc51d31
--- /dev/null
+++ b/test/mentions-identity-siblings.test.ts
@@ -0,0 +1,174 @@
+/**
+ * Identity siblings and the entity card's identity fields (Cat 40 Hard fix
+ * wave, F1): pages naming one subject under different title prefixes are
+ * shown side by side (never unioned), a name they share links to every
+ * candidate, and the card carries verbatim identity lines and honest `aka`
+ * guidance. PGLite, through MCP dispatch where the caller matters.
+ *
+ * Protects: a document that names an account only by its name reaches the
+ * card's referenced_by although two pages claim the name (it was dropped as
+ * an alias collision); a nickname declared on the account sheet reaches a
+ * card that resolves to the CRM record; people, look-alikes, large groups,
+ * excluded and `identity: separate` pages are never grouped; private
+ * siblings and private fence text never reach an untrusted caller.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+import { excerptLines, EXCERPT_CARD_CHARS, EXCERPT_PAGE_CHARS } from '../src/core/verbs/entity-card-identity.ts';
+import { siblingVerdict } from '../src/core/mentions/siblings.ts';
+import { mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+const config = { engine: 'pglite' } as never;
+const local = { remote: false, sourceId: 'default', config };
+const remote = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };
+
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function call(op: string, args: Record<string, unknown>, opts: Record<string, unknown> = local) {
+ const r = await dispatchToolCall(engine, op, args, opts as never);
+ return { json: r.isError ? null : JSON.parse(r.content[0].text), notices: r.content.slice(1).map(c => c.text) };
+}
+
+const pair = async (sheetFm: Record<string, unknown> = {}) => {
+ await page(engine, 'accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Segment: freight\nTeam handle: Copper Fox\nRegion: west', { frontmatter: sheetFm });
+ await page(engine, 'crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO\nOwner: Dana Example');
+};
+
+describe('identity siblings on the card', () => {
+ test('sheet + CRM record: siblings listed with their own aliases; aka stays the card page\'s own', async () => {
+ await pair();
+ await page(engine, 'accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Segment: freight\nInternal nickname: Copper Fox');
+ await sweep(engine);
+ const { json } = await call('entity', { name: 'WGCO' });
+ const card = json.card;
+ expect(card.entity.slug).toBe('crm/widget-co');
+ expect(card.aka).toEqual(['wgco', 'widget co']);
+ expect(card.aka_sources).toEqual([{ origin: 'declared', slug: 'crm/widget-co' }, { origin: 'subject', slug: 'crm/widget-co' }]);
+ expect(card.identity_siblings).toEqual({ capped: false,
+ pages: [{ slug: 'accounts/widget-co', title: 'Account sheet: Widget Co', type: 'account', aka: ['Copper Fox', 'Widget Co'] }] });
+ expect(card.identity_excerpt).toContainEqual({ slug: 'accounts/widget-co', line: 'Internal nickname: Copper Fox' });
+ expect(card.alias_guidance.text).toContain('not proof the list is complete');
+ expect(card.alias_guidance.requires_surface).toBeUndefined();
+ });
+
+ test('a name both siblings claim links to every candidate; a document naming only the subject reaches referenced_by', async () => {
+ await pair();
+ await page(engine, 'notes/n1', 'note', 'Renewal call', 'Talked to Widget Co about the renewal.');
+ await sweep(engine);
+ const links = await mentionLinks(engine);
+ expect(links).toContain('notes/n1 -> accounts/widget-co');
+ expect(links).toContain('notes/n1 -> crm/widget-co');
+ expect(links).not.toContain('crm/widget-co -> accounts/widget-co');
+ const card = (await buildEntityCard(engine, 'default', 'Widget Co', { remote: false, includeReferences: true })).card!;
+ expect(card.referenced_by!.flatMap(g => g.rows.map(r => r.slug))).toContain('notes/n1');
+ });
+
+ test('an unknown label carrying the nickname shows in the excerpt below 600+ characters of ordinary fields', async () => {
+ const ordinary = Array.from({ length: 30 }, (_, i) => `field ${i}: value number ${i} for the record`).join('\n');
+ await page(engine, 'accounts/widget-co', 'account', 'Account sheet: Widget Co', `${ordinary}\nCrew shorthand: Kumquat Example`);
+ await page(engine, 'crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO');
+ expect(ordinary.length).toBeGreaterThan(600);
+ await sweep(engine);
+ const card = (await buildEntityCard(engine, 'default', 'WGCO', { remote: false, includeReferences: true })).card!;
+ expect(card.identity_excerpt!.map(l => l.line)).toContain('Crew shorthand: Kumquat Example');
+ });
+
+ test('verbs surface: guidance names the starter surface; an entity with nothing to say gets no guidance', async () => {
+ await pair();
+ await page(engine, 'companies/plain', 'company', 'plain', 'nothing here');
+ await sweep(engine);
+ const verbs = await buildEntityCard(engine, 'default', 'WGCO', { remote: false, includeReferences: true, surfaceCeiling: 'verbs' });
+ expect(verbs.card!.alias_guidance).toMatchObject({ requires_surface: 'starter' });
+ const bare = await buildEntityCard(engine, 'default', 'plain', { remote: false, includeReferences: true });
+ expect(bare.card!.alias_guidance).toBeUndefined();
+ expect(bare.card!.identity_siblings).toBeUndefined();
+ });
+});
+
+describe('the sibling rule', () => {
+ const pack = { page_types: [{ name: 'account', primitive: 'entity', aliases: ['crm'] }, { name: 'person', primitive: 'entity' }] };
+ const policy = { siblingMerge: true, excludeSlugs: [] as string[] };
+ const p = (slug: string, title: string, type = 'account', identity?: string) => ({ slug, title, type, identity });
+
+ test('verdicts', () => {
+ expect(siblingVerdict([p('a', 'Account sheet: Widget Co'), p('b', 'CRM record: Widget Co', 'crm')], pack, policy)).toBe('group');
+ expect(siblingVerdict([p('a', 'Profile: Dana Example', 'person'), p('b', 'Contact: Dana Example', 'person')], pack, policy)).toBe('person');
+ expect(siblingVerdict([p('a', 'CRM record: Widget Co'), p('b', 'CRM record: Widget Co')], pack, policy)).toBe('same_prefix');
+ expect(siblingVerdict(['A', 'B', 'C', 'D'].map(x => p(x, `${x} sheet: Widget Co`)), pack, policy)).toBe('capped');
+ expect(siblingVerdict([p('a', 'Account: Widget Co'), p('b', 'Account sheet: Widget Co Successor')], pack, policy)).toBe('subject_mismatch');
+ expect(siblingVerdict([p('a', 'Account sheet: Widget Co'), p('b', 'CRM record: Widget Co', 'crm', 'separate')], pack, policy)).toBe('separate');
+ expect(siblingVerdict([p('a', 'Account sheet: Widget Co'), p('b', 'CRM record: Widget Co')], pack, { ...policy, excludeSlugs: ['b'] })).toBe('excluded');
+ expect(siblingVerdict([p('a', 'Account sheet: Widget Co'), p('b', 'CRM record: Widget Co')], pack, { ...policy, siblingMerge: false })).toBe('disabled');
+ });
+
+ test('people with the same name stay separate (same or different prefixes), in the card and the gazetteer', async () => {
+ await page(engine, 'people/dana-a', 'person', 'Profile: Dana Example', 'x');
+ await page(engine, 'people/dana-b', 'person', 'Contact: Dana Example', 'y');
+ await page(engine, 'notes/n1', 'note', 'Note', 'Met Dana Example today.');
+ await sweep(engine);
+ const card = (await buildEntityCard(engine, 'default', 'people/dana-a', { remote: false, includeReferences: true })).card!;
+ expect(card.identity_siblings).toBeUndefined();
+ expect((await mentionLinks(engine)).filter(l => l.startsWith('notes/n1'))).toEqual([]);
+ });
+
+ test('a four-page group shows nothing, is capped and emits the explain notice', async () => {
+ for (const x of ['Account sheet', 'CRM record', 'Billing record', 'Support record']) {
+ await page(engine, `accounts/${x.toLowerCase().replace(' ', '-')}`, 'account', `${x}: Widget Co`, 'Owner: Dana Example');
+ }
+ await sweep(engine);
+ const { json, notices } = await call('entity', { name: 'accounts/account-sheet' });
+ expect(json.card.identity_siblings).toEqual({ pages: [], capped: true });
+ expect(notices.join('\n')).toContain('identity_siblings_capped');
+ expect(notices.join('\n')).toContain('gbrain extract mentions --explain accounts/account-sheet');
+ });
+
+ test('identity: separate, mentions.exclude_slugs and mentions.sibling_merge=false keep pages apart', async () => {
+ await pair({ identity: 'separate' });
+ await sweep(engine);
+ const card = async () => (await buildEntityCard(engine, 'default', 'crm/widget-co', { remote: false, includeReferences: true })).card!;
+ expect((await card()).identity_siblings).toBeUndefined();
+ await resetMentionBrain(engine);
+ await pair();
+ expect((await card()).identity_siblings?.pages.length).toBe(1);
+ await engine.setConfig('mentions.exclude_slugs', 'accounts/widget-co');
+ expect((await card()).identity_siblings).toBeUndefined();
+ await engine.unsetConfig('mentions.exclude_slugs');
+ await engine.setConfig('mentions.sibling_merge', 'false');
+ expect((await card()).identity_siblings).toBeUndefined();
+ });
+});
+
+describe('excerpt privacy and size', () => {
+ test('remote caller: a private sibling, private fence text and forgotten facts never show', async () => {
+ const fence = '## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n'
+ + '| 1 | Secret handle: Hidden Heron | fact | 1.0 | private | medium | 2026-01-01 | | test | |\n'
+ + '| 2 | ~~Old handle: Gone Gull~~ | fact | 1.0 | world | medium | 2026-01-01 | | test | forgotten: user asked |\n<!--- gbrain:facts:end -->\n';
+ await page(engine, 'crm/widget-co', 'crm', 'CRM record: Widget Co', `Account code: WGCO\n\n${fence}`);
+ await page(engine, 'accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Internal nickname: Private Plover', { frontmatter: { visibility: 'private' } });
+ await sweep(engine);
+ const { json } = await call('entity', { name: 'WGCO' }, remote);
+ const text = JSON.stringify(json.card);
+ for (const secret of ['Hidden Heron', 'Gone Gull', 'Private Plover', 'accounts/widget-co']) expect(text).not.toContain(secret);
+ const localCard = (await buildEntityCard(engine, 'default', 'WGCO', { remote: false, includeReferences: true })).card!;
+ expect(JSON.stringify(localCard.identity_excerpt)).not.toContain('Hidden Heron');
+ expect(JSON.stringify(localCard.identity_excerpt)).not.toContain('Gone Gull');
+ expect(localCard.identity_siblings?.pages.map(p => p.slug)).toEqual(['accounts/widget-co']);
+ });
+
+ test('caps: 600 characters per page, 1,200 per card; omitted pages are listed', async () => {
+ const long = Array.from({ length: 40 }, (_, i) => `Contact ${i}: Person Number${i} Example`).join('\n');
+ expect(excerptLines(long, 'X').join('').length).toBeLessThanOrEqual(EXCERPT_PAGE_CHARS);
+ await page(engine, 'accounts/a', 'account', 'Account sheet: Widget Co', long);
+ await page(engine, 'crm/b', 'crm', 'CRM record: Widget Co', long);
+ await page(engine, 'billing/c', 'account', 'Billing record: Widget Co', long);
+ await sweep(engine);
+ const card = (await buildEntityCard(engine, 'default', 'crm/b', { remote: false, includeReferences: true })).card!;
+ expect(card.identity_excerpt!.reduce((n, l) => n + l.line.length, 0)).toBeLessThanOrEqual(EXCERPT_CARD_CHARS);
+ expect(card.identity_excerpt_omitted!.length).toBeGreaterThan(0);
+ });
+});
diff --git a/test/mentions-policy-aliases.test.ts b/test/mentions-policy-aliases.test.ts
index 620a01073d..9099e44dfc 100644
--- a/test/mentions-policy-aliases.test.ts
+++ b/test/mentions-policy-aliases.test.ts
@@ -15,7 +15,7 @@ import { loadResolvedPackByName } from '../src/core/schema-pack/load-active.ts';
import {
ALWAYS_LINKABLE_TYPES, canonicalTypeOf, linkableTypesFor, parseNameList, typeAliasPairs,
} from '../src/core/mentions/policy.ts';
-import { aliasRejection, declaredNames, deriveEntityAliases, titleSubject } from '../src/core/mentions/aliases.ts';
+import { aliasRejection, captureName, declarationsIn, declaredNames, deriveEntityAliases, titleSubject } from '../src/core/mentions/aliases.ts';
import { aliasDeclarations } from '../src/core/ops/search.ts';
const none = { typeAdds: [], typeRemoves: [] };
@@ -91,12 +91,12 @@ describe('derived aliases', () => {
});
test('guards: 3-character code, first word of the own name, generic word', () => {
- const r = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'Ticker: QCO. Also known as Quormiro Capital. aka Team' });
+ const r = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'Ticker: QCO. Also known as Quormiro Capital.\nShort name: Quormiro\naka Staff' });
expect(r.aliases.map(a => a.alias_text)).toEqual(['Quormiro Capital']);
expect(r.rejected).toEqual(expect.arrayContaining([
- { alias: 'QCO', origin: 'declared', reason: 'below_min_length' },
- { alias: 'Quormiro', origin: 'declared', reason: 'ambiguous_first_word' },
- { alias: 'Team', origin: 'declared', reason: 'generic_token' },
+ expect.objectContaining({ alias: 'QCO', origin: 'declared', reason: 'below_min_length' }),
+ expect.objectContaining({ alias: 'Quormiro', origin: 'declared', reason: 'ambiguous_first_word' }),
+ expect.objectContaining({ alias: 'Staff', origin: 'declared', reason: 'generic_token' }),
]));
expect(aliasRejection('Grace', 'Grace Hopper-Example')).toBe('ambiguous_first_word');
});
@@ -112,3 +112,83 @@ describe('derived aliases', () => {
.toEqual([{ name: 'Quormiro Capital', alias: 'QUCO', slug: 'crm/1' }]);
});
});
+
+// docs/designs/ALIAS_CONVENTIONS.md: one positive fixture per convention, and the negatives the spec names.
+describe('declared-name grammar (alias conventions spec)', () => {
+ const names = (text: string, name = 'Widget Co') => declaredNames(text, name);
+
+ test.each([
+ ['also known as', 'Widget Co, also known as Blue Harbor, renewed.', ['Blue Harbor']],
+ ['a.k.a.', 'Widget Co (a.k.a. Blue Harbor) renewed.', ['Blue Harbor']],
+ ['known internally as', 'Widget Co, known internally as Project Kestrel, renewed.', ['Project Kestrel']],
+ ['nicknamed, quoted', 'The account is nicknamed "Copper Fox".', ['Copper Fox']],
+ ['goes by', 'Widget Co goes by WCX in chat.', ['WCX']],
+ ['also called', 'Widget Co, also called Northwind Ops.', ['Northwind Ops']],
+ ['referred to as, curly quotes', 'commonly referred to as \u201cAtlas North\u201d', ['Atlas North']],
+ ['formerly, parenthetical', 'Widget Co (formerly Gearbox Labs) renewed.', ['Gearbox Labs']],
+ ['doing business as', 'Widget Co LLC d/b/a Northwind Partners', ['Northwind Partners']],
+ ['trading as', 'Widget Co, trading as Harbor Freight Example.', ['Harbor Freight Example']],
+ ['short name label', 'Short name: WGCO', ['WGCO']],
+ ['code label', 'Account code: QUCO', ['QUCO']],
+ ['alias cue', 'Also filed under the alias "Red Kite".', ['Red Kite']],
+ ['qualified nickname label', 'Internal nickname: Copper Fox', ['Copper Fox']],
+ ['label with a phrase', 'Nickname (sales team): Copper Fox', ['Copper Fox']],
+ ['bold key-value list', '- **Aliases:** Copper Fox, WCX', ['Copper Fox', 'WCX']],
+ ['plain key-value', 'trading name: Northwind Ops', ['Northwind Ops']],
+ ['table row', '| Nickname | Copper Fox |', ['Copper Fox']],
+ ['table row, qualified label', '| Former legal name | Gearbox Labs Inc |', ['Gearbox Labs Inc']],
+ ['values joined by or', 'Aliases: Copper Fox or Red Kite', ['Copper Fox', 'Red Kite']],
+ ['defined term after the own name', 'Widget Co Holdings, Inc. ("Widgetry") signed.', ['Widgetry']],
+ ])('%s', (_label, text, want) => {
+ expect(names(text, _label === 'defined term after the own name' ? 'Widget Co Holdings' : 'Widget Co')).toEqual(want);
+ });
+
+ test.each([
+ 'the team calls it a success',
+ 'Dana Example goes by the book.',
+ 'known as a leader in freight',
+ 'formerly the head of sales',
+ 'referred to as needed',
+ 'aka the usual',
+ 'aka Monday', 'also known as the Board', 'aka Finance', 'aka Legal', 'aka Q3 Plan', 'aka FY26 Review',
+ 'Our competitor, also known as Blue Harbor, cut prices.',
+ 'Their parent company, formerly Gearbox Labs, filed.',
+ 'also known as Blue Harbor\'s team',
+ 'also known as Blue Harbor Shipping Lines Group',
+ 'Another firm ("Bluebird") bid.',
+ '| Alias | Notes |\n|---|---|',
+ ])('no alias: %s', text => {
+ expect(names(text)).toEqual([]);
+ });
+
+ test('a capture ends at punctuation, a lowercase word or the line end; the possessive is never part of it', () => {
+ expect(captureName(' Copper Fox, renewed')).toBe('Copper Fox');
+ expect(captureName(' Copper Fox renewed')).toBe('Copper Fox');
+ expect(captureName(' Copper Fox')).toBe('Copper Fox');
+ expect(captureName(" Copper Fox's desk")).toBeNull();
+ expect(captureName(' "Copper Fox"\'s desk')).toBeNull();
+ });
+
+ test('declarations carry their line; multi-word captures can be turned off', () => {
+ const text = 'Owner: Dana Example\nInternal nickname: Copper Fox\nAccount code: QUCO';
+ expect(declarationsIn(text)).toEqual([{ alias: 'Copper Fox', line: 1 }, { alias: 'QUCO', line: 2 }]);
+ expect(declarationsIn(text, { multiword: false })).toEqual([{ alias: 'QUCO', line: 2 }]);
+ });
+
+ test('a multi-word alias is case-insensitive; deny lists drop a derived alias', () => {
+ const page = { title: 'Account sheet: Widget Co', compiled_truth: 'Internal nickname: Copper Fox\nAccount code: WGCO', frontmatter: { alias_deny: ['WGCO'] } };
+ const r = deriveEntityAliases(page);
+ expect(r.aliases.map(a => [a.alias_text, a.case_sensitive])).toEqual([['Widget Co', false], ['Copper Fox', false]]);
+ expect(r.rejected).toContainEqual({ alias: 'WGCO', origin: 'declared', reason: 'denied', line: 'Account code: WGCO' });
+ expect(r.lines.get('copper fox')).toBe('Internal nickname: Copper Fox');
+ expect(deriveEntityAliases({ ...page, frontmatter: null }, { deny: ['copper fox'] }).aliases.map(a => a.alias_text)).toEqual(['Widget Co', 'WGCO']);
+ expect(deriveEntityAliases({ ...page, frontmatter: null }, { multiword: false }).aliases.map(a => a.alias_text)).toEqual(['Widget Co', 'WGCO']);
+ });
+
+ test('parsing stays linear on adversarial lines', () => {
+ const line = `aka ${'A '.repeat(5000)}` + `\n| ${'Nickname '.repeat(3000)}|` + `\nNickname: ${'"'.repeat(5000)}`;
+ const t0 = performance.now();
+ declaredNames(line, 'Widget Co');
+ expect(performance.now() - t0).toBeLessThan(200);
+ });
+});
diff --git a/test/search-alias-fanout.test.ts b/test/search-alias-fanout.test.ts
new file mode 100644
index 0000000000..ecf59395fc
--- /dev/null
+++ b/test/search-alias-fanout.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Search's alias fan-out (Cat 40 Hard fix wave, F1.6): a query that names an
+ * entity also searches every other name the entity and its identity siblings
+ * go by, keyword-only with the name required, and each spliced row says which
+ * name found it.
+ *
+ * Protects: records filed only under a nickname or a code reach a query that
+ * names the account (gbrain-evals Cat 40 Hard: code-only misses with the code
+ * on the card); a lowercase common word never fans out; the per-call caps
+ * (4 names, 8 rows) hold and say so; a private sibling's names never reach an
+ * untrusted caller.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { aliasPhrase, aliasRankQuery, resolveQueryEntity, searchAliasRequired } from '../src/core/search/alias-fanout.ts';
+import { mentionBrain, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+const remote = { remote: true, transport: 'http' as const, sourceId: 'default' };
+
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function put(slug: string, type: string, title: string, body: string, fm: Record<string, unknown> = {}) {
+ await importFromContent(engine, slug, serializeMarkdown(fm, body, '', { type, title, tags: [] }), { noEmbed: true, forceRechunk: true });
+}
+
+async function search(query: string, opts: Record<string, unknown> = remote) {
+ const r = await dispatchToolCall(engine, 'search', { query }, opts as never);
+ return {
+ rows: JSON.parse(r.content[0].text!) as Array<{ slug: string; matched_alias?: string; chunk_text?: string }>,
+ fanout: (r._meta?.retrieval as Record<string, unknown> | undefined)?.fanout as Record<string, any> | undefined,
+ visible: r.content.map(c => c.text ?? '').join('\n'),
+ };
+}
+
+const account = async () => {
+ await put('accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Segment: freight\nInternal nickname: Copper Fox');
+ await put('crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO\nOwner: Dana Example');
+ await put('tickets/t1', 'ticket', 'Ticket 1', 'Copper Fox asked for a refund on the March invoice.');
+ await put('contracts/a1', 'amendment', 'Amendment 1', 'For WGCO the discount moves to 12 percent, effective 2025-04-01.');
+ for (let i = 0; i < 6; i++) await put(`notes/n${i}`, 'note', `Note ${i}`, `Widget Co weekly check-in number ${i}. Discount discussed.`);
+ await sweep(engine);
+};
+
+describe('alias fan-out', () => {
+ test('a query naming the account returns records filed only under its nickname and its code, with matched_alias', async () => {
+ await account();
+ const { rows, fanout } = await search('Widget Co discount history');
+ const slugs = rows.map(r => r.slug);
+ expect(slugs).toContain('contracts/a1');
+ expect(slugs).toContain('tickets/t1');
+ for (const r of rows.filter(r => r.matched_alias)) expect((r.chunk_text ?? '').toLowerCase()).toContain(r.matched_alias!.toLowerCase());
+ expect(rows.find(r => r.slug === 'tickets/t1')?.matched_alias).toBe('Copper Fox');
+ expect(fanout!.resolved_entity).toMatch(/widget-co$/);
+ expect(fanout!.aliases_searched.map((a: { alias: string }) => a.alias)).toEqual(expect.arrayContaining(['WGCO', 'Copper Fox']));
+ expect(fanout!.truncated).toBe(false);
+ });
+
+ test('the sibling tie resolves to the group; a lowercase common word never fans out', async () => {
+ await account();
+ const r = await resolveQueryEntity(engine, 'Widget Co renewal', { sourceId: 'default', excludePrivate: false });
+ expect(r!.pages.map(p => p.slug).sort()).toEqual(['accounts/widget-co', 'crm/widget-co']);
+ await put('companies/discount', 'company', 'discount', 'A company literally named discount.');
+ await sweep(engine);
+ expect(await resolveQueryEntity(engine, 'what is the discount', { sourceId: 'default', excludePrivate: false })).toBeNull();
+ });
+
+ test('at most 4 names per call, the rest are listed and the model-visible notice names them; spliced rows stop at 8', async () => {
+ const names = ['Alpha Kite', 'Beta Kite', 'Gamma Kite', 'Delta Kite', 'Epsilon Kite', 'Zeta Kite'];
+ await put('crm/kite-co', 'crm', 'CRM record: Kite Co', `Account code: KTCO\nAliases: ${names.join(', ')}`);
+ for (const n of names) for (let i = 0; i < 3; i++) await put(`docs/${n.split(' ')[0]!.toLowerCase()}-${i}`, 'note', `Doc ${n} ${i}`, `${n} order number ${i}.`);
+ await sweep(engine);
+ const { rows, fanout, visible } = await search('Kite Co orders');
+ expect(fanout!.aliases_searched).toHaveLength(4);
+ expect(fanout!.aliases_skipped).toHaveLength(3);
+ expect(fanout!.truncated).toBe(true);
+ expect(visible).toContain('alias_fanout');
+ for (const skipped of fanout!.aliases_skipped) expect(visible).toContain(skipped);
+ expect(rows.filter(r => r.matched_alias).length).toBeLessThanOrEqual(8);
+ });
+
+ test('a resolved entity in a source still being indexed carries the mention_index notice', async () => {
+ await account();
+ expect((await search('Widget Co discount history')).visible).not.toContain('mention_index');
+ await engine.executeRaw('UPDATE page_mention_state SET mention_version = 1, alias_version = 1');
+ await engine.executeRaw("UPDATE mention_index_status SET policy_fingerprint = split_part(policy_fingerprint, ';', 1)");
+ expect((await search('Widget Co discount history')).visible).toContain('mention_index');
+ });
+
+ test('search.alias_fanout_max=0 turns fan-out off', async () => {
+ await account();
+ await engine.setConfig('search.alias_fanout_max', '0');
+ const { rows, fanout } = await search('Widget Co discount history');
+ expect(fanout).toBeUndefined();
+ expect(rows.some(r => r.matched_alias)).toBe(false);
+ });
+
+ test('a private sibling\'s names never reach an untrusted caller', async () => {
+ await put('accounts/widget-co', 'account', 'Account sheet: Widget Co', 'Internal nickname: Private Plover', { visibility: 'private' });
+ await put('crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO');
+ await put('tickets/t9', 'ticket', 'Ticket 9', 'Private Plover escalated.');
+ await sweep(engine);
+ const { visible, fanout, rows } = await search('Widget Co escalations');
+ expect(JSON.stringify(fanout ?? {})).not.toContain('Private Plover');
+ expect(rows.some(r => r.matched_alias === 'Private Plover')).toBe(false);
+ expect(visible).not.toContain('accounts/widget-co');
+ });
+
+ test('the alias-required query escapes codes and quotes and ranks by the other terms', async () => {
+ await put('docs/x1', 'note', 'X1', 'ZX-41 shipped late; refund issued.');
+ await put('docs/x2', 'note', 'X2', 'ZX-41 shipped on time.');
+ await put('docs/x3', 'note', 'X3', 'A refund for someone else.');
+ expect(aliasPhrase('Say "hi"')).toBe('"Say hi"');
+ expect(aliasRankQuery('"ZX-41"', ['refund'])).toBe('"ZX-41" OR refund');
+ const rows = await searchAliasRequired(engine, 'ZX-41', ['refund'], { sourceId: 'default', limit: 5 });
+ expect(rows.map(r => r.slug)).toEqual(['docs/x1', 'docs/x2']);
+ });
+});