Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(whois): exact identity lookup op for agents (GBRA-156)

garrytan7b7da6e7c248
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10e5879492..6d35532d45 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,30 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.434.0] - 2026-10-24
+
+**Agents triaging email or calendar can now ask whether a sender or attendee is a known contact and get an exact answer: `gbrain whois <email or name>` (MCP tool `whois`) returns only pages whose email, title or declared alias equals the query, and an empty list when none does.**
+
+Semantic search can rank the wrong person first for a name or address, and `gbrain entity` resolves fuzzy name variants on purpose. `whois` never does either.
+
+**Say to your agent:** *"Is [email protected] a known contact in my brain?"*
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| Checking an email address against the brain | search or query, which can return a different person with a high score | `whois [email protected]` matches frontmatter `email` / `emails` (whole address, case-insensitive), the title or a declared alias |
+| Checking a display name | search, or `entity`, which accepts nicknames, initials and one-letter typos | `whois "José Example"` matches a title or declared alias equal to the name, ignoring case, accents, width forms and surrounding quotes; "Jose Example" finds "José Example", "Matt Example" never finds "Matthew Example" |
+| Two pages carry the same name or address | the agent saw whichever ranked first | every match is returned, labeled `email`, `title` or `alias` (in that order), with `ambiguous: true` |
+| No page matches | an unrelated nearest result | `matches: []`, not an error and never a search fallback |
+
+### What to watch for after you upgrade
+
+- By default `whois` reads the schema pack's entity types (people, companies, accounts); pass `types` to widen or narrow it, and `source_id` for one source.
+- A remote caller sees only the sources its grant covers, and never a private or quarantined page.
+- Matching is exact by design, and two cases depend on how a page is written. An unaccented query finds an accented title when the page's slug follows the title (`people/jose-example`), because slugs drop accents; on a page whose slug does not, write the accents or declare the unaccented name as an alias. A frontmatter email stored in mixed case is found from its exact spelling, its lowercase form, or a declared alias.
+- Nothing is rewritten on upgrade, and there is no schema migration.
+
## [0.60.427.0] - 2026-10-24
**A search for a full name that uses a short first name ("Matt Example") now finds the page titled "Matthew Example". Before, the person's own page could drop out of the results entirely, behind a different person who only shared the first name.**
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 336abaeafa..3069b7256c 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 161 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 162 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -197,6 +197,7 @@ Every non-localOnly operation on the MCP surface: 161 tools across 25 areas. **S
| `revert_version` | Restore a page to an earlier version from its history (a new revision; history is kept). | write | | |
| `unpurge_page` | Owner-only (`gbrain pages unpurge <slug>`). | admin | | |
| `upload_page_part` | Send the next part of an upload: part equals next_part, the whole call within part_max_frame_bytes, cut between code points. | write | | |
+| `whois` | Exact identity lookup: entity pages whose email, title or declared alias equals an email address or name, ignoring case, accents and quotes. | read | | |
## questions
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 7e0d23b696..6d5095a8e7 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -35,6 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).
- `src/core/engine-sql/graph-rank.ts` — #7168: `rankEntitiesStatement(opts)`, the one `rank_entities` aggregate for both engines (a statement builder: the op runs it through `executeRaw` with its statement deadline, like `extractionLagStatement`). Edges are distinct `(from, to, link_type)` triples between live, in-scope endpoints (both endpoints scoped by `sourceIds`), self-links, non-ranking types (`rankingLinkSql`) and, unless `includeMentions`, mention rows excluded. Retired pages (`retiredPageSql`) fold into their `superseded_by`/`merged_into` target in the same source through a recursive chain over retired pages only, capped at `MAX_RETIREMENT_HOPS`; edges dedupe after folding and folded self-links drop. With `remote` every endpoint, chain hop, fold target and non-null link origin must be in scope, live, unquarantined, in an unarchived source and (with `excludePrivate`) not private, so a hidden target never folds. Ordered by the direction's count, then slug and source id (`COLLATE "C"`), LIMIT after folding. Tests: `test/rank-entities.test.ts`.
+- `src/core/engine-sql/exact-identity.ts` — GBRA-156: `exactIdentityStatement(opts)`, the `whois` candidate read (a statement builder the op runs through `executeRaw`): a UNION of equality probes each served by an existing index, `lower(title)` (`idx_pages_source_title_lower`; the raw query is also lowered by the database), the slug basename (`idx_pages_slug_basename`, accent-folded by the slug grammar), `page_aliases.alias_norm`, and one GIN containment arm per address and shape (`email: x`, `email: [x]`, `emails: x`, `emails: [x]`; one OR of them plans a scan). Every probe and row stays in `sourceIds`; rows are live, in an unarchived source, of a type the `EntityTypeFilter` admits, and with `remote` unquarantined and (with `excludePrivate`) not private. The rows are candidates; the op verifies each. Accent-insensitive titles are found only through the lowered title (same accents, or none in the title) or the slug basename; a case-insensitive frontmatter email only through its as-written or lowercase value or a declared alias. Closing those gaps needs expression indexes (a migration). Tests: the index-plan case in `test/whois.test.ts` and `test/e2e/whois-postgres.test.ts`.
- `src/core/engine-sql/chunks.ts` `upsertChunksOnce` — a chunk replacement inside the caller's transaction: the batched `chunkWriteInvalidations` guard, then one prune (`moveDisplacedChunksAndPrune`: a row whose vector still matches its text (`movableChunkSql`) and whose exact text and source reappear at another index is parked at a negative index and moved there; rows outside the new set are deleted), then one multi-row INSERT per `jsonRowBatches` batch (at most `ROW_BATCH_MAX_ROWS` rows and `ROW_BATCH_MAX_BYTES` encoded bytes; the first is pipelined with the seal). A failure in any batch rolls back the prune and every earlier batch. Tests: `engine-sql-chunks-batched-write.test.ts`, the multi-batch case in `helpers/engine-sql-rollback-cases.ts`.
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 9a65015fb7..f963f16d65 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -17,6 +17,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `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 (#6876) is the keyset-paged `Link[]` from `ops/links.ts` / `ops/link-paging.ts`; `filterBacklinkRows` only filters each page by referrer type. With `group: "page"`, `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values. F3 (`entity.row_page_status`, default on): `withLinkPageStatus` adds the referring page's `page_status` to link rows, and `group: "page"` rows get it through `readReferrerPage {pageStatus}`; a record type's continuation keeps it through `recordMetadata` when the key is off.
- `src/core/ops/graph-rank.ts` — #7168: `rank_entities` (CLI `rank-entities`): validates every parameter with `invalidParam` (no coercion; type and link-type names are pattern-checked, non-ranking link types refused, `limit` 1-100), scopes with `assertSourceInCallerScope` / `resolveRequestedScope` then `linkReadScopeOpts` (remote scalar scopes promoted to `sourceIds`), defaults `types` to `resolveEntityTypes`, runs `engine-sql/graph-rank.ts` under `RANK_ENTITIES_STATEMENT_MS` (a 57014 becomes `rank_entities_timeout`), attaches `possible_duplicates` (`readPossibleDuplicates`) to at most `RANK_ENTITIES_DUPLICATE_ROWS` top rows within a 3 s budget, and `coverage` from `readExtractionLag` per source in scope (state only for remote callers). Guide: [graph ranking](../../guides/graph-ranking.md). Tests: `test/rank-entities.test.ts`.
+- `src/core/ops/whois.ts` — GBRA-156: `whois` (CLI `whois <query>`), the exact identity lookup. A query is an email address (`identityEmailKey`: NFKC, lowercase, surrounding quotes and angle brackets dropped, whole address compared) or a name (`identityNameKey`: `normalizeAlias`, surrounding straight and typographic quotes dropped, NFKD with combining marks stripped, `foldNonDecomposingLatin`). Scope: `parseSourceIdParam` + `federatedSearchScope` + `assertExplicitSourceLive`, an unscoped trusted call reading every unarchived source; `types` defaults to `resolveEntityTypes` for that scope. Candidates come from `engine-sql/exact-identity.ts`; `identityMatchKind` keeps a candidate only when a frontmatter `email`/`emails` value (email queries), the title, or a `normalizeAliasList` alias folds to exactly the query, labeled `email` > `title` > `alias` (ordered so, then source id and slug). Returns `matches`, `ambiguous` (more than one match), `types_status`, and `truncated` + `note` past `WHOIS_CANDIDATE_CAP` candidates; no match is an empty list, never a search fallback. Registered `labeled`, output redaction `retrieval`. Tests: `test/whois.test.ts`, `test/e2e/whois-postgres.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-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` reads `entityLookupScope` once per batch, then resolves each name through the card's candidate selection (`selectEntityCandidates`, no card assembled), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; the lead comes from the candidate row's bounded, withdrawal-overlaid `compiled_truth` prefix (`page-window/bounded-lead.ts`), siblings from `readSiblingIdentity` with the batch's policy and pack. Output is byte-identical to the old full-card path (`test/entity-names-parity.test.ts`, Postgres twin `test/e2e/entity-names-parity-postgres.test.ts`, fixtures and the reference resolver in `test/helpers/entity-names-parity.ts`). `pageLead` is the body's opening prose from `boundedProjectedPrefix` (the 64 KiB prefix, sanitized and credential-projected) plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. `attachReferences` adds `referenced_by_count`, the card `next` and `records` to every found page and sibling from one `readRowReferences` call. Tests: `test/entity-names.test.ts`, `test/entity-names-parity.test.ts`, `test/entity-records.test.ts`.
- `src/core/verbs/entity-references.ts` — the F1 reference fields on compact rows: `readRowReferences` (config gate per surface `names` / `pack` / `full_card`, `REFERENCES_DEADLINE_MS` 2 s cooperative deadline, `references_unavailable` marker + degraded notice, per-type `next` to `get_backlinks` returning exactly the rest, `record_types_undeclared` notice), `readPackReferences` (context_pack pull verb only: card page + identity siblings), `renderRecordLines` / `RECORDS_HEADER` (packed text, "page date"). Config: `src/core/entity-references-config.ts` (`entity.names_references` default on, `entity.record_types` default empty). Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
diff --git a/plugin/README.md b/plugin/README.md
index ff8fb74cfe..71a530e901 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 182
+The plugin's MCP server runs `gbrain serve --surface full` — 183
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 847cebd3eb..1e265ed905 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2858 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured)
src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075
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 244 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); 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; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import
+src/core/operations.ts 245 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); 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; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line)
src/core/pglite-engine.ts 3089 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move)
src/core/postgres-engine.ts 3147 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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 40dbbecfe7..e7e9c62aa9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1217,6 +1217,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.424.0', text: 'doctor `parked_effects` and `gbrain sources writer status` now report `stalled_catchups`: per source, effects that have waited on a busy canonical worktree for over 10 minutes, with when the wait began and the read-only writer status command that shows who holds the worktree. doctor warns "Catch-up not progressing" for them even when nothing is parked.' },
{ since: '0.60.426.0', text: 'With `--job-isolation process`, `--max-rss` now caps each job child too: the worker measures the child\'s process tree (RssAnon + RssShmem) every 5 seconds, and a child past the cap gets SIGTERM, then SIGKILL after the 25-second grace. Its attempt fails with `ChildRssLimitError`, so a job that grows the same way on every retry ends at its `max_attempts`. Before, the cap read only the worker\'s own memory, and a runaway child grew until the host or container limit restarted every process.' },
{ since: '0.60.427.0', text: 'A search for a full name with a short first name ("Matt Example") now finds the page titled "Matthew Example", and back (Bob and Robert, Liz and Elizabeth and the other common given-name groups): the title arm also matches the other forms of the given name, and the title boost counts them as a title match. When no title holds every word of a query of up to four words, the title arm\'s any-word retry now puts titles holding the rarest word first instead of tying them with titles that hold only a common word (#7471).' },
+ // GBRA-156 (exact identity lookup). `since` is stamped at the merge slot.
+ { since: '0.60.434.0', id: 'whois_exact_identity', text: 'New read operation `whois` (CLI `gbrain whois <email or name>`, MCP tool `whois`): an exact identity lookup for agents triaging email or calendar. It returns the entity pages whose frontmatter `email`/`emails`, title or declared alias equals the query, ignoring case, accents and surrounding quotes, labels each match `email`, `title` or `alias`, sets `ambiguous` when more than one page matches, and returns an empty list, never a search fallback, when none does. Remote callers see only their granted sources and no private or quarantined page. Nothing existing changes.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.ts
index bada1b3182..413e01bc41 100644
--- a/src/core/eligibility/registry.ts
+++ b/src/core/eligibility/registry.ts
@@ -31,7 +31,7 @@ export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {
assemble_evidence: 'filtered',
entity: 'labeled', synthesize: 'labeled', think: 'labeled',
search_by_image: 'labeled', list_pages: 'labeled', volunteer_context: 'filtered',
- get_versions: 'labeled', get_raw_data: 'labeled', resolve_slugs: 'labeled',
+ get_versions: 'labeled', get_raw_data: 'labeled', resolve_slugs: 'labeled', whois: 'labeled',
get_recent_salience: 'labeled', find_anomalies: 'labeled', get_recent_transcripts: 'labeled',
find_orphans: 'labeled', traverse_graph: 'labeled', get_links: 'labeled', get_backlinks: 'labeled', rank_entities: 'labeled',
wanted_pages: 'labeled', get_tags: 'labeled', get_ingest_log: 'labeled',
diff --git a/src/core/engine-sql/exact-identity.ts b/src/core/engine-sql/exact-identity.ts
new file mode 100644
index 0000000000..d373ad4444
--- /dev/null
+++ b/src/core/engine-sql/exact-identity.ts
@@ -0,0 +1,101 @@
+/**
+ * GBRA-156: the candidate read behind `whois` (src/core/ops/whois.ts), a
+ * statement builder like graph-rank.ts: the op runs it through `executeRaw`.
+ *
+ * Every arm is an equality probe an existing index serves, so the read never
+ * scans a source's pages:
+ *
+ * title lower(title) = key idx_pages_source_title_lower
+ * basename slug basename = key idx_pages_slug_basename (the slug
+ * grammar already folds accents)
+ * alias page_aliases.alias_norm = key the (source_id, alias_norm) indexes
+ * email frontmatter @> {email|emails} idx_pages_frontmatter (GIN), one
+ * arm per address and shape
+ *
+ * The rows are candidates, not answers: the op keeps a row only when its
+ * title, email or declared alias folds to exactly the query. Visibility: live
+ * pages in unarchived sources of `sourceIds` whose type passes `types`; with
+ * `remote`, unquarantined and (with `excludePrivate`) not private.
+ */
+import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
+import { entityTypePredicateSql, type EntityTypeFilter } from '../schema-pack/entity-types.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { quarantineFilterFragment } from '../quarantine.ts';
+
+export interface ExactIdentityProbes {
+ /** Keys for lower(title), already lowercased. */
+ titleKeys: string[];
+ /** The query as written, lowercased by the database so both sides share one case map. */
+ titleRaw: string;
+ /** Slug basenames (the part after the last '/'). */
+ basenames: string[];
+ /** page_aliases.alias_norm keys. */
+ aliasKeys: string[];
+ /** Exact frontmatter `email` / `emails` values. */
+ emails: string[];
+}
+
+export interface ExactIdentityStatementOpts {
+ probes: ExactIdentityProbes;
+ /** Every probe and every returned page stays inside these sources. */
+ sourceIds: string[];
+ /** The page's type must match; an empty filter matches nothing. */
+ types: EntityTypeFilter;
+ /** Untrusted caller: quarantined and (with excludePrivate) private pages are never candidates. */
+ remote?: { excludePrivate: boolean };
+ limit: number;
+}
+
+export interface ExactIdentityRow {
+ slug: string;
+ source_id: string;
+ title: string | null;
+ type: string | null;
+ email: unknown;
+ emails: unknown;
+ aliases: unknown;
+}
+
+/**
+ * One arm per address and frontmatter shape (`email: x`, `email: [x]`,
+ * `emails: x`, `emails: [x]`). Separate arms, not one OR: each single
+ * containment plans its own GIN bitmap scan, where an OR of several costs
+ * more than a scan of the source and plans one.
+ */
+function emailArms(sourceIds: string[], emails: string[]): SqlFragment[] {
+ return emails.flatMap((v) => [
+ sqlFragment`jsonb_build_object('email', ${v}::text)`,
+ sqlFragment`jsonb_build_object('email', jsonb_build_array(${v}::text))`,
+ sqlFragment`jsonb_build_object('emails', ${v}::text)`,
+ sqlFragment`jsonb_build_object('emails', jsonb_build_array(${v}::text))`,
+ ]).map((shape) => sqlFragment`SELECT p.id FROM pages p WHERE p.source_id = ANY(${sourceIds}::text[]) AND p.frontmatter @> ${shape}`);
+}
+
+export function exactIdentityStatement(opts: ExactIdentityStatementOpts): { text: string; params: unknown[] } {
+ const { probes, sourceIds } = opts;
+ const arms: SqlFragment[] = [sqlFragment`SELECT p.id FROM pages p
+ WHERE p.source_id = ANY(${sourceIds}::text[]) AND lower(p.title) = ANY(${probes.titleKeys}::text[] || lower(${probes.titleRaw}::text))`];
+ if (probes.basenames.length) {
+ arms.push(sqlFragment`SELECT p.id FROM pages p
+ WHERE p.source_id = ANY(${sourceIds}::text[]) AND regexp_replace(p.slug, '^.*/', '') = ANY(${probes.basenames}::text[])`);
+ }
+ if (probes.aliasKeys.length) {
+ arms.push(sqlFragment`SELECT p.id FROM page_aliases a JOIN pages p ON p.source_id = a.source_id AND p.slug = a.slug
+ WHERE a.source_id = ANY(${sourceIds}::text[]) AND a.alias_norm = ANY(${probes.aliasKeys}::text[])`);
+ }
+ arms.push(...emailArms(sourceIds, probes.emails));
+ const privacy = opts.remote?.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('p')}`) : sqlFragment``;
+ const remote = opts.remote ? sqlFragment` AND ${trustedSql(quarantineFilterFragment('p'))}${privacy}` : sqlFragment``;
+ return renderFragment(sqlFragment`
+ WITH cand AS (
+ ${joinFragments(arms, '\n UNION\n ')}
+ )
+ SELECT p.slug, p.source_id, p.title, p.type,
+ p.frontmatter->'email' AS email, p.frontmatter->'emails' AS emails, p.frontmatter->'aliases' AS aliases
+ FROM cand JOIN pages p ON p.id = cand.id
+ WHERE p.deleted_at IS NULL
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id = p.source_id AND s.archived IS NOT TRUE)
+ AND ${entityTypePredicateSql('p', opts.types)}${remote}
+ ORDER BY p.source_id COLLATE "C", p.slug COLLATE "C"
+ LIMIT ${opts.limit}::int`);
+}
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index 428d2b80af..51cc638fc3 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -34,7 +34,7 @@ const OP_AREAS: Record<string, string> = {
get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages',
restore_page: 'pages', purge_deleted_pages: 'pages',
get_versions: 'pages', revert_version: 'pages',
- resolve_slugs: 'pages', get_chunks: 'pages',
+ resolve_slugs: 'pages', whois: 'pages', get_chunks: 'pages',
put_raw_data: 'pages', get_raw_data: 'pages',
fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)
// search
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index a3f3f93578..f824bdb4f6 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -54,6 +54,7 @@ const load_timeline = () => import('./ops/timeline.ts') as Promise<Record<string
const load_transcripts = () => import('./ops/transcripts.ts') as Promise<Record<string, unknown>>;
const load_trust = () => import('./ops/trust.ts') as Promise<Record<string, unknown>>;
const load_usage = () => import('./ops/usage.ts') as Promise<Record<string, unknown>>;
+const load_whois = () => import('./ops/whois.ts') as Promise<Record<string, unknown>>;
const load_verbs = () => import('./verbs.ts') as Promise<Record<string, unknown>>;
export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<string, unknown>>, string]> = {
@@ -135,6 +136,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"get_raw_data": [load_raw_data, "rawDataOperations"],
"resolve_slugs": [load_chunks, "chunksOperations"],
"get_chunks": [load_chunks, "chunksOperations"],
+ "whois": [load_whois, "whoisOperations"],
"log_ingest": [load_ingest_log, "ingestLogOperations"],
"get_ingest_log": [load_ingest_log, "ingestLogOperations"],
"get_usage": [load_usage, "usageOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 2ee7cf1e52..4df139ec11 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -3412,6 +3412,39 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"scope": "read",
"area": "pages"
},
+ {
+ "name": "whois",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "scope": "read",
+ "description": "Exact identity lookup: entity pages whose email, title or declared alias equals an email address or name, ignoring case, accents and quotes. Never fuzzy: empty matches means no exact match; ambiguous means several.",
+ "params": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Email address or name, e.g. '[email protected]'."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Page types; default: the schema pack's entity types."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source; '__all__' spans your sources."
+ }
+ },
+ "cliHints": {
+ "name": "whois",
+ "positional": [
+ "query"
+ ]
+ },
+ "area": "pages"
+ },
{
"name": "log_ingest",
"idempotent": false,
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 07970e14b3..5a5970c8cc 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -85,6 +85,7 @@ import { brainMembershipOperations } from './ops/brain-membership.ts';
import { syncStatusOperations } from './ops/sync-status.ts';
import { rawDataOperations } from './ops/raw-data.ts';
import { chunksOperations } from './ops/chunks.ts';
+import { whoisOperations } from './ops/whois.ts';
import { ingestLogOperations } from './ops/ingest-log.ts';
import { usageOperations } from './ops/usage.ts';
import { filesOperations } from './ops/files.ts';
@@ -170,8 +171,8 @@ export const operations: Operation[] = [
...syncStatusOperations,
// Raw data (put_raw_data, get_raw_data) — ops/raw-data.ts
...rawDataOperations,
- // Resolution & chunks (resolve_slugs, get_chunks) — ops/chunks.ts
- ...chunksOperations,
+ // Resolution & chunks (resolve_slugs, get_chunks) — ops/chunks.ts; whois — ops/whois.ts
+ ...chunksOperations, ...whoisOperations,
// Ingest log (log_ingest, get_ingest_log) — ops/ingest-log.ts
...ingestLogOperations,
// Usage accounting (get_usage, #4218) — ops/usage.ts
diff --git a/src/core/ops/whois.ts b/src/core/ops/whois.ts
new file mode 100644
index 0000000000..59ebdb1e19
--- /dev/null
+++ b/src/core/ops/whois.ts
@@ -0,0 +1,161 @@
+/**
+ * GBRA-156: `whois` — exact identity lookup for triage agents ("is this
+ * sender a known contact?"). Semantic search can rank the wrong person first,
+ * and `entity` resolves fuzzy name variants on purpose; this op answers only
+ * on an exact match: a frontmatter `email` / `emails` value, the page title,
+ * or a declared alias equal to the query, ignoring case, accents (NFKD with
+ * marks stripped, stroke letters folded), compatibility width forms and
+ * surrounding whitespace or quotes. An email query compares whole addresses
+ * case-insensitively, with no accent folding. No nickname, typo, prefix or
+ * semantic matching, and no search fallback: no match is an empty list.
+ *
+ * Candidates come from index-served equality probes
+ * (engine-sql/exact-identity.ts); every candidate is verified here.
+ */
+import type { Operation, OperationContext } from './contract.ts';
+import { invalidParam } from './op-fix.ts';
+import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam } from './context.ts';
+import { foldNonDecomposingLatin } from '../latin-fold.ts';
+import { normalizeAlias, normalizeAliasList } from '../search/alias-normalize.ts';
+import { slugify } from '../entities/resolve.ts';
+import { slugifySegment } from '../sync.ts';
+import { exactIdentityStatement, type ExactIdentityProbes, type ExactIdentityRow } from '../engine-sql/exact-identity.ts';
+
+export const WHOIS_MAX_QUERY_CHARS = 320;
+export const WHOIS_MAX_TYPES = 20;
+/** Candidate rows verified per call; past it the answer says truncated. */
+export const WHOIS_CANDIDATE_CAP = 100;
+
+export type IdentityMatchKind = 'email' | 'title' | 'alias';
+const MATCH_RANK: Record<IdentityMatchKind, number> = { email: 0, title: 1, alias: 2 };
+const TYPE_NAME = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,63}$/;
+const EMAIL = /^[^\s@]+@[^\s@]+$/;
+const EDGE_QUOTES = /^[\s"'`\u2018\u2019\u201c\u201d\u00ab\u00bb]+|[\s"'`\u2018\u2019\u201c\u201d\u00ab\u00bb]+$/g;
+
+/** NFKC, lowercase, whitespace collapsed, surrounding quotes and brackets dropped. */
+function displayKey(raw: string): string {
+ return normalizeAlias(raw).replace(EDGE_QUOTES, '');
+}
+
+/** displayKey with accents stripped (NFKD, combining marks removed) and stroke letters folded. */
+export function identityNameKey(raw: string): string {
+ return foldNonDecomposingLatin(displayKey(raw).normalize('NFKD').replace(/\p{M}/gu, '')).replace(/\s+/g, ' ').trim();
+}
+
+/** The whole address, lowercased, or null when the value is not one email address. */
+export function identityEmailKey(raw: string): string | null {
+ const key = displayKey(raw).replace(/^<|>$/g, '');
+ return EMAIL.test(key) ? key : null;
+}
+
+interface IdentityQuery { email: string | null; name: string }
+
+/** A jsonb column as read: drivers hand it back parsed or as JSON text. */
+function decoded(value: unknown): unknown {
+ if (typeof value !== 'string' || !/^[[{"]/.test(value)) return value;
+ try { return JSON.parse(value) as unknown; } catch { return value; }
+}
+
+function strings(value: unknown): string[] {
+ const v = decoded(value);
+ return (Array.isArray(v) ? v : [v]).filter((s): s is string => typeof s === 'string');
+}
+
+/** The strongest exact match of the query on one candidate page, or null. */
+export function identityMatchKind(query: IdentityQuery, row: Pick<ExactIdentityRow, 'title' | 'email' | 'emails' | 'aliases'>): IdentityMatchKind | null {
+ const same = (v: string) => (query.email ? identityEmailKey(v) === query.email : identityNameKey(v) === query.name);
+ if (query.email && [...strings(row.email), ...strings(row.emails)].some(same)) return 'email';
+ if (row.title && same(row.title)) return 'title';
+ return normalizeAliasList(decoded(row.aliases)).some(same) ? 'alias' : null;
+}
+
+function probesFor(raw: string, query: IdentityQuery): ExactIdentityProbes {
+ const uniq = (values: string[]) => [...new Set(values.filter(Boolean))];
+ const written = displayKey(raw);
+ if (query.email) {
+ const asGiven = raw.normalize('NFKC').replace(EDGE_QUOTES, '').replace(/^<|>$/g, '');
+ return { titleKeys: [query.email], titleRaw: asGiven, basenames: [], aliasKeys: [query.email], emails: uniq([asGiven, query.email]) };
+ }
+ const nfkc = raw.normalize('NFKC').replace(EDGE_QUOTES, '').replace(/\s+/g, ' ');
+ return {
+ titleKeys: uniq([written, query.name]),
+ titleRaw: nfkc,
+ basenames: uniq([slugify(nfkc), slugifySegment(nfkc)]),
+ aliasKeys: uniq([written, query.name]),
+ emails: [],
+ };
+}
+
+function parseParams(ctx: OperationContext, p: Record<string, unknown>) {
+ const bad = (param: string, message: string, example: unknown) =>
+ invalidParam(ctx, 'whois', param, 'whois: ' + message, { def: whois.params[param], example });
+ const raw = typeof p.query === 'string' ? p.query : '';
+ if (raw.length > WHOIS_MAX_QUERY_CHARS) throw bad('query', 'query must be at most ' + WHOIS_MAX_QUERY_CHARS + ' characters', '[email protected]');
+ const query: IdentityQuery = { email: identityEmailKey(raw), name: identityNameKey(raw) };
+ if (!query.name) throw bad('query', 'query must be an email address or a name', '[email protected]');
+ let types: string[] | undefined;
+ if (p.types !== undefined) {
+ const ok = Array.isArray(p.types) && p.types.length >= 1 && p.types.length <= WHOIS_MAX_TYPES && p.types.every(t => typeof t === 'string' && TYPE_NAME.test(t));
+ if (!ok) throw bad('types', 'types must be a list of 1-' + WHOIS_MAX_TYPES + ' page type names', ['person']);
+ types = [...new Set(p.types as string[])].sort();
+ }
+ return { raw, query, types };
+}
+
+const whois: Operation = {
+ name: 'whois',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'retrieval',
+ scope: 'read',
+ description: 'Exact identity lookup: entity pages whose email, title or declared alias equals an email address or name, ignoring case, accents and quotes. '
+ + 'Never fuzzy: empty matches means no exact match; ambiguous means several.',
+ params: {
+ query: { type: 'string', required: true, description: "Email address or name, e.g. '[email protected]'." },
+ types: { type: 'array', items: { type: 'string' }, description: "Page types; default: the schema pack's entity types." },
+ source_id: { type: 'string', description: "One source; '__all__' spans your sources." },
+ },
+ handler: async (ctx, p) => {
+ const params = parseParams(ctx, p);
+ const sourceIdParam = parseSourceIdParam(p.source_id, 'whois', { allowAll: true });
+ const scope = federatedSearchScope(ctx, sourceIdParam);
+ await assertExplicitSourceLive(ctx, sourceIdParam);
+ const sourceIds = scope.sourceIds ?? (scope.sourceId !== undefined
+ ? [scope.sourceId]
+ : (await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(r => r.id));
+ const { resolveEntityTypes } = await import('../schema-pack/entity-types.ts');
+ const resolution = params.types
+ ? { status: 'explicit' as const, filter: { types: params.types, per_source: [] } }
+ : await resolveEntityTypes(ctx.engine, sourceIds);
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const { text, params: values } = exactIdentityStatement({
+ probes: probesFor(params.raw, params.query),
+ sourceIds,
+ types: resolution.filter,
+ ...(ctx.remote !== false ? { remote: { excludePrivate } } : {}),
+ limit: WHOIS_CANDIDATE_CAP + 1,
+ });
+ const rows = await ctx.engine.executeRaw<ExactIdentityRow>(text, values);
+ const matches = rows.slice(0, WHOIS_CANDIDATE_CAP)
+ .map(r => ({ slug: r.slug, source_id: r.source_id, title: r.title, type: r.type, match: identityMatchKind(params.query, r) }))
+ .filter((m): m is typeof m & { match: IdentityMatchKind } => m.match !== null)
+ .sort((a, b) => MATCH_RANK[a.match] - MATCH_RANK[b.match] || (a.source_id < b.source_id ? -1 : a.source_id > b.source_id ? 1 : 0) || (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
+ const notes: string[] = [];
+ if (resolution.status === 'pack_unavailable') notes.push('The schema pack did not load, so no entity types are known: pass types explicitly, e.g. ["person"].');
+ if (rows.length > WHOIS_CANDIDATE_CAP) notes.push('More candidates than ' + WHOIS_CANDIDATE_CAP + ' share this key, so matches may be incomplete: narrow with source_id or types.');
+ return {
+ query: params.raw.trim(),
+ query_kind: params.query.email ? 'email' : 'name',
+ types: params.types ?? 'schema_pack_entity_types',
+ types_status: resolution.status,
+ matches,
+ ambiguous: matches.length > 1,
+ ...(rows.length > WHOIS_CANDIDATE_CAP ? { truncated: true } : {}),
+ ...(notes.length ? { note: notes.join(' ') } : {}),
+ };
+ },
+ cliHints: { name: 'whois', positional: ['query'] },
+};
+
+export const whoisOperations: Operation[] = [whois];
diff --git a/test/e2e/whois-postgres.test.ts b/test/e2e/whois-postgres.test.ts
new file mode 100644
index 0000000000..fa39fa0c47
--- /dev/null
+++ b/test/e2e/whois-postgres.test.ts
@@ -0,0 +1,82 @@
+/**
+ * GBRA-156: `whois` on real Postgres. The unit suite (test/whois.test.ts)
+ * pins matching, ambiguity, validation and the remote read contract on
+ * PGLite; this proves the same statement on pgvector Postgres: exact matches
+ * through every probe, no near-name match, a remote caller blind to
+ * ungranted sources and private or quarantined pages, and index-served
+ * candidate arms.
+ *
+ * Gated by DATABASE_URL — skips gracefully without real Postgres.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { seedWhoisFixture, whoisCandidatePlan } from '../helpers/whois-fixture.ts';
+
+const SKIP = !hasDatabase();
+const describePg = SKIP ? describe.skip : describe;
+
+function mkCtx(overrides: Record<string, unknown> = {}) {
+ return { engine: getEngine(), config: {} as never, logger: { info: () => {}, warn: () => {}, error: () => {} } as never,
+ dryRun: false, remote: false, ...overrides } as never;
+}
+const remote = () => mkCtx({ remote: true, transport: 'stdio', sourceId: 'source-a', auth: { allowedSources: ['source-a'] } });
+
+interface Result { matches: Array<{ slug: string; source_id: string; match: string }>; ambiguous: boolean }
+const whois = (ctx: unknown, params: Record<string, unknown>) => operationsByName['whois']!.handler(ctx as never, params) as Promise<Result>;
+const hits = (r: Result) => r.matches.map(m => `${m.source_id}:${m.slug}:${m.match}`);
+
+describePg('whois on real Postgres (GBRA-156)', () => {
+ beforeAll(async () => {
+ await setupDB();
+ await seedWhoisFixture(getEngine());
+ }, 240_000);
+
+ afterAll(async () => {
+ await teardownDB();
+ });
+
+ test('accents, case, width forms and quotes fold; email compares whole addresses case-insensitively', async () => {
+ for (const query of ['Jose Example', 'JOSÉ EXAMPLE', 'Jose\u3000Example', ' "José Example" ']) {
+ expect(hits(await whois(mkCtx(), { query }))).toEqual(['source-a:people/jose-example:title']);
+ }
+ expect(hits(await whois(mkCtx(), { query: 'José Sample' }))).toEqual(['source-a:people/jose-sample:title']);
+ expect(hits(await whois(mkCtx(), { query: 'Lukasz Example' }))).toEqual(['source-a:people/lukasz-example:title']);
+ expect(hits(await whois(mkCtx(), { query: '[email protected]' }))).toEqual(['source-a:people/alice-example:email']);
+ expect(hits(await whois(mkCtx(), { query: '[email protected]' }))).toEqual(['source-a:people/bob-example:email']);
+ expect(hits(await whois(mkCtx(), { query: '[email protected]' }))).toEqual(['source-a:contacts/contact-0001:email']);
+ });
+
+ test('aliases match as alias, ranked after titles and emails, and ambiguity is explicit', async () => {
+ const byName = await whois(mkCtx(), { query: 'erin example' });
+ expect(hits(byName)).toEqual(['source-a:people/erin-example:title', 'source-b:people/erin-example:title', 'source-a:people/e-example:alias']);
+ expect(byName.ambiguous).toBe(true);
+ expect(hits(await whois(mkCtx(), { query: '[email protected]', source_id: 'source-a' })))
+ .toEqual(['source-a:people/erin-example:email', 'source-a:people/e-example:alias']);
+ });
+
+ test('near names never match and the result is an explicit empty list', async () => {
+ for (const query of ['Matt Example', 'Rob Example', 'Jose Exampel', 'Example', 'Kim Example', '[email protected]']) {
+ expect(await whois(mkCtx(), { query })).toMatchObject({ matches: [], ambiguous: false });
+ }
+ });
+
+ test('a remote caller never sees an ungranted source, a private or quarantined page, a deleted page or an archived source', async () => {
+ expect(hits(await whois(mkCtx(), { query: '[email protected]' }))).toEqual(['source-b:people/frank-example:email']);
+ expect(hits(await whois(mkCtx(), { query: 'Grace Example' }))).toEqual(['source-a:people/grace-example:title']);
+ for (const query of ['[email protected]', 'Frank Example', '[email protected]', 'Grace Example', '[email protected]', 'Heidi Example', '[email protected]', 'Judy Example']) {
+ const res = await whois(remote(), { query });
+ expect(res.matches).toEqual([]);
+ expect(JSON.stringify(res)).not.toMatch(/frank-example|grace-example|heidi-example|ivan-example|judy-example/);
+ }
+ await expect(whois(remote(), { query: 'Frank Example', source_id: 'source-b' })).rejects.toMatchObject({ code: 'permission_denied' });
+ expect(hits(await whois(remote(), { query: 'Erin Example' }))).toEqual(['source-a:people/erin-example:title', 'source-a:people/e-example:alias']);
+ });
+
+ test('every probe is served by an index: no sequential scan of pages or page_aliases', async () => {
+ const plan = await whoisCandidatePlan(getEngine());
+ expect(plan).not.toMatch(/Seq Scan on (pages|page_aliases)\b/);
+ for (const index of ['idx_pages_source_title_lower', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index);
+ expect(plan).toMatch(/(on|using) page_aliases_\w+/);
+ });
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 7400005fa8..592de1f020 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 262702,
- "stdoutSha256": "bfd962a82f16847c7969963ab23410170196491231dcdef214ab3863873b495e",
+ "stdoutBytes": 263785,
+ "stdoutSha256": "88d8d8cd845c772508f60bcbf8048bb0f92e046ee544617d0789b86742dee497",
"toolNames": [
"remember",
"entity",
@@ -83,6 +83,7 @@
"get_raw_data",
"resolve_slugs",
"get_chunks",
+ "whois",
"log_ingest",
"get_ingest_log",
"get_usage",
@@ -4055,6 +4056,43 @@
},
"scope": "read"
},
+ {
+ "description": "Exact identity lookup: entity pages whose email, title or declared alias equals an email address or name, ignoring case, accents and quotes. Never fuzzy: empty matches means no exact match; ambiguous means several.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "whois",
+ "parameters": {
+ "query": "string",
+ "source_id": "string?",
+ "types": "array?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "query": {
+ "description": "Email address or name, e.g. '[email protected]'.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "One source; '__all__' spans your sources.",
+ "type": "string"
+ },
+ "types": {
+ "description": "Page types; default: the schema pack's entity types.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "query"
+ ],
+ "type": "object"
+ },
+ "scope": "read"
+ },
{
"description": "Record one ingestion event (source type, reference, pages updated, summary) in the brain's ingest log. Use after importing or enriching content. Needs write scope.",
"idempotent": false,
diff --git a/test/helpers/whois-fixture.ts b/test/helpers/whois-fixture.ts
new file mode 100644
index 0000000000..0e83e14325
--- /dev/null
+++ b/test/helpers/whois-fixture.ts
@@ -0,0 +1,73 @@
+/**
+ * GBRA-156: the synthetic corpus the `whois` suites share (PGLite unit suite
+ * test/whois.test.ts and the Postgres twin test/e2e/whois-postgres.test.ts).
+ * Sources source-a and source-b; source-c is archived.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { normalizeAliasList } from '../../src/core/search/alias-normalize.ts';
+import { exactIdentityStatement } from '../../src/core/engine-sql/exact-identity.ts';
+
+/**
+ * The plan of a name-and-email candidate read over 5,000 analyzed filler
+ * pages (a third with an email, every one with an alias), so the planner
+ * prices every probe against a real table: an arm no index serves plans a
+ * Seq Scan on pages or page_aliases.
+ */
+export async function whoisCandidatePlan(engine: BrainEngine): Promise<string> {
+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, frontmatter)
+ SELECT CASE WHEN g % 2 = 0 THEN 'source-a' ELSE 'source-b' END, 'people/filler-' || g, 'person', 'Filler Example ' || g,
+ CASE WHEN g % 3 = 0 THEN jsonb_build_object('email', 'filler-' || g || '@widget-co.example') ELSE '{}'::jsonb END
+ FROM generate_series(1, 5000) g`);
+ await engine.executeRaw(`INSERT INTO page_aliases (source_id, alias_norm, slug)
+ SELECT CASE WHEN g % 2 = 0 THEN 'source-a' ELSE 'source-b' END, 'filler alias ' || g, 'people/filler-' || g
+ FROM generate_series(1, 5000) g`);
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE page_aliases');
+ const { text, params } = exactIdentityStatement({
+ probes: {
+ titleKeys: ['jose example'], titleRaw: 'José Example', basenames: ['jose-example'],
+ aliasKeys: ['jose example', '[email protected]'], emails: ['[email protected]'],
+ },
+ sourceIds: ['source-a', 'source-b'],
+ types: { types: ['person'], per_source: [] },
+ remote: { excludePrivate: true },
+ limit: 101,
+ });
+ const rows = await engine.executeRaw<Record<string, string>>('EXPLAIN ' + text, params);
+ return rows.map(r => Object.values(r)[0]).join('\n');
+}
+
+type Fm = Record<string, unknown>;
+
+export async function seedWhoisFixture(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(
+ "INSERT INTO sources(id, name) VALUES ('source-a', 'source-a'), ('source-b', 'source-b'), ('source-c', 'source-c') ON CONFLICT DO NOTHING");
+ const page = async (slug: string, type: string, title: string, frontmatter: Fm = {}, sourceId = 'source-a') => {
+ await engine.putPage(slug, { type, title, compiled_truth: 'Synthetic page.', timeline: '', frontmatter } as never, { sourceId });
+ const aliases = normalizeAliasList(frontmatter.aliases);
+ if (aliases.length) await engine.setPageAliases(slug, sourceId, aliases);
+ };
+ await page('people/jose-example', 'person', 'José Example');
+ await page('people/jose-sample', 'person', 'Jose Sample');
+ await page('people/lukasz-example', 'person', 'Łukasz Example');
+ await page('people/matthew-example', 'person', 'Matthew Example', {}, 'source-a');
+ await page('people/robert-example', 'person', 'Robert Example');
+ await page('people/kim-example', 'person', 'Kim Example-Acme');
+ await page('notes/matt-example-meeting', 'note', 'Matt Example meeting', {});
+ await page('notes/jose-example', 'note', 'José Example');
+ await page('people/alice-example', 'person', 'Alice Example', { email: '[email protected]' });
+ await page('people/bob-example', 'person', 'Bob Example', { emails: ['[email protected]', '[email protected]'] });
+ await page('contacts/contact-0001', 'person', 'Dana Example', {
+ emails: ['[email protected]'], aliases: ['[email protected]', 'Dana Example'],
+ });
+ await page('people/erin-example', 'person', 'Erin Example', { email: '[email protected]' });
+ await page('people/e-example', 'person', 'E. Example', { aliases: ['Erin Example', '[email protected]'] });
+ await page('people/erin-example', 'person', 'Erin Example', {}, 'source-b');
+ await page('people/frank-example', 'person', 'Frank Example', { email: '[email protected]' }, 'source-b');
+ await page('people/grace-example', 'person', 'Grace Example', { email: '[email protected]', visibility: 'private' });
+ await page('people/heidi-example', 'person', 'Heidi Example', { email: '[email protected]', quarantine: 'synthetic' });
+ await page('people/ivan-example', 'person', 'Ivan Example', { email: '[email protected]' });
+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'people/ivan-example'");
+ await page('people/judy-example', 'person', 'Judy Example', { email: '[email protected]' }, 'source-c');
+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'source-c'");
+}
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index 8d14b5cd8d..47ccdd5321 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -107,6 +107,7 @@ const LEDGER: Record<string, string> = {
put_raw_data: 'test/source-id-tx-regression.test.ts',
get_raw_data: 'test/get-page-federated-scope.test.ts',
resolve_slugs: 'test/local-federated-search-scope.test.ts',
+ whois: 'test/whois.test.ts',
get_chunks: 'test/get-page-federated-scope.test.ts',
log_ingest: 'test/e2e/v0_29-mcp-dispatch-pglite.test.ts',
get_ingest_log: 'test/e2e/v0_29-mcp-dispatch-pglite.test.ts',
diff --git a/test/operations-source-isolation-matrix.test.ts b/test/operations-source-isolation-matrix.test.ts
index 8a9312d37b..a0dd5e4582 100644
--- a/test/operations-source-isolation-matrix.test.ts
+++ b/test/operations-source-isolation-matrix.test.ts
@@ -168,6 +168,10 @@ const MATRIX: Row[] = [
{ name: 'get_versions', mode: 'isolated', args: { slug: 'notes/beta-note' } },
{ name: 'get_raw_data', mode: 'isolated', args: { slug: 'notes/beta-note' } },
{ name: 'resolve_slugs', mode: 'isolated', args: { partial: 'beta' } },
+ // whois echoes its query, so the probe reads the matches.
+ { name: 'whois', mode: 'isolated', args: { query: 'BETAMARKER Person' },
+ controlSees: r => leakToken((r as any).matches) !== null,
+ expectScoped: r => { expect(leakToken((r as any).matches)).toBeNull(); } },
{ name: 'get_chunks', mode: 'isolated', args: { slug: 'notes/beta-note' } },
{ name: 'get_ingest_log', mode: 'isolated', args: { limit: 50 } },
{ name: 'find_orphans', mode: 'isolated', args: {} },
diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.ts
index ea01e9cd82..6453a41a77 100644
--- a/test/remote-privacy-sweep.test.ts
+++ b/test/remote-privacy-sweep.test.ts
@@ -179,6 +179,7 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {
get_write_attribution: { slug: WORLD_FENCE_SLUG, versions: true },
get_chunks: { slug: WORLD_FENCE_SLUG },
resolve_slugs: { partial: 'world-page' },
+ whois: { query: WORLD.pageTitle },
volunteer_context: { window: 'Recent discussion about WORLDSWEEP topics and pages.' },
chronicle_day: { date: '2026-01-02' },
chronicle_since: { date: '2020-01-01' },
@@ -267,6 +268,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {
get_versions: 'data',
get_chunks: 'data',
resolve_slugs: 'data',
+ whois: 'data',
get_backlinks: 'data',
traverse_graph: 'data',
rank_entities: 'data',
diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.ts
index fcd9d28e43..2ee1053e05 100644
--- a/test/retrieval-op-redaction.test.ts
+++ b/test/retrieval-op-redaction.test.ts
@@ -137,6 +137,7 @@ const SWEEP: Record<string, Row> = {
search: { args: { query: 'PLANTMARK note body', limit: 20 } },
query: { args: { query: 'PLANTMARK note body', limit: 20 } },
search_exact: { args: { phrase: 'PLANTMARK' } },
+ whois: { args: { query: planted('person') } },
assemble_evidence: { args: { hits: [{ source_id: SRC, slug: 'notes/n1', chunk_id: 0 }], return_unit: 'page' } },
search_by_image: { skip: 'needs image-embedding infra; cross-modal suites own it. Wrapper coverage is the registration test below.' },
get_links: { args: { slug: 'notes/n1' } },
diff --git a/test/whois.test.ts b/test/whois.test.ts
new file mode 100644
index 0000000000..44a4f0cfaa
--- /dev/null
+++ b/test/whois.test.ts
@@ -0,0 +1,180 @@
+/**
+ * GBRA-156: `whois`, the exact identity lookup, on PGLite.
+ *
+ * Protects: an email or name resolves only on an exact match (email, title or
+ * declared alias, ignoring case, accents, width forms and surrounding quotes),
+ * never on a fuzzy, nickname, typo or partial one; ambiguity and an empty
+ * result are explicit; and a remote caller never sees a page in an ungranted
+ * source, a private or quarantined page, a deleted page or an archived source.
+ * The Postgres twin is test/e2e/whois-postgres.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { seedWhoisFixture, whoisCandidatePlan } from './helpers/whois-fixture.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetPrivateVisibilityCacheForTests();
+ await seedWhoisFixture(engine);
+});
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as never,
+ config: {} as never,
+ logger: { info: () => {}, warn: () => {}, error: () => {} } as never,
+ dryRun: false,
+ remote: false,
+ ...overrides,
+ } as OperationContext;
+}
+const local = () => ctxOf();
+const remote = () => ctxOf({ remote: true, transport: 'stdio', sourceId: 'source-a', auth: { allowedSources: ['source-a'] } as never });
+
+interface Match { slug: string; source_id: string; title: string; type: string; match: string }
+interface Result { query_kind: string; matches: Match[]; ambiguous: boolean; types_status: string; note?: string }
+const whois = async (ctx: OperationContext, params: Record<string, unknown>) =>
+ await operationsByName['whois']!.handler(ctx, params) as Result;
+const hits = (r: Result) => r.matches.map(m => `${m.source_id}:${m.slug}:${m.match}`);
+
+describe('whois matches exactly, ignoring case, accents, width and quotes', () => {
+ test.each([
+ ['unaccented query, accented title', 'Jose Example', 'source-a:people/jose-example:title'],
+ ['accented query, unaccented title', 'José Sample', 'source-a:people/jose-sample:title'],
+ ['upper case', 'JOSÉ EXAMPLE', 'source-a:people/jose-example:title'],
+ ['mixed case', 'jOsE eXaMpLe', 'source-a:people/jose-example:title'],
+ ['full-width forms and an ideographic space', 'Jose\u3000Example', 'source-a:people/jose-example:title'],
+ ['surrounding quotes and whitespace', ' "José Example" ', 'source-a:people/jose-example:title'],
+ ['typographic quotes', '\u201cJose Example\u201d', 'source-a:people/jose-example:title'],
+ ['decomposed accent in the query', 'Jose\u0301 Example', 'source-a:people/jose-example:title'],
+ ['stroke letter', 'Lukasz Example', 'source-a:people/lukasz-example:title'],
+ ])('%s', async (_label, query, expected) => {
+ const res = await whois(local(), { query });
+ expect(res.query_kind).toBe('name');
+ expect(hits(res)).toEqual([expected]);
+ expect(res.ambiguous).toBe(false);
+ });
+
+ test.each([
+ ['frontmatter email, query in another case', '[email protected]', 'source-a:people/alice-example:email'],
+ ['second address of an emails list', '[email protected]', 'source-a:people/bob-example:email'],
+ ['angle brackets around the address', '<[email protected]>', 'source-a:people/alice-example:email'],
+ ['mixed-case stored address declared as an alias (contact shape)', '[email protected]', 'source-a:contacts/contact-0001:email'],
+ ])('email: %s', async (_label, query, expected) => {
+ const res = await whois(local(), { query });
+ expect(res.query_kind).toBe('email');
+ expect(hits(res)).toEqual([expected]);
+ });
+
+ test('a declared alias matches and is labeled alias; titles rank before aliases; ambiguity is explicit', async () => {
+ const res = await whois(local(), { query: 'erin example' });
+ expect(hits(res)).toEqual([
+ 'source-a:people/erin-example:title',
+ 'source-b:people/erin-example:title',
+ 'source-a:people/e-example:alias',
+ ]);
+ expect(res.ambiguous).toBe(true);
+ });
+
+ test('an email match ranks before an alias holding the same address', async () => {
+ const res = await whois(local(), { query: '[email protected]', source_id: 'source-a' });
+ expect(hits(res)).toEqual(['source-a:people/erin-example:email', 'source-a:people/e-example:alias']);
+ expect(res.ambiguous).toBe(true);
+ });
+
+ test('source_id narrows the lookup to one source', async () => {
+ expect(hits(await whois(local(), { query: 'Erin Example', source_id: 'source-b' }))).toEqual(['source-b:people/erin-example:title']);
+ });
+});
+
+describe('whois never matches a near name', () => {
+ test.each([
+ ['short given name', 'Matt Example'],
+ ['nickname', 'Rob Example'],
+ ['typo', 'Jose Exampel'],
+ ['surname alone', 'Example'],
+ ['given name alone', 'José'],
+ ['reordered name', 'Example, José'],
+ ['first word of a title', 'Matthew'],
+ ['the slug basename but not the title', 'Kim Example'],
+ ['different address', '[email protected]'],
+ ['address local part only', 'alice'],
+ ])('%s: explicit empty result, not an error', async (_label, query) => {
+ const res = await whois(local(), { query });
+ expect(res.matches).toEqual([]);
+ expect(res.ambiguous).toBe(false);
+ });
+
+ test('a page whose body or longer title mentions the name is not a match', async () => {
+ expect(hits(await whois(local(), { query: 'Matt Example', types: ['note', 'person'] }))).toEqual([]);
+ });
+});
+
+describe('whois type filter', () => {
+ test('defaults to the schema pack entity types; types widens or narrows it', async () => {
+ expect(hits(await whois(local(), { query: 'Jose Example' }))).toEqual(['source-a:people/jose-example:title']);
+ expect(hits(await whois(local(), { query: 'Jose Example', types: ['note'] }))).toEqual(['source-a:notes/jose-example:title']);
+ const both = await whois(local(), { query: 'Jose Example', types: ['person', 'note'] });
+ expect(hits(both)).toEqual(['source-a:notes/jose-example:title', 'source-a:people/jose-example:title']);
+ expect(both.ambiguous).toBe(true);
+ });
+
+ test('invalid parameters are refused', async () => {
+ for (const params of [{ query: '' }, { query: ' "" ' }, { query: 'x'.repeat(321) }, { query: 'Jose Example', types: [] }, { query: 'Jose Example', types: ['bad type'] }]) {
+ await expect(whois(local(), params)).rejects.toBeInstanceOf(OperationError);
+ }
+ });
+});
+
+describe('whois candidate read', () => {
+ test('every probe is served by an index: no sequential scan of pages or page_aliases', async () => {
+ const plan = await whoisCandidatePlan(engine);
+ expect(plan).not.toMatch(/Seq Scan on (pages|page_aliases)\b/);
+ for (const index of ['idx_pages_source_title_lower', 'idx_pages_slug_basename', 'idx_pages_frontmatter']) expect(plan).toContain(index);
+ expect(plan).toMatch(/(on|using) page_aliases_\w+/);
+ });
+});
+
+describe('whois read safety', () => {
+ test('a local caller sees every live page; deleted pages and archived sources never match', async () => {
+ expect(hits(await whois(local(), { query: '[email protected]' }))).toEqual(['source-b:people/frank-example:email']);
+ expect(hits(await whois(local(), { query: '[email protected]' }))).toEqual(['source-a:people/grace-example:email']);
+ expect(hits(await whois(local(), { query: 'Heidi Example' }))).toEqual(['source-a:people/heidi-example:title']);
+ expect(hits(await whois(local(), { query: '[email protected]' }))).toEqual([]);
+ expect(hits(await whois(local(), { query: 'Judy Example' }))).toEqual([]);
+ });
+
+ test('a remote caller never sees a page in an ungranted source', async () => {
+ expect(hits(await whois(remote(), { query: '[email protected]' }))).toEqual([]);
+ expect(hits(await whois(remote(), { query: 'Frank Example', source_id: '__all__' }))).toEqual([]);
+ expect(hits(await whois(remote(), { query: 'Erin Example' }))).toEqual(['source-a:people/erin-example:title', 'source-a:people/e-example:alias']);
+ await expect(whois(remote(), { query: 'Frank Example', source_id: 'source-b' })).rejects.toMatchObject({ code: 'permission_denied' });
+ const scalar = ctxOf({ remote: true, transport: 'stdio', sourceId: 'source-a' });
+ expect(hits(await whois(scalar, { query: 'Frank Example' }))).toEqual([]);
+ });
+
+ test('a remote caller never sees a private or quarantined page, by email, title or alias', async () => {
+ for (const query of ['[email protected]', 'Grace Example', '[email protected]', 'Heidi Example']) {
+ const res = await whois(remote(), { query });
+ expect(res.matches).toEqual([]);
+ expect(JSON.stringify(res)).not.toContain('people/grace-example');
+ expect(JSON.stringify(res)).not.toContain('people/heidi-example');
+ }
+ });
+});