Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): rank_entities op and rank-entities CLI (#7168)

garrytan51887da7cdac
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index f999fc141d..51375c1b95 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: 157 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: 158 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
@@ -122,6 +122,7 @@ Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **S
| `get_backlinks` | Links to a page, ≤500/call; group:"page" by referrer, newest first. | read | yes | |
| `get_links` | List a page's outgoing links (typed edges to other pages). | read | | |
| `list_link_sources` | Link provenances (e.g. | read | yes | |
+| `rank_entities` | Rank pages by graph connections: the most-linked people, companies or other entities. | read | | |
| `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |
| `traverse_graph` | Walk the link graph from a page. | read | yes | |
| `wanted_pages` | Link targets that have no page yet, most-referenced first: each was written as a link but its page does not exist, so no edge exists. | read | | |
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 98f3d3c923..6cc28d0b8d 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -33,6 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.
- `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/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 4b0a0f0253..ebe1e30423 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -16,6 +16,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. F3: `pageStatusValue` (string, trimmed, at most `PAGE_STATUS_MAX_CHARS` 40) is the one `page_status` rule; `readPageStatusByRef` reads it by `(source_id, slug)` in one statement (private pages hidden from untrusted callers, quarantined pages unless allowed) for `readReferrerPage {pageStatus}`, `get_backlinks` link rows and `context_pack` cards and newer-mention rows. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while index-due pages exist (`previewMentionPass`), including every page behind the binary's mention or alias version on an unchanged brain. Post-upgrade does not run the sweep; autopilot's cycle extract phase continues it on its stale-drain budget (`CYCLE_STALE_DRAIN_BUDGET_MS`).
- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode (#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/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/docs/guides/agent-to-gbrain.md b/docs/guides/agent-to-gbrain.md
index c7fcee3bca..16dd01f367 100644
--- a/docs/guides/agent-to-gbrain.md
+++ b/docs/guides/agent-to-gbrain.md
@@ -35,7 +35,8 @@ The two surfaces are **not interchangeable**. Pick by op, not by preference.
## Surface 1 — MCP ops over HTTP (thin-client + OAuth)
Use for any operation that has an MCP equivalent: `search`, `query`,
-`put_page`, `get_page`, `find_experts`, `find_orphans`, `find_anomalies`,
+`put_page`, `get_page`, `find_experts`, `find_orphans`, `rank_entities`
+([graph ranking](graph-ranking.md)), `find_anomalies`,
`get_recent_salience`, `find_trajectory`, and so on. The canonical list is
the set of ops in `src/core/operations.ts` whose `localOnly` flag is unset
(or `false`).
@@ -179,7 +180,7 @@ worker env.
| `search` / `query` | HTTP MCP via thin-client | Has MCP op; OAuth-scoped. |
| `get_page` / `list_pages` | HTTP MCP | Same. |
| `put_page` | HTTP MCP | Same; respects subagent allow-list when applicable. |
-| `find_experts` / `find_orphans` | HTTP MCP | Same. |
+| `find_experts` / `find_orphans` / `rank_entities` | HTTP MCP | Same. |
| `sync` / `embed` / `extract` | Shell job + `inherit:` | Thin-client refused; needs local engine + FS. |
| `dream` | Shell job + `inherit:` | Thin-client refused; synthesis runs on the host. |
| `doctor` | Run directly (any install) | Not refused: thin clients get the remote probe set. |
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7ca67e4726..96405ba6cf 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3129,6 +3129,16 @@ More: [docs/guides/pinned-questions.md#who-can-see-pinned-questions](../../docs/
|---|---|---|---|---|---|---|
| The bounded queue is full; existing requests keep their place. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### rank_entities_timeout
+
+<a id="rank_entities_timeout"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| rank_entities did not finish within its statement deadline (Postgres statement_timeout); nothing was ranked. | The ranking aggregates every edge in scope in one statement; a whole-brain ranking on a large graph can exceed the deadline, and a partial ranking would misstate the top rows. | Narrow the ranking with source_id, types or link_type, then call rank_entities again. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/graph-ranking.md#rank_entities_timeout](../../docs/guides/graph-ranking.md#rank_entities_timeout)
+
### rate_limited
<a id="rate_limited"></a>
diff --git a/docs/guides/graph-ranking.md b/docs/guides/graph-ranking.md
new file mode 100644
index 0000000000..b29cb8b541
--- /dev/null
+++ b/docs/guides/graph-ranking.md
@@ -0,0 +1,99 @@
+# Graph ranking: the most connected entities
+
+`rank_entities` answers "who are the most connected people" or "which companies
+have the most inbound links" in one call. Use it instead of grouping link rows
+yourself: a hand-written count over `links` counts provenance duplicates,
+self-links, deleted pages and redirect stubs, so one entity's duplicate pages
+can take the top rows. `get_backlinks` lists who links to one page and
+`find_experts` ranks pages for a topic; neither ranks the whole graph.
+
+## Try it
+
+```bash
+gbrain rank-entities --types '["person"]' --direction in --limit 10 --json
+```
+
+The same call from an agent over MCP:
+
+```json
+{ "tool": "rank_entities", "arguments": { "types": ["person"], "direction": "in", "limit": 10 } }
+```
+
+A row:
+
+```json
+{ "slug": "people/alice-example", "title": "Alice Example", "type": "person", "source_id": "default",
+ "inbound": 4, "outbound": 1, "neighbors": 5,
+ "folded": [{ "slug": "people/al-example-stub", "reason": "superseded_by" }], "folded_total": 1,
+ "possible_duplicates": [{ "slug": "people/mayor-example", "title": "Mayor Example", "reason": "title_prefix" }] }
+```
+
+## Parameters
+
+| Parameter | Default | Meaning |
+|---|---|---|
+| `direction` | `in` | Rank by inbound edges (`in`), outbound edges (`out`) or both summed (`both`). Every row carries all three counts. |
+| `types` | the schema pack's entity types | Page types to rank, 1 to 20 names. Only the ranked page is filtered; the page on the other end of an edge can be any type. |
+| `source_id` | your current source | One source inside your grant, or `__all__` for every source you can read (locally: the whole brain). |
+| `link_type` | every ranking type | Count only edges of this type, for example `works_at`. A non-ranking type (`amends`) is refused. |
+| `include_mentions` | `false` | Also count mention links (`link_source` `mentions`), as backlink counts do. |
+| `limit` | 20 | Rows to return, 1 to 100, applied after folding. |
+
+A value outside these rules is refused with `invalid_params` and a corrected
+example; nothing is coerced.
+
+## How counting works
+
+- An edge is a distinct (from page, to page, link_type). Several provenance
+ rows for one edge (markdown, frontmatter, manual) count once.
+- Both pages must be live: a link to or from a deleted page does not count.
+ Both pages must be inside the scope.
+- Self-links never count, and neither do non-ranking link types.
+- `inbound` and `outbound` count edges, so two typed links from one page
+ count twice. `neighbors` counts the distinct pages on the other end, in
+ either direction.
+- Rows order by the chosen count, highest first; ties order by slug, then
+ source id, so the same graph always returns the same order.
+- The same slug in two sources is two rows.
+
+## Redirect stubs and duplicates
+
+A retired page (frontmatter `canonical: false`, `superseded_by` or
+`merged_into`) whose redirect chain reaches a live page in the same source
+within five hops is folded into that page: its edges count toward the target,
+edges are deduplicated after folding, and an edge that becomes a self-link is
+dropped. The row lists the folded pages under `folded` (at most 10;
+`folded_total` counts them all).
+
+Title-prefixed person pages that probably name the same person
+(`people/mayor-example` next to `people/alice-example`) are not folded,
+because that would be a guess from the name. The top 10 rows list them under
+`possible_duplicates`, the same field the `entity` card uses;
+`duplicates_checked` says how many rows were checked. `entity.name_variants false`
+turns the check off.
+
+## Remote callers
+
+Over MCP a counted edge needs both pages inside your source grant, neither
+page private (unless the operator set `search.remote_private_pages`) or
+quarantined, both sources unarchived, and the link's origin page, when it has
+one, readable on the same terms. A redirect stub folds only into a target you
+can read: when the target is hidden, the stub keeps its own row and the
+target is never named. A private redirect stub contributes nothing. The local
+CLI keeps the trusted view (deleted pages and the scope still apply).
+
+## Coverage
+
+`coverage.state` is `current`, `behind` (link extraction has pages to catch up,
+so counts cover only pages whose links are extracted; `note` says so) or
+`unread` (the backlog could not be read). It reads the same backlog as doctor's
+`links_extraction_lag` for each source in scope. The local CLI also gets the
+page counts; a remote caller gets the state alone, because the counts include
+pages it cannot read. The brain host catches up with `gbrain extract --stale`.
+
+## rank_entities_timeout
+
+On Postgres the ranking runs under a 15-second statement deadline. A ranking
+of a large whole graph that does not finish is refused with
+`rank_entities_timeout` rather than returning partial counts. Narrow it with
+`source_id`, `types` or `link_type` and call again.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 249aaeb8ed..1fd7cb150a 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -77,6 +77,7 @@ const VETTED_BUILDERS: Record<string, string> = {
stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',
atomRetirementPurgeHold: 'src/core/persistence/atom-retirement-hold.ts: constant #7013 restorable-atom purge-hold predicate over a caller pages alias; no values',
rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',
+ retiredPageSql: 'src/core/entities/resolve.ts: constant retired-page frontmatter predicate over a caller alias; no values',
vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',
temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',
projectionEligibleSql: 'src/core/eligibility/sql.ts: read-eligibility predicate over a caller alias; splices only closed tier and reason-family vocabularies (no values)',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 43b9f4c481..9904613961 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 2832 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
src/core/import-file.ts 2064 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
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 242 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; 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)
+src/core/operations.ts 243 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)
src/core/pglite-engine.ts 3085 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)
src/core/postgres-engine.ts 3107 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)
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/engine-sql/graph-rank.ts b/src/core/engine-sql/graph-rank.ts
new file mode 100644
index 0000000000..8361272c3b
--- /dev/null
+++ b/src/core/engine-sql/graph-rank.ts
@@ -0,0 +1,163 @@
+/**
+ * #7168: the `rank_entities` aggregate, one statement for both engines.
+ *
+ * Counting (the definition the op documents): an edge is a distinct
+ * (from page, to page, link_type) triple over `links` rows whose both
+ * endpoints are live (`deleted_at IS NULL`, get_health's liveness rule,
+ * #6940) and inside the scope. Provenance duplicates (one triple written by
+ * several `link_source` / `origin_page_id` rows) count once; self-links never
+ * count; non-ranking link types (link-ranking-policy.ts) never count; mention
+ * rows (`link_source = 'mentions'`) count only with `includeMentions`, the
+ * backlink-count convention. `inbound` and `outbound` count edges, and
+ * `neighbors` counts the distinct pages on the other end in either direction.
+ *
+ * Folding: a retired page (entities/resolve.ts `retiredPageSql`) whose
+ * `superseded_by` (else `merged_into`) chain reaches a live, non-retired page
+ * in the same source within MAX_RETIREMENT_HOPS hops hands its edges to that
+ * page before counting: edges are deduplicated after folding and an edge that
+ * folds into a self-link is dropped. Every page on the chain and the target
+ * must pass the same endpoint predicate, so a hidden target or hop never
+ * folds: the retired page keeps its own row (it is visible itself, and its
+ * redirect field is its own content), and a hidden retired page contributes
+ * nothing at all. The chain walks only retired pages and stops at the hop
+ * cap, so a cycle terminates.
+ *
+ * Visibility: with `remote` set, every endpoint, chain hop and fold target
+ * must be in `sourceIds`, live, unquarantined, in an unarchived source and
+ * (with `excludePrivate`) not private; a row's origin page, when set, must
+ * pass the same predicate (the backlink-count origin rule in
+ * search/read-enrichment.ts). Without `remote` (trusted local CLI) pages need
+ * only be live and in scope. Every value binds as a parameter; only
+ * code-constant aliases and predicates are spliced.
+ *
+ * Cost: the readable-page predicate runs once per page (the `readable` CTE),
+ * never per link row; edges hash-join links against it. A whole-graph ranking
+ * scans every link in scope, so the op runs it under a statement deadline.
+ * On Postgres 16 with 200k pages and 985k links a brain-wide ranking took
+ * about 3 s locally and remotely.
+ */
+import { 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';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
+import { MAX_RETIREMENT_HOPS, retiredPageSql } from '../entities/resolve.ts';
+
+export type RankDirection = 'in' | 'out' | 'both';
+
+export interface RankEntitiesStatementOpts {
+ direction: RankDirection;
+ /** The ranked page's type must match; an empty filter matches nothing. */
+ types: EntityTypeFilter;
+ /** Both endpoints of every counted edge; undefined is brain-wide (trusted local only). */
+ sourceIds?: string[];
+ linkType?: string;
+ includeMentions: boolean;
+ limit: number;
+ /** Folded slugs returned per row; folded_total counts them all. */
+ foldedCap: number;
+ /** Untrusted caller: authorize endpoints, chain hops, fold targets and link origins. */
+ remote?: { excludePrivate: boolean };
+}
+
+export interface RankEntityRow {
+ slug: string;
+ title: string | null;
+ type: string | null;
+ source_id: string;
+ inbound: number;
+ outbound: number;
+ neighbors: number;
+ folded_total: number;
+ folded: unknown;
+}
+
+const RANK_KEYS = { in: 'd.inbound', out: 'd.outbound', both: '(d.inbound + d.outbound)' } as const;
+
+/** The redirect field of alias rp as a slug: [[people/x|X]], people/x.md and /people/x read people/x (resolve.ts redirectSlug). */
+const REDIRECT_TARGET_SQL = "regexp_replace(regexp_replace(btrim(split_part(regexp_replace(regexp_replace("
+ + "COALESCE(NULLIF(btrim(rp.frontmatter->>'superseded_by'), ''), NULLIF(btrim(rp.frontmatter->>'merged_into'), ''), ''),"
+ + " '^\\[\\[', ''), '\\]\\]$', ''), '|', 1)), '\\.md$', '', 'i'), '^/+', '')";
+
+const FOLD_REASON_SQL = "CASE WHEN btrim(COALESCE(rp.frontmatter->>'superseded_by', '')) <> '' THEN 'superseded_by' ELSE 'merged_into' END";
+
+/** The pages (alias vp) a counted edge, chain hop, fold target or link origin may touch, evaluated once per page. */
+function readablePageSql(opts: RankEntitiesStatementOpts): SqlFragment {
+ const scope = opts.sourceIds ? sqlFragment` AND vp.source_id = ANY(${opts.sourceIds}::text[])` : sqlFragment``;
+ if (!opts.remote) return sqlFragment`vp.deleted_at IS NULL${scope}`;
+ const privacy = opts.remote.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('vp')}`) : sqlFragment``;
+ return sqlFragment`vp.deleted_at IS NULL${scope} AND ${trustedSql(quarantineFilterFragment('vp'))}${privacy}
+ AND EXISTS (SELECT 1 FROM sources rank_source WHERE rank_source.id = vp.source_id AND NOT rank_source.archived)`;
+}
+
+export function rankEntitiesStatement(opts: RankEntitiesStatementOpts): { text: string; params: unknown[] } {
+ const mentions = opts.includeMentions ? sqlFragment`` : sqlFragment` AND l.link_source IS DISTINCT FROM 'mentions'`;
+ const linkType = opts.linkType !== undefined ? sqlFragment` AND l.link_type = ${opts.linkType}` : sqlFragment``;
+ const origin = opts.remote
+ ? sqlFragment` AND (l.origin_page_id IS NULL OR EXISTS (SELECT 1 FROM readable og WHERE og.id = l.origin_page_id))`
+ : sqlFragment``;
+ const key = trustedSql(RANK_KEYS[opts.direction]);
+ return renderFragment(sqlFragment`
+ WITH RECURSIVE readable AS MATERIALIZED (
+ SELECT vp.id FROM pages vp WHERE ${readablePageSql(opts)}
+ ),
+ retired AS MATERIALIZED (
+ SELECT rp.id, rp.source_id, ${trustedSql(REDIRECT_TARGET_SQL)} AS target_slug
+ FROM pages rp
+ JOIN readable rv ON rv.id = rp.id
+ WHERE ${trustedSql(retiredPageSql('rp'))}
+ ),
+ chain AS (
+ SELECT r.id AS start_id, r.source_id, r.target_slug, 1 AS hop FROM retired r WHERE r.target_slug <> ''
+ UNION ALL
+ SELECT c.start_id, c.source_id, r2.target_slug, c.hop + 1
+ FROM chain c
+ JOIN pages nx ON nx.source_id = c.source_id AND nx.slug = c.target_slug
+ JOIN retired r2 ON r2.id = nx.id
+ WHERE c.hop < ${MAX_RETIREMENT_HOPS}::int AND r2.target_slug <> ''
+ ),
+ fold AS MATERIALIZED (
+ SELECT DISTINCT ON (c.start_id) c.start_id AS retired_id, t.id AS target_id
+ FROM chain c
+ JOIN pages t ON t.source_id = c.source_id AND t.slug = c.target_slug
+ JOIN readable tv ON tv.id = t.id
+ WHERE t.id <> c.start_id AND NOT ${trustedSql(retiredPageSql('t'))}
+ ORDER BY c.start_id, c.hop
+ ),
+ edges AS MATERIALIZED (
+ SELECT DISTINCT COALESCE(ff.target_id, l.from_page_id) AS src, COALESCE(ft.target_id, l.to_page_id) AS dst, l.link_type
+ FROM links l
+ JOIN readable a ON a.id = l.from_page_id
+ JOIN readable b ON b.id = l.to_page_id
+ LEFT JOIN fold ff ON ff.retired_id = l.from_page_id
+ LEFT JOIN fold ft ON ft.retired_id = l.to_page_id
+ WHERE l.from_page_id <> l.to_page_id
+ AND ${trustedSql(rankingLinkSql('l'))}${mentions}${linkType}${origin}
+ ),
+ ends AS (
+ SELECT e.dst AS node, e.src AS other, 1 AS inb, 0 AS outb FROM edges e WHERE e.src <> e.dst
+ UNION ALL
+ SELECT e.src AS node, e.dst AS other, 0 AS inb, 1 AS outb FROM edges e WHERE e.src <> e.dst
+ ),
+ d AS (
+ SELECT x.node, sum(x.inb)::int AS inbound, sum(x.outb)::int AS outbound, count(DISTINCT x.other)::int AS neighbors
+ FROM ends x
+ JOIN pages p ON p.id = x.node
+ WHERE ${entityTypePredicateSql('p', opts.types)}
+ GROUP BY x.node
+ )
+ SELECT p.slug, p.title, p.type, p.source_id, d.inbound, d.outbound, d.neighbors,
+ (SELECT count(*)::int FROM fold f WHERE f.target_id = p.id) AS folded_total,
+ (SELECT jsonb_agg(jsonb_build_object('slug', fx.slug, 'reason', fx.reason) ORDER BY fx.slug COLLATE "C")
+ FROM (SELECT rp.slug, ${trustedSql(FOLD_REASON_SQL)} AS reason
+ FROM fold f JOIN pages rp ON rp.id = f.retired_id
+ WHERE f.target_id = p.id
+ ORDER BY rp.slug COLLATE "C"
+ LIMIT ${opts.foldedCap}::int) fx) AS folded
+ FROM d
+ JOIN pages p ON p.id = d.node
+ WHERE ${key} > 0
+ ORDER BY ${key} DESC, p.slug COLLATE "C", p.source_id COLLATE "C"
+ LIMIT ${opts.limit}::int
+ `);
+}
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index b36e9aa2ec..e68760b861 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -213,7 +213,7 @@ export function retiredPageSql(p: string): string {
OR lower(COALESCE(${p}.frontmatter->>'status', '')) ~ '(^|[^a-z])(alias|redirect|redirected)([^a-z]|$)')`;
}
-const MAX_RETIREMENT_HOPS = 5;
+export const MAX_RETIREMENT_HOPS = 5;
/** A frontmatter redirect value as a slug: `[[people/x|X]]`, `people/x.md` and `/people/x` are `people/x`. */
function redirectSlug(value: string): string | null {
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index d53a36762c..91329d64d9 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -545,6 +545,7 @@ export const CODES = {
question_not_found: { class: 'caller', summary: "No pinned question has this id in the caller's scope; ids are source-qualified (default:questions/<slug>).", docs: 'docs/guides/pinned-questions.md#ids-and-scope' },
question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },
queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },
+ rank_entities_timeout: { class: 'caller', summary: "rank_entities did not finish within its statement deadline (Postgres statement_timeout); nothing was ranked.", why: 'The ranking aggregates every edge in scope in one statement; a whole-brain ranking on a large graph can exceed the deadline, and a partial ranking would misstate the top rows.', docs: 'docs/guides/graph-ranking.md#rank_entities_timeout', suggestion: 'Narrow the ranking with source_id, types or link_type, then call rank_entities again.' },
rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },
read_budget_exhausted: { class: 'caller', summary: "A subagent's get_page result came back as a short summary because the job has used its read budget (for the dream patterns child, dream.patterns.child_read_budget_kb).", why: 'A CLI-backed model replays the whole transcript on every turn, so a child that read every page in full filled the model window. The summary keeps the slug, title, type and a short excerpt; writes still work.', docs: 'docs/guides/dream-patterns.md#child-read-budget', suggestion: 'Work from the pages already read and append with add_timeline_entry instead of rewriting a summarized page. An operator who needs more reads raises dream.patterns.child_read_budget_kb (0 turns the budget off).' },
receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index ef2ebfd745..0447100588 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -44,7 +44,7 @@ const OP_AREAS: Record<string, string> = {
// links + graph
add_link: 'links', remove_link: 'links', get_links: 'links',
get_backlinks: 'links', list_link_sources: 'links', traverse_graph: 'links',
- find_orphans: 'links',
+ find_orphans: 'links', rank_entities: 'links',
wanted_pages: 'links',
// timeline
add_timeline_entry: 'timeline', get_timeline: 'timeline',
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 84eadef04d..62490bad58 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -21,6 +21,7 @@ const load_extraction = () => import('./ops/extraction.ts') as Promise<Record<st
const load_facts = () => import('./ops/facts.ts') as Promise<Record<string, unknown>>;
const load_feedback = () => import('./ops/feedback.ts') as Promise<Record<string, unknown>>;
const load_files = () => import('./ops/files.ts') as Promise<Record<string, unknown>>;
+const load_graph_rank = () => import('./ops/graph-rank.ts') as Promise<Record<string, unknown>>;
const load_image = () => import('./ops/image.ts') as Promise<Record<string, unknown>>;
const load_ingest_log = () => import('./ops/ingest-log.ts') as Promise<Record<string, unknown>>;
const load_insights = () => import('./ops/insights.ts') as Promise<Record<string, unknown>>;
@@ -152,6 +153,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"get_agent_job": [load_jobs, "jobsOperations"],
"get_job_stats": [load_jobs, "jobsOperations"],
"find_orphans": [load_orphans, "orphansOperations"],
+ "rank_entities": [load_graph_rank, "graphRankOperations"],
"get_calibration_profile": [load_calibration, "calibrationOperations"],
"takes_list": [load_takes, "takesOperations"],
"takes_search": [load_takes, "takesOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index b0aa76284b..cf20d7a1c5 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -140,6 +140,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "string",
"description": "Source to try first (thin clients send .gbrain-source here); never narrows.",
"fullSurfaceOnly": true
+ },
+ "variants": {
+ "type": "boolean",
+ "description": "Default true: when no exact name matches, resolve one unambiguous name variant (nickname, initial, title, order, surname typo, unique surname; card.match says which). false: exact names only."
}
},
"scope": "read",
@@ -3772,6 +3776,52 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"area": "links"
},
+ {
+ "name": "rank_entities",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "scope": "read",
+ "description": "Rank pages by graph connections: the most-linked people, companies or other entities. Use instead of counting link rows yourself. An edge is a distinct (from page, to page, link_type) between live pages in scope: self-links, links to deleted pages, non-ranking types (amends) and, unless include_mentions, mention rows do not count; several provenance rows for one edge count once. inbound/outbound count edges, neighbors counts distinct linked pages. A redirect stub (canonical: false, superseded_by, merged_into) is folded into its live target in the same source (listed under folded) and its edges count once; title-prefixed person duplicates are listed under possible_duplicates, never merged. Ties order by slug, then source_id. coverage.state is behind when link extraction lags, so counts cover only extracted pages.",
+ "params": {
+ "direction": {
+ "type": "string",
+ "enum": [
+ "in",
+ "out",
+ "both"
+ ],
+ "description": "Rank by 'in' (inbound edges, default), 'out' (outbound edges) or 'both' (inbound + outbound)."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Page types to rank, e.g. ['person']. Default: the schema pack's entity types."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Only this source (it must be inside your source grant); '__all__' spans every source you can read. Both ends of a counted edge stay in scope."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "Count only edges of this link type, e.g. works_at."
+ },
+ "include_mentions": {
+ "type": "boolean",
+ "description": "Also count mention links (link_source mentions); default false."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Rows to return (default 20, max 100)."
+ }
+ },
+ "cliHints": {
+ "name": "rank-entities"
+ },
+ "area": "links"
+ },
{
"name": "get_calibration_profile",
"mutating": false,
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 4d1449b83f..6c5f6a98b4 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -89,6 +89,7 @@ import { usageOperations } from './ops/usage.ts';
import { filesOperations } from './ops/files.ts';
import { jobsOperations } from './ops/jobs.ts';
import { orphansOperations } from './ops/orphans.ts';
+import { graphRankOperations } from './ops/graph-rank.ts';
import { calibrationOperations } from './ops/calibration.ts';
import { salienceOperations } from './ops/salience.ts';
@@ -180,8 +181,8 @@ export const operations: Operation[] = [
// get_job_progress, pause_job, resume_job, replay_job, send_job_message)
// + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts
...jobsOperations,
- // Orphans (find_orphans) — ops/orphans.ts
- ...orphansOperations,
+ // Orphans (find_orphans) — ops/orphans.ts; rank_entities — ops/graph-rank.ts
+ ...orphansOperations, ...graphRankOperations,
// v0.36.1.0 (T7) — Hindsight calibration wave (get_calibration_profile) —
// ops/calibration.ts
...calibrationOperations,
diff --git a/src/core/ops/graph-rank.ts b/src/core/ops/graph-rank.ts
new file mode 100644
index 0000000000..b7a590d270
--- /dev/null
+++ b/src/core/ops/graph-rank.ts
@@ -0,0 +1,223 @@
+/**
+ * #7168: `rank_entities` — graph aggregates without hand-written SQL over
+ * `links`. Agents asked "who are the most connected people" by grouping link
+ * rows themselves, and one owner's duplicate pages took the top rows. This op
+ * ranks pages by inbound, outbound or total edges with one aggregate
+ * statement (engine-sql/graph-rank.ts holds the counting and folding rules),
+ * folds redirect stubs into their live target, flags title-prefixed person
+ * duplicates without merging them, and says when link extraction is behind.
+ *
+ * get_backlinks answers "who links to this page" for one page and
+ * find_experts ranks pages for a topic; neither ranks the whole graph.
+ */
+import { opError, type Operation, type OperationContext } from './contract.ts';
+import { invalidParam } from './op-fix.ts';
+import { assertSourceInCallerScope, linkReadScopeOpts, resolveRequestedScope, sourceScopeOpts } from './context.ts';
+import { ALL_SOURCES } from '../source-id.ts';
+import { NON_RANKING_LINK_TYPES } from '../link-ranking-policy.ts';
+import { rankEntitiesStatement, type RankDirection, type RankEntityRow } from '../engine-sql/graph-rank.ts';
+import type { EntityTypeFilter } from '../schema-pack/entity-types.ts';
+
+export const RANK_ENTITIES_DEFAULT_LIMIT = 20;
+export const RANK_ENTITIES_MAX_LIMIT = 100;
+export const RANK_ENTITIES_MAX_TYPES = 20;
+/** Statement deadline (Postgres; PGLite has no statement timeout). */
+export const RANK_ENTITIES_STATEMENT_MS = 15_000;
+/** Folded slugs listed per row; folded_total counts them all. */
+export const RANK_ENTITIES_FOLDED_CAP = 10;
+/** Top rows checked for title-prefixed person duplicates, and the wall-clock budget for those checks. */
+export const RANK_ENTITIES_DUPLICATE_ROWS = 10;
+const DUPLICATE_BUDGET_MS = 3_000;
+/** Above this many sources in scope, coverage is not read. */
+const COVERAGE_SOURCE_CAP = 20;
+const NAME = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,63}$/;
+const DIRECTIONS = ['in', 'out', 'both'] as const;
+
+interface PossibleDuplicate { slug: string; title: string; reason: string }
+
+interface RankedEntity {
+ slug: string;
+ title: string;
+ type: string | null;
+ source_id: string;
+ inbound: number;
+ outbound: number;
+ neighbors: number;
+ folded?: Array<{ slug: string; reason: string }>;
+ folded_total?: number;
+ possible_duplicates?: PossibleDuplicate[];
+}
+
+type Coverage =
+ | { state: 'current' | 'behind'; total?: number; actionable?: number; attendance_blocked?: number; held?: number; mention_due?: number | null }
+ | { state: 'unread'; reason: 'too_many_sources' | 'read_failed' };
+
+function parseParams(ctx: OperationContext, p: Record<string, unknown>) {
+ const bad = (param: string, message: string, example: unknown, choices?: readonly string[]) =>
+ invalidParam(ctx, 'rank_entities', param, `rank_entities: ${message}`, { def: rank_entities.params[param], example, ...(choices ? { choices } : {}) });
+ const direction = p.direction ?? 'in';
+ if (!DIRECTIONS.includes(direction as RankDirection)) throw bad('direction', "direction must be 'in', 'out' or 'both'", 'in', DIRECTIONS);
+ let types: string[] | undefined;
+ if (p.types !== undefined) {
+ const ok = Array.isArray(p.types) && p.types.length >= 1 && p.types.length <= RANK_ENTITIES_MAX_TYPES
+ && p.types.every(t => typeof t === 'string' && NAME.test(t));
+ if (!ok) throw bad('types', `types must be a list of 1-${RANK_ENTITIES_MAX_TYPES} page type names (letters, digits, _ . : / -)`, ['person']);
+ types = [...new Set(p.types as string[])].sort();
+ }
+ const linkType = p.link_type;
+ if (linkType !== undefined && (typeof linkType !== 'string' || !NAME.test(linkType))) {
+ throw bad('link_type', 'link_type must be one link type name (letters, digits, _ . : / -)', 'works_at');
+ }
+ if (typeof linkType === 'string' && NON_RANKING_LINK_TYPES.includes(linkType)) {
+ throw bad('link_type', `link type '${linkType}' takes no part in ranking (link-ranking-policy); read it with get_links or get_backlinks`, 'works_at');
+ }
+ if (p.include_mentions !== undefined && typeof p.include_mentions !== 'boolean') throw bad('include_mentions', 'include_mentions must be true or false', true);
+ const limit = p.limit ?? RANK_ENTITIES_DEFAULT_LIMIT;
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > RANK_ENTITIES_MAX_LIMIT) {
+ throw bad('limit', `limit must be an integer from 1 to ${RANK_ENTITIES_MAX_LIMIT}`, RANK_ENTITIES_DEFAULT_LIMIT);
+ }
+ const sourceId = p.source_id;
+ if (sourceId !== undefined && (typeof sourceId !== 'string' || sourceId.trim() === '')) throw bad('source_id', 'source_id must be a source id', 'default');
+ return { direction: direction as RankDirection, types, linkType: linkType as string | undefined, includeMentions: p.include_mentions === true, limit, sourceId: sourceId as string | undefined };
+}
+
+/** Both endpoints of every counted edge stay inside this list; undefined is brain-wide. Remote scalar scopes are promoted (linkReadScopeOpts). */
+function rankScope(ctx: OperationContext, named: string | undefined): string[] | undefined {
+ let scope: { sourceId?: string; sourceIds?: string[] };
+ if (named === ALL_SOURCES) scope = resolveRequestedScope(ctx, named);
+ else if (named !== undefined) {
+ assertSourceInCallerScope(ctx, named);
+ scope = { sourceId: named };
+ } else scope = sourceScopeOpts(ctx);
+ scope = linkReadScopeOpts(ctx, scope);
+ if (scope.sourceIds?.length) return [...new Set(scope.sourceIds)].sort();
+ return scope.sourceId ? [scope.sourceId] : undefined;
+}
+
+function typesFor(filter: EntityTypeFilter, sourceId: string): string[] {
+ return filter.per_source.find(s => s.source_id === sourceId)?.types ?? filter.types;
+}
+
+function parseFolded(value: unknown): Array<{ slug: string; reason: string }> {
+ const list = typeof value === 'string' ? JSON.parse(value) : value;
+ return Array.isArray(list) ? list.map(f => ({ slug: String(f.slug), reason: String(f.reason) })) : [];
+}
+
+async function readCoverage(ctx: OperationContext, sourceIds: string[] | undefined, includeMentions: boolean): Promise<Coverage> {
+ const targets: Array<string | undefined> = sourceIds ?? [undefined];
+ if (targets.length > COVERAGE_SOURCE_CAP) return { state: 'unread', reason: 'too_many_sources' };
+ const { readExtractionLag } = await import('../extraction-lag.ts');
+ const sum = { total: 0, actionable: 0, attendance_blocked: 0, held: 0, mention_due: null as number | null };
+ try {
+ for (const sourceId of targets) {
+ const lag = await readExtractionLag(ctx.engine, sourceId ? { sourceId } : {});
+ sum.total += lag.total;
+ sum.actionable += lag.actionable;
+ sum.attendance_blocked += lag.attendance_blocked;
+ sum.held += lag.held ?? 0;
+ if (lag.mention_due !== null) sum.mention_due = (sum.mention_due ?? 0) + lag.mention_due;
+ }
+ } catch {
+ return { state: 'unread', reason: 'read_failed' };
+ }
+ const state = sum.actionable > 0 || (includeMentions && (sum.mention_due ?? 0) > 0) ? 'behind' : 'current';
+ // The counts include pages a remote caller cannot read, so remote callers get the state alone.
+ return ctx.remote === false ? { state, ...sum } : { state };
+}
+
+async function attachDuplicates(ctx: OperationContext, rows: RankedEntity[], filter: EntityTypeFilter, excludePrivate: boolean): Promise<number> {
+ const { nameVariantsEnabled, readPossibleDuplicates } = await import('../verbs/entity-variants.ts');
+ if (!(await nameVariantsEnabled(ctx.engine))) return 0;
+ const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const deadline = Date.now() + DUPLICATE_BUDGET_MS;
+ let checked = 0;
+ for (const row of rows.slice(0, RANK_ENTITIES_DUPLICATE_ROWS)) {
+ if (Date.now() > deadline) break;
+ checked++;
+ const duplicates = await readPossibleDuplicates(ctx.engine, row.source_id, { slug: row.slug, title: row.title, type: row.type, frontmatter: null }, {
+ selectColumns: 'slug, title, type, frontmatter',
+ entityTypes: new Set(typesFor(filter, row.source_id)),
+ omitQuarantined: ctx.remote !== false,
+ privatePredicate: excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '',
+ retirementPrivacy: excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '',
+ });
+ if (duplicates.length) row.possible_duplicates = duplicates;
+ }
+ return checked;
+}
+
+const rank_entities: Operation = {
+ name: 'rank_entities',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'retrieval',
+ scope: 'read',
+ description: 'Rank pages by graph connections: the most-linked people, companies or other entities. Use instead of counting link rows yourself. '
+ + 'An edge is a distinct (from page, to page, link_type) between live pages in scope: self-links, links to deleted pages, non-ranking types (amends) and, unless include_mentions, mention rows do not count; several provenance rows for one edge count once. '
+ + 'inbound/outbound count edges, neighbors counts distinct linked pages. A redirect stub (canonical: false, superseded_by, merged_into) is folded into its live target in the same source (listed under folded) and its edges count once; '
+ + 'title-prefixed person duplicates are listed under possible_duplicates, never merged. Ties order by slug, then source_id. coverage.state is behind when link extraction lags, so counts cover only extracted pages.',
+ params: {
+ direction: { type: 'string', enum: [...DIRECTIONS], description: "Rank by 'in' (inbound edges, default), 'out' (outbound edges) or 'both' (inbound + outbound)." },
+ types: { type: 'array', items: { type: 'string' }, description: "Page types to rank, e.g. ['person']. Default: the schema pack's entity types." },
+ source_id: { type: 'string', description: "Only this source (it must be inside your source grant); '__all__' spans every source you can read. Both ends of a counted edge stay in scope." },
+ link_type: { type: 'string', description: 'Count only edges of this link type, e.g. works_at.' },
+ include_mentions: { type: 'boolean', description: 'Also count mention links (link_source mentions); default false.' },
+ limit: { type: 'number', description: `Rows to return (default ${RANK_ENTITIES_DEFAULT_LIMIT}, max ${RANK_ENTITIES_MAX_LIMIT}).` },
+ },
+ handler: async (ctx, p) => {
+ const params = parseParams(ctx, p);
+ const sourceIds = rankScope(ctx, params.sourceId);
+ 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 ?? null);
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const { text, params: values } = rankEntitiesStatement({
+ direction: params.direction,
+ types: resolution.filter,
+ ...(sourceIds ? { sourceIds } : {}),
+ ...(params.linkType !== undefined ? { linkType: params.linkType } : {}),
+ includeMentions: params.includeMentions,
+ limit: params.limit,
+ foldedCap: RANK_ENTITIES_FOLDED_CAP,
+ ...(ctx.remote !== false ? { remote: { excludePrivate } } : {}),
+ });
+ let raw: RankEntityRow[];
+ try {
+ raw = await ctx.engine.executeRaw<RankEntityRow>(text, values, { timeoutMs: RANK_ENTITIES_STATEMENT_MS });
+ } catch (e) {
+ const { isStatementTimeoutError } = await import('../retry-matcher.ts');
+ if (!isStatementTimeoutError(e)) throw e;
+ throw opError('rank_entities_timeout', `rank_entities: the ranking did not finish within ${RANK_ENTITIES_STATEMENT_MS / 1000} s`,
+ 'Narrow the ranking: pass source_id, types (e.g. ["person"]) or link_type, then call rank_entities again.');
+ }
+ const entities: RankedEntity[] = raw.map(r => {
+ const folded = Number(r.folded_total) > 0 ? { folded: parseFolded(r.folded), folded_total: Number(r.folded_total) } : {};
+ return { slug: r.slug, title: r.title ?? r.slug, type: r.type, source_id: r.source_id,
+ inbound: Number(r.inbound), outbound: Number(r.outbound), neighbors: Number(r.neighbors), ...folded };
+ });
+ const duplicatesChecked = await attachDuplicates(ctx, entities, resolution.filter, excludePrivate);
+ const coverage = await readCoverage(ctx, sourceIds, params.includeMentions);
+ 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 (coverage.state === 'behind') notes.push('Link extraction is behind: counts cover only pages whose links are extracted (the brain host runs gbrain extract --stale to catch up).');
+ if (coverage.state === 'unread') notes.push('Link-extraction coverage was not read, so counts may cover only part of the brain.');
+ return {
+ direction: params.direction,
+ ranked_by: params.direction === 'in' ? 'inbound' : params.direction === 'out' ? 'outbound' : 'inbound+outbound',
+ types: params.types ?? 'schema_pack_entity_types',
+ types_status: resolution.status,
+ ...(params.linkType !== undefined ? { link_type: params.linkType } : {}),
+ include_mentions: params.includeMentions,
+ limit: params.limit,
+ entities,
+ duplicates_checked: duplicatesChecked,
+ coverage,
+ ...(notes.length ? { note: notes.join(' ') } : {}),
+ };
+ },
+ cliHints: { name: 'rank-entities' },
+};
+
+export const graphRankOperations: Operation[] = [rank_entities];
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index fc9e438d91..0845d751e3 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": 252798,
- "stdoutSha256": "71b348f0e16ec33eeb7b856a2fa24821a5f971503416d541e00226572381ab56",
+ "stdoutBytes": 255567,
+ "stdoutSha256": "6e03322c34dc19d7996345e9127c6954e637bdeec38ff3abab2f08db5dfed8db",
"toolNames": [
"remember",
"entity",
@@ -102,6 +102,7 @@
"get_agent_job",
"get_job_stats",
"find_orphans",
+ "rank_entities",
"get_calibration_profile",
"takes_list",
"takes_search",
@@ -306,7 +307,8 @@
"name": "string?",
"names": "array?",
"prefer_source_id": "string?",
- "source_id": "string?"
+ "source_id": "string?",
+ "variants": "boolean?"
},
"required_scopes": [],
"schema": {
@@ -329,6 +331,10 @@
"source_id": {
"description": "Read only this source. Default: your source first, then every source you can read.",
"type": "string"
+ },
+ "variants": {
+ "description": "Default true: when no exact name matches, resolve one unambiguous name variant (nickname, initial, title, order, surname typo, unique surname; card.match says which). false: exact names only.",
+ "type": "boolean"
}
},
"required": [],
@@ -4559,6 +4565,61 @@
},
"scope": "read"
},
+ {
+ "description": "Rank pages by graph connections: the most-linked people, companies or other entities. Use instead of counting link rows yourself. An edge is a distinct (from page, to page, link_type) between live pages in scope: self-links, links to deleted pages, non-ranking types (amends) and, unless include_mentions, mention rows do not count; several provenance rows for one edge count once. inbound/outbound count edges, neighbors counts distinct linked pages. A redirect stub (canonical: false, superseded_by, merged_into) is folded into its live target in the same source (listed under folded) and its edges count once; title-prefixed person duplicates are listed under possible_duplicates, never merged. Ties order by slug, then source_id. coverage.state is behind when link extraction lags, so counts cover only extracted pages.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "rank_entities",
+ "parameters": {
+ "direction": "string?",
+ "include_mentions": "boolean?",
+ "limit": "number?",
+ "link_type": "string?",
+ "source_id": "string?",
+ "types": "array?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "direction": {
+ "description": "Rank by 'in' (inbound edges, default), 'out' (outbound edges) or 'both' (inbound + outbound).",
+ "enum": [
+ "in",
+ "out",
+ "both"
+ ],
+ "type": "string"
+ },
+ "include_mentions": {
+ "description": "Also count mention links (link_source mentions); default false.",
+ "type": "boolean"
+ },
+ "limit": {
+ "description": "Rows to return (default 20, max 100).",
+ "type": "number"
+ },
+ "link_type": {
+ "description": "Count only edges of this link type, e.g. works_at.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Only this source (it must be inside your source grant); '__all__' spans every source you can read. Both ends of a counted edge stay in scope.",
+ "type": "string"
+ },
+ "types": {
+ "description": "Page types to rank, e.g. ['person']. Default: the schema pack's entity types.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "scope": "read"
+ },
{
"description": "Read the active calibration profile for a holder. Returns the latest row from calibration_profiles (per-source, per-holder) including Brier score, accuracy, pattern statements, and active bias tags. Source-scoped via sourceScopeOpts — federated_read scopes see the union of allowed sources, scalar source-bound clients see only their source. Returns null when no profile exists yet (cold-brain branch: builds after 5+ resolved takes + a calibration_profile phase run).",
"idempotent": true,
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index 4ea1e697f7..e62b4da677 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -122,6 +122,7 @@ const LEDGER: Record<string, string> = {
get_agent_job: 'test/get-agent-job.test.ts',
get_job_stats: 'test/get-job-stats-op.test.ts',
find_orphans: 'test/orphans-source-scope.test.ts',
+ rank_entities: 'test/rank-entities.test.ts',
wanted_pages: 'test/wanted-links.test.ts',
get_calibration_profile: 'test/calibration-cli.test.ts',
takes_list: 'test/takes-mcp-allowlist.test.ts',
diff --git a/test/operations-source-isolation-matrix.test.ts b/test/operations-source-isolation-matrix.test.ts
index 3a1056d1e7..cce15c8755 100644
--- a/test/operations-source-isolation-matrix.test.ts
+++ b/test/operations-source-isolation-matrix.test.ts
@@ -167,6 +167,7 @@ const MATRIX: Row[] = [
{ 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: {} },
+ { name: 'rank_entities', mode: 'isolated', args: {} },
{ name: 'wanted_pages', mode: 'isolated', args: {} },
{ name: 'takes_list', mode: 'isolated', args: { limit: 50 } },
{ name: 'takes_search', mode: 'isolated', args: { query: 'BETAMARKER', limit: 20 } },
diff --git a/test/rank-entities.test.ts b/test/rank-entities.test.ts
new file mode 100644
index 0000000000..0b37b1e716
--- /dev/null
+++ b/test/rank-entities.test.ts
@@ -0,0 +1,289 @@
+/**
+ * #7168: rank_entities — counting, folding, filters, validation and the
+ * remote visibility contract, on PGLite.
+ */
+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 { operations, type OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.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 engine.executeRaw("INSERT INTO sources(id, name) VALUES ('source-a', 'source-a'), ('source-b', 'source-b') ON CONFLICT DO NOTHING");
+});
+
+const op = operations.find(o => o.name === 'rank_entities')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: { info: () => {}, warn: () => {}, error: () => {} } as any,
+ dryRun: false,
+ remote: false,
+ sourceId: 'source-a',
+ ...overrides,
+ } as OperationContext;
+}
+const local = () => ctxOf();
+const remote = () => ctxOf({ remote: true, transport: 'stdio', auth: { allowedSources: ['source-a'] } as any });
+
+interface Row { slug: string; source_id: string; inbound: number; outbound: number; neighbors: number; folded?: Array<{ slug: string; reason: string }>; folded_total?: number }
+async function rank(ctx: OperationContext, params: Record<string, unknown> = {}): Promise<{ entities: Row[]; coverage: { state: string }; note?: string; types_status: string }> {
+ return await op.handler(ctx, { types: ['person', 'company'], ...params }) as any;
+}
+const brief = (rows: Row[]) => rows.map(r => ({ slug: r.slug, source_id: r.source_id, inbound: r.inbound, outbound: r.outbound, neighbors: r.neighbors, folded: r.folded ?? [] }));
+
+async function page(slug: string, type: string, sourceId = 'source-a', frontmatter: Record<string, unknown> = {}) {
+ await engine.putPage(slug, { type, title: slug.split('/').pop()!, compiled_truth: 'Synthetic page.', frontmatter } as any, { sourceId });
+}
+async function link(from: string, to: string, opts: { type?: string; source?: string; origin?: string; fromSource?: string; toSource?: string } = {}) {
+ await engine.addLink(from, to, '', opts.type ?? 'references', opts.source ?? 'manual', opts.origin, undefined,
+ { fromSourceId: opts.fromSource ?? 'source-a', toSourceId: opts.toSource ?? 'source-a', ...(opts.origin ? { originSourceId: opts.fromSource ?? 'source-a' } : {}) });
+}
+
+/** The base graph in source-a. */
+async function seedBase() {
+ for (const p of ['people/alice-example', 'people/bob-example', 'people/carol-example']) await page(p, 'person');
+ await page('companies/acme-example', 'company');
+ for (const n of ['notes/n1', 'notes/n2', 'notes/n3', 'notes/n4']) await page(n, 'note');
+ await page('people/al-stub', 'person', 'source-a', { superseded_by: '[[people/alice-example|Alice]]' });
+ for (const n of ['notes/n1', 'notes/n2', 'notes/n3']) await link(n, 'people/alice-example');
+ await link('notes/n1', 'people/alice-example', { source: 'markdown' });
+ for (const n of ['notes/n1', 'notes/n2']) { await link(n, 'people/bob-example'); await link(n, 'people/carol-example'); }
+ await link('notes/n4', 'people/al-stub');
+ await link('notes/n1', 'people/al-stub');
+ await link('people/alice-example', 'companies/acme-example', { type: 'works_at' });
+ await link('people/alice-example', 'companies/acme-example', { type: 'mentions', source: 'mentions' });
+ await link('people/bob-example', 'companies/acme-example', { type: 'mentions', source: 'mentions' });
+ await link('people/alice-example', 'people/alice-example');
+}
+
+describe('rank_entities counting', () => {
+ test('ranks by inbound edges with deterministic ties, folding a redirect stub without double counting', async () => {
+ await seedBase();
+ const { entities } = await rank(local());
+ expect(brief(entities)).toEqual([
+ { slug: 'people/alice-example', source_id: 'source-a', inbound: 4, outbound: 1, neighbors: 5, folded: [{ slug: 'people/al-stub', reason: 'superseded_by' }] },
+ { slug: 'companies/acme-example', source_id: 'source-a', inbound: 1, outbound: 0, neighbors: 1, folded: [] },
+ { slug: 'people/bob-example', source_id: 'source-a', inbound: 2, outbound: 0, neighbors: 2, folded: [] },
+ { slug: 'people/carol-example', source_id: 'source-a', inbound: 2, outbound: 0, neighbors: 2, folded: [] },
+ ].sort((a, b) => b.inbound - a.inbound || (a.slug < b.slug ? -1 : 1)));
+ expect(entities.some(r => r.slug === 'people/al-stub')).toBe(false);
+ expect(entities[0]!.folded_total).toBe(1);
+ });
+
+ test('direction out and both pick the ranking key', async () => {
+ await seedBase();
+ const out = await rank(local(), { direction: 'out' });
+ expect(brief(out.entities).map(r => [r.slug, r.outbound])).toEqual([['people/alice-example', 1]]);
+ const both = await rank(local(), { direction: 'both' });
+ expect(both.entities.map(r => [r.slug, r.inbound + r.outbound])).toEqual([
+ ['people/alice-example', 5], ['people/bob-example', 2], ['people/carol-example', 2], ['companies/acme-example', 1],
+ ]);
+ });
+
+ test('type filter, link_type filter and include_mentions', async () => {
+ await seedBase();
+ expect((await rank(local(), { types: ['company'] })).entities.map(r => r.slug)).toEqual(['companies/acme-example']);
+ expect((await rank(local(), { link_type: 'works_at' })).entities.map(r => [r.slug, r.inbound])).toEqual([['companies/acme-example', 1]]);
+ const withMentions = await rank(local(), { include_mentions: true, types: ['company'] });
+ expect(brief(withMentions.entities)).toEqual([{ slug: 'companies/acme-example', source_id: 'source-a', inbound: 3, outbound: 0, neighbors: 2, folded: [] }]);
+ });
+
+ test('default types come from the schema pack entity types', async () => {
+ await seedBase();
+ const res = await op.handler(local(), {}) as any;
+ expect(res.types_status).toBe('resolved');
+ expect(res.entities.some((r: Row) => r.slug.startsWith('notes/'))).toBe(false);
+ expect(res.entities[0].slug).toBe('people/alice-example');
+ });
+
+ test('self-links and links to or from deleted pages do not count', async () => {
+ await seedBase();
+ const before = brief((await rank(local(), { direction: 'both' })).entities);
+ await page('notes/n5', 'note');
+ await link('notes/n5', 'people/bob-example');
+ await page('companies/gone-example', 'company');
+ await link('people/alice-example', 'companies/gone-example');
+ await link('people/carol-example', 'people/carol-example');
+ await engine.softDeletePage('notes/n5', { sourceId: 'source-a' });
+ await engine.softDeletePage('companies/gone-example', { sourceId: 'source-a' });
+ expect(brief((await rank(local(), { direction: 'both' })).entities)).toEqual(before);
+ });
+
+ test('an edge that folds into a self-link is dropped', async () => {
+ await seedBase();
+ await link('people/al-stub', 'people/alice-example');
+ const alice = (await rank(local(), { direction: 'both' })).entities.find(r => r.slug === 'people/alice-example')!;
+ expect([alice.inbound, alice.outbound]).toEqual([4, 1]);
+ });
+
+ test('the same slug in two sources stays two rows; a stub folds only within its own source', async () => {
+ await seedBase();
+ await page('people/alice-example', 'person', 'source-b');
+ await page('notes/b1', 'note', 'source-b');
+ await page('people/al-stub', 'person', 'source-b', { superseded_by: 'people/alice-example' });
+ await link('notes/b1', 'people/al-stub', { fromSource: 'source-b', toSource: 'source-b' });
+ const { entities } = await rank(local(), { source_id: '__all__' });
+ const alices = entities.filter(r => r.slug === 'people/alice-example');
+ expect(alices.map(r => [r.source_id, r.inbound, r.folded?.map(f => f.slug)])).toEqual([
+ ['source-a', 4, ['people/al-stub']], ['source-b', 1, ['people/al-stub']],
+ ]);
+ expect((await rank(local(), { source_id: 'source-b' })).entities.map(r => [r.slug, r.source_id])).toEqual([['people/alice-example', 'source-b']]);
+ });
+
+ test('limit caps rows after folding', async () => {
+ await seedBase();
+ expect((await rank(local(), { limit: 1 })).entities.map(r => r.slug)).toEqual(['people/alice-example']);
+ });
+
+ test('coverage says when link extraction is behind', async () => {
+ await seedBase();
+ const res = await rank(local());
+ expect(res.coverage.state).toBe('behind');
+ expect(res.note).toContain('counts cover only pages whose links are extracted');
+ });
+});
+
+describe('rank_entities remote visibility', () => {
+ test('private pages, private-origin links, quarantined pages and foreign-source pages change no remote counts, rows or folded entries', async () => {
+ await seedBase();
+ const baseline = brief((await rank(remote(), { direction: 'both' })).entities);
+ expect(baseline).toEqual(brief((await rank(local(), { direction: 'both' })).entities));
+ const cases: Array<[string, () => Promise<void>]> = [
+ ['private page', async () => {
+ await page('notes/secret', 'note', 'source-a', { visibility: 'private' });
+ await link('notes/secret', 'people/bob-example');
+ await page('people/private-person', 'person', 'source-a', { visibility: 'private' });
+ await link('notes/n3', 'people/private-person');
+ }],
+ ['private-origin link', async () => {
+ await page('notes/private-origin', 'note', 'source-a', { visibility: 'private' });
+ await link('notes/n3', 'people/carol-example', { source: 'frontmatter', origin: 'notes/private-origin' });
+ }],
+ ['quarantined page', async () => {
+ await page('notes/quarantined', 'note', 'source-a', { quarantine: 'synthetic' });
+ await link('notes/quarantined', 'people/bob-example');
+ await page('people/quarantined-person', 'person', 'source-a', { quarantine: 'synthetic' });
+ await link('notes/n4', 'people/quarantined-person');
+ }],
+ ['foreign-source page', async () => {
+ await page('notes/foreign', 'note', 'source-b');
+ await link('notes/foreign', 'people/bob-example', { fromSource: 'source-b', toSource: 'source-a' });
+ await page('people/foreign-person', 'person', 'source-b');
+ await link('notes/foreign', 'people/foreign-person', { fromSource: 'source-b', toSource: 'source-b' });
+ }],
+ ['private redirect stub', async () => {
+ await page('people/private-stub', 'person', 'source-a', { visibility: 'private', merged_into: 'people/bob-example' });
+ await link('notes/n4', 'people/private-stub');
+ }],
+ ];
+ for (const [label, seed] of cases) {
+ const localBefore = brief((await rank(ctxOf({ sourceId: '__all__' }), { direction: 'both', source_id: '__all__' })).entities);
+ await seed();
+ const localAfter = brief((await rank(ctxOf({ sourceId: '__all__' }), { direction: 'both', source_id: '__all__' })).entities);
+ expect({ label, changedLocally: JSON.stringify(localAfter) !== JSON.stringify(localBefore) }).toEqual({ label, changedLocally: true });
+ expect({ label, rows: brief((await rank(remote(), { direction: 'both' })).entities) }).toEqual({ label, rows: baseline });
+ }
+ });
+
+ test('a stub whose target is hidden stays unfolded remotely and never names the target', async () => {
+ await seedBase();
+ await page('people/hidden-target', 'person', 'source-a', { visibility: 'private' });
+ await page('people/visible-stub', 'person', 'source-a', { superseded_by: 'people/hidden-target' });
+ await link('notes/n1', 'people/visible-stub');
+ const localRows = (await rank(local())).entities;
+ expect(localRows.find(r => r.slug === 'people/hidden-target')?.folded).toEqual([{ slug: 'people/visible-stub', reason: 'superseded_by' }]);
+ const remoteResult = await rank(remote());
+ expect(JSON.stringify(remoteResult)).not.toContain('hidden-target');
+ expect(remoteResult.entities.find(r => r.slug === 'people/visible-stub')).toMatchObject({ inbound: 1 });
+ });
+
+ test('remote coverage reports a state without page counts', async () => {
+ await seedBase();
+ const res = await rank(remote()) as any;
+ expect(res.coverage).toEqual({ state: 'behind' });
+ expect(Object.keys((await rank(local()) as any).coverage)).toContain('actionable');
+ });
+
+ test('a source outside the grant answers not_found', async () => {
+ await seedBase();
+ await expect(rank(remote(), { source_id: 'source-b' })).rejects.toMatchObject({ code: 'not_found' });
+ });
+});
+
+describe('rank_entities parameter validation', () => {
+ const invalid: Array<[string, Record<string, unknown>]> = [
+ ['direction', { direction: 'sideways' }],
+ ['types', { types: 'person' }],
+ ['types', { types: [] }],
+ ['types', { types: ["person'; DROP TABLE links; --"] }],
+ ['link_type', { link_type: "x' OR '1'='1" }],
+ ['link_type', { link_type: 'amends' }],
+ ['include_mentions', { include_mentions: 'yes' }],
+ ['limit', { limit: 0 }],
+ ['limit', { limit: 101 }],
+ ['limit', { limit: 2.5 }],
+ ['limit', { limit: '10' }],
+ ['source_id', { source_id: '' }],
+ ];
+ for (const [param, params] of invalid) {
+ test(`rejects ${param}=${JSON.stringify(params[param])} with a corrected example`, async () => {
+ await seedBase();
+ const err = await op.handler(local(), { types: ['person'], ...params }).then(() => null, e => e);
+ expect(err).toBeInstanceOf(OperationError);
+ expect(err.code).toBe('invalid_params');
+ expect(err.suggestion).toContain('Example:');
+ });
+ }
+
+ test('the links table survives an injection-shaped type', async () => {
+ await seedBase();
+ await op.handler(local(), { types: ["person'; DROP TABLE links; --"] }).catch(() => {});
+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');
+ expect(Number(row!.n)).toBeGreaterThan(0);
+ });
+});
+
+describe('rank_entities possible duplicates', () => {
+ async function seedDuplicate(stubFrontmatter: Record<string, unknown> = {}) {
+ await engine.putPage('people/alice-zebraexample', { type: 'person', title: 'Alice Zebraexample', compiled_truth: 'Synthetic page.' } as any, { sourceId: 'source-a' });
+ await engine.putPage('people/mayor-zebraexample', { type: 'person', title: 'Mayor Zebraexample', compiled_truth: 'Synthetic page.', frontmatter: stubFrontmatter } as any, { sourceId: 'source-a' });
+ await page('notes/d1', 'note');
+ await page('notes/d2', 'note');
+ await link('notes/d1', 'people/alice-zebraexample');
+ await link('notes/d2', 'people/alice-zebraexample');
+ await link('notes/d1', 'people/mayor-zebraexample');
+ }
+
+ test('a title-prefixed duplicate is listed, never folded', async () => {
+ await seedDuplicate();
+ const res = await rank(local(), { types: ['person'] }) as any;
+ expect(res.entities.map((r: Row) => [r.slug, r.inbound])).toEqual([['people/alice-zebraexample', 2], ['people/mayor-zebraexample', 1]]);
+ expect(res.entities[0].possible_duplicates).toEqual([{ slug: 'people/mayor-zebraexample', title: 'Mayor Zebraexample', reason: 'title_prefix' }]);
+ expect(res.duplicates_checked).toBe(2);
+ });
+
+ test('a private duplicate is not named to a remote caller', async () => {
+ await seedDuplicate({ visibility: 'private' });
+ expect((await rank(local(), { types: ['person'] }) as any).entities[0].possible_duplicates).toHaveLength(1);
+ const res = await rank(remote(), { types: ['person'] }) as any;
+ expect(JSON.stringify(res)).not.toContain('mayor-zebraexample');
+ });
+});