Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(entity): records and reference counts on entity names rows, the card and context_pack (F1)
garrytanb2a5dfe68637
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f87d752f54..a53ff013b9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased: cat40 next wave part 1, version stamped at merge] - 2026-10-12++**Entity rows now point at the records behind an account.** Every found `entity names` row (and each identity sibling) carries `referenced_by_count` and a `next` to its full card, so an agent that resolved a batch of names knows which ones have pages to read and how to open them. With `entity.record_types` set (off by default), the rows, the full card and `context_pack` also list the referring contracts, amendments or other record types you enroll: newest page date first, each with its page date labeled as a page date, its `status`, the record it amends (with the terms-start date when the link records one) and what it replaces, bounded per page and per call, with continuations that return exactly the rest. The order never claims which record governs. A late or failed read is marked `references_unavailable` with a degraded notice, never shown as an empty list.++### Itemized changes++- `src/core/mentions/referrers.ts`: `readTargetReferences`, the batched variant of the shared referrer CTE (target index on every row, the same filters), with per-type totals and record filtering inside the membership query before ORDER BY, LIMIT and hydration; `readRecordMetadata` (page status, `amends` with `since` from the caller's temporal scope, `supersedes`), shared with `get_backlinks {group:"page"}` continuations of an enrolled type.+- `src/core/verbs/entity-references.ts`: the row fields, caps (5 per page, 24 per call, input order, repeated pages counted once), per-type `next`, the 2-second cooperative deadline, the `references_unavailable` marker and notice, the `record_types_undeclared` notice, and `context_pack`'s records block (pull verb only).+- `src/core/entity-references-config.ts`: `entity.names_references` (default on) and `entity.record_types` (default empty).+- `src/core/verbs/entity-names.ts`, `entity-card.ts`, `src/core/ops/facts.ts`: names rows, the full card (records, and the `referenced_by` failure marker) and `context_pack` cards; `src/core/verbs.ts` output schemas; `src/core/verbs/usage-log.ts` `records_firing` (listed, zero, unavailable).+- Docs: MEMORY_VERBS v1 "entity names reference fields and records", "entity records" and "context_pack records"; `docs/guides/entity-records.md`.+- Tests: `test/entity-records.test.ts` and `test/e2e/entity-records-postgres.test.ts` (shared scenarios: batched-vs-single parity with private, quarantined and below-floor referrers, hidden amends dates, caps and continuations, deadline and failure markers, schema validity, packing order); a 50-names / 150-target case in `test/entity-card-perf.slow.test.ts`.+## [0.60.180.0] - 2026-10-12**When `remember` refuses a forgotten claim, the refusal now says when and how widely it was forgotten.** An agent that re-saves a claim the user forgot gets `fact_withdrawn` as before, and the refusal now carries `withdrawn: { at, subject, visibility }`, where `subject` is the entity the claim was forgotten for or `all_entities`. The agent can tell the user "you asked me to forget that on <date>" instead of retrying. The object rides the immediate refusal, the batch item error, the failed write receipt and `get_write_request`. It covers the exact claim only, the message, code and suggestion are unchanged, and nothing is ever restored.diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.mdindex 6689a132d3..7cd576e7ad 100644--- a/docs/architecture/key-files/entity-recall.md+++ b/docs/architecture/key-files/entity-recall.md@@ -13,11 +13,12 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list, `mentions.alias_deny`, `mentions.multiword_aliases`, `mentions.sibling_merge`) marks every page due and recounts `pending`; the status row's `policy_fingerprint` carries the extractor versions its count reflects after the hash (`<hash>;v<mention>.<alias>`, `INDEX_VERSION_STAMP`), and a stamp that differs from the binary's recounts `pending` once (version-behind pages are already due, so nothing is invalidated); `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, `pending` (`countIndexDuePages`: mention-due pages plus linkable entity pages whose derived aliases are behind their content or `ALIAS_DERIVATION_VERSION`, counted when the source finishes or the deadline stops it) and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-coverage-version.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (index-due pages per source, as `countIndexDuePages` counts them, and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.-- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).+- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while index-due pages exist (`previewMentionPass`), including every page behind the binary's mention or alias version on an unchanged brain. Post-upgrade does not run the sweep; autopilot's cycle extract phase continues it on its stale-drain budget (`CYCLE_STALE_DRAIN_BUDGET_MS`).- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode filters by referrer type and cuts at `limit` with a `listing_truncated` notice naming the paged call. `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values.- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `denied_by_config`, `not_a_known_name`); only `pending` names a sweep. A slug query also lists each derived name with origin and declaring line, the rejected candidates with reasons, and the sibling decision. Tests: `test/mentions-explain.test.ts`.-- `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` resolves each name through `buildEntityCard` (no references), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; siblings come from `readCardIdentity`. `pageLead` is the body's opening prose from `sanitizeRemoteBody` plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. Tests: `test/entity-names.test.ts`.+- `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` resolves each name through `buildEntityCard` (no references), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; siblings come from `readCardIdentity`. `pageLead` is the body's opening prose from `sanitizeRemoteBody` plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. `attachReferences` adds `referenced_by_count`, the card `next` and `records` to every found page and sibling from one `readRowReferences` call. Tests: `test/entity-names.test.ts`, `test/entity-records.test.ts`.+- `src/core/verbs/entity-references.ts` — the F1 reference fields on compact rows: `readRowReferences` (config gate per surface `names` / `pack` / `full_card`, `REFERENCES_DEADLINE_MS` 2 s cooperative deadline, `references_unavailable` marker + degraded notice, per-type `next` to `get_backlinks` returning exactly the rest, `record_types_undeclared` notice), `readPackReferences` (context_pack pull verb only: card page + identity siblings), `renderRecordLines` / `RECORDS_HEADER` (packed text, "page date"). Config: `src/core/entity-references-config.ts` (`entity.names_references` default on, `entity.record_types` default empty). Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.- `src/core/verbs/entity-card-identity.ts` — the `entity` card's `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines of the page and its siblings from `sanitizeRemoteBody`, tiered: declarations, label lines with a name-like value, other label lines, lines with another capitalized run or code; 600 characters per page, 1,200 per card, `identity_excerpt_omitted`), `alias_guidance` (surface-aware) and the `identity_siblings_capped` notice. Tests: `test/mentions-identity-siblings.test.ts`.- `src/core/search/alias-fanout.ts` — search and query's alias fan-out: `resolveQueryEntity` (query n-grams up to 4 tokens through `resolveAliases` and linkable exact titles, longest first, capitalized or code-shaped unless a multi-word n-gram resolves to one page, case-sensitive aliases as written, a tie only when the pages are identity siblings), the names of the entity and its siblings by origin then length, at most `search.alias_fanout_max` (4) keyword queries of 5 rows (`searchAliasRequired`: the name as a required websearch phrase, ranked by the query's other terms through `SearchOpts.rankQuery` on both engines), at most 8 spliced rows with `matched_alias`, and the `fanout` meta (`alias_fanout` notice when capped). Offset 0 only. Tests: `test/search-alias-fanout.test.ts`, `test/search-other-names.test.ts`, `test/e2e/mentions-parity.test.ts`. `wholeQueryEntityNames`: when the whole query is one entity's name or alias, `match: "keyword"` lists pages matching any of its names (one websearch OR of phrases; `match_names` in the meta and the count line; rows found by another name carry `matched_alias`). `resolveQueryEntities` returns every entity a text names.- `src/core/search/entity-facts.ts` — `entitySavedFacts`: when a search names an entity, its newest active saved facts (`factEntitySlugs`, 5) lead the model-visible saved-facts block, then up to 3 facts each of up to 2 entities those facts name (`linked_from`), before the word-overlap matches. Same active, audit-row and visibility rules as recall. Tests: `test/memory-sibling-facts.test.ts`.diff --git a/docs/guides/entity-records.md b/docs/guides/entity-records.mdnew file mode 100644index 0000000000..8ba923fa4a--- /dev/null+++ b/docs/guides/entity-records.md@@ -0,0 +1,107 @@+# Entity records: contracts, amendments and orders on entity rows++An account's governing terms usually live in a few documents among many: the+contract, its amendments, an order form. GBrain can list those documents where+agents already look, the compact `entity names` rows, the full `entity` card+and `context_pack`, so a later amendment is not lost behind a page of older+hits.++Records are off until you name the page types that count as records. Every+found `entity names` row already carries `referenced_by_count` and a `next` to+its full card.++**Say to your agent:**+- *"Which contracts and amendments reference acme-example?"*+- *"Show me the records for these five accounts."*++## Turn records on++```bash+gbrain config set entity.record_types contract,amendment,order-form+gbrain config get entity.record_types+```++The value is a comma-separated list of page types. A stored type alias is read+as its schema-pack type (with `gbrain-base-v2`, `term-sheet` lists under+`deal`). A type that neither the pack declares nor any page uses gives a+`record_types_undeclared` notice instead of an empty list. Unset it to turn+records off again: `gbrain config unset entity.record_types`.++`entity.names_references` (default `true`) controls the `referenced_by_count`+and card `next` on `entity names` rows; `false` turns them off.++## A record page++```markdown+---+type: amendment+title: Acme Example MSA amendment 2+date: 2026-02-10+status: signed+amends:+ - name: contracts/acme-example-msa+ since: 2026-03-01+---+Amendment 2 to the master services agreement with [Acme Example](../accounts/acme-example.md).+Effective 2026-03-01, the monthly fee changes to 12,000 USD. All other terms are unchanged.+```++- `date` is the page's own date: when it was written or signed. It never+ means "these terms are in effect".+- `status` is shown as `page_status` (any string up to 40 characters; the+ documented convention for unsigned or provisional records is `draft` or+ `unsigned`).+- `amends` is a relationship field: a non-ranking `amends` link to the record+ it changes, with the terms-start date in `since`. Map the field for your page+ type in the schema pack's frontmatter links and re-extract, as described in+ [temporal edges](temporal-edges.md). Without the mapping the page is still a+ record; it just shows no `amends`.+- Whole-record replacement is a `supersedes` link, which also down-ranks the+ replaced page in search. Use it only when the new record replaces the old one+ entirely.++## What the agent gets++`entity {names: ["Acme Example"]}` returns, for the found page (and for each+identity sibling, side by side):++```json+{+ "name": "Acme Example", "found": true, "slug": "accounts/acme-example",+ "referenced_by_count": 14,+ "next": { "tool": "entity", "arguments": { "name": "accounts/acme-example" } },+ "records": [+ { "canonical_type": "amendment", "total": 2, "rows": [+ { "slug": "contracts/acme-example-msa-amendment-2", "title": "Acme Example MSA amendment 2",+ "date": "2026-02-10T00:00:00.000000Z", "date_source": "date", "page_status": "signed",+ "amends": [{ "slug": "contracts/acme-example-msa", "since": "2026-03-01" }] },+ { "slug": "contracts/acme-example-msa-amendment-1", "title": "Acme Example MSA amendment 1",+ "date": "2025-07-01T00:00:00.000000Z", "date_source": "date",+ "amends": [{ "slug": "contracts/acme-example-msa" }] } ] },+ { "canonical_type": "contract", "total": 1, "rows": [+ { "slug": "contracts/acme-example-msa", "title": "Acme Example MSA",+ "date": "2025-01-15T00:00:00.000000Z", "date_source": "date" } ] }+ ]+}+```++Rows are newest page date first, and the order does not say which record+governs. Each page shows at most 5 records (24 per call); a group with more+carries `capped` and a `next` that returns exactly the rest:+`get_backlinks {slug, source_id, type, group: "page", limit, cursor}`.+`context_pack` cards carry the same `records` and render them in `text` under+"Records that reference these entities". When the read fails or runs past its+deadline, rows say `references_unavailable` with a degraded notice: that means+unread, not empty.++## Check which pages count as records++Read-only, no agent needed:++```bash+gbrain config get entity.record_types+gbrain call get_backlinks '{"slug":"accounts/acme-example","type":"amendment","group":"page"}'+gbrain call list_pages '{"type":"amendment"}'+```++Full field contract: [MEMORY_VERBS v1, entity records](../protocol/MEMORY_VERBS_v1.md#entity-records-record-types-enrolled-by-config-additive).diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 0c71583e6d..6a3d8a60b9 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -430,13 +430,75 @@ row is `{ name, found: true, slug, title, type, aka[], lead, siblings? }` or`{ name, found: false, suggestions? }` (up to 3 `{slug, title}`). `lead` is thepage's opening prose, up to 200 characters (headings, table rows, privatefences and secrets removed); `siblings` lists the identity siblings with their-own `slug`, `title`, `type`, `aka` and `lead`. Rows carry no references, facts-or open threads: call `entity` with `name` for the full card.+own `slug`, `title`, `type`, `aka` and `lead`. Rows carry no facts or open+threads: call `entity` with `name` for the full card.++#### entity names reference fields and records (additive)++Every found row and each of its `siblings` carries `referenced_by_count` (the+full card's count, every link source) and a row-level `next`, `{ tool: "entity",+arguments: { name: <slug> } }`, the call that returns that page's full card,+under `entity.names_references` (default on; `false` drops both). When+`entity.record_types` names page types (empty by default, so records are off),+each found row and sibling also carries `records[]` (below). The found page and+each sibling get their own count and records, side by side, never merged. When+a row carries either field, the source's `mention_index` coverage notice rides+the response as on the full card.++#### entity records: record types enrolled by config (additive)++`entity.record_types` is a comma-separated list of canonical page types that+count as records (a stored alias is read as its pack type). When it names+types, `entity` names rows and siblings, the full card (`card.records`, and+`records` on each `identity_siblings.pages[]` entry) and `context_pack` cards+list the referring pages of those types:++- `records[]`: one group per type with at least one record, `{ canonical_type,+ total, rows[], capped?, next? }`, groups ordered by their newest row. An+ enrolled entity with no records has `records: []`.+- A row is exactly `{ slug, title, date, date_source, page_status?, amends?,+ supersedes? }`. `date` is the page's own date (`COALESCE(effective_date,+ updated_at)`, `date_source` says which), not when its terms take effect.+ `page_status` is the page's own frontmatter `status` when it is a string of+ at most 40 characters (search rows carry the same value as raw `status`; link+ rows' temporal relationship `status` is a different field). `amends[]` is+ `{ slug, since? }` per page this one amends through an `amends` link, `since`+ only when the link records a terms-start date (frontmatter `amends: [{ name,+ since }]`); `supersedes[]` is `{ slug }` per page this one replaces as a+ whole. Each list holds at most 5 entries; absent fields mean nothing is+ recorded.+- Rows are newest page date first. The order never says which record governs:+ compare `amends[].since` and the documents themselves with the date asked+ about. No validity status is computed.+- Bounded: 5 rows per page (all of them when it has 5 or fewer), 24 per call,+ allotted in input order, a page repeated in the call counted once. A group+ with `rows.length < total` carries `capped` (`per_page`, or `per_call` when+ earlier entities took the call's rows, including a group with no rows) and+ `next`, `{ tool: "get_backlinks", arguments: { slug, source_id, type, group:+ "page", limit, cursor? } }`, which returns exactly the remaining records of+ that type (with the same `page_status` / `amends` / `supersedes` fields);+ on a verbs-only connection it carries `requires_surface: "starter"`.+- Records use the referrer read's visibility: an untrusted caller never sees a+ private, derived-private or quarantined referrer, a link whose origin page is+ private, an `amends` target it cannot read, or a `since` whose only evidence+ is private.+- Unavailable is not empty: when the count or records read fails or misses its+ 2-second deadline, the row carries `references_unavailable: "deadline" |+ "read_failed"` instead of the fields, and one `[gbrain notice+ references_unavailable]` (degraded) block rides the response. The full+ card's `referenced_by` follows the same rule. An enrolled type that neither+ the schema pack declares nor any page uses adds a `record_types_undeclared`+ info notice.++Check which pages count as records without calling an agent: `gbrain config+get entity.record_types`, then `get_backlinks {slug, type: <record type>,+group: "page"}` or `list_pages {type: <record type>}`.#### entity references and coverage (additive)The `entity` verb adds three optional card fields (ambient callers,-`context_pack` and `delta`, do not compute them):+`context_pack` and `delta`, do not compute them; `context_pack` adds only the+record view, below):- `referenced_by_count` — distinct pages with any inbound link to the entity,every link source included (`backlink_count` keeps excluding mentions).@@ -811,6 +873,24 @@ memory), so other facts can appear; `recall` with `entity` reads one entitystrictly. `facts[]` here and in `delta` carry `fact_id` (what `forget` takes)and `provenance` (the stored source), never rendered into `text`.+#### context_pack records (additive)++When `entity.record_types` names page types, each card of the `context_pack`+pull verb (never the ambient push hook, which stays unchanged) carries+`referenced_by_count`, `records[]` (the entity records view, same row shape,+caps, continuations and visibility) and `sibling_records[]` (`{ slug, title,+referenced_by_count, records[] }` per identity sibling, side by side), or+`references_unavailable` with its degraded notice. `text` renders them last,+after newer mentions, under `## Records that reference these entities (page+date = when the page was written, newest first; …)`, one line per record:+`- <entity>: <type> <slug> "<title>" — page date <YYYY-MM-DD> (<date_source>);+status: <page_status>; amends <slug> (terms start <since>); supersedes <slug>`.+Under `budget_tokens` records pack into what cards, facts and newer mentions+left; a card whose records do not fit keeps its count. With nothing enrolled,+cards carry none of these fields, so `context_pack` still computes no+references by default. `backlink_count` keeps excluding mentions;+`referenced_by_count` counts every link source.+#### context_pack core memory (additive)`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries thediff --git a/llms-full.txt b/llms-full.txtindex 4bda4b309a..573bd031ee 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8926,13 +8926,75 @@ row is `{ name, found: true, slug, title, type, aka[], lead, siblings? }` or`{ name, found: false, suggestions? }` (up to 3 `{slug, title}`). `lead` is thepage's opening prose, up to 200 characters (headings, table rows, privatefences and secrets removed); `siblings` lists the identity siblings with their-own `slug`, `title`, `type`, `aka` and `lead`. Rows carry no references, facts-or open threads: call `entity` with `name` for the full card.+own `slug`, `title`, `type`, `aka` and `lead`. Rows carry no facts or open+threads: call `entity` with `name` for the full card.++#### entity names reference fields and records (additive)++Every found row and each of its `siblings` carries `referenced_by_count` (the+full card's count, every link source) and a row-level `next`, `{ tool: "entity",+arguments: { name: <slug> } }`, the call that returns that page's full card,+under `entity.names_references` (default on; `false` drops both). When+`entity.record_types` names page types (empty by default, so records are off),+each found row and sibling also carries `records[]` (below). The found page and+each sibling get their own count and records, side by side, never merged. When+a row carries either field, the source's `mention_index` coverage notice rides+the response as on the full card.++#### entity records: record types enrolled by config (additive)++`entity.record_types` is a comma-separated list of canonical page types that+count as records (a stored alias is read as its pack type). When it names+types, `entity` names rows and siblings, the full card (`card.records`, and+`records` on each `identity_siblings.pages[]` entry) and `context_pack` cards+list the referring pages of those types:++- `records[]`: one group per type with at least one record, `{ canonical_type,+ total, rows[], capped?, next? }`, groups ordered by their newest row. An+ enrolled entity with no records has `records: []`.+- A row is exactly `{ slug, title, date, date_source, page_status?, amends?,+ supersedes? }`. `date` is the page's own date (`COALESCE(effective_date,+ updated_at)`, `date_source` says which), not when its terms take effect.+ `page_status` is the page's own frontmatter `status` when it is a string of+ at most 40 characters (search rows carry the same value as raw `status`; link+ rows' temporal relationship `status` is a different field). `amends[]` is+ `{ slug, since? }` per page this one amends through an `amends` link, `since`+ only when the link records a terms-start date (frontmatter `amends: [{ name,+ since }]`); `supersedes[]` is `{ slug }` per page this one replaces as a+ whole. Each list holds at most 5 entries; absent fields mean nothing is+ recorded.+- Rows are newest page date first. The order never says which record governs:+ compare `amends[].since` and the documents themselves with the date asked+ about. No validity status is computed.+- Bounded: 5 rows per page (all of them when it has 5 or fewer), 24 per call,+ allotted in input order, a page repeated in the call counted once. A group+ with `rows.length < total` carries `capped` (`per_page`, or `per_call` when+ earlier entities took the call's rows, including a group with no rows) and+ `next`, `{ tool: "get_backlinks", arguments: { slug, source_id, type, group:+ "page", limit, cursor? } }`, which returns exactly the remaining records of+ that type (with the same `page_status` / `amends` / `supersedes` fields);+ on a verbs-only connection it carries `requires_surface: "starter"`.+- Records use the referrer read's visibility: an untrusted caller never sees a+ private, derived-private or quarantined referrer, a link whose origin page is+ private, an `amends` target it cannot read, or a `since` whose only evidence+ is private.+- Unavailable is not empty: when the count or records read fails or misses its+ 2-second deadline, the row carries `references_unavailable: "deadline" |+ "read_failed"` instead of the fields, and one `[gbrain notice+ references_unavailable]` (degraded) block rides the response. The full+ card's `referenced_by` follows the same rule. An enrolled type that neither+ the schema pack declares nor any page uses adds a `record_types_undeclared`+ info notice.++Check which pages count as records without calling an agent: `gbrain config+get entity.record_types`, then `get_backlinks {slug, type: <record type>,+group: "page"}` or `list_pages {type: <record type>}`.#### entity references and coverage (additive)The `entity` verb adds three optional card fields (ambient callers,-`context_pack` and `delta`, do not compute them):+`context_pack` and `delta`, do not compute them; `context_pack` adds only the+record view, below):- `referenced_by_count` — distinct pages with any inbound link to the entity,every link source included (`backlink_count` keeps excluding mentions).@@ -9307,6 +9369,24 @@ memory), so other facts can appear; `recall` with `entity` reads one entitystrictly. `facts[]` here and in `delta` carry `fact_id` (what `forget` takes)and `provenance` (the stored source), never rendered into `text`.+#### context_pack records (additive)++When `entity.record_types` names page types, each card of the `context_pack`+pull verb (never the ambient push hook, which stays unchanged) carries+`referenced_by_count`, `records[]` (the entity records view, same row shape,+caps, continuations and visibility) and `sibling_records[]` (`{ slug, title,+referenced_by_count, records[] }` per identity sibling, side by side), or+`references_unavailable` with its degraded notice. `text` renders them last,+after newer mentions, under `## Records that reference these entities (page+date = when the page was written, newest first; …)`, one line per record:+`- <entity>: <type> <slug> "<title>" — page date <YYYY-MM-DD> (<date_source>);+status: <page_status>; amends <slug> (terms start <since>); supersedes <slug>`.+Under `budget_tokens` records pack into what cards, facts and newer mentions+left; a card whose records do not fit keeps its count. With nothing enrolled,+cards carry none of these fields, so `context_pack` still computes no+references by default. `backlink_count` keeps excluding mentions;+`referenced_by_count` counts every link source.+#### context_pack core memory (additive)`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries thediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e1859121e8..b1d66b7249 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1955 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts)+src/core/config.ts 1956 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +1 F1 entity reference fields: the entity.names_references / entity.record_types KNOWN_CONFIG_KEYS row (reader in entity-references-config.ts)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex bc34ae7ce0..5b22fbc574 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -468,6 +468,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Fix wave 15 group 1 (managed sync authority and data safety).// Cat 40 next wave, Part 3 step 1. `since` is provisional; the integrator restamps it at the merge slot.{ since: '0.60.180.0', text: 'A `remember` refused with `fact_withdrawn` now carries an additive `withdrawn` object (`at`, `subject`: the entity slug or `all_entities`, `visibility`) on the immediate refusal, the batch item error, the failed write receipt and `get_write_request`, so an agent can tell the user when and how widely the exact claim was forgotten instead of retrying. The message, code and suggestion are unchanged; the object is absent when the caller cannot read the forgotten rows.' },+ { since: '0.60.180.0', text: 'Every found `entity names` row, and each identity sibling on it, now carries `referenced_by_count` (the same count as the full card: distinct pages linking to it, every link source) and a row-level `next` (`{tool: "entity", arguments: {name: <slug>}}`) that returns its full card, and the source\'s `mention_index` coverage notice rides the response when coverage is incomplete. `gbrain config set entity.names_references false` drops both. The count is read in one batched statement for the call; when it fails or misses its 2-second deadline the row carries `references_unavailable` and one degraded `references_unavailable` notice instead of the count.' },+ { since: '0.60.180.0', text: 'The full `entity` card\'s `referenced_by` used to be silently left out when its read failed; the card now carries `references_unavailable: "read_failed"` and one degraded `references_unavailable` notice, so an agent does not read a missing list as "nothing references this". New and off by default: `entity.record_types` (comma-separated page types) lists the referring pages of those types as `records` on `entity names` rows, the full card and `context_pack` cards (pull verb only), newest page date first with `page_status`, `amends` (with its recorded `since`) and `supersedes`, 5 per page and 24 per call with exact-remainder continuations.' },{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },{ since: '0.60.179.0', text: 'A managed sync no longer parks forever on a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: the file is held `worktree_dirty` with the rest of the source synced, the cursor finishes, and committing the file (or `gbrain sync unblock --source <id> --apply`) imports it. Before, that refusal (`source_changed` / `pinned_git_worktree_conflict`, "Canonical sanitization cannot overwrite newer working-tree bytes.") blocked the cursor with no exit: `--retry-failed` replayed the same pin, `sources refresh` refused `sync_in_progress` and `--acknowledge-managed` refused `cursor_unfinished`. A cursor an older release left blocked this way converts on its next `--retry-failed` run. Working-tree bytes that already are the correction (gbrain\'s own writeback, published before its request settled) import without a second write.' },];diff --git a/src/core/config.ts b/src/core/config.tsindex 32ff08c483..c0363e2c0a 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1411,6 +1411,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)'search.temporal_fact_reserve', // temporal-cue queries reserve up to 15% of the token budget for question-ranked dated facts (default off; search/facts-arm.ts)'think.return_unit',+ 'entity.names_references', 'entity.record_types', // entity rows: count + card next (default on), record types (default empty); entity-references-config.ts'think.pages_budget_chars', // #5461: total chars for the synthesize pages block (4000-200000, default 12000; soft: the 600-char floor wins); think/pages-budget.ts'think.excerpt_ceiling_chars', // #5461: per-page excerpt cap for the synthesize pages block (600-200000, default 2400); think/pages-budget.ts// Models tier system (v0.31.12)diff --git a/src/core/entity-references-config.ts b/src/core/entity-references-config.tsnew file mode 100644index 0000000000..6b004010c0--- /dev/null+++ b/src/core/entity-references-config.ts@@ -0,0 +1,35 @@+/**+ * Config for the reference fields on compact entity rows (`entity names`,+ * `context_pack` cards) and the record view they carry.+ *+ * - `entity.names_references` (default on): every found `entity names` row+ * (and each identity sibling) carries `referenced_by_count` and a row-level+ * `next` to the full card. `false` leaves the rows as before.+ * - `entity.record_types` (default empty): the canonical page types that+ * count as records (contracts, amendments, orders, …). When it names a type,+ * rows list those referring pages under `records`, newest page date first;+ * empty leaves records off. A stored type alias is read as its pack type.+ *+ * Fail-closed: a read error keeps the defaults (names rows on, records off).+ */+import type { BrainEngine } from './engine.ts';+import { isConfigTruthy } from './config.ts';+import { parseNameList } from './mentions/policy.ts';++export const ENTITY_NAMES_REFERENCES_KEY = 'entity.names_references';+export const ENTITY_RECORD_TYPES_KEY = 'entity.record_types';++export interface EntityReferencesConfig {+ namesRow: boolean;+ recordTypes: string[];+}++export async function readEntityReferencesConfig(engine: Pick<BrainEngine, 'getConfig'>): Promise<EntityReferencesConfig> {+ try {+ const [names, types] = await Promise.all([engine.getConfig(ENTITY_NAMES_REFERENCES_KEY), engine.getConfig(ENTITY_RECORD_TYPES_KEY)]);+ const namesRow = names === null || names === undefined || String(names).trim() === '' ? true : isConfigTruthy(names);+ return { namesRow, recordTypes: [...new Set(parseNameList(types))] };+ } catch {+ return { namesRow: true, recordTypes: [] };+ }+}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1d1834c163..c45dd690c4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -511,6 +511,8 @@ export const NOTICE_CODES = {migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },+ record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },+ references_unavailable: { kind: 'degraded', summary: 'The reference count and records on entity rows did not finish (deadline or read failure); rows marked references_unavailable are unread, not empty.' },listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },identity_siblings_capped: { kind: 'info', summary: 'More than three pages share an entity\'s title subject, so the card shows no identity siblings; the fix (for the user) lists them with `gbrain extract mentions --explain`.' },diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.tsindex 86598c6b04..7ce9ad7f3d 100644--- a/src/core/mentions/referrers.ts+++ b/src/core/mentions/referrers.ts@@ -94,11 +94,18 @@ async function targetPages(engine: BrainEngine, scope: ReferrerScope): Promise<{* ids are collected once in `refs`, so a hub with thousands of inbound links* costs one hashed membership test per candidate page.*/+/** The caller's read filters, shared by the single-target CTE and its batched variant. */+function referrerFilters(scope: Pick<ReferrerScope, 'excludePrivate' | 'eligibility' | 'includeQuarantined'>) {+ return {+ targetPriv: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '',+ linkPriv: scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '',+ pagePriv: scope.excludePrivate ? ` AND ${privatePagesFilterFragmentFast('f')}` : '',+ pageTrust: ` AND ${pageEligibleSql('f', scope.eligibility)}${scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('f')}`}`,+ };+}+function referrersCte(scope: ReferrerScope): string {- const targetPriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '';- const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '';- const pagePriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragmentFast('f')}` : '';- const pageTrust = ` AND ${pageEligibleSql('f', scope.eligibility)}${scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('f')}`}`;+ const { targetPriv, linkPriv, pagePriv, pageTrust } = referrerFilters(scope);return `WITH tgt AS MATERIALIZED (SELECT t.id FROM pages t JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON t.source_id = k.s AND t.slug = k.gWHERE t.deleted_at IS NULL${targetPriv}@@ -175,7 +182,7 @@ export async function referrerTypes(engine: BrainEngine, scope: ReferrerScope):/** One page of referring pages (newest first), optionally of one type. */export async function readReferrerPage(engine: BrainEngine, scope: ReferrerScope,- opts: { type?: string; limit: number; cursor?: [string | null, string, string] | null }): Promise<{ rows: ReferenceRow[]; total: number; truncated: boolean; cursor: string | null }> {+ opts: { type?: string; limit: number; cursor?: [string | null, string, string] | null; recordMetadata?: boolean }): Promise<{ rows: Array<ReferenceRow & RecordMetadata>; total: number; truncated: boolean; cursor: string | null }> {const t = await targetPages(engine, scope);const pairs = typeAliasPairs(scope.pack);const params: unknown[] = [t.sources, t.slugs, scope.referrerSources, pairs.stored, pairs.canonical, opts.type ?? null];@@ -194,7 +201,12 @@ export async function readReferrerPage(engine: BrainEngine, scope: ReferrerScopeWHERE ${typeFilter}${after}ORDER BY d DESC NULLS LAST, source_id, slug LIMIT $${params.length}`, params);const truncated = raw.length > opts.limit;- const rows = await hydrate(engine, raw.slice(0, opts.limit), scope.keepVisibility);+ const page = raw.slice(0, opts.limit);+ const rows: Array<ReferenceRow & RecordMetadata> = await hydrate(engine, page, scope.keepVisibility);+ if (opts.recordMetadata) {+ const meta = await readRecordMetadata(engine, page.map(r => Number(r.id)), scope);+ page.forEach((r, i) => Object.assign(rows[i]!, meta.get(Number(r.id)) ?? {}));+ }return { rows, total: Number(count?.n ?? 0), truncated, cursor: truncated ? encodeCursor(rows[rows.length - 1]!) : null };}@@ -243,3 +255,235 @@ export async function readReferrerGroups(engine: BrainEngine, scope: ReferrerScoreturn { total: groups.reduce((n, g) => n + g.total, 0), groups };}++// ---------------------------------------------------------------------------+// Records: the referring pages of enrolled record types, for many entities at once+// ---------------------------------------------------------------------------++/** Record rows per target page (all of them when it has this many or fewer). */+export const RECORD_ROWS_PER_TARGET = 5;+/** Record rows per call, allotted to target pages in input order. */+export const RECORD_ROWS_PER_CALL = 24;+/** `amends` / `supersedes` entries kept per record row. */+export const RECORD_LINKS_CAP = 5;+/** A frontmatter `status` longer than this, or not a string, is not shown. */+export const PAGE_STATUS_MAX_CHARS = 40;++/** The metadata a record row adds to a referring page; shared by the record view and its `get_backlinks` continuation. */+export interface RecordMetadata {+ /** The page's own frontmatter `status` (a string up to PAGE_STATUS_MAX_CHARS), only when set. */+ page_status?: string;+ /** Records this page amends (an `amends` link), each with the terms-start date its link records (`since`), when recorded. */+ amends?: Array<{ slug: string; since?: string }>;+ /** Records this page replaces as a whole (a `supersedes` link). */+ supersedes?: Array<{ slug: string }>;+}++/** One record: the referring page, its own date labeled as a page date with its source, and its record metadata. */+export interface RecordRow extends RecordMetadata {+ slug: string;+ title: string;+ /** The page's own date (when it was written or dated), not when its terms take effect. */+ date: string | null;+ date_source: string;+}++export interface RecordGroupRaw {+ canonical_type: string;+ total: number;+ rows: RecordRow[];+ /** The cursor that continues this type after the last shown row (null when no row is shown). */+ cursor: string | null;+ /** Why rows < total: the per-page cap, or the per-call cap (an earlier entity in the call took the rows). */+ capped?: 'per_page' | 'per_call';+}++export interface TargetReferences {+ /** Distinct referring pages, every type (the card's `referenced_by_count`). */+ referenced_by_count: number;+ /** Record groups, one per enrolled type with at least one record, newest group first. Absent when nothing is enrolled. */+ records?: RecordGroupRaw[];+}++export interface RecordTarget { slug: string; sourceId: string }++/** Enrolled types as pack-canonical types (a stored alias maps to its type), in enrollment order. */+export function canonicalRecordTypes(types: string[], pack: PackTypes | null): string[] {+ const pairs = typeAliasPairs(pack);+ return [...new Set(types.map(t => pairs.canonical[pairs.stored.indexOf(t)] ?? t))];+}++/**+ * The batched variant of `referrersCte`: the same membership, filters and+ * date, with a target index `i` on every row so many entities are read in+ * one statement. Params $1..$3 are the targets (sources, slugs, indexes);+ * $4 referrer sources; $5/$6 the stored type aliases and their canonical types.+ */+function referrersCteBatched(scope: Pick<ReferrerScope, 'excludePrivate' | 'eligibility' | 'includeQuarantined'>): string {+ const { targetPriv, linkPriv, pagePriv, pageTrust } = referrerFilters(scope);+ return `WITH tgt AS MATERIALIZED (+ SELECT k.i, t.id FROM pages t JOIN unnest($1::text[], $2::text[], $3::int[]) AS k(s, g, i) ON t.source_id = k.s AND t.slug = k.g+ WHERE t.deleted_at IS NULL${targetPriv}+ ),+ refs AS MATERIALIZED (+ SELECT DISTINCT tg.i, l.from_page_id AS id FROM links l JOIN tgt tg ON l.to_page_id = tg.id WHERE true${linkPriv}+ ),+ typed AS MATERIALIZED (+ SELECT r.i, f.id, f.slug, f.source_id, f.type,+ COALESCE(f.effective_date, f.updated_at) AS d,+ COALESCE(($6::text[])[array_position($5::text[], f.type)], NULLIF(f.type, ''), 'untyped') AS canonical_type+ FROM refs r JOIN pages f ON f.id = r.id+ WHERE f.deleted_at IS NULL AND f.source_id = ANY($4::text[])+ AND NOT EXISTS (SELECT 1 FROM tgt x WHERE x.i = r.i AND x.id = f.id)${pagePriv}${pageTrust}+ )`;+}++/**+ * The record metadata of referring pages: `page_status` from frontmatter,+ * `amends` and `supersedes` links to pages the caller can see (link origins+ * under the same privacy rule as the referrer read), and each amends link's+ * `since` from the temporal relationship state for the caller's scope+ * (`world` for untrusted callers, so a date whose only evidence is private+ * stays hidden).+ */+export async function readRecordMetadata(engine: BrainEngine, pageIds: number[],+ scope: Pick<ReferrerScope, 'excludePrivate' | 'includeQuarantined'>): Promise<Map<number, RecordMetadata>> {+ const out = new Map<number, RecordMetadata>();+ if (!pageIds.length) return out;+ const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '';+ const targetPriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '';+ const targetQuarantine = scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('t')}`;+ const [status, links] = await Promise.all([+ engine.executeRaw<{ id: number; status: unknown }>(`SELECT id, frontmatter->'status' AS status FROM pages WHERE id = ANY($1::int[])`, [pageIds]),+ engine.executeRaw<{ from_id: number; slug: string; link_type: string; since: string | null }>(+ `SELECT DISTINCT l.from_page_id AS from_id, t.slug, l.link_type,+ CASE WHEN l.link_type = 'amends' THEN to_char(r.first_start, 'YYYY-MM-DD') END AS since+ FROM links l JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL${targetPriv}${targetQuarantine}+ LEFT JOIN link_relationships r ON r.from_page_id = l.from_page_id AND r.to_page_id = l.to_page_id+ AND r.link_type = l.link_type AND r.scope = $2+ WHERE l.from_page_id = ANY($1::int[]) AND l.link_type IN ('amends', 'supersedes')${linkPriv}+ ORDER BY l.from_page_id, t.slug`, [pageIds, scope.excludePrivate ? 'world' : 'all']).catch(() => []),+ ]);+ for (const row of status) {+ const raw = typeof row.status === 'string' ? row.status : null;+ const value = raw?.trim();+ if (value && value.length <= PAGE_STATUS_MAX_CHARS) out.set(Number(row.id), { page_status: value });+ }+ for (const link of links) {+ const id = Number(link.from_id);+ const meta = out.get(id) ?? {};+ if (link.link_type === 'amends') {+ const list = meta.amends ?? [];+ const existing = list.find(a => a.slug === link.slug);+ if (existing) { if (!existing.since && link.since) existing.since = link.since; }+ else if (list.length < RECORD_LINKS_CAP) list.push({ slug: link.slug, ...(link.since ? { since: link.since } : {}) });+ meta.amends = list;+ } else {+ const list = meta.supersedes ?? [];+ if (!list.some(s => s.slug === link.slug) && list.length < RECORD_LINKS_CAP) list.push({ slug: link.slug });+ meta.supersedes = list;+ }+ out.set(id, meta);+ }+ return out;+}++interface RecordCandidate { i: number; id: number; slug: string; source_id: string; canonical_type: string; d: string | null }++/**+ * `referenced_by_count` and the enrolled-type records of many target pages in+ * one batched read. Each target expands like the single-target read (its+ * identity co-members under `entity_identity.union`), and its rows, totals+ * and cursors equal `readReferrerPage(…, { type })` for that target: records+ * are filtered by type inside the membership query, before ORDER BY, LIMIT+ * and hydration. Rows per target are capped at RECORD_ROWS_PER_TARGET, newest+ * page date first across the target's record types; the call cap is applied+ * after, in target order, before hydration. Targets repeating a page reuse+ * its result without taking more of the call cap.+ */+export async function readTargetReferences(engine: BrainEngine,+ scope: Omit<ReferrerScope, 'slug' | 'sourceId'>, targets: RecordTarget[],+ opts: { recordTypes: string[]; perTarget?: number; perCall?: number; isExpired?: () => boolean }): Promise<TargetReferences[]> {+ const keyOf = (t: RecordTarget) => `${t.sourceId}\0${t.slug}`;+ const unique: RecordTarget[] = [];+ const index = new Map<string, number>();+ for (const t of targets) if (!index.has(keyOf(t))) { index.set(keyOf(t), unique.length); unique.push(t); }+ if (!unique.length) return [];+ const expanded = await Promise.all(unique.map(t => targetPages(engine, { ...scope, slug: t.slug, sourceId: t.sourceId })));+ const sources: string[] = [];+ const slugs: string[] = [];+ const idx: number[] = [];+ expanded.forEach((e, i) => e.slugs.forEach((slug, j) => { sources.push(e.sources[j]!); slugs.push(slug); idx.push(i); }));+ const pairs = typeAliasPairs(scope.pack);+ const recordTypes = canonicalRecordTypes(opts.recordTypes, scope.pack);+ const base = [sources, slugs, idx, scope.referrerSources, pairs.stored, pairs.canonical];+ const expired = () => opts.isExpired?.() === true;+ const counts = await engine.executeRaw<{ i: number; canonical_type: string | null; n: number }>(+ `${referrersCteBatched(scope)}+ SELECT i, NULL::text AS canonical_type, count(*)::int AS n FROM typed GROUP BY i+ UNION ALL+ SELECT i, canonical_type, count(*)::int AS n FROM typed WHERE canonical_type = ANY($7::text[]) GROUP BY i, canonical_type`,+ [...base, recordTypes]);+ if (expired()) throw new ReferencesDeadlineError();+ const perTarget = opts.perTarget ?? RECORD_ROWS_PER_TARGET;+ const candidates = recordTypes.length ? await engine.executeRaw<RecordCandidate>(+ `${referrersCteBatched(scope)}+ SELECT x.i, x.id, x.slug, x.source_id, x.canonical_type, ${dateText('x.d')} AS d+ FROM (SELECT DISTINCT i FROM tgt) q CROSS JOIN LATERAL (+ SELECT * FROM typed t WHERE t.i = q.i AND t.canonical_type = ANY($7::text[])+ ORDER BY t.d DESC NULLS LAST, t.source_id, t.slug LIMIT $8+ ) x+ ORDER BY x.i, x.d DESC NULLS LAST, x.source_id, x.slug`, [...base, recordTypes, perTarget]) : [];+ if (expired()) throw new ReferencesDeadlineError();+ let left = opts.perCall ?? RECORD_ROWS_PER_CALL;+ const kept: RecordCandidate[] = [];+ const callCut = new Set<number>();+ for (let i = 0; i < unique.length; i++) {+ const mine = candidates.filter(c => Number(c.i) === i);+ const rows = mine.slice(0, Math.max(0, left));+ if (rows.length < mine.length) callCut.add(i);+ left -= rows.length;+ kept.push(...rows);+ }+ const hydrated = await hydrateRecords(engine, kept, scope);+ if (expired()) throw new ReferencesDeadlineError();+ const results = unique.map((_, i): TargetReferences => {+ const total = counts.find(c => Number(c.i) === i && c.canonical_type === null)?.n ?? 0;+ if (!recordTypes.length) return { referenced_by_count: Number(total) };+ const typeTotals = counts.filter(c => Number(c.i) === i && c.canonical_type !== null);+ const mine = kept.map((k, j) => ({ k, row: hydrated[j]! })).filter(x => Number(x.k.i) === i);+ const groups = typeTotals.map((c): RecordGroupRaw & { newest: string } => {+ const shown = mine.filter(x => x.k.canonical_type === c.canonical_type);+ const last = shown[shown.length - 1]?.k;+ const capped = shown.length >= Number(c.n) ? undefined : callCut.has(i) ? 'per_call' as const : 'per_page' as const;+ return { canonical_type: c.canonical_type!, total: Number(c.n), rows: shown.map(x => x.row),+ cursor: last ? encodeCursor({ date: last.d, source_id: last.source_id, slug: last.slug }) : null,+ ...(capped ? { capped } : {}), newest: shown[0]?.k.d ?? '' };+ }).sort((a, b) => b.newest.localeCompare(a.newest) || recordTypes.indexOf(a.canonical_type) - recordTypes.indexOf(b.canonical_type))+ .map(({ newest: _n, ...g }) => g);+ return { referenced_by_count: Number(total), records: groups };+ });+ return targets.map(t => results[index.get(keyOf(t))!]!);+}++async function hydrateRecords(engine: BrainEngine, rows: RecordCandidate[],+ scope: Pick<ReferrerScope, 'excludePrivate' | 'includeQuarantined'>): Promise<RecordRow[]> {+ if (!rows.length) return [];+ const ids = [...new Set(rows.map(r => Number(r.id)))];+ const [pages, meta] = await Promise.all([+ engine.executeRaw<{ id: number; title: string | null; date_source: string }>(+ `SELECT id, title, CASE WHEN effective_date IS NULL THEN 'updated_at' ELSE COALESCE(effective_date_source, 'effective_date') END AS date_source+ FROM pages WHERE id = ANY($1::int[])`, [ids]),+ readRecordMetadata(engine, ids, scope),+ ]);+ const byId = new Map(pages.map(p => [Number(p.id), p]));+ return rows.map(r => {+ const page = byId.get(Number(r.id));+ return { slug: r.slug, title: page?.title ?? r.slug, date: r.d, date_source: page?.date_source ?? 'updated_at', ...(meta.get(Number(r.id)) ?? {}) };+ });+}++/** The records/count phase ran past its deadline; callers show the unavailable marker. */+export class ReferencesDeadlineError extends Error {+ constructor() { super('references deadline'); this.name = 'ReferencesDeadlineError'; }+}diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex d92b4f2639..61bf6e0a03 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -23,7 +23,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. *//** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded']);export interface NoticeAudience {transport: Transport;diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.tsindex 94b7b436fa..93a7f3b7ad 100644--- a/src/core/ops/backlinks-paged.ts+++ b/src/core/ops/backlinks-paged.ts@@ -15,9 +15,10 @@ import type { Link, PageReadPolicy } from '../types.ts';import type { Notice } from '../agent-output.ts';import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';import {- decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,+ canonicalRecordTypes, decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,} from '../mentions/referrers.ts';import { mentionCoverageNotice, readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';+import { readEntityReferencesConfig } from '../entity-references-config.ts';export interface BacklinkPage {rows: ReferenceRow[];@@ -97,7 +98,10 @@ export async function readBacklinkPage(ctx: OperationContext, p: Record<string,if (!resolved) return { rows: [], total: 0, truncated: false, cursor: null, coverage };const type = typeof p.type === 'string' && p.type ? p.type : undefined;if (type) await assertKnownType(ctx, resolved.scope, type);- return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor }), coverage };+ // F1: a record type's continuation rows carry the same record metadata as the record view (membership unchanged).+ const recordMetadata = type !== undefined && canonicalRecordTypes((await readEntityReferencesConfig(ctx.engine)).recordTypes, resolved.scope.pack)+ .includes(canonicalTypeOf(type, resolved.scope.pack));+ return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor, recordMetadata }), coverage };}/**diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex fcc0f94929..3584cf2c67 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -731,7 +731,15 @@ const context_pack: Operation = {// Pack, price and render the redacted presentation sets (one echo// dictionary); local callers get the delivered facts back raw below.const rawFacts = await withProvenance(ctx.engine, sourceId, res.facts ?? []);- const view = redactRetrievalOutput([{ cards: res.cards ?? [], facts: rawFacts }], {}).results[0];+ // F1 records (pull verb only; the ambient push path never reads them): the count and enrolled-type records of each card.+ const { readPackReferences, renderRecordLines, RECORDS_HEADER } = await import('../verbs/entity-references.ts');+ type PackRefs = Awaited<ReturnType<typeof readPackReferences>>;+ const packRefs: PackRefs = await readPackReferences(ctx.engine, sourceId, res.cards ?? [], { remote: !includePrivate, eligibility, surfaceCeiling: ctx.surfaceCeiling,+ emitNotice: (n) => ctx.emitNotice?.(n) })+ .catch((): PackRefs => ({ bySlug: new Map(), notice: null }));+ if (packRefs.notice) ctx.emitNotice?.(packRefs.notice);+ const withRefs = (res.cards ?? []).map((c) => (packRefs.bySlug.has(c.entity.slug) ? { ...c, ...packRefs.bySlug.get(c.entity.slug) } : c));+ const view = redactRetrievalOutput([{ cards: withRefs, facts: rawFacts }], {}).results[0];let cards = view.cards;let facts = view.facts;// The SAME since filter the assembler applied (pre-landing review: the raw@@ -760,6 +768,14 @@ const context_pack: Operation = {: dropAll(withMentions);const keptMentions = new Set(mentionPack.items);cards = cards.map((c) => (c.newer_mentions && !keptMentions.has(c) ? { ...c, newer_mentions: undefined } : c));+ // Records pack last, into what everything else left; a card whose records do not fit keeps its count.+ const recordBudget = mentionBudget - mentionPack.meta.used - lineCost('') - lineCost(RECORDS_HEADER);+ const withRecords = cards.filter((c) => renderRecordLines(c).length);+ const recordPack = recordBudget > 0+ ? packToBudget(withRecords, (c) => renderRecordLines(c).reduce((n, l) => n + lineCost(l), 0), recordBudget)+ : dropAll(withRecords);+ const keptRecords = new Set(recordPack.items);+ cards = cards.map((c) => (renderRecordLines(c).length && !keptRecords.has(c) ? { ...c, records: undefined, sibling_records: undefined } : c));droppedCount = cardPack.meta.dropped + factPack.meta.dropped;}const open_threads = cards.flatMap(threadsOf);@@ -767,7 +783,9 @@ const context_pack: Operation = {// `text` is what harnesses inject, so it must honor the same budget the// structured arrays report — the assembler's pre-budget rendering would// overrun the declared budget_tokens. budget_used reports that text.- const packText = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;+ const recordLines = cards.flatMap(renderRecordLines);+ const basePack = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;+ const packText = recordLines.length ? [basePack, ['', RECORDS_HEADER, ...recordLines].join('\n')].filter(Boolean).join('\n') : basePack;const text = [coreText, packText].filter(Boolean).join('\n\n');const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;@@ -787,6 +805,10 @@ const context_pack: Operation = {...(c.quarantined ? { quarantined: true } : {}),...(c.unconfirmed ? { unconfirmed: true } : {}),...(c.newer_mentions ? { newer_mentions: c.newer_mentions } : {}),+ ...(c.referenced_by_count !== undefined ? { referenced_by_count: c.referenced_by_count } : {}),+ ...(c.records ? { records: c.records } : {}),+ ...(c.sibling_records ? { sibling_records: c.sibling_records } : {}),+ ...(c.references_unavailable ? { references_unavailable: c.references_unavailable } : {}),})),open_threads,facts: (ctx.remote === false ? rawFacts.slice(0, facts.length) : facts).map((f) => ({diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 8069dd5845..20f97f658d 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -229,7 +229,8 @@ const entity: Operation = {`Pass either name: "Alice Example" for one full card, or names: ["Alice Example", "WGCO"] (up to ${ENTITY_NAMES_MAX}) for compact rows.`);}const t0 = Date.now();- const out = await lookupEntityNames(ctx.engine, ctx.sourceId ?? 'default', names, { remote: ctx.remote !== false, surfaceCeiling: ctx.surfaceCeiling });+ const out = await lookupEntityNames(ctx.engine, ctx.sourceId ?? 'default', names, { remote: ctx.remote !== false, surfaceCeiling: ctx.surfaceCeiling,+ emitNotice: n => ctx.emitNotice?.(n) });return { protocol_version: 1, latency_ms: Date.now() - t0, ...out };}const name = typeof p.name === 'string' ? p.name.trim() : '';@@ -245,6 +246,7 @@ const entity: Operation = {const result = await buildEntityCard(ctx.engine, ctx.sourceId ?? 'default', name, {remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling,omitQuarantined: ctx.remote !== false, // #5575: like get_page, a remote reader never gets a quarantined page's card+ emitNotice: n => ctx.emitNotice?.(n),});const coverage = result.card?.coverage ?? result.coverage;if (coverage) {@@ -505,6 +507,27 @@ const REFERENCE_ROW_SCHEMA = {},} as const;+/** One record group (verbs/entity-references.ts): referring pages of an enrolled record type, newest page date first. */+const RECORD_GROUP_SCHEMA = {+ type: 'object',+ required: ['canonical_type', 'total', 'rows'],+ properties: {+ canonical_type: { type: 'string' },+ total: { type: 'integer' },+ rows: { type: 'array', items: { type: 'object', required: ['slug', 'title', 'date', 'date_source'], properties: {+ slug: { type: 'string' }, title: { type: 'string' }, date: { type: ['string', 'null'] }, date_source: { type: 'string' },+ page_status: { type: 'string' },+ amends: { type: 'array', items: { type: 'object', required: ['slug'], properties: { slug: { type: 'string' }, since: { type: 'string' } } } },+ supersedes: { type: 'array', items: { type: 'object', required: ['slug'], properties: { slug: { type: 'string' } } } },+ } } },+ capped: { type: 'string', enum: ['per_page', 'per_call'] },+ next: { type: 'object', required: ['tool', 'arguments'], properties: {+ tool: { type: 'string', const: 'get_backlinks' }, arguments: { type: 'object' }, requires_surface: { type: 'string', enum: ['starter'] } } },+ },+} as const;++const REFERENCES_UNAVAILABLE_SCHEMA = { type: 'string', enum: ['deadline', 'read_failed'] } as const;+const RECALL_BUDGET_ARM_SCHEMA = {type: 'object',required: ['candidates', 'kept', 'dropped', 'used'],@@ -689,6 +712,9 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {},},coverage: COVERAGE_SCHEMA,+ // F1 record view — ADDITIVE OPTIONAL (frozen-v1 legal): only when record types are enrolled.+ records: { type: 'array', items: RECORD_GROUP_SCHEMA },+ references_unavailable: REFERENCES_UNAVAILABLE_SCHEMA,},},coverage: COVERAGE_SCHEMA,@@ -827,6 +853,13 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {},backlink_count: { type: 'integer' },relationship_note: { type: 'string' },+ // F1 record view — ADDITIVE OPTIONAL: only when record types are enrolled (pull verb only).+ referenced_by_count: { type: 'integer' },+ records: { type: 'array', items: RECORD_GROUP_SCHEMA },+ sibling_records: { type: 'array', items: { type: 'object', required: ['slug', 'title'], properties: {+ slug: { type: 'string' }, title: { type: 'string' }, referenced_by_count: { type: 'integer' },+ records: { type: 'array', items: RECORD_GROUP_SCHEMA }, references_unavailable: REFERENCES_UNAVAILABLE_SCHEMA } } },+ references_unavailable: REFERENCES_UNAVAILABLE_SCHEMA,},},},diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.tsindex 47b59c2a68..57f4053277 100644--- a/src/core/verbs/entity-card-identity.ts+++ b/src/core/verbs/entity-card-identity.ts@@ -23,6 +23,7 @@ import { sanitizeRemoteBody } from '../remote-body.ts';import { ALIAS_ORIGIN_RANK, declarationsIn, titleName, type AliasOrigin } from '../mentions/aliases.ts';import { readIdentitySiblings, SIBLING_GROUP_CAP } from '../mentions/siblings.ts';import type { Notice } from '../agent-output.ts';+import type { RecordGroupView } from './entity-references.ts';export const EXCERPT_PAGE_CHARS = 600;export const EXCERPT_CARD_CHARS = 1200;@@ -97,7 +98,8 @@ export function excerptLines(body: string, title: string, budget = EXCERPT_PAGE_export interface CardIdentity {aka_sources: Array<{ origin: string; slug: string }>;- identity_siblings?: { pages: Array<{ slug: string; title: string; type: string | null; aka: string[] }>; capped: boolean };+ /** Each sibling page; `records` (the full card's record view for that sibling) only when record types are enrolled. */+ identity_siblings?: { pages: Array<{ slug: string; title: string; type: string | null; aka: string[]; records?: RecordGroupView[] }>; capped: boolean };identity_excerpt?: IdentityExcerptLine[];identity_excerpt_omitted?: string[];alias_guidance?: { text: string; requires_surface?: 'starter' };diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 8c672fb8a2..f1bd33b027 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -37,6 +37,8 @@ import type { NewerMentions } from '../mentions/newer-mentions.ts';import { loadLinkableTypes } from '../mentions/policy.ts';import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';+import { readRowReferences, referencesUnavailableNotice, type RecordGroupView, type ReferencesUnavailable, type RowReferences } from './entity-references.ts';+import type { Notice } from '../agent-output.ts';import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';import { factEntitySlugs } from '../mentions/siblings.ts';@@ -111,6 +113,15 @@ export interface EntityCard {referenced_by_count?: number;/** Those pages grouped by pack-canonical type, newest first; capped per group and per card. `entity` verb only. */referenced_by?: ReferenceGroupView[];+ /**+ * The referring pages of the enrolled record types (`entity.record_types`), one group per type, newest page date first+ * (the order never says which record governs). `entity` and `context_pack` only, and only when types are enrolled.+ */+ records?: RecordGroupView[];+ /** `context_pack` cards: the same reference fields for each identity sibling, side by side, never merged. */+ sibling_records?: Array<{ slug: string; title: string } & RowReferences>;+ /** The reference count and records could not be read (deadline or failure); unread, not empty. */+ references_unavailable?: ReferencesUnavailable;/** Whether every page in this source has been scanned for this entity's names. `entity` verb only. */coverage?: MentionCoverage;/** Parallel to `aka`: each entry's origin (frontmatter, declared, subject) and the page that declares it. `entity` verb only. */@@ -163,6 +174,8 @@ export interface EntityCardOpts {includeReferences?: boolean;/** The serving surface ceiling; on `verbs` a continuation names the starter surface. */surfaceCeiling?: 'verbs' | 'starter' | 'full';+ /** Receives the degraded notice when the card's references or records could not be read. */+ emitNotice?: (n: Notice) => void;/*** #5575 (ENG-8, CEO-20): the eligibility for the card's facts and timeline* rows. Always hides quarantined-page projections and rows awaiting@@ -326,6 +339,7 @@ export async function buildEntityCard(if (opts.includeReferences) {Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes),await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));+ await attachCardRecords(engine, sourceId, card, opts, excludePrivate);}return {found: true,@@ -346,7 +360,7 @@ function exactMatchPreference(row: CardPageRow, exactSlugs: string[], entityType* read leaves the card without them rather than failing the lookup.*/async function cardReferences(engine: BrainEngine, sourceId: string, row: CardPageRow, opts: EntityCardOpts, excludePrivate: boolean,- entityTypes: ReadonlySet<string>): Promise<Pick<EntityCard, 'referenced_by_count' | 'referenced_by' | 'coverage'>> {+ entityTypes: ReadonlySet<string>): Promise<Pick<EntityCard, 'referenced_by_count' | 'referenced_by' | 'coverage' | 'references_unavailable'>> {try {const { pack } = await loadLinkableTypes(engine, sourceId);const { total, groups } = await readReferrerGroups(engine, { slug: row.slug, sourceId, referrerSources: [sourceId], excludePrivate, pack,@@ -363,10 +377,24 @@ async function cardReferences(engine: BrainEngine, sourceId: string, row: CardPa});return { referenced_by_count: total, referenced_by, coverage };} catch {- return {};+ opts.emitNotice?.(referencesUnavailableNotice('read_failed'));+ return { references_unavailable: 'read_failed' };}}+/** The full card's record view for the page and each identity sibling (records only: the card has its own count). */+async function attachCardRecords(engine: BrainEngine, sourceId: string, card: EntityCard, opts: EntityCardOpts, excludePrivate: boolean): Promise<void> {+ const siblings = card.identity_siblings?.pages ?? [];+ const refs = await readRowReferences(engine, sourceId, [card.entity.slug, ...siblings.map(p => p.slug)].map(slug => ({ slug, sourceId })),+ { remote: opts.remote, excludePrivate, surfaceCeiling: opts.surfaceCeiling, eligibility: opts.eligibility, surface: 'full_card', emitNotice: opts.emitNotice });+ const [own, ...rest] = refs.rows;+ if (own?.records) card.records = own.records;+ siblings.forEach((p, i) => { if (rest[i]?.records) Object.assign(p, { records: rest[i]!.records }); });+ if (!own?.references_unavailable || card.references_unavailable) return;+ card.references_unavailable = own.references_unavailable;+ if (refs.notice) opts.emitNotice?.(refs.notice);+}+async function assembleCard(engine: BrainEngine,sourceId: string,diff --git a/src/core/verbs/entity-names.ts b/src/core/verbs/entity-names.tsindex d0feb4c358..97c8f3a081 100644--- a/src/core/verbs/entity-names.ts+++ b/src/core/verbs/entity-names.ts@@ -5,22 +5,30 @@* (buildEntityCard's alias, slug, title and fuzzy arms; private and* quarantined pages, siblings included, hidden from remote callers) and returns a compact row: the page, its names, the* opening lines of its body (`lead`) and its identity siblings with theirs.- * No references, facts or open threads: a full card per name is `entity name:`.+ * Each found page and sibling also carries `referenced_by_count` and a `next`+ * to its full card (`entity.names_references`, default on), and `records`+ * when record types are enrolled (`entity.record_types`), from one batched+ * read for the whole call (verbs/entity-references.ts). No facts or open+ * threads: a full card per name is `entity name:`.** Bounded: at most ENTITY_NAMES_MAX names, ENTITY_LEAD_CHARS per lead,- * duplicates resolved once.+ * duplicates resolved once; records RECORD_ROWS_PER_TARGET per page and+ * RECORD_ROWS_PER_CALL per call, allotted in input order.*/import type { BrainEngine } from '../engine.ts';import { buildEntityCard } from './entity-card.ts';import { readCardIdentity } from './entity-card-identity.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { redactFindings } from '../secret-scan.ts';+import type { Notice } from '../agent-output.ts';+import { readRowReferences, type RowReferences } from './entity-references.ts';+import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';export const ENTITY_NAMES_MAX = 50;export const ENTITY_LEAD_CHARS = 200;const CONCURRENCY = 8;-export interface EntityNamePage { slug: string; title: string; type: string | null; aka: string[]; lead: string }+export interface EntityNamePage extends RowReferences { slug: string; title: string; type: string | null; aka: string[]; lead: string }export type EntityNameRow =| ({ name: string; found: true } & EntityNamePage & { siblings?: EntityNamePage[] })| { name: string; found: false; suggestions?: Array<{ slug: string; title: string }> };@@ -35,17 +43,36 @@ export function pageLead(body: string | null, max = ENTITY_LEAD_CHARS): string {}export async function lookupEntityNames(engine: BrainEngine, sourceId: string, names: string[],- opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full' }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {+ opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {const unique = [...new Set(names.map(n => n.trim()).filter(Boolean))];const rows = new Map<string, EntityNameRow>();for (let i = 0; i < unique.length; i += CONCURRENCY) {await Promise.all(unique.slice(i, i + CONCURRENCY).map(async name => rows.set(name, await lookupOne(engine, sourceId, name, opts))));}const results = unique.map(n => rows.get(n)!);+ await attachReferences(engine, sourceId, results, opts);const found = results.filter(r => r.found).length;return { results, found, missing: results.length - found };}+/** One batched reference read for every found page and sibling, in input order (page first, then its siblings). */+async function attachReferences(engine: BrainEngine, sourceId: string, results: EntityNameRow[],+ opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<void> {+ const pages: EntityNamePage[] = [];+ for (const r of results) if (r.found) pages.push(r, ...(r.siblings ?? []));+ if (!pages.length) return;+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');+ const excludePrivate = await resolveExcludePrivatePages(engine, opts.remote ? undefined : false);+ const refs = await readRowReferences(engine, sourceId, pages.map(p => ({ slug: p.slug, sourceId })),+ { remote: opts.remote, excludePrivate, surfaceCeiling: opts.surfaceCeiling, surface: 'names', emitNotice: opts.emitNotice });+ pages.forEach((p, i) => Object.assign(p, refs.rows[i]));+ if (refs.notice) opts.emitNotice?.(refs.notice);+ if (!refs.rows.some(r => r.referenced_by_count !== undefined || r.records)) return;+ const coverage = await readMentionCoverage(engine, [sourceId]).catch(() => null);+ const notice = coverage ? mentionCoverageNotice(coverage) : null;+ if (notice) opts.emitNotice?.(notice);+}+async function lookupOne(engine: BrainEngine, sourceId: string, name: string,opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full' }): Promise<EntityNameRow> {const result = await buildEntityCard(engine, sourceId, name, { remote: opts.remote, includeReferences: false, omitQuarantined: opts.remote });diff --git a/src/core/verbs/entity-references.ts b/src/core/verbs/entity-references.tsnew file mode 100644index 0000000000..95df8cb038--- /dev/null+++ b/src/core/verbs/entity-references.ts@@ -0,0 +1,229 @@+/**+ * The reference fields compact entity rows carry (`entity names` rows and+ * their identity siblings, `context_pack` cards and the full card's record+ * view), from one batched referrer read (mentions/referrers.ts):+ *+ * - `referenced_by_count` and a row-level `next` to the full card, under+ * `entity.names_references` (default on);+ * - `records`: the referring pages of the enrolled record types+ * (`entity.record_types`, empty by default), one group per type with its+ * `total` and, when rows < total, a `next` that returns exactly the rest.+ * Rows are newest page date first; the order never says which record+ * governs, and `date` is the page's own date, not when its terms start.+ *+ * Bounded (RECORD_ROWS_PER_TARGET per page, RECORD_ROWS_PER_CALL per call)+ * and under a cooperative deadline: a failed or late read marks every row+ * `references_unavailable` and emits one degraded notice, never an empty list.+ */+import type { BrainEngine } from '../engine.ts';+import { inertText, type Notice } from '../agent-output.ts';+import type { ReadEligibility } from '../eligibility/policy.ts';+import { loadSourcePack, type PackTypes } from '../mentions/policy.ts';+import { readEntityReferencesConfig, type EntityReferencesConfig } from '../entity-references-config.ts';+import {+ PAGE_MAX_LIMIT, ReferencesDeadlineError, canonicalRecordTypes, readTargetReferences,+ type RecordGroupRaw, type RecordRow, type RecordTarget,+} from '../mentions/referrers.ts';++/** Records and counts give up after this long; the rows say so. */+export const REFERENCES_DEADLINE_MS = 2000;+let deadlineOverride: number | null = null;+let delayForTests = 0;++/** Test seam: a shorter deadline and an injected delay before the read. */+export function __setReferencesTimingForTests(opts: { deadlineMs?: number | null; delayMs?: number }): () => void {+ const prev = { deadlineOverride, delayForTests };+ deadlineOverride = opts.deadlineMs ?? null;+ delayForTests = opts.delayMs ?? 0;+ return () => { deadlineOverride = prev.deadlineOverride; delayForTests = prev.delayForTests; };+}++export type ReferencesUnavailable = 'deadline' | 'read_failed';++export interface RecordGroupView {+ canonical_type: string;+ total: number;+ rows: RecordRow[];+ /** Why rows < total: `per_page` (RECORD_ROWS_PER_TARGET) or `per_call` (RECORD_ROWS_PER_CALL, taken by earlier entities). */+ capped?: 'per_page' | 'per_call';+ /** The call that returns exactly the remaining records of this type (`requires_surface` when this connection cannot call it). */+ next?: { tool: 'get_backlinks'; arguments: Record<string, unknown>; requires_surface?: 'starter' };+}++/** What a row gains: absent fields are switched off by config. */+export interface RowReferences {+ referenced_by_count?: number;+ next?: { tool: 'entity'; arguments: { name: string } };+ records?: RecordGroupView[];+ /** The count and records could not be read in time (or failed); not "no references". */+ references_unavailable?: ReferencesUnavailable;+}++export interface ReferencesRequest {+ remote: boolean;+ excludePrivate: boolean;+ surfaceCeiling?: 'verbs' | 'starter' | 'full';+ eligibility?: ReadEligibility;+ /**+ * `names`: count and card `next` under `entity.names_references`, records when enrolled.+ * `pack` (context_pack cards): count and records, only when enrolled. `full_card`: records only (it has its own count).+ */+ surface: 'names' | 'pack' | 'full_card';+ config?: EntityReferencesConfig;+ /** Receives the info notice naming enrolled record types the schema pack does not declare. */+ emitNotice?: (n: Notice) => void;+}++/** Whether this request computes anything (no read when every field is off). */+export function referencesWanted(config: EntityReferencesConfig, surface: ReferencesRequest['surface']): boolean {+ return config.recordTypes.length > 0 || (surface === 'names' && config.namesRow);+}++/**+ * The reference fields for each target page, in target order. Fail-soft:+ * a deadline or read failure marks every target unavailable (one notice).+ */+export async function readRowReferences(engine: BrainEngine, sourceId: string, targets: RecordTarget[], req: ReferencesRequest):+ Promise<{ rows: RowReferences[]; notice: Notice | null; config: EntityReferencesConfig }> {+ const config = req.config ?? await readEntityReferencesConfig(engine);+ if (!targets.length || !referencesWanted(config, req.surface)) return { rows: targets.map(() => ({})), notice: null, config };+ const deadlineMs = deadlineOverride ?? REFERENCES_DEADLINE_MS;+ const deadlineAt = Date.now() + deadlineMs;+ const isExpired = () => Date.now() >= deadlineAt;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let undeclared: string[] = [];+ const late = new Promise<'deadline'>(resolve => { timer = setTimeout(() => resolve('deadline'), deadlineMs); });+ const read = (async () => {+ if (delayForTests) await new Promise(r => setTimeout(r, delayForTests));+ if (isExpired()) throw new ReferencesDeadlineError();+ const pack = await loadSourcePack(engine, sourceId);+ undeclared = await undeclaredRecordTypes(engine, sourceId, config.recordTypes, pack).catch(() => []);+ return readTargetReferences(engine, { referrerSources: [sourceId], excludePrivate: req.excludePrivate, pack,+ keepVisibility: req.remote ? ['world'] : ['private', 'world'], eligibility: req.eligibility },+ targets, { recordTypes: canonicalRecordTypes(config.recordTypes, pack), isExpired });+ })();+ let raw: Awaited<typeof read> | ReferencesUnavailable;+ try {+ const won = await Promise.race([read, late]);+ raw = won === 'deadline' ? 'deadline' : won;+ } catch (e) {+ raw = e instanceof ReferencesDeadlineError ? 'deadline' : 'read_failed';+ } finally {+ clearTimeout(timer);+ }+ read.catch(() => {});+ if (typeof raw === 'string') {+ const reason = raw;+ return { rows: targets.map(() => ({ references_unavailable: reason })), notice: referencesUnavailableNotice(reason), config };+ }+ if (undeclared.length) req.emitNotice?.(undeclaredRecordTypesNotice(undeclared));+ const rows = raw.map((r, i): RowReferences => {+ const slug = targets[i]!.slug;+ const out: RowReferences = {};+ if (req.surface === 'names' ? config.namesRow : req.surface === 'pack' && config.recordTypes.length > 0) out.referenced_by_count = r.referenced_by_count;+ if (req.surface === 'names' && config.namesRow) out.next = { tool: 'entity', arguments: { name: slug } };+ if (r.records) out.records = r.records.map(g => recordGroupView(g, slug, sourceId, req.surfaceCeiling));+ return out;+ });+ return { rows, notice: null, config };+}++function recordGroupView(g: RecordGroupRaw, slug: string, sourceId: string, surfaceCeiling: ReferencesRequest['surfaceCeiling']): RecordGroupView {+ const view: RecordGroupView = { canonical_type: g.canonical_type, total: g.total, rows: g.rows };+ const remaining = g.total - g.rows.length;+ if (remaining <= 0) return view;+ if (g.capped) view.capped = g.capped;+ view.next = { tool: 'get_backlinks', arguments: { slug, source_id: sourceId, type: g.canonical_type, group: 'page',+ limit: Math.min(remaining, PAGE_MAX_LIMIT), ...(g.cursor ? { cursor: g.cursor } : {}) },+ ...(surfaceCeiling === 'verbs' ? { requires_surface: 'starter' as const } : {}) };+ return view;+}++/** One degraded notice for a call whose reference read did not finish. */+export function referencesUnavailableNotice(reason: ReferencesUnavailable): Notice {+ return {+ code: 'references_unavailable', kind: 'degraded',+ why: reason === 'deadline'+ ? 'The reference count and records for these entities did not finish in time; rows marked references_unavailable are unread, not empty.'+ : 'The reference count and records for these entities could not be read; rows marked references_unavailable are unread, not empty.',+ };+}++/** The `context_pack` records block: page dates, newest first; the order never says which record governs. */+export const RECORDS_HEADER = '## Records that reference these entities (page date = when the page was written, newest first; the order does not say which record governs)';++export interface PackCardReferences extends RowReferences {+ sibling_records?: Array<{ slug: string; title: string } & RowReferences>;+}++/**+ * `context_pack` (pull verb only, never the ambient push path): the count and+ * records of each card's page and its identity siblings, side by side, in one+ * batched read. Nothing is read unless record types are enrolled.+ */+export async function readPackReferences(engine: BrainEngine, sourceId: string, cards: Array<{ entity: { slug: string; title: string } }>,+ req: Omit<ReferencesRequest, 'surface' | 'excludePrivate'>): Promise<{ bySlug: Map<string, PackCardReferences>; notice: Notice | null }> {+ const bySlug = new Map<string, PackCardReferences>();+ const config = req.config ?? await readEntityReferencesConfig(engine);+ if (!cards.length || !referencesWanted(config, 'pack')) return { bySlug, notice: null };+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');+ const excludePrivate = await resolveExcludePrivatePages(engine, req.remote ? undefined : false);+ const { readIdentitySiblings } = await import('../mentions/siblings.ts');+ const siblings = await Promise.all(cards.map(c => readIdentitySiblings(engine, sourceId, c.entity, { excludePrivate, excludeQuarantined: true })));+ const targets: RecordTarget[] = [];+ cards.forEach((c, i) => targets.push({ slug: c.entity.slug, sourceId }, ...siblings[i]!.pages.map(p => ({ slug: p.slug, sourceId }))));+ const refs = await readRowReferences(engine, sourceId, targets, { ...req, excludePrivate, surface: 'pack', config });+ let at = 0;+ cards.forEach((c, i) => {+ const own: PackCardReferences = { ...refs.rows[at++] };+ const sib = siblings[i]!.pages.map(p => ({ slug: p.slug, title: p.title, ...refs.rows[at++] }));+ if (sib.length) own.sibling_records = sib;+ bySlug.set(c.entity.slug, own);+ });+ return { bySlug, notice: refs.notice };+}++function recordLine(owner: string, type: string, r: RecordRow): string {+ const parts = [`page date ${r.date ? r.date.slice(0, 10) : 'unknown'} (${r.date_source})`];+ if (r.page_status) parts.push(`status: ${r.page_status}`);+ if (r.amends?.length) parts.push(`amends ${r.amends.map(a => a.since ? `${a.slug} (terms start ${a.since})` : a.slug).join(', ')}`);+ if (r.supersedes?.length) parts.push(`supersedes ${r.supersedes.map(s => s.slug).join(', ')}`);+ return `- ${owner}: ${type} ${r.slug} "${inertText(r.title, 160)}" — ${parts.join('; ')}`;+}++/** The packed-text lines for one card's records (its page, then each sibling), with each type's total when rows were cut. */+export function renderRecordLines(card: { entity: { slug: string } } & PackCardReferences): string[] {+ const lines: string[] = [];+ const add = (owner: string, refs: RowReferences) => {+ if (refs.references_unavailable) { lines.push(`- ${owner}: records unavailable (${refs.references_unavailable}); unread, not empty`); return; }+ for (const g of refs.records ?? []) {+ for (const r of g.rows) lines.push(recordLine(owner, g.canonical_type, r));+ if (g.rows.length < g.total) lines.push(`- ${owner}: ${g.total - g.rows.length} more ${g.canonical_type} records (get_backlinks type ${g.canonical_type})`);+ }+ };+ add(card.entity.slug, card);+ for (const s of card.sibling_records ?? []) add(s.slug, s);+ return lines;+}++/** Enrolled record types that are neither declared by the source's schema pack (name or alias) nor the stored type of any live page. */+export async function undeclaredRecordTypes(engine: BrainEngine, sourceId: string, types: string[], pack: PackTypes | null): Promise<string[]> {+ const declared = new Set((pack?.page_types ?? []).flatMap(pt => [pt.name, ...(pt.aliases ?? [])]));+ const unknown = types.filter(t => !declared.has(t));+ if (!unknown.length) return [];+ const present = new Set((await engine.executeRaw<{ type: string }>(+ 'SELECT DISTINCT type FROM pages WHERE source_id = $1 AND type = ANY($2::text[]) AND deleted_at IS NULL', [sourceId, unknown])).map(r => r.type));+ return unknown.filter(t => !present.has(t));+}++/** An enrolled type the pack does not declare lists no records: say so instead of showing nothing. */+export function undeclaredRecordTypesNotice(types: string[]): Notice {+ const shown = types.map(t => inertText(t, 60)).join(', ');+ return {+ code: 'record_types_undeclared', kind: 'info',+ why: `entity.record_types names ${shown}, which neither this source's schema pack declares nor any page here uses, so no record of that type is listed.`,+ fix: { argv: ['gbrain', 'config', 'get', 'entity.record_types'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Shows the enrolled record types; set it to page types the schema pack declares (gbrain config set entity.record_types <types>).' },+ };+}+diff --git a/src/core/verbs/usage-log.ts b/src/core/verbs/usage-log.tsindex 20e3ed8dfb..1d4ade50fc 100644--- a/src/core/verbs/usage-log.ts+++ b/src/core/verbs/usage-log.ts@@ -39,6 +39,33 @@ export interface VerbUsageEvent {* doctor's memory_writeback check labels it exactly that way (OV-A11):* a per-call ambient/explicit distinction does not exist on the wire. */remember_status?: string;+ /** `entity` / `context_pack` with enrolled record types: rows that listed records, listed none, or were unavailable. */+ records_firing?: RecordsFiring;+}++export interface RecordsFiring { listed: number; zero: number; unavailable: number }++/**+ * The firing counter for a verb result (usage log): every row that carried+ * the record view, split into rows that listed records, rows that listed none+ * and rows marked unavailable. Null when no row carried it (nothing enrolled).+ */+export function recordsFiring(result: unknown): RecordsFiring | null {+ type Row = { found?: unknown; records?: unknown; references_unavailable?: unknown; siblings?: Row[]; sibling_records?: Row[];+ identity_siblings?: { pages?: Row[] } };+ const r = result as { results?: Row[]; cards?: Row[]; card?: Row } | null;+ const rows: Row[] = [];+ for (const x of r?.results ?? []) if (x?.found) rows.push(x, ...(x.siblings ?? []));+ for (const c of r?.cards ?? []) rows.push(c, ...(c.sibling_records ?? []));+ if (r?.card) rows.push(r.card, ...(r.card.identity_siblings?.pages ?? []));+ const counted = rows.filter(x => Array.isArray(x.records) || x.references_unavailable);+ if (!counted.length) return null;+ const listed = (x: Row) => Array.isArray(x.records) && x.records.length > 0;+ return {+ listed: counted.filter(listed).length,+ zero: counted.filter(x => Array.isArray(x.records) && x.records.length === 0).length,+ unavailable: counted.filter(x => x.references_unavailable).length,+ };}let _pathOverride: string | null = null;diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 2398f7405d..1e47b182ba 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -18,7 +18,7 @@ import { cliRenderContext, orderNotices, redactForTransport, renderNotice, toAgeimport { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger, type NoticeAudience } from '../core/notice-ledger.ts';-import { logVerbUsage } from '../core/verbs/usage-log.ts';+import { logVerbUsage, recordsFiring, type RecordsFiring } from '../core/verbs/usage-log.ts';import { searchCountLine } from '../core/search/keyword-paging.ts';import { dateLabelLine } from '../core/search/date-labels.ts';import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';@@ -754,7 +754,7 @@ export async function dispatchToolCall(const isVerb = VERB_NAME_SET.has(name);// [c11] dispatch-layer usage sidecar for the five verbs — counts validation// failures too. Fire-and-forget; never awaited, never throws.- const logVerb = (ok: boolean, extra?: { budget_dropped?: number; entity_found?: boolean; remember_status?: string }) => {+ const logVerb = (ok: boolean, extra?: { budget_dropped?: number; entity_found?: boolean; remember_status?: string; records_firing?: RecordsFiring }) => {if (!isVerb) return;logVerbUsage({verb: name,@@ -959,6 +959,7 @@ export async function dispatchToolCall(// the memory_writeback doctor counters read this (all-MCP-callers// semantics, labeled honestly there; OV-A11)....(name === 'remember' && typeof r?.status === 'string' ? { remember_status: r.status } : {}),+ ...((name === 'entity' || name === 'context_pack') && recordsFiring(result) ? { records_firing: recordsFiring(result)! } : {}),});}// D8: model-visible loudness for empty retrievals. The body stays a barediff --git a/test/e2e/entity-records-postgres.test.ts b/test/e2e/entity-records-postgres.test.tsnew file mode 100644index 0000000000..77a246525c--- /dev/null+++ b/test/e2e/entity-records-postgres.test.ts@@ -0,0 +1,33 @@+/**+ * Postgres twin of test/entity-records.test.ts: entity reference fields and+ * the record view on real Postgres (bound text[]/int[] targets, the batched+ * referrer CTE, LATERAL top-N and the temporal `since` join).+ */+import { afterAll, beforeAll, describe, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import * as S from '../helpers/entity-records-scenarios.ts';++const d = hasDatabase() ? describe : describe.skip;+let engine: BrainEngine;++d('entity records (Postgres)', () => {+ beforeAll(async () => {+ engine = await setupDB();+ await engine.executeRaw('DELETE FROM mention_gazetteer_entries');+ await engine.executeRaw('DELETE FROM mention_index_status');+ }, 120_000);+ afterAll(async () => { await S.resetRecordsWorld(engine); await teardownDB(); });++ test('names rows carry the count and a card next by default; the key turns them off', () => S.namesRowDefaults(engine), 60_000);+ test('enrolled records on names rows: groups, order, row shape, metadata, caps, continuations', () => S.recordsOnNamesRows(engine), 60_000);+ test('batched read equals the single-target read for every target, type and caller', () => S.batchedMatchesSingle(engine), 60_000);+ test('the per-call cap allots rows in input order and keeps every total and next', () => S.callCapInInputOrder(engine), 60_000);+ test('a forced-slow read is marked unavailable with a degraded notice', () => S.deadlineGivesUnavailable(engine), 60_000);+ test('context_pack records: structured, packed text, hidden referrers excluded, push path unchanged', () => S.contextPackRecords(engine), 60_000);+ test('the full card keeps referenced_by and gains records; an undeclared type says so', () => S.fullCardRecords(engine), 60_000);+ test('a failing read is marked unavailable on the card and names rows, with one notice', () => S.readFailureGivesUnavailable(engine), 60_000);+ test('zero records is an empty list; the firing counter separates listed, zero and unavailable', () => S.zeroRecordsAndFiring(engine), 60_000);+ test('every optional record field validates against the v1 response schemas', () => S.recordFieldsSchemaValid(engine), 60_000);+ test('records pack last under 1,500 and 2,000 token budgets; newer mentions unaffected', () => S.recordsPackLast(engine), 60_000);+});diff --git a/test/entity-card-perf.slow.test.ts b/test/entity-card-perf.slow.test.tsindex 9240ec944a..134fa5da06 100644--- a/test/entity-card-perf.slow.test.ts+++ b/test/entity-card-perf.slow.test.ts@@ -408,3 +408,72 @@ describe('delta p99 latency gate (v0.45.7 ambient recall)', () => {expect(p99).toBeLessThan(BOUNDARY_P99_BUDGET_MS);}, 300_000);});++// F1: `entity names` with the reference fields and records, 50 names with two identity siblings each (150 target+// pages). Gates: one batched referrer read per call (2 statements whatever the name count), and the reference phase+// adds at most REFERENCES_ADDED_CEILING to the same call with every reference field off (the names lookup itself, 50+// card resolutions, is the baseline; measured interleaved so runner load lands on both).+const REFERENCES_ADDED_CEILING = 0.5;+describe('entity names with records (50 names, 150 target pages)', () => {+ it(`50 names with siblings: references add at most ${REFERENCES_ADDED_CEILING * 100}% and a constant number of referrer statements`, async () => {+ const { lookupEntityNames } = await import('../src/core/verbs/entity-names.ts');+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const db = (engine as any).db;+ for (let i = 0; i < 50; i++) {+ for (const [prefix, label] of [['crm', 'CRM record'], ['accounts', 'Account sheet'], ['deals', 'Deal room']]) {+ await engine.putPage(`${prefix}/perf-account-${i}`, { type: 'company', title: `${label}: Perf Account ${i}`, compiled_truth: `Perf Account ${i}.`, frontmatter: {} }, { sourceId: 'default' });+ }+ }+ await db.query(+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source)+ SELECT f.id, t.id, '', 'markdown'+ FROM (SELECT id, row_number() OVER (ORDER BY id) rn FROM pages WHERE type = 'contract' ORDER BY id LIMIT 1500) f+ JOIN (SELECT id, row_number() OVER (ORDER BY id) rn FROM pages WHERE slug LIKE '%/perf-account-%') t ON (f.rn % 150) + 1 = t.rn+ ON CONFLICT DO NOTHING`);+ await engine.executeRaw('ANALYZE pages, links');+ const names = Array.from({ length: 50 }, (_, i) => `crm/perf-account-${i}`);+ let referrerStatements = 0;+ const raw = engine.executeRaw.bind(engine);+ engine.executeRaw = ((sql: string, params?: unknown[]) => {+ if (sql.includes('refs AS MATERIALIZED')) referrerStatements++;+ return raw(sql, params as never);+ }) as typeof engine.executeRaw;+ const on = async () => { await engine.setConfig('entity.record_types', 'contract'); await engine.unsetConfig('entity.names_references'); };+ const off = async () => { await engine.unsetConfig('entity.record_types'); await engine.setConfig('entity.names_references', 'false'); };+ try {+ for (let i = 0; i < 2; i++) { await on(); await lookupEntityNames(engine, 'default', names, { remote: true }); await off(); await lookupEntityNames(engine, 'default', names, { remote: true }); }+ const withRefs: number[] = [];+ const base: number[] = [];+ let last: Awaited<ReturnType<typeof lookupEntityNames>> | null = null;+ let statements = 0;+ for (let i = 0; i < 10; i++) {+ await on();+ referrerStatements = 0;+ let t0 = performance.now();+ last = await lookupEntityNames(engine, 'default', names, { remote: true });+ withRefs.push(performance.now() - t0);+ statements += referrerStatements;+ await off();+ t0 = performance.now();+ await lookupEntityNames(engine, 'default', names, { remote: true });+ base.push(performance.now() - t0);+ }+ withRefs.sort((a, b) => a - b);+ base.sort((a, b) => a - b);+ const added = percentile(withRefs, 50) / percentile(base, 50) - 1;+ // eslint-disable-next-line no-console+ console.log(`[entity-names-records-perf] 50 names / 150 targets with references p50=${percentile(withRefs, 50).toFixed(2)}ms ` ++ `| all reference fields off p50=${percentile(base, 50).toFixed(2)}ms | added=${(added * 100).toFixed(1)}% (ceiling ${REFERENCES_ADDED_CEILING * 100}%)`);+ const rows = last!.results.flatMap(r => (r.found ? [r, ...(r.siblings ?? [])] : []));+ expect(rows).toHaveLength(150);+ expect(rows.every(r => typeof r.referenced_by_count === 'number' && Array.isArray(r.records))).toBe(true);+ expect(rows.reduce((n, r) => n + (r.records ?? []).reduce((m, g) => m + g.rows.length, 0), 0)).toBe(24);+ expect(statements).toBe(10 * 2);+ expect(added).toBeLessThanOrEqual(REFERENCES_ADDED_CEILING);+ } finally {+ engine.executeRaw = raw;+ await engine.unsetConfig('entity.record_types');+ await engine.unsetConfig('entity.names_references');+ }+ }, 300_000);+});diff --git a/test/entity-records.test.ts b/test/entity-records.test.tsnew file mode 100644index 0000000000..dfff4a4cc9--- /dev/null+++ b/test/entity-records.test.ts@@ -0,0 +1,33 @@+/**+ * Entity reference fields and the record view (PGLite). The same scenarios run+ * on Postgres in test/e2e/entity-records-postgres.test.ts.+ *+ * Protects: compact `entity names` rows carry `referenced_by_count` and a card+ * `next` by default, and enrolled record types as `records` (page date labeled+ * as such, status, amends with its recorded `since`, supersedes), bounded per+ * page and per call with exact-remainder continuations, from one batched read+ * that equals the single-target read; hidden referrers and private dates never+ * reach untrusted callers; a late read is marked unavailable, never empty.+ */+import { afterAll, beforeAll, describe, test } from 'bun:test';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { mentionBrain } from './helpers/mention-brain.ts';+import * as S from './helpers/entity-records-scenarios.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });++describe('entity records (PGLite)', () => {+ test('names rows carry the count and a card next by default; the key turns them off', () => S.namesRowDefaults(engine), 60_000);+ test('enrolled records on names rows: groups, order, row shape, metadata, caps, continuations', () => S.recordsOnNamesRows(engine), 60_000);+ test('batched read equals the single-target read for every target, type and caller', () => S.batchedMatchesSingle(engine), 60_000);+ test('the per-call cap allots rows in input order and keeps every total and next', () => S.callCapInInputOrder(engine), 60_000);+ test('a forced-slow read is marked unavailable with a degraded notice', () => S.deadlineGivesUnavailable(engine), 60_000);+ test('context_pack records: structured, packed text, hidden referrers excluded, push path unchanged', () => S.contextPackRecords(engine), 60_000);+ test('the full card keeps referenced_by and gains records; an undeclared type says so', () => S.fullCardRecords(engine), 60_000);+ test('a failing read is marked unavailable on the card and names rows, with one notice', () => S.readFailureGivesUnavailable(engine), 60_000);+ test('zero records is an empty list; the firing counter separates listed, zero and unavailable', () => S.zeroRecordsAndFiring(engine), 60_000);+ test('every optional record field validates against the v1 response schemas', () => S.recordFieldsSchemaValid(engine), 60_000);+ test('records pack last under 1,500 and 2,000 token budgets; newer mentions unaffected', () => S.recordsPackLast(engine), 60_000);+});diff --git a/test/helpers/entity-records-scenarios.ts b/test/helpers/entity-records-scenarios.tsnew file mode 100644index 0000000000..fa391efe95--- /dev/null+++ b/test/helpers/entity-records-scenarios.ts@@ -0,0 +1,360 @@+/**+ * Entity reference fields and the record view (F1), run on PGLite+ * (test/entity-records.test.ts) and Postgres (test/e2e/entity-records-postgres.test.ts).+ *+ * World: two accounts with identity siblings (a CRM record and an account+ * sheet per account), dated contracts and amendments referencing them, an+ * amendment that amends a contract (a terms-start `since` on the link), a+ * draft amendment with `status`, a whole-record replacement (`supersedes`),+ * and hidden referrers: a private page, a quarantined page, a below-floor page+ * and an amends date whose only evidence is private.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { loadSourcePack } from '../../src/core/mentions/policy.ts';+import { readReferrerGroups, readReferrerPage, readTargetReferences, encodeCursor } from '../../src/core/mentions/referrers.ts';+import { __setReferencesTimingForTests } from '../../src/core/verbs/entity-references.ts';+import { assembleContextPack } from '../../src/core/context/turn-context.ts';++const SRC = 'default';++async function put(engine: BrainEngine, slug: string, type: string, title: string, opts: { date?: string; fm?: Record<string, unknown>; body?: string } = {}) {+ await engine.putPage(slug, { type: type as never, title, compiled_truth: opts.body ?? `${title}.`, timeline: '', frontmatter: opts.fm ?? {} }, { sourceId: SRC });+ if (opts.date) await engine.executeRaw(`UPDATE pages SET effective_date = $2::timestamptz, effective_date_source = 'date' WHERE source_id = $1 AND slug = $3`, [SRC, opts.date, slug]);+}++async function link(engine: BrainEngine, from: string, to: string, type = '', origin: string | null = from) {+ await engine.executeRaw(+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source, origin_page_id)+ SELECT f.id, t.id, $3, 'markdown', o.id FROM pages f JOIN pages t ON t.slug = $2 AND t.source_id = $4+ LEFT JOIN pages o ON o.slug = $5 AND o.source_id = $4+ WHERE f.slug = $1 AND f.source_id = $4`, [from, to, type, SRC, origin]);+}++async function since(engine: BrainEngine, from: string, to: string, scope: 'all' | 'world', date: string) {+ await engine.executeRaw(+ `INSERT INTO link_relationships (from_page_id, to_page_id, link_type, scope, source_id, semantics, valid_ranges, status_now, first_start, last_start, evidence_hash)+ SELECT f.id, t.id, 'amends', $3, $4, 'event', datemultirange(daterange($5::date, NULL)), 'event', $5::date, $5::date, 'test'+ FROM pages f JOIN pages t ON t.slug = $2 AND t.source_id = $4 WHERE f.slug = $1 AND f.source_id = $4`, [from, to, scope, SRC, date]);+}++export async function resetRecordsWorld(engine: BrainEngine): Promise<void> {+ for (const t of ['link_relationships', 'links', 'page_aliases', 'pages']) await engine.executeRaw(`DELETE FROM ${t}`);+ for (const k of ['entity.names_references', 'entity.record_types', 'entity_identity.union', 'mentions.sibling_merge']) await engine.unsetConfig(k);+ await engine.setConfig('schema_pack', 'gbrain-base-v2');+}++/** Seeds the world; returns nothing (slugs are fixed). */+export async function seedRecordsWorld(engine: BrainEngine): Promise<void> {+ await resetRecordsWorld(engine);+ await put(engine, 'crm/acme-example', 'account', 'CRM record: Acme Example');+ await put(engine, 'accounts/acme-example', 'account', 'Account sheet: Acme Example');+ await put(engine, 'crm/widget-example', 'account', 'CRM record: Widget Example');+ // Records about Acme (type `contract`: stored, not a pack type; `deal` is a pack type with alias `term-sheet`).+ await put(engine, 'contracts/acme-msa', 'contract', 'Acme MSA', { date: '2025-01-10T00:00:00Z' });+ await put(engine, 'contracts/acme-amend-1', 'contract', 'Acme amendment 1', { date: '2025-06-01T00:00:00Z' });+ await put(engine, 'contracts/acme-amend-2-draft', 'contract', 'Acme amendment 2 (draft)', { date: '2025-09-01T00:00:00Z', fm: { status: 'draft' } });+ await put(engine, 'contracts/acme-msa-v2', 'contract', 'Acme MSA v2', { date: '2025-11-01T00:00:00Z' });+ await put(engine, 'deals/acme-term-sheet', 'term-sheet', 'Acme term sheet', { date: '2024-12-01T00:00:00Z' });+ await put(engine, 'notes/acme-call', 'note', 'Call with Acme', { date: '2025-10-01T00:00:00Z' });+ for (const s of ['contracts/acme-msa', 'contracts/acme-amend-1', 'contracts/acme-amend-2-draft', 'contracts/acme-msa-v2', 'deals/acme-term-sheet', 'notes/acme-call']) {+ await link(engine, s, 'crm/acme-example');+ }+ await link(engine, 'contracts/acme-amend-1', 'contracts/acme-msa', 'amends');+ await since(engine, 'contracts/acme-amend-1', 'contracts/acme-msa', 'all', '2025-07-01');+ await since(engine, 'contracts/acme-amend-1', 'contracts/acme-msa', 'world', '2025-07-01');+ await link(engine, 'contracts/acme-amend-2-draft', 'contracts/acme-msa', 'amends');+ await link(engine, 'contracts/acme-msa-v2', 'contracts/acme-msa', 'supersedes');+ // Sibling-only record: a contract that names only the account sheet.+ await put(engine, 'contracts/acme-sheet-order', 'contract', 'Acme order form', { date: '2025-03-01T00:00:00Z' });+ await link(engine, 'contracts/acme-sheet-order', 'accounts/acme-example');+ // Hidden referrers of Acme.+ await put(engine, 'contracts/acme-private', 'contract', 'Acme private side letter', { date: '2025-12-01T00:00:00Z', fm: { visibility: 'private' } });+ await link(engine, 'contracts/acme-private', 'crm/acme-example');+ await put(engine, 'contracts/acme-quarantined', 'contract', 'Acme junk', { date: '2025-12-02T00:00:00Z',+ fm: { quarantine: { reason: 'junk_pattern', detail: 'test', assessed_at: '2026-10-07T00:00:00Z' } } });+ await link(engine, 'contracts/acme-quarantined', 'crm/acme-example');+ await put(engine, 'contracts/acme-low-trust', 'contract', 'Acme scraped copy', { date: '2025-12-03T00:00:00Z' });+ await engine.executeRaw(`UPDATE pages SET trust_tier = 'external_untrusted' WHERE slug = 'contracts/acme-low-trust'`);+ await link(engine, 'contracts/acme-low-trust', 'crm/acme-example');+ // A dated amends statement whose only evidence is private (no world-scope relationship row).+ await put(engine, 'contracts/acme-amend-3', 'contract', 'Acme amendment 3', { date: '2025-10-15T00:00:00Z' });+ await link(engine, 'contracts/acme-amend-3', 'crm/acme-example');+ await link(engine, 'contracts/acme-amend-3', 'contracts/acme-msa', 'amends');+ await since(engine, 'contracts/acme-amend-3', 'contracts/acme-msa', 'all', '2026-01-01');+ // An amends link to a private target is hidden from untrusted callers.+ await link(engine, 'contracts/acme-amend-3', 'contracts/acme-private', 'amends');+ // Widget: seven contracts (more than the per-page cap).+ for (let i = 1; i <= 7; i++) {+ await put(engine, `contracts/widget-${i}`, 'contract', `Widget contract ${i}`, { date: `2025-0${i}-15T00:00:00Z` });+ await link(engine, `contracts/widget-${i}`, 'crm/widget-example');+ }+}++export async function call(engine: BrainEngine, tool: string, args: Record<string, unknown>, remote = true) {+ const r = await dispatchToolCall(engine, tool, args, { remote, sourceId: SRC } as never);+ const body = JSON.parse(r.content[0]!.text!) as Record<string, any>;+ const notices = r.content.slice(1).map(c => ({ code: /\[gbrain notice ([a-z_]+)/.exec(c.text ?? '')?.[1] ?? '', text: c.text ?? '' }));+ return { isError: r.isError === true, body, notices };+}++const slugsOf = (g: { rows: Array<{ slug: string }> }) => g.rows.map(r => r.slug);+const ROW_KEYS = new Set(['slug', 'title', 'date', 'date_source', 'page_status', 'amends', 'supersedes']);++/** Default config: every found names row and sibling carries the count and a card `next`; no records. */+export async function namesRowDefaults(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ const { body } = await call(engine, 'entity', { names: ['CRM record: Acme Example', 'CRM record: Widget Example', 'Nobody Example'] });+ const [acme, widget, nobody] = body.results;+ const card = (await call(engine, 'entity', { name: 'crm/acme-example' })).body.card;+ expect(acme.referenced_by_count).toBe(card.referenced_by_count);+ expect(acme.referenced_by_count).toBe(8);+ expect(acme.next).toEqual({ tool: 'entity', arguments: { name: 'crm/acme-example' } });+ expect(widget.referenced_by_count).toBe(7);+ expect(acme.records).toBeUndefined();+ expect(nobody).toEqual({ name: 'Nobody Example', found: false });+ expect(card.records).toBeUndefined();+ await engine.setConfig('entity.names_references', 'false');+ const off = (await call(engine, 'entity', { names: ['CRM record: Acme Example'] })).body.results[0];+ expect(off.referenced_by_count).toBeUndefined();+ expect(off.next).toBeUndefined();+}++/** Enrolled types: grouped, newest page date first, the exact sparse row, metadata, caps and exact-remainder continuations. */+export async function recordsOnNamesRows(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract,term-sheet');+ const local = (await call(engine, 'entity', { names: ['CRM record: Acme Example', 'CRM record: Widget Example'] }, false)).body.results;+ const [acme, widget] = (await call(engine, 'entity', { names: ['CRM record: Acme Example', 'CRM record: Widget Example'] })).body.results;+ expect(acme.records.map((g: { canonical_type: string }) => g.canonical_type)).toEqual(['contract', 'deal']);+ const contracts = acme.records[0];+ // The entity verb applies no trust floor (like referenced_by): the low-trust copy is listed, labeled by nothing but its date.+ expect(contracts.total).toBe(6);+ expect(slugsOf(contracts)).toEqual(['contracts/acme-low-trust', 'contracts/acme-msa-v2', 'contracts/acme-amend-3', 'contracts/acme-amend-2-draft', 'contracts/acme-amend-1']);+ expect(contracts).toMatchObject({ capped: 'per_page' });+ expect((await call(engine, 'get_backlinks', contracts.next.arguments)).body.rows.map((r: { slug: string }) => r.slug)).toEqual(['contracts/acme-msa']);+ for (const row of contracts.rows) for (const k of Object.keys(row)) expect(ROW_KEYS.has(k)).toBe(true);+ const bySlug = Object.fromEntries(contracts.rows.map((r: { slug: string }) => [r.slug, r]));+ expect(bySlug['contracts/acme-amend-1']).toEqual({ slug: 'contracts/acme-amend-1', title: 'Acme amendment 1', date: '2025-06-01T00:00:00.000000Z', date_source: 'date',+ amends: [{ slug: 'contracts/acme-msa', since: '2025-07-01' }] });+ expect(bySlug['contracts/acme-amend-2-draft']).toMatchObject({ page_status: 'draft', amends: [{ slug: 'contracts/acme-msa' }] });+ expect(bySlug['contracts/acme-amend-2-draft'].amends[0].since).toBeUndefined();+ expect(bySlug['contracts/acme-msa-v2'].supersedes).toEqual([{ slug: 'contracts/acme-msa' }]);+ // Hidden: the private date and the private target never reach a remote caller; a local caller sees both.+ expect(bySlug['contracts/acme-amend-3'].amends).toEqual([{ slug: 'contracts/acme-msa' }]);+ const localAmend3 = local[0].records[0].rows.find((r: { slug: string }) => r.slug === 'contracts/acme-amend-3');+ expect(localAmend3.amends).toEqual([{ slug: 'contracts/acme-msa', since: '2026-01-01' }, { slug: 'contracts/acme-private' }]);+ // The stored alias resolves to the pack type; the group is named by the pack type.+ expect(acme.records[1]).toMatchObject({ canonical_type: 'deal', total: 1 });+ // Sibling records side by side, never merged.+ const sheet = acme.siblings.find((s: { slug: string }) => s.slug === 'accounts/acme-example');+ expect(sheet.records).toEqual([expect.objectContaining({ canonical_type: 'contract', total: 1, rows: [expect.objectContaining({ slug: 'contracts/acme-sheet-order' })] })]);+ expect(sheet.next).toEqual({ tool: 'entity', arguments: { name: 'accounts/acme-example' } });+ // Per-page cap: 5 of 7, with the total, the reason and a next that returns exactly the remaining 2 with the same metadata projection.+ const w = widget.records[0];+ expect(w).toMatchObject({ canonical_type: 'contract', total: 7, capped: 'per_page' });+ expect(w.rows).toHaveLength(5);+ expect(w.next.tool).toBe('get_backlinks');+ const rest = (await call(engine, 'get_backlinks', w.next.arguments)).body;+ expect(rest.rows.map((r: { slug: string }) => r.slug)).toEqual(['contracts/widget-2', 'contracts/widget-1']);+ expect(rest.total).toBe(7);+ // Local callers also see the private referrer; quarantined referrers are never listed.+ expect(local[0].records[0].total).toBe(7);+}++/** The batched read equals the single-target read (rows, order, totals, cursors) for every target, type and caller. */+export async function batchedMatchesSingle(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ const pack = await loadSourcePack(engine, SRC);+ const targets = ['crm/acme-example', 'accounts/acme-example', 'crm/widget-example', 'crm/acme-example'].map(slug => ({ slug, sourceId: SRC }));+ for (const excludePrivate of [true, false]) {+ for (const eligibility of [undefined, { floor: 'unknown' as const }]) {+ const scope = { referrerSources: [SRC], excludePrivate, pack, keepVisibility: excludePrivate ? ['world' as const] : ['private' as const, 'world' as const], eligibility };+ const batched = await readTargetReferences(engine, scope, targets, { recordTypes: ['contract', 'deal', 'note'], perCall: 1000 });+ expect(batched[3]).toEqual(batched[0]!);+ for (const [i, t] of targets.entries()) {+ const groups = await readReferrerGroups(engine, { ...scope, slug: t.slug, sourceId: SRC });+ expect(batched[i]!.referenced_by_count).toBe(groups.total);+ for (const g of batched[i]!.records!) {+ const single = await readReferrerPage(engine, { ...scope, slug: t.slug, sourceId: SRC }, { type: g.canonical_type, limit: g.rows.length || 1 });+ expect(g.total).toBe(single.total);+ if (!g.rows.length) continue;+ expect(slugsOf(g)).toEqual(single.rows.map(r => r.slug));+ expect(g.rows.map(r => r.date)).toEqual(single.rows.map(r => r.date));+ expect(g.cursor).toBe(encodeCursor(single.rows[single.rows.length - 1]!));+ }+ }+ // Hidden referrers: private only for trusted callers, quarantined never, below-floor never under a floor.+ const all = batched[0]!.records!.flatMap(slugsOf);+ expect(all.includes('contracts/acme-private')).toBe(!excludePrivate);+ expect(all.includes('contracts/acme-quarantined')).toBe(false);+ expect(all.includes('contracts/acme-low-trust')).toBe(eligibility === undefined);+ }+ }+}++/** The call cap: rows allotted in input order, every name keeps its total and next, a repeated page takes no more. */+export async function callCapInInputOrder(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ for (let a = 1; a <= 5; a++) {+ await put(engine, `crm/bulk-${a}`, 'account', `CRM record: Bulk ${a}`);+ for (let i = 1; i <= 6; i++) {+ await put(engine, `contracts/bulk-${a}-${i}`, 'contract', `Bulk ${a} contract ${i}`, { date: `2025-0${i}-0${a}T00:00:00Z` });+ await link(engine, `contracts/bulk-${a}-${i}`, `crm/bulk-${a}`);+ }+ }+ await engine.setConfig('entity.record_types', 'contract');+ const names = [1, 1, 2, 3, 4, 5].map(a => `crm/bulk-${a}`);+ const { body } = await call(engine, 'entity', { names });+ const rows = body.results;+ expect(rows).toHaveLength(5);+ expect(rows.map((r: { records: Array<{ rows: unknown[] }> }) => r.records[0]!.rows.length)).toEqual([5, 5, 5, 5, 4]);+ expect(rows.map((r: { records: Array<{ total: number }> }) => r.records[0]!.total)).toEqual([6, 6, 6, 6, 6]);+ expect(rows[4].records[0]).toMatchObject({ capped: 'per_call' });+ expect(rows[0].records[0]).toMatchObject({ capped: 'per_page' });+ const sixth = await call(engine, 'entity', { names: ['crm/bulk-1', 'crm/bulk-2', 'crm/bulk-3', 'crm/bulk-4', 'crm/bulk-5', 'crm/widget-example'] });+ const zero = sixth.body.results[5].records[0];+ expect(zero).toMatchObject({ canonical_type: 'contract', total: 7, rows: [], capped: 'per_call' });+ expect(zero.next.arguments.cursor).toBeUndefined();+ expect((await call(engine, 'get_backlinks', zero.next.arguments)).body.rows).toHaveLength(7);+}++/** A forced-slow read gives the unavailable marker and one degraded notice on names rows, the card and context_pack. */+export async function deadlineGivesUnavailable(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract');+ const restore = __setReferencesTimingForTests({ deadlineMs: 30, delayMs: 300 });+ try {+ const names = await call(engine, 'entity', { names: ['crm/acme-example'] });+ expect(names.body.results[0]).toMatchObject({ found: true, references_unavailable: 'deadline' });+ expect(names.body.results[0].records).toBeUndefined();+ expect(names.body.results[0].referenced_by_count).toBeUndefined();+ expect(names.body.results[0].siblings[0]).toMatchObject({ references_unavailable: 'deadline' });+ expect(names.notices.map(n => n.code)).toContain('references_unavailable');+ const card = await call(engine, 'entity', { name: 'crm/acme-example' });+ expect(card.body.card).toMatchObject({ references_unavailable: 'deadline', referenced_by_count: 8 });+ expect(card.notices.map(n => n.code)).toContain('references_unavailable');+ const pack = await call(engine, 'context_pack', { entities: 'crm/acme-example' });+ expect(pack.body.cards[0]).toMatchObject({ references_unavailable: 'deadline' });+ expect(pack.body.text).toContain('records unavailable (deadline); unread, not empty');+ expect(pack.notices.map(n => n.code)).toContain('references_unavailable');+ } finally {+ restore();+ }+}++/** context_pack: records only when enrolled, structured and packed text, hidden referrers excluded; the push assembler never reads them. */+export async function contextPackRecords(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ const before = (await call(engine, 'context_pack', { entities: 'crm/acme-example' })).body;+ expect(before.cards[0].records).toBeUndefined();+ expect(before.cards[0].referenced_by_count).toBeUndefined();+ await engine.setConfig('entity.record_types', 'contract');+ const { body } = await call(engine, 'context_pack', { entities: 'crm/acme-example', min_trust: 'unknown' });+ const card = body.cards[0];+ expect(card.referenced_by_count).toBe(7);+ expect(slugsOf(card.records[0])).toEqual(['contracts/acme-msa-v2', 'contracts/acme-amend-3', 'contracts/acme-amend-2-draft', 'contracts/acme-amend-1', 'contracts/acme-msa']);+ expect(card.sibling_records).toEqual([expect.objectContaining({ slug: 'accounts/acme-example', referenced_by_count: 1 })]);+ expect(body.text).toContain('## Records that reference these entities (page date = when the page was written');+ expect(body.text).toContain('- crm/acme-example: contract contracts/acme-amend-1 "Acme amendment 1" — page date 2025-06-01 (date); amends contracts/acme-msa (terms start 2025-07-01)');+ expect(body.text).toContain('status: draft');+ expect(body.text).toContain('- accounts/acme-example: contract contracts/acme-sheet-order');+ const recordsText = body.text.slice(body.text.indexOf('## Records'));+ for (const hidden of ['acme-private', 'acme-quarantined', 'acme-low-trust', '2026-01-01']) {+ expect(JSON.stringify([card.records, card.sibling_records])).not.toContain(hidden);+ expect(recordsText).not.toContain(hidden);+ }+ const push = await assembleContextPack(engine, { sourceId: SRC, entities: ['crm/acme-example'], maxEntities: 8 });+ expect(push.text).not.toContain('## Records');+ expect(JSON.stringify(push.cards)).not.toContain('"records"');+}++/** The full card keeps referenced_by and gains the record view; an undeclared enrolled type says so. */+export async function fullCardRecords(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract,nonexistent-type');+ const { body, notices } = await call(engine, 'entity', { name: 'crm/acme-example' });+ expect(body.card.referenced_by_count).toBe(8);+ expect(body.card.referenced_by.map((g: { canonical_type: string }) => g.canonical_type).sort()).toEqual(['contract', 'deal', 'note']);+ expect(body.card.records[0]).toMatchObject({ canonical_type: 'contract', total: 6 });+ expect(body.card.identity_siblings.pages[0]).toMatchObject({ slug: 'accounts/acme-example', records: [expect.objectContaining({ total: 1 })] });+ expect(notices.map(n => n.code)).toContain('record_types_undeclared');+}++/** A failing referrer read marks the full card (and names rows) unavailable with one degraded notice, instead of a silent omission. */+export async function readFailureGivesUnavailable(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract');+ const broken = Object.create(engine) as BrainEngine;+ broken.executeRaw = ((sql: string, params?: unknown[]) => sql.includes('refs AS MATERIALIZED')+ ? Promise.reject(new Error('synthetic referrer failure')) : engine.executeRaw(sql, params as never)) as never;+ const card = await call(broken, 'entity', { name: 'crm/acme-example' });+ expect(card.body.card.references_unavailable).toBe('read_failed');+ expect(card.body.card.referenced_by).toBeUndefined();+ expect(card.body.card.records).toBeUndefined();+ expect(card.notices.filter(n => n.code === 'references_unavailable')).toHaveLength(1);+ const names = await call(broken, 'entity', { names: ['crm/acme-example'] });+ expect(names.body.results[0]).toMatchObject({ found: true, references_unavailable: 'read_failed' });+ expect(names.notices.map(n => n.code)).toContain('references_unavailable');+}++/** Zero records under enrollment is an empty list (not the unavailable marker); the firing counter separates the three. */+export async function zeroRecordsAndFiring(engine: BrainEngine): Promise<void> {+ const { recordsFiring } = await import('../../src/core/verbs/usage-log.ts');+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract');+ await put(engine, 'crm/empty-example', 'account', 'CRM record: Empty Example');+ const { body } = await call(engine, 'entity', { names: ['crm/empty-example', 'crm/widget-example'] });+ expect(body.results[0]).toMatchObject({ referenced_by_count: 0, records: [] });+ expect(recordsFiring(body)).toEqual({ listed: 1, zero: 1, unavailable: 0 });+ await engine.unsetConfig('entity.record_types');+ expect(recordsFiring((await call(engine, 'entity', { names: ['crm/widget-example'] })).body)).toBeNull();+}++/** Every optional record field validates against the frozen v1 response schemas (card and context_pack), one fixture each. */+export async function recordFieldsSchemaValid(engine: BrainEngine): Promise<void> {+ const { validateAgainstSchema } = await import('../../src/core/verbs/conformance.ts');+ const { RESPONSE_SCHEMAS } = await import('../../src/core/verbs.ts');+ await seedRecordsWorld(engine);+ await engine.setConfig('entity.record_types', 'contract');+ const card = (await call(engine, 'entity', { name: 'crm/acme-example' }, false)).body;+ const rows = card.card.records[0].rows as Array<Record<string, unknown>>;+ for (const field of ['page_status', 'amends', 'supersedes']) expect(rows.some(r => field in r)).toBe(true);+ expect(rows.some(r => (r.amends as Array<{ since?: string }> | undefined)?.some(a => a.since))).toBe(true);+ expect(card.card.records[0].next).toBeDefined();+ expect(validateAgainstSchema(card, RESPONSE_SCHEMAS.entity)).toEqual([]);+ const pack = (await call(engine, 'context_pack', { entities: 'crm/acme-example' })).body;+ expect(pack.cards[0].sibling_records).toBeDefined();+ expect(validateAgainstSchema(pack, RESPONSE_SCHEMAS.context_pack)).toEqual([]);+ const restore = __setReferencesTimingForTests({ deadlineMs: 30, delayMs: 300 });+ try {+ expect(validateAgainstSchema((await call(engine, 'entity', { name: 'crm/acme-example' })).body, RESPONSE_SCHEMAS.entity)).toEqual([]);+ expect(validateAgainstSchema((await call(engine, 'context_pack', { entities: 'crm/acme-example' })).body, RESPONSE_SCHEMAS.context_pack)).toEqual([]);+ } finally { restore(); }+}++/** Records pack last: newer mentions still pack under 1,500 and 2,000 token budgets with records present, and the text honors the budget. */+export async function recordsPackLast(engine: BrainEngine): Promise<void> {+ await seedRecordsWorld(engine);+ // The entity page is dated before most referrers, so they are its newer mentions too.+ await engine.executeRaw(`UPDATE pages SET effective_date = '2025-05-01T00:00:00Z', effective_date_source = 'date' WHERE slug = 'crm/acme-example'`);+ const without = await call(engine, 'context_pack', { entities: 'crm/acme-example', budget_tokens: 1500 });+ expect(without.body.cards[0].newer_mentions).toBeDefined();+ await engine.setConfig('entity.record_types', 'contract');+ for (const budget of [1500, 2000]) {+ const { body } = await call(engine, 'context_pack', { entities: 'crm/acme-example', budget_tokens: budget });+ expect(body.budget_used).toBeLessThanOrEqual(budget);+ expect(body.cards[0].newer_mentions).toEqual(without.body.cards[0].newer_mentions);+ const mentionsAt = body.text.indexOf('## Newer pages');+ const recordsAt = body.text.indexOf('## Records');+ expect(mentionsAt).toBeGreaterThan(0);+ expect(recordsAt).toBeGreaterThan(mentionsAt);+ expect(body.cards[0].referenced_by_count).toBe(8);+ }+ const tiny = (await call(engine, 'context_pack', { entities: 'crm/acme-example', budget_tokens: 120 })).body;+ if (tiny.cards.length) {+ expect(tiny.cards[0].records).toBeUndefined();+ expect(tiny.cards[0].referenced_by_count).toBeDefined();+ }+}