Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep the engines key-files doc under its size cap after the merge

garrytan57da58589b4b
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 4307fa9bb1..e9b4960cb9 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.
- `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 and every OR re-run match `ts_filter(search_vector, '{a}') @@ q` (weight A is the title alone) and rank on the same slice: served by the expression index `idx_pages_title_search` (GBRA-156, v267), which holds title lexemes only, so a term in timeline text never makes its page a candidate; title-only for negated and phrase terms, following the stored `search_vector` language. Postgres runs each attempt with the keyword statement's `work_mem` (`statementSettings`). Pages with a NULL `search_vector` are absent from the remote arm. #7471: a 2-4 word name query ORs in its given-name variants (`titleNameVariants`: "Matt Example" also matches the title "Matthew Example"), each its own bound websearch query; the OR fallback of a query of at most `RARITY_MAX_TERMS` words runs once per word in one scoped read and `rankByRarity` puts titles holding the rarest word first (ts_rank_cd knows no term rarity, so a surname's one title used to tie thousands of first-name titles and lose on page id). #7491: OR-retry titles holding every identifier the query names (`holdsIdentifiers`, search/keyword-identifier-probe.ts) lead untagged; the rest stay `keyword_relaxed`.
-- `src/core/engine-sql/page-lookup.ts` + `src/core/page-find.ts` + `src/core/page-counts.ts` + `src/core/ops/find-pages.ts` + `src/core/ops/stats-by.ts` + `src/cli/format-page-lookup.ts` — find-by-name and grouped counts (`gbrain find` / `find_pages`, `gbrain stats --by` / `get_stats` `by`, `since`, `collapse_aliases`). `parseFindPattern` turns a glob (`*`/`?`, whole slug or source path), a slug prefix (contains `/`) or a name (title or last slug segment substring) into one `escapeLikePattern`-escaped ILIKE pattern; names are served by `idx_pages_trgm` + `idx_pages_slug_trgm`, while globs and prefixes also match `source_path` (no trigram index). Rows sort by slug then source in the C collation, carry `count(*) OVER ()` as `total`, and the op reports `complete` (limit default 50, cap 500 local, 100 remote). Find hides the ranked-search hard excludes (`resolveHardExcludes` + `buildHardExcludeClause`) unless the pattern's literal lead is inside one, and names them in `hidden_prefixes`. `countPagesBy` returns per (source, type) counts plus raw and distinct-slug totals (per type group through an `unnest` mapping and GROUPING SETS), so cross-source twins are never silently double counted; `since` is the query effective-date bound (`resolveDateBoundary`). Every caller sees live pages in unarchived sources; a remote caller's `readPolicyOpts` policy adds `pageReadFilter(..., live)`. `collapseTypes` lets the active pack decide (declared stays, alias joins canonical), else normalizes (last segment, lower case, singular) and joins a `-<name>` suffix to an existing group; each group lists `member_types` with its rule (`exact`, `pack_alias`, `normalized`, `suffix`). Without the grouping params `get_stats` returns its unchanged counters. `visiblePageTypes` (GBRA-449) is the same count summed per type, most pages first, for `get_backlinks`' type check and an empty `list_pages` notice. Tests: `test/page-find-pattern-7191.test.ts`, `test/page-lookup-7191.test.ts` (Postgres arm: `test/e2e/page-lookup-7191.test.ts`).
+- `src/core/engine-sql/page-lookup.ts` + `src/core/page-find.ts` + `src/core/page-counts.ts` + `src/core/ops/find-pages.ts` + `src/core/ops/stats-by.ts` + `src/cli/format-page-lookup.ts` — find-by-name and grouped counts (`gbrain find` / `find_pages`, `gbrain stats --by` / `get_stats` `by`, `since`, `collapse_aliases`). `parseFindPattern` turns a glob (`*`/`?`, whole slug or source path), a slug prefix (contains `/`) or a name (title or last slug segment substring) into one `escapeLikePattern`-escaped ILIKE pattern; names are served by `idx_pages_trgm` + `idx_pages_slug_trgm`, while globs and prefixes also match `source_path` (no trigram index). Rows sort by slug then source in the C collation, carry `count(*) OVER ()` as `total`, and the op reports `complete` (limit default 50, cap 500 local, 100 remote). Find hides the ranked-search hard excludes (`resolveHardExcludes` + `buildHardExcludeClause`) unless the pattern's literal lead is inside one, and names them in `hidden_prefixes`. `countPagesBy` returns per (source, type) counts plus raw and distinct-slug totals (per type group through an `unnest` mapping and GROUPING SETS), so cross-source twins are never silently double counted; `since` is the query effective-date bound (`resolveDateBoundary`). Every caller sees live pages in unarchived sources; a remote caller's `readPolicyOpts` policy adds `pageReadFilter(..., live)`. `collapseTypes` lets the active pack decide (declared stays, alias joins canonical), else normalizes (last segment, lower case, singular) and joins a `-<name>` suffix to an existing group; each group lists `member_types` with its rule (`exact`, `pack_alias`, `normalized`, `suffix`). Without the grouping params `get_stats` returns its unchanged counters. Tests: `test/page-find-pattern-7191.test.ts`, `test/page-lookup-7191.test.ts` (Postgres arm: `test/e2e/page-lookup-7191.test.ts`).
- `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`.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index b9a4e125b9..a33fbcbd99 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -15,7 +15,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). 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, `untyped` or a type of any page the caller can read in its scope, `ops/stats-by.ts visiblePageTypes`) is `invalid_params` naming the valid values (only types of pages the caller can read); a type other visible pages have but no referrer has answers empty with an `empty_retrieval` info notice naming the referrer types (GBRA-449, `test/backlinks-type-exists-gbra449.test.ts`). 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/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, `untyped` or a type of any page the caller can read in its scope, `ops/stats-by.ts visiblePageTypes`: the `countPagesBy` count summed per type, most pages first, also behind the empty `list_pages` notice) is `invalid_params` naming the valid values (only types of pages the caller can read); a type other visible pages have but no referrer has answers empty with an `empty_retrieval` info notice naming the referrer types (GBRA-449, `test/backlinks-type-exists-gbra449.test.ts`). F3 (`entity.row_page_status`, default on): `withLinkPageStatus` adds the referring page's `page_status` to link rows, and `group: "page"` rows get it through `readReferrerPage {pageStatus}`; a record type's continuation keeps it through `recordMetadata` when the key is off.
- `src/core/ops/graph-rank.ts` — #7168: `rank_entities` (CLI `rank-entities`): validates every parameter with `invalidParam` (no coercion; type and link-type names are pattern-checked, non-ranking link types refused, `limit` 1-100), scopes with `assertSourceInCallerScope` / `resolveRequestedScope` then `linkReadScopeOpts` (remote scalar scopes promoted to `sourceIds`), defaults `types` to `resolveEntityTypes`, runs `engine-sql/graph-rank.ts` under `RANK_ENTITIES_STATEMENT_MS` (a 57014 becomes `rank_entities_timeout`), attaches `possible_duplicates` (`readPossibleDuplicates`) to at most `RANK_ENTITIES_DUPLICATE_ROWS` top rows within a 3 s budget, and `coverage` from `readExtractionLag` per source in scope (state only for remote callers). Guide: [graph ranking](../../guides/graph-ranking.md). Tests: `test/rank-entities.test.ts`.
- `src/core/ops/whois.ts` — GBRA-156: `whois` (CLI `whois <query>`), the exact identity lookup. A query is an email address (`identityEmailKey`: NFKC, lowercase, surrounding quotes and angle brackets dropped, whole address compared) or a name (`identityNameKey`: `normalizeAlias`, surrounding straight and typographic quotes dropped, NFKD with combining marks stripped, `foldNonDecomposingLatin`). Scope: `parseSourceIdParam` + `federatedSearchScope` + `assertExplicitSourceLive`, an unscoped trusted call reading every unarchived source; `types` defaults to `resolveEntityTypes` for that scope. Candidates come from `engine-sql/exact-identity.ts`; `identityMatchKind` keeps a candidate only when a frontmatter `email`/`emails` value (email queries), the title, or a `normalizeAliasList` alias folds to exactly the query, labeled `email` > `title` > `alias` (ordered so, then source id and slug). Returns `matches`, `ambiguous` (more than one match), `types_status`, and `truncated` + `note` past `WHOIS_CANDIDATE_CAP` candidates; no match is an empty list, never a search fallback. Registered `labeled`, output redaction `retrieval`. Tests: `test/whois.test.ts`, `test/e2e/whois-postgres.test.ts`.
- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `denied_by_config`, `not_a_known_name`); only `pending` names a sweep. A slug query also lists each derived name with origin and declaring line, the rejected candidates with reasons, and the sibling decision. Tests: `test/mentions-explain.test.ts`.