Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

F3: page_status on context_pack and get_backlinks rows behind entity.row_page_status

garrytanb6607b82e009
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b5d5797b9b..6af014e51b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ identifiers and attribution are available in the pre-removal Git revision
- **A record can say it amends another without changing how either ranks.** A schema pack declares `amends` (`temporal: event`) and maps it from frontmatter per page type, so `amends: [{name, since}]` links the amendment to the record it changes and records when the new terms take effect (`link_relationships.first_start`). Amends edges are references only: every link-counting ranking reader skips them through one policy (`src/core/link-ranking-policy.ts`): backlink, in-set and cross-source adjacency boosts, relational fanout and chain hops, chain hub degree, enrich inbound order, entity-resolution connection count, generated-page demotion and entity anchoring. `get_links`, `get_backlinks`, `traverse_graph`, card edges, `backlink_count` and `referenced_by` still return them, and `supersedes` keeps its 0.5 down-rank for whole-record replacement. An amends edge whose `since` is still ahead is never hidden by the default liveness filter (`LIVENESS_EXEMPT_LINK_TYPES` in `src/core/link-validity.ts`), and card edges rank it beside events. Example pack: `examples/schema-packs/amends-example/pack.yaml`; guide: [amendments](docs/guides/temporal-edges.md#amendments-the-amends-link); existing pages pick it up with `gbrain extract links --source db --include-frontmatter`.
- **Frontmatter `since`/`until` dates only the exact target when several objects match.** `src/core/link-temporal-evidence.ts` still accepts a slug-prefix name (`Acme` for `acme-example`) when it is the only match, but when several objects in one field match one target only the exact name dates it, so `{name: MSA Example}` no longer dates `msa-example-renewal`.
- Tests: `test/amends-link.test.ts` (PGLite) and `test/e2e/amends-link-postgres.test.ts` (Postgres) share `test/helpers/amends-ranking-scenarios.ts`: one final-output invariance row per link-counting consumer, each with a ranking-type control that crosses its threshold; amendments versus `supersedes` through final search scores and labels; frontmatter `since` per exact target; and a frozen-clock check that a future-`since` amends edge stays in `get_backlinks`, `traverse_graph` and card edges. `test/link-temporal-evidence.test.ts` adds the prefix-sharing target pair.
+- **Document status where agents look (F3): `page_status` on `context_pack` and `get_backlinks` rows, on by default.** A page's own frontmatter `status`, only when set to a string (trimmed, at most 40 characters), now rides `context_pack` cards (the card's page) and their `newer_mentions` rows, and every `get_backlinks` link row (the referring page) and `group: "page"` row, as the additive `page_status` that F1 record rows already carry. Nothing is inferred: no title, subject or first-line heuristics, and a draft is not treated as lesser evidence. The documented convention for a record not in force yet is `status: draft` or `status: unsigned`. Search rows carry the same value as raw `status` (unbounded); a link row's `status` stays the relationship's temporal state, and the `status` filter is unchanged. Private pages (untrusted callers) and quarantined pages (unless the caller may read them) show none; `context_pack` `text` is unchanged. New key `entity.row_page_status` (default `true`); `false` removes the field from these rows only, and record rows (`records[]`, and a record type's `get_backlinks` continuation) keep it. `src/core/mentions/referrers.ts` (`pageStatusValue`, `readPageStatusByRef`), `src/core/ops/backlinks-paged.ts` (`withLinkPageStatus`), `src/core/ops/facts.ts`. Docs: MEMORY_VERBS v1 "page_status on context_pack and get_backlinks rows", `docs/guides/entity-records.md`, `docs/mcp/TOOL_REFERENCE.md`. Tests: two shared scenarios in `test/entity-records.test.ts` and `test/e2e/entity-records-postgres.test.ts` (additive against the key off, bounded and trimmed, hidden pages none, schema-valid; F1 on with F3 off keeps `page_status` on names rows, the full card, `context_pack` records and the record continuation, and on no other row).
- **Evidence delivery (F2 plumbing): long non-conversation pages can come back in a delivery unit, off by default.** New key `search.long_page_unit` (`off` default | `window` | `section` | `page`; `gbrain config set` refuses other values; `section` is the value under test). Under the implied `auto` on `search` and `query`, a hit on a page whose rendered body holds at least `search.long_page_min_chars` characters (new key, default 20,000) is widened to that unit inside the existing `search.return_budget_conversation` budget; every other hit keeps its ranked chunk, reserved first, and widened units fill only what is left. One precedence table (`docs/evidence-delivery.md`, "Long pages"): an explicit `return_unit`, then a non-`auto` `search.return_unit`, then this key; an explicit `token_budget` keeps it off. A widened row is exempt from `snippet_chars` and comes back whole, still inside `search.return_budget_conversation` and the long-page limits; `snippet_chars` keeps cutting every ranked chunk row, and `delivered {unit, reason}` explains the longer row. The policy is resolved at the search/query caller (`withLongPagePolicy`), so recall, think and `assemble_evidence` are byte-identical with it on. `selectLongPages` runs one character/byte-count preflight under the read scope, and delivery confirms the threshold on the rendered body; at most 5 long pages and 1,000,000 body bytes per call are fetched in their own bounded batched call under a 2,000 ms deadline, whole pages only; any long page it cannot deliver keeps its ranked chunk (`delivered.reason: "long_page_chunk"`, a `long_page_*` fallback code). Lean rows keep `delivered: {unit, reason}` on long-page rows (plus `truncated: true` when cut); every other lean row keeps `{truncated: true}` only. The off path is byte-identical (`test/evidence-delivery-golden.test.ts` unchanged); a second frozen golden pins the on path (`test/fixtures/goldens/evidence-delivery/long-page-on-path.json`). Tests: `test/evidence-long-page.test.ts` (PGLite: replay case, threshold key, cap and explicit-unit paths byte-identical with the key on, `snippet_chars` 300 survival of the widened row on the serialized lean MCP output), `test/e2e/evidence-long-page.test.ts` (Postgres). No passage selector is built; the unit is chosen later by the frozen-hit comparison.
- **Served instructions (F4): the record in effect on the date asked about governs, not the newest one.** Instruction 7 now reads "The record whose terms are in effect on the date asked about governs: a page's `date`/`effective_date` is when it was written, not when its terms take effect, and a change not yet effective does not apply yet; drafts, proposals and agent-written notes do not override records." (`date` is named only where `entity` is callable). It replaces "prefer the newest governing source: a later correction, handoff or executed change outranks an older record". The rule now leads the answering clause and ends inside the first 2,048 characters capped harnesses read (starter 1,566–1,842, full 1,717–1,993; it started at 1,943 and 2,094). New key `mcp.instructions_governing_rule` (`in_effect` default, `newest` serves the earlier sentence for measurement). Budget: the sentence is 74 characters longer; 11 are paid by cutting "the best-ranked excerpts" to "top excerpts" in the same clause, and +63 is recorded in `test/mcp-schema-budget.test.ts` (5,108 for the maximal rendering). Tests: `test/mcp-instructions-governing-rule.test.ts`.
- **Served instructions (d5b): the brief clause no longer recommends a `referenced_by` walk batch mode cannot do.** `src/mcp/instructions.ts`: the walk is on the single-name `entity` card, and the clause names what a compact `entity names` row carries on this brain (its `next` to the card while `entity.names_references` is on, the default; `records` by type once `entity.record_types` enrolls page types, empty by default). Every transport reads both keys at initialize through `readInstructionContent` (fail-closed to the defaults); the static contract, bootstrap's instructions file and the SDK constructor fallback are the defaults rendering. One reader module, `src/core/entity-references-config.ts`, serves both keys. Budget: +70 characters for the maximal rendering (+39 at the default), recorded in `test/mcp-schema-budget.test.ts` and `test/mcp-initialize-instructions.test.ts`. Tests: `test/mcp-instructions-references.test.ts`.
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index ad7890b7ce..6b7a634c03 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
-- `src/core/entity-references-config.ts` — the one reader for `entity.names_references` (default on: found `names` rows and siblings carry `referenced_by_count` and a row-level `next` to the card) and `entity.record_types` (comma-separated canonical page types, default empty: no `records`). `readEntityReferencesConfig(engine)` fails closed to `{namesRow: true, recordTypes: []}`; the names verb and the MCP instruction builder (`readInstructionContent`) both read it. Test: `test/mcp-instructions-references.test.ts`.
+- `src/core/entity-references-config.ts` — the one reader for `entity.names_references` (default on: found `names` rows and siblings carry `referenced_by_count` and a row-level `next` to the card) and `entity.record_types` (comma-separated canonical page types, default empty: no `records`), plus `readRowPageStatus` for `entity.row_page_status` (F3, default on: `page_status` on `context_pack` cards and newer-mention rows and on `get_backlinks` rows; record rows keep it when off). `readEntityReferencesConfig(engine)` fails closed to `{namesRow: true, recordTypes: []}`; the names verb and the MCP instruction builder (`readInstructionContent`) both read it. Test: `test/mcp-instructions-references.test.ts`.
- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exempt `amends`, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)).
- `src/core/mentions/newer-mentions.ts` — `readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined})`: the entity page's `COALESCE(effective_date, updated_at)`, then `readReferrerPage` (limit `NEWER_MENTIONS_CAP` 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within `NEWER_MENTIONS_CARD_CHARS` (2,000) of rendered rows; `more` when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized `include_quarantined`; `renderNewerMentionRow` labels each preview with its page's trust fields (`renderTrustedInline`; a quarantined one as external data). `isNewerMentionsEnabled` reads `mentions.newer_on_cards` (unset = on). `assemblePack` (`src/core/context/turn-context.ts`) reads them after cards and hot facts under the pack deadline and `NEWER_MENTIONS_PACK_CHARS` (6,000), `renderPack` puts them in a section after hot memory, and the `context_pack` op packs them last under `budget_tokens`. Test: `test/context-pack-newer-mentions.test.ts`.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 7cd576e7ad..c80c03db27 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -13,9 +13,9 @@ 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). 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/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. F3: `pageStatusValue` (string, trimmed, at most `PAGE_STATUS_MAX_CHARS` 40) is the one `page_status` rule; `readPageStatusByRef` reads it by `(source_id, slug)` in one statement (private pages hidden from untrusted callers, quarantined pages unless allowed) for `readReferrerPage {pageStatus}`, `get_backlinks` link rows and `context_pack` cards and newer-mention rows. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while index-due pages exist (`previewMentionPass`), including every page behind the binary's mention or alias version on an unchanged brain. Post-upgrade does not run the sweep; autopilot's cycle extract phase continues it on its stale-drain budget (`CYCLE_STALE_DRAIN_BUDGET_MS`).
-- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode 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/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. F3 (`entity.row_page_status`, default on): `withLinkPageStatus` adds the referring page's `page_status` to link rows, and `group: "page"` rows get it through `readReferrerPage {pageStatus}`; a record type's continuation keeps it through `recordMetadata` when the key is off.
- `src/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. `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`.
diff --git a/docs/guides/entity-records.md b/docs/guides/entity-records.md
index e94c5baafc..21c839c695 100644
--- a/docs/guides/entity-records.md
+++ b/docs/guides/entity-records.md
@@ -62,6 +62,25 @@ Effective 2026-03-01, the monthly fee changes to 12,000 USD. All other terms are
replaced page in search. Use it only when the new record replaces the old one
entirely.
+## Document status on other rows
+
+The same `page_status` rides more than records. Under `entity.row_page_status`
+(default `true`), `context_pack` cards (the card's own page) and their
+`newer_mentions` rows, and `get_backlinks` link rows and `group: "page"` rows,
+carry it whenever the page sets `status`. Set `entity.row_page_status false` to
+remove it from those rows only; record rows keep it.
+
+`page_status` is the page's own frontmatter `status`, copied only when it is set
+to a string: trimmed, at most 40 characters (longer or non-string values are not
+shown). It is never inferred from a title, subject or text, and it does not make
+a page lesser evidence. The documented convention for a record that is not in
+force yet is `status: draft` or `status: unsigned`; any other string is passed
+through as written. Search rows carry the same frontmatter value as raw
+`status` (`frontmatter->>'status'`, unbounded and untrimmed), so a search row's
+`status` and a pack or backlink row's `page_status` agree whenever the value is
+a string of 40 characters or fewer. A link row's `status` is the relationship's
+temporal state, a different field, and the `status` input filter is unchanged.
+
## What the agent gets
`entity {names: ["Acme Example"]}` returns, for the found page (and for each
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index c58a6d3a26..297659cfbd 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -78,6 +78,8 @@ MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing en
Each card may carry `newer_mentions` (`since`, `rows` of `date`/`slug`/`title`/`preview`, `more`): the newest pages dated after the entity's own page that mention it, at most 8 rows and 2,000 characters per card, rendered in `text` after hot memory. They follow the `entity` card's read policy and pack last under `budget_tokens`. Off with `mentions.newer_on_cards false`.
+The card and each `newer_mentions` row carry `page_status` when that page's frontmatter sets `status` (a string up to 40 characters, never inferred; the convention for a record not yet in force is `draft` or `unsigned`). Structured rows only; `text` is unchanged. Off with `entity.row_page_status false`; `records` rows keep theirs.
+
## `delta`
MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts; threads are never dropped). protocol_version rides every response.
@@ -143,6 +145,8 @@ Poll an agent job submitted via submit_agent. Returns a trimmed status view (id,
List incoming links to a page
+Each link row and each `group: "page"` row carries `page_status`, the referring page's frontmatter `status`, when set (a string up to 40 characters; never inferred). The link row's own `status` is the relationship's temporal state and the `status` filter acts on that. Off with `entity.row_page_status false`; a record type's continuation keeps it.
+
| Parameter | Type | Guidance |
| --- | --- | --- |
| `slug` (required) | string | Slug of the page whose incoming links to list. |
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 6a3d8a60b9..7be6120e26 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -891,6 +891,29 @@ 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.
+#### page_status on context_pack and get_backlinks rows (additive)
+
+Under `entity.row_page_status` (default `true`), each `context_pack` card
+carries `page_status` for its own page, and each `newer_mentions.rows[]` entry
+for the referring page; `get_backlinks` adds it to every link row (the
+referring page's status) and every `group: "page"` row. Absent when the page
+has no status. A private page (for an untrusted caller) or a quarantined page
+(unless the caller may read quarantined pages) shows none. `text` is unchanged:
+the field rides the structured rows only. `false` removes it from these rows;
+record rows (`records[]`, and a record type's `get_backlinks` continuation)
+keep their `page_status` either way.
+
+`page_status` is the page's own frontmatter `status`, copied only when it is set
+to a string: trimmed, at most 40 characters (longer or non-string values are not
+shown). It is never inferred from a title, subject or text, and it does not make
+a page lesser evidence. The documented convention for a record that is not in
+force yet is `status: draft` or `status: unsigned`; any other string is passed
+through as written. Search rows carry the same frontmatter value as raw
+`status` (`frontmatter->>'status'`, unbounded and untrimmed), so a search row's
+`status` and a pack or backlink row's `page_status` agree whenever the value is
+a string of 40 characters or fewer. A link row's `status` is the relationship's
+temporal state, a different field, and the `status` input filter is unchanged.
+
#### context_pack core memory (additive)
`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries the
diff --git a/llms-full.txt b/llms-full.txt
index 573bd031ee..cfd62a84ef 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9387,6 +9387,29 @@ 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.
+#### page_status on context_pack and get_backlinks rows (additive)
+
+Under `entity.row_page_status` (default `true`), each `context_pack` card
+carries `page_status` for its own page, and each `newer_mentions.rows[]` entry
+for the referring page; `get_backlinks` adds it to every link row (the
+referring page's status) and every `group: "page"` row. Absent when the page
+has no status. A private page (for an untrusted caller) or a quarantined page
+(unless the caller may read quarantined pages) shows none. `text` is unchanged:
+the field rides the structured rows only. `false` removes it from these rows;
+record rows (`records[]`, and a record type's `get_backlinks` continuation)
+keep their `page_status` either way.
+
+`page_status` is the page's own frontmatter `status`, copied only when it is set
+to a string: trimmed, at most 40 characters (longer or non-string values are not
+shown). It is never inferred from a title, subject or text, and it does not make
+a page lesser evidence. The documented convention for a record that is not in
+force yet is `status: draft` or `status: unsigned`; any other string is passed
+through as written. Search rows carry the same frontmatter value as raw
+`status` (`frontmatter->>'status'`, unbounded and untrimmed), so a search row's
+`status` and a pack or backlink row's `page_status` agree whenever the value is
+a string of 40 characters or fewer. A link row's `status` is the relationship's
+temporal state, a different field, and the `status` input filter is unchanged.
+
#### context_pack core memory (additive)
`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries the
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 65a1cd94d4..08baa1b8cf 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -472,6 +472,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ 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.' },
// Cat 40 next wave, Part 1. `since` is provisional; the integrator restamps it at the merge slot.
+ { since: '0.60.180.0', text: '`context_pack` cards and their `newer_mentions` rows, and every `get_backlinks` link row and `group: "page"` row, now carry `page_status`: the page\'s own frontmatter `status`, only when it is a string of at most 40 characters (trimmed), never inferred. A link row\'s `status` is still the relationship state and the `status` filter is unchanged; `context_pack` `text` is unchanged. `gbrain config set entity.row_page_status false` removes it from these rows; record rows keep it.' },
{ since: '0.60.180.0', text: 'The MCP instructions no longer tell agents to walk `referenced_by` after an `entity` `names` batch, whose rows carry no references: the brief clause now puts that walk on the single-name card and says what a `names` row holds on this brain (its `next` to the card, and `records` by type once `entity.record_types` names page types). `gbrain config set entity.names_references false` drops the names-row fields and that part of the clause.' },
{ since: '0.60.180.0', text: 'The MCP instructions now say the record whose terms are in effect on the date asked about governs, that a page\'s `date`/`effective_date` is when it was written (not when its terms take effect), and that a change not yet effective does not apply yet; they no longer say a later correction, handoff or executed change outranks an older record. Drafts, proposals and agent-written notes still do not override records. The rule now sits inside the first 2,048 characters. `gbrain config set mcp.instructions_governing_rule newest` serves the earlier sentence.' },
{ 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.ts
index 846a4a3521..7159de4d9e 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1620,7 +1620,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'mcp.strict_params',
'mcp.result_rows', // C1 row shape, read dual-plane by src/mcp/result-rows.ts
'mcp.allow_session_widen', // stdio request_tools session widening (default on), read dual-plane by src/mcp/surface.ts
- 'entity.names_references', 'entity.record_types', // names-row referenced_by_count + card `next` (default on); canonical page types listed as `records` (default empty); src/core/entity-references-config.ts
+ 'entity.names_references', 'entity.record_types', 'entity.row_page_status', // names-row referenced_by_count + card `next` (default on); canonical page types listed as `records` (default empty); F3 page_status on context_pack/get_backlinks rows (default on); src/core/entity-references-config.ts
'mcp.instructions_governing_rule', // instruction 7: in_effect (default: the record in effect on the date asked about governs) | newest (the earlier recency sentence); src/mcp/instructions.ts
// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.
'skillpack.nag_disabled',
diff --git a/src/core/entity-references-config.ts b/src/core/entity-references-config.ts
index a1a903118b..675d1b424d 100644
--- a/src/core/entity-references-config.ts
+++ b/src/core/entity-references-config.ts
@@ -12,12 +12,19 @@
* the full card and `context_pack` cards (verbs/entity-references.ts); a
* stored type alias is read as its pack type. Empty means no records.
*
+ * - `entity.row_page_status` (boolean, default on): F3. `context_pack` cards
+ * and their `newer_mentions` rows, and `get_backlinks` rows (link rows and
+ * `group: "page"` rows), carry the page's own frontmatter `status` as
+ * `page_status` when set. Off removes it from those rows only; record rows
+ * (`records`, and a record type's `get_backlinks` continuation) keep it.
+ *
* Fail-closed: a read error yields the defaults (names rows on, no records),
* never a field the agent would not receive.
*/
export const ENTITY_NAMES_REFERENCES_KEY = 'entity.names_references';
export const ENTITY_RECORD_TYPES_KEY = 'entity.record_types';
+export const ROW_PAGE_STATUS_KEY = 'entity.row_page_status';
export interface EntityReferencesConfig {
namesRow: boolean;
@@ -44,3 +51,8 @@ export async function readEntityReferencesConfig(engine: { getConfig(key: string
return { namesRow: true, recordTypes: [] };
}
}
+
+/** F3 `page_status` on `context_pack` and `get_backlinks` rows: on unless explicitly off; a read error keeps the default. */
+export async function readRowPageStatus(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ return parseNamesReferences(await engine.getConfig(ROW_PAGE_STATUS_KEY).catch(() => null));
+}
diff --git a/src/core/mentions/newer-mentions.ts b/src/core/mentions/newer-mentions.ts
index 69ae60da56..9af0cbb3ce 100644
--- a/src/core/mentions/newer-mentions.ts
+++ b/src/core/mentions/newer-mentions.ts
@@ -37,6 +37,8 @@ export interface NewerMention extends TrustFields {
/** The referrer preview `referenced_by` shows: page text, not evidence; fetch the page. */
preview: string;
quarantined?: true;
+ /** F3: the page's own frontmatter `status`, only when set (`context_pack` only; never rendered in the text block). */
+ page_status?: string;
}
export interface NewerMentions {
diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.ts
index 7ce9ad7f3d..7aa939c7ee 100644
--- a/src/core/mentions/referrers.ts
+++ b/src/core/mentions/referrers.ts
@@ -182,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; recordMetadata?: boolean }): Promise<{ rows: Array<ReferenceRow & RecordMetadata>; total: number; truncated: boolean; cursor: string | null }> {
+ opts: { type?: string; limit: number; cursor?: [string | null, string, string] | null; recordMetadata?: boolean; pageStatus?: 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];
@@ -206,6 +206,9 @@ export async function readReferrerPage(engine: BrainEngine, scope: ReferrerScope
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)) ?? {}));
+ } else if (opts.pageStatus) {
+ const status = await readPageStatusByRef(engine, rows, scope);
+ rows.forEach(r => { const value = status.get(`${r.source_id}:${r.slug}`); if (value) r.page_status = value; });
}
return { rows, total: Number(count?.n ?? 0), truncated, cursor: truncated ? encodeCursor(rows[rows.length - 1]!) : null };
}
@@ -338,6 +341,36 @@ function referrersCteBatched(scope: Pick<ReferrerScope, 'excludePrivate' | 'elig
)`;
}
+/** A frontmatter `status` as `page_status`: a string, trimmed, at most PAGE_STATUS_MAX_CHARS; anything else is not shown. */
+export function pageStatusValue(raw: unknown): string | undefined {
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ return value && value.length <= PAGE_STATUS_MAX_CHARS ? value : undefined;
+}
+
+/**
+ * F3: `page_status` of live pages by `(source_id, slug)`, keyed
+ * `source_id:slug`, one statement. A private page (for an untrusted caller)
+ * or a quarantined page (unless the caller may read quarantined pages) gets
+ * none.
+ */
+export async function readPageStatusByRef(engine: BrainEngine, refs: Array<{ source_id: string; slug: string }>,
+ scope: { excludePrivate: boolean; includeQuarantined?: boolean }): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ if (!refs.length) return out;
+ const priv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '';
+ const quarantine = scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('p')}`;
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; status: unknown }>(
+ `SELECT p.source_id, p.slug, p.frontmatter->'status' AS status
+ FROM pages p JOIN unnest($1::text[], $2::text[]) AS u(s, g) ON p.source_id = u.s AND p.slug = u.g
+ WHERE p.deleted_at IS NULL AND p.frontmatter ? 'status'${priv}${quarantine}`,
+ [refs.map(r => r.source_id), refs.map(r => r.slug)]);
+ for (const row of rows) {
+ const value = pageStatusValue(row.status);
+ if (value) out.set(`${row.source_id}:${row.slug}`, value);
+ }
+ return out;
+}
+
/**
* The record metadata of referring pages: `page_status` from frontmatter,
* `amends` and `supersedes` links to pages the caller can see (link origins
@@ -365,9 +398,8 @@ export async function readRecordMetadata(engine: BrainEngine, pageIds: number[],
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 });
+ const value = pageStatusValue(row.status);
+ if (value) out.set(Number(row.id), { page_status: value });
}
for (const link of links) {
const id = Number(link.from_id);
diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.ts
index 93a7f3b7ad..a7352d463b 100644
--- a/src/core/ops/backlinks-paged.ts
+++ b/src/core/ops/backlinks-paged.ts
@@ -15,10 +15,10 @@ import type { Link, PageReadPolicy } from '../types.ts';
import type { Notice } from '../agent-output.ts';
import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';
import {
- canonicalRecordTypes, decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,
+ canonicalRecordTypes, decodeCursor, readPageStatusByRef, 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';
+import { readEntityReferencesConfig, readRowPageStatus } from '../entity-references-config.ts';
export interface BacklinkPage {
rows: ReferenceRow[];
@@ -101,7 +101,25 @@ export async function readBacklinkPage(ctx: OperationContext, p: Record<string,
// 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 };
+ const pageStatus = !recordMetadata && await readRowPageStatus(ctx.engine);
+ return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor, recordMetadata, pageStatus }), coverage };
+}
+
+/**
+ * F3 (`entity.row_page_status`, default on): each link row carries its
+ * referring page's frontmatter `status` as `page_status` when set. The link's
+ * own `status` (the relationship's temporal state) and the `status` input
+ * filter are unchanged.
+ */
+export async function withLinkPageStatus(ctx: OperationContext, policy: () => Promise<PageReadPolicy>, links: Link[]): Promise<Array<Link & { page_status?: string }>> {
+ if (!links.length || !(await readRowPageStatus(ctx.engine))) return links;
+ const excludePrivate = (await policy()).excludePrivate === true;
+ const status = await readPageStatusByRef(ctx.engine, links.map(l => ({ source_id: l.from_source_id, slug: l.from_slug })), { excludePrivate })
+ .catch(() => new Map<string, string>());
+ return links.map(l => {
+ const value = status.get(`${l.from_source_id}:${l.from_slug}`);
+ return value ? { ...l, page_status: value } : l;
+ });
}
/**
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 3584cf2c67..eab333bdb1 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -703,6 +703,7 @@ const context_pack: Operation = {
: null;
// #5575 (CEO-20, CEO-18): a proactive surface under the connection's floor.
const eligibility = await proactiveEligibility(ctx, 'context_pack', { minTrust: p.min_trust });
+ const includeQuarantined = p.include_quarantined === true && (ctx.remote === false || hasScope(ctx.auth?.scopes ?? [], 'admin') || hasScope(ctx.auth?.scopes ?? [], MEMORY_CONFIRM_SCOPE));
const res = entities.length === 0
? { cards: [], facts: [], text: '', pointers: [], factsCount: 0 } as unknown as Awaited<ReturnType<typeof assembleContextPack>>
: await assembleContextPack(ctx.engine, {
@@ -714,7 +715,7 @@ const context_pack: Operation = {
maxEntities: PACK_DEFAULT_MAX_ENTITIES,
eligibility,
// #5575 ENG-15: same rule as get_page: quarantined cards only on an authorized explicit ask.
- includeQuarantined: p.include_quarantined === true && (ctx.remote === false || hasScope(ctx.auth?.scopes ?? [], 'admin') || hasScope(ctx.auth?.scopes ?? [], MEMORY_CONFIRM_SCOPE)),
+ includeQuarantined,
});
// Always-loaded core tier (core-memory.ts): owner-designated pages of
// `default` plus this source, inside the caller's grant; it packs first.
@@ -738,7 +739,20 @@ const context_pack: Operation = {
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));
+ // F3 (`entity.row_page_status`, default on): each card and newer-mentions row carries its page's frontmatter `status` (pull verb only).
+ const { readRowPageStatus } = await import('../entity-references-config.ts');
+ const { readPageStatusByRef } = await import('../mentions/referrers.ts');
+ const statusRefs = (res.cards ?? []).flatMap((c) => [c.entity.slug, ...(c.newer_mentions?.rows ?? []).map((r) => r.slug)]).map((slug) => ({ source_id: sourceId, slug }));
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const pageStatus = statusRefs.length && await readRowPageStatus(ctx.engine)
+ ? await readPageStatusByRef(ctx.engine, statusRefs, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, includePrivate ? false : undefined), includeQuarantined })
+ .catch(() => new Map<string, string>())
+ : new Map<string, string>();
+ const statusOf = (slug: string) => { const value = pageStatus.get(`${sourceId}:${slug}`); return value ? { page_status: value } : {}; };
+ const withRefs = (res.cards ?? []).map((c) => ({
+ ...c, ...packRefs.bySlug.get(c.entity.slug), ...statusOf(c.entity.slug),
+ ...(c.newer_mentions ? { newer_mentions: { ...c.newer_mentions, rows: c.newer_mentions.rows.map((r) => ({ ...r, ...statusOf(r.slug) })) } } : {}),
+ }));
const view = redactRetrievalOutput([{ cards: withRefs, facts: rawFacts }], {}).results[0];
let cards = view.cards;
let facts = view.facts;
@@ -796,6 +810,7 @@ const context_pack: Operation = {
slug: c.entity.slug,
title: c.entity.title,
type: c.entity.type,
+ ...(c.page_status ? { page_status: c.page_status } : {}),
summary: c.quarantined && c.summary ? renderTrustedText(c.summary, { trust_tier: 'external_untrusted', origin: 'quarantined' }) : c.summary,
open_threads: c.open_threads,
edges: c.edges,
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index f496558410..8945d5788c 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -1,5 +1,5 @@
import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';
-import { filterBacklinkRows, readBacklinkPage, wantsPagedBacklinks } from './backlinks-paged.ts';
+import { filterBacklinkRows, readBacklinkPage, wantsPagedBacklinks, withLinkPageStatus } from './backlinks-paged.ts';
/**
* Links + graph operation cluster — pure move from operations.ts (v0.46.x
* tranche 1). MANAGED_LINK_SOURCES stays exported (test suite + operations.ts
@@ -410,10 +410,10 @@ const get_backlinks: Operation = {
cursor: { type: 'string', description: 'Paging.' },
},
handler: async (ctx, p) => {
- if (!wantsPagedBacklinks(p)) return readLinkEdges(ctx, p, 'get_backlinks', 'in');
if (p.group !== undefined) return readBacklinkPage(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy);
const links = await readLinkEdges(ctx, p, 'get_backlinks', 'in');
- return filterBacklinkRows(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy, links);
+ const policy = async () => (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy;
+ return withLinkPageStatus(ctx, policy, wantsPagedBacklinks(p) ? await filterBacklinkRows(ctx, p, await policy(), links) : links);
},
scope: 'read',
cliHints: { name: 'backlinks', positional: ['slug'] },
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 20f97f658d..8b65dbadf8 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -853,6 +853,8 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
backlink_count: { type: 'integer' },
relationship_note: { type: 'string' },
+ // F3 — ADDITIVE OPTIONAL: the card page's own frontmatter `status`, only when set (entity.row_page_status).
+ page_status: { type: 'string', maxLength: 40 },
// 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 },
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 9f75c2f495..28cf766ece 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -107,6 +107,8 @@ export interface EntityCard {
* a relationship that ended. Absent when there is nothing to say.
*/
relationship_note?: string;
+ /** F3: this page's own frontmatter `status` (a string up to 40 characters), only when set. `context_pack` cards only. */
+ page_status?: string;
/** Pages dated after this page that mention it, newest first, bounded. `context_pack` cards only (mentions/newer-mentions.ts). */
newer_mentions?: NewerMentions;
/** Distinct pages with any inbound link (every link source, mentions included). `entity` verb only. */
diff --git a/test/e2e/entity-records-postgres.test.ts b/test/e2e/entity-records-postgres.test.ts
index 77a246525c..633a4a87cf 100644
--- a/test/e2e/entity-records-postgres.test.ts
+++ b/test/e2e/entity-records-postgres.test.ts
@@ -30,4 +30,6 @@ d('entity records (Postgres)', () => {
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);
+ test('F3 page_status on get_backlinks and context_pack rows: additive, bounded, hidden pages none; its key removes it there', () => S.pageStatusOnRows(engine), 60_000);
+ test('F1 on, F3 off: record rows keep page_status on initial and continued outputs; other rows have none', () => S.recordsKeepPageStatusWithRowKeyOff(engine), 60_000);
});
diff --git a/test/entity-records.test.ts b/test/entity-records.test.ts
index dfff4a4cc9..fc46b24c5e 100644
--- a/test/entity-records.test.ts
+++ b/test/entity-records.test.ts
@@ -30,4 +30,6 @@ describe('entity records (PGLite)', () => {
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);
+ test('F3 page_status on get_backlinks and context_pack rows: additive, bounded, hidden pages none; its key removes it there', () => S.pageStatusOnRows(engine), 60_000);
+ test('F1 on, F3 off: record rows keep page_status on initial and continued outputs; other rows have none', () => S.recordsKeepPageStatusWithRowKeyOff(engine), 60_000);
});
diff --git a/test/helpers/entity-records-scenarios.ts b/test/helpers/entity-records-scenarios.ts
index ffa77465a9..0deb6d094e 100644
--- a/test/helpers/entity-records-scenarios.ts
+++ b/test/helpers/entity-records-scenarios.ts
@@ -41,7 +41,7 @@ async function since(engine: BrainEngine, from: string, to: string, scope: 'all'
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);
+ for (const k of ['entity.names_references', 'entity.record_types', 'entity.row_page_status', 'entity_identity.union', 'mentions.sibling_merge']) await engine.unsetConfig(k);
await engine.setConfig('schema_pack', 'gbrain-base-v2');
}
@@ -361,3 +361,91 @@ export async function recordsPackLast(engine: BrainEngine): Promise<void> {
expect(tiny.cards[0].referenced_by_count).toBeDefined();
}
}
+
+const statusMap = (rows: Array<{ slug?: string; from_slug?: string; page_status?: string }>) =>
+ Object.fromEntries(rows.filter(r => r.page_status !== undefined).map(r => [r.slug ?? r.from_slug, r.page_status]));
+const withoutPageStatus = (v: unknown): unknown => JSON.parse(JSON.stringify(v, (k, x) => (k === 'page_status' ? undefined : x)));
+
+async function seedStatuses(engine: BrainEngine): Promise<void> {
+ await seedRecordsWorld(engine);
+ const set = (slug: string, status: string) => engine.executeRaw(
+ `UPDATE pages SET frontmatter = frontmatter || jsonb_build_object('status', $2::text) WHERE source_id = $1 AND slug = $3`, [SRC, status, slug]);
+ await set('crm/acme-example', 'active');
+ await set('contracts/acme-msa', ' signed ');
+ await set('notes/acme-call', 'x'.repeat(41));
+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || jsonb_build_object('status', 3) WHERE source_id = $1 AND slug = 'deals/acme-term-sheet'`, [SRC]);
+ await set('contracts/acme-private', 'unsigned');
+ await set('contracts/acme-quarantined', 'binding');
+ await engine.executeRaw(`UPDATE pages SET effective_date = '2025-05-01T00:00:00Z', effective_date_source = 'date' WHERE slug = 'crm/acme-example'`);
+}
+
+/** F3 (default on): `page_status` on get_backlinks link and page rows and on context_pack cards and newer-mention rows; additive, bounded, hidden pages none. */
+export async function pageStatusOnRows(engine: BrainEngine): Promise<void> {
+ const { validateAgainstSchema } = await import('../../src/core/verbs/conformance.ts');
+ const { RESPONSE_SCHEMAS } = await import('../../src/core/verbs.ts');
+ const { readPageStatusByRef, PAGE_STATUS_MAX_CHARS } = await import('../../src/core/mentions/referrers.ts');
+ await seedStatuses(engine);
+ const shown = { 'contracts/acme-amend-2-draft': 'draft', 'contracts/acme-msa': 'signed' };
+ const reads = async () => ({
+ links: (await call(engine, 'get_backlinks', { slug: 'crm/acme-example' })).body as unknown as Array<Record<string, any>>,
+ typed: (await call(engine, 'get_backlinks', { slug: 'crm/acme-example', type: 'contract', limit: 50 })).body as unknown as Array<Record<string, any>>,
+ page: (await call(engine, 'get_backlinks', { slug: 'crm/acme-example', group: 'page' })).body,
+ pack: (await call(engine, 'context_pack', { entities: 'crm/acme-example' })).body,
+ });
+ const on = await reads();
+ expect(statusMap(on.links)).toEqual(shown);
+ expect(statusMap(on.typed)).toEqual(shown);
+ expect(statusMap(on.page.rows)).toEqual(shown);
+ // The relationship `status` on link rows is unchanged; page_status only adds.
+ await engine.setConfig('entity.row_page_status', 'false');
+ const off = await reads();
+ await engine.unsetConfig('entity.row_page_status');
+ expect(JSON.stringify([off.links, off.typed, off.page, off.pack])).not.toContain('page_status');
+ expect(withoutPageStatus([on.links, on.typed, on.page])).toEqual([off.links, off.typed, off.page]);
+ expect(on.links.some(l => typeof l.status === 'string')).toBe(off.links.some(l => typeof l.status === 'string'));
+ // context_pack: the card's own status and each newer-mention row's; the injected text is unchanged.
+ const card = on.pack.cards[0];
+ expect(card.page_status).toBe('active');
+ expect(statusMap(card.newer_mentions.rows)).toEqual({ 'contracts/acme-amend-2-draft': 'draft' });
+ expect(on.pack.text).toBe(off.pack.text);
+ expect(withoutPageStatus(on.pack)).toEqual(off.pack);
+ expect(validateAgainstSchema(on.pack, RESPONSE_SCHEMAS.context_pack)).toEqual([]);
+ // Only a string up to the bound is shown, trimmed; a private or quarantined page shows none unless the caller may read it.
+ const refs = ['notes/acme-call', 'deals/acme-term-sheet', 'contracts/acme-private', 'contracts/acme-quarantined', 'contracts/acme-msa'].map(slug => ({ source_id: SRC, slug }));
+ expect(PAGE_STATUS_MAX_CHARS).toBe(40);
+ expect(Object.fromEntries(await readPageStatusByRef(engine, refs, { excludePrivate: true }))).toEqual({ [`${SRC}:contracts/acme-msa`]: 'signed' });
+ expect(Object.fromEntries(await readPageStatusByRef(engine, refs, { excludePrivate: false, includeQuarantined: true }))).toEqual({
+ [`${SRC}:contracts/acme-msa`]: 'signed', [`${SRC}:contracts/acme-private`]: 'unsigned', [`${SRC}:contracts/acme-quarantined`]: 'binding' });
+ for (const hidden of ['unsigned', 'binding']) expect(JSON.stringify(on)).not.toContain(`"${hidden}"`);
+}
+
+/** F1 on, F3 off: record rows keep `page_status` on the initial outputs (names rows, card, context_pack) and on the record-type continuation; every other row has none. */
+export async function recordsKeepPageStatusWithRowKeyOff(engine: BrainEngine): Promise<void> {
+ await seedStatuses(engine);
+ await engine.setConfig('entity.record_types', 'contract');
+ await engine.setConfig('entity.row_page_status', 'false');
+ try {
+ const names = (await call(engine, 'entity', { names: ['CRM record: Acme Example'] })).body.results[0];
+ const fullCard = (await call(engine, 'entity', { name: 'crm/acme-example' })).body.card;
+ const pack = (await call(engine, 'context_pack', { entities: 'crm/acme-example' })).body;
+ for (const group of [names.records[0], fullCard.records[0], pack.cards[0].records[0]]) {
+ expect(statusMap(group.rows)['contracts/acme-amend-2-draft']).toBe('draft');
+ }
+ const next = names.records[0].next;
+ const continued = (await call(engine, 'get_backlinks', next.arguments)).body;
+ expect(continued.rows.map((r: { slug: string }) => r.slug)).toEqual(['contracts/acme-msa']);
+ expect(continued.rows[0].page_status).toBe('signed');
+ expect(pack.cards[0].page_status).toBeUndefined();
+ expect(JSON.stringify(pack.cards[0].newer_mentions)).not.toContain('page_status');
+ const untyped = (await call(engine, 'get_backlinks', { slug: 'crm/acme-example', group: 'page' })).body;
+ expect(JSON.stringify(untyped)).not.toContain('page_status');
+ expect(JSON.stringify((await call(engine, 'get_backlinks', { slug: 'crm/acme-example' })).body)).not.toContain('page_status');
+ // Turning F3 back on changes only the non-record rows.
+ await engine.unsetConfig('entity.row_page_status');
+ const continuedOn = (await call(engine, 'get_backlinks', next.arguments)).body;
+ expect(continuedOn).toEqual(continued);
+ expect((await call(engine, 'entity', { names: ['CRM record: Acme Example'] })).body.results[0]).toEqual(names);
+ } finally {
+ await engine.unsetConfig('entity.row_page_status');
+ }
+}