Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): cap get_links/get_backlinks at 500 rows with keyset cursor paging (#6876)

time-attack833ceb1f3ba2
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 704fd9f613..f2c68e4cb1 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -119,7 +119,7 @@ Every non-localOnly operation on the MCP surface: 151 tools across 25 areas. **S
|---|---|---|---|---|
| `add_link` | Create a typed link (edge) from one page to another in the same source. | write | | |
| `find_orphans` | Find disconnected pages. | read | | |
-| `get_backlinks` | Links to a page; group:"page" pages by referrer, newest first. | read | yes | |
+| `get_backlinks` | Links to a page, ≤500/call; group:"page" by referrer, newest first. | read | yes | |
| `get_links` | List a page's outgoing links (typed edges to other pages). | read | | |
| `list_link_sources` | Link provenances (e.g. | read | yes | |
| `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index ba6a597c12..bc975ab917 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -39,7 +39,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/insights.ts` — `find_contradictions` (`filtered`, takes `min_trust`) returns the stored report as written only to explicitly trusted, unscoped, unfloored local callers. Remote, source-scoped and floored callers get `eval-contradictions/scoped-read.ts` findings (both sides re-read live, `total_visible` instead of the run total); a remote context with no source scope gets an empty list and a note. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
-- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.
+- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. (4) Row paging (#6876): rows are keyset-paged by `ops/link-paging.ts` (cap after the source/identity merge; see its header). Pinned by `test/link-read-paging.test.ts`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.
- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`).
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 871f24f971..4b0a0f0253 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -15,7 +15,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate). F1 records: `referrersCteBatched` is the same CTE with a target index (`referrerFilters` shared), `readTargetReferences` reads `referenced_by_count` plus enrolled-type records for many targets in two statements (totals per type; top `RECORD_ROWS_PER_TARGET` per target newest first; `RECORD_ROWS_PER_CALL` allotted in target order before hydration; rows, totals and cursors equal `readReferrerPage {type}`), `readRecordMetadata` adds `page_status`, `amends` (+ `since` from `link_relationships.first_start` in the caller's scope) and `supersedes`, also on `readReferrerPage {recordMetadata}` continuations. F3: `pageStatusValue` (string, trimmed, at most `PAGE_STATUS_MAX_CHARS` 40) is the one `page_status` rule; `readPageStatusByRef` reads it by `(source_id, slug)` in one statement (private pages hidden from untrusted callers, quarantined pages unless allowed) for `readReferrerPage {pageStatus}`, `get_backlinks` link rows and `context_pack` cards and newer-mention rows. Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while index-due pages exist (`previewMentionPass`), including every page behind the binary's mention or alias version on an unchanged brain. Post-upgrade does not run the sweep; autopilot's cycle extract phase continues it on its stale-drain budget (`CYCLE_STALE_DRAIN_BUDGET_MS`).
-- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode 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/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode (#6876) is the keyset-paged `Link[]` from `ops/links.ts` / `ops/link-paging.ts`; `filterBacklinkRows` only filters each page by referrer type. With `group: "page"`, `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values. F3 (`entity.row_page_status`, default on): `withLinkPageStatus` adds the referring page's `page_status` to link rows, and `group: "page"` rows get it through `readReferrerPage {pageStatus}`; a record type's continuation keeps it through `recordMetadata` when the key is off.
- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `denied_by_config`, `not_a_known_name`); only `pending` names a sweep. A slug query also lists each derived name with origin and declaring line, the rejected candidates with reasons, and the sibling decision. Tests: `test/mentions-explain.test.ts`.
- `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` reads `entityLookupScope` once per batch, then resolves each name through the card's candidate selection (`selectEntityCandidates`, no card assembled), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; the lead comes from the candidate row's bounded, withdrawal-overlaid `compiled_truth` prefix (`page-window/bounded-lead.ts`), siblings from `readSiblingIdentity` with the batch's policy and pack. Output is byte-identical to the old full-card path (`test/entity-names-parity.test.ts`, Postgres twin `test/e2e/entity-names-parity-postgres.test.ts`, fixtures and the reference resolver in `test/helpers/entity-names-parity.ts`). `pageLead` is the body's opening prose from `boundedProjectedPrefix` (the 64 KiB prefix, sanitized and credential-projected) plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. `attachReferences` adds `referenced_by_count`, the card `next` and `records` to every found page and sibling from one `readRowReferences` call. Tests: `test/entity-names.test.ts`, `test/entity-names-parity.test.ts`, `test/entity-records.test.ts`.
- `src/core/verbs/entity-references.ts` — the F1 reference fields on compact rows: `readRowReferences` (config gate per surface `names` / `pack` / `full_card`, `REFERENCES_DEADLINE_MS` 2 s cooperative deadline, `references_unavailable` marker + degraded notice, per-type `next` to `get_backlinks` returning exactly the rest, `record_types_undeclared` notice), `readPackReferences` (context_pack pull verb only: card page + identity siblings), `renderRecordLines` / `RECORDS_HEADER` (packed text, "page date"). Config: `src/core/entity-references-config.ts` (`entity.names_references` default on, `entity.record_types` default empty). Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
index 37ae184815..4e7296b2e4 100644
--- a/docs/guides/entity-recall.md
+++ b/docs/guides/entity-recall.md
@@ -96,8 +96,10 @@ gbrain backlinks crm/acme-example --type ticket --group page --limit 2
returns `{rows, total, truncated, cursor, coverage}`, newest first by
`(date, source, slug)`; pass `cursor` back to continue. Without `group`,
-`get_backlinks` returns the link rows it always did (`type` and `limit` filter
-them). `type` takes a schema-pack type, one of its aliases (`crm` and
+`get_backlinks` returns link rows, 500 per call by default (`limit`, up to 5000):
+when more match, the last row carries `truncated: true` and `next_cursor`, which
+you pass back as `cursor`. `type` filters each page of rows, so a page can hold
+fewer rows than `limit` while the cursor continues. `type` takes a schema-pack type, one of its aliases (`crm` and
`account` both mean the account group), a type seen on a referring page
(`ticket`), or `untyped`.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index f7595c6f22..99b9da2383 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -157,6 +157,12 @@ gbrain links people/alice-example --all-sources --json # every source
gbrain graph people/alice-example --depth 2 --all-sources
```
+Each call returns at most 500 rows (`--limit N`, up to 5000), merged across
+sources and identity members in link order before the cut. When more match, the
+last row carries `truncated: true` and `next_cursor`; continue with
+`--cursor <next_cursor>` and the same flags, or pass `--all` to page through
+every row.
+
`get_links` keeps working as an alias of `links`. Passing `--source` together
with `--source-id` or `--all-sources` is an error. A source that does not exist
or is archived answers `unknown_source`; a remote agent naming a source outside
diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.md
index ea9173431f..99e8a6b0c8 100644
--- a/docs/guides/temporal-edges.md
+++ b/docs/guides/temporal-edges.md
@@ -175,7 +175,9 @@ sections). A link may keep a `mentions` row beside a typed one.
`all`) and `as_of`; `traverse_graph` walks live relationships (read history with
`get_links` or `get_backlinks`). When a default read leaves relationships
out, the response carries a `former_relationships_hidden` notice with the exact call
-that shows them, and `gbrain.temporal` response metadata with the count.
+that shows them, and `gbrain.temporal` response metadata with the count. Both filters run before the
+500-row page cap, so a hidden relationship never takes a row; on a paged read the count
+covers the rows that page spans.
Recipe for "where did alice-example work in 2022":
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index a069435c4a..654f6e5200 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -145,6 +145,8 @@ Poll an agent job submitted via submit_agent. Returns a trimmed status view (id,
List incoming links to a page
+Link rows come 500 per call by default (`limit`, up to 5000), in link order. When more match, the last row carries `truncated: true` and `next_cursor`; pass it back as `cursor` with the same parameters for the next rows (a cursor from another listing is refused `link_cursor_invalid`). `get_links` pages the same way. Each row's `context` is cut to 2000 characters, ending in an ellipsis.
+
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 |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ace5e85f7d..3c9061ce83 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3014 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move)
+src/cli/main.ts 3015 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 #6876: links --help paging example (limit/cursor/all; the paging lives in core/ops/link-paging.ts)
src/commands/autopilot.ts 1650 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 7900b3f3ee..f5695aa999 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2933,6 +2933,7 @@ const OP_HELP_EXAMPLES: Record<string, string[]> = {
'gbrain links people/alice-example # resolved source (every federated source when unpinned)',
'gbrain links people/alice-example --source business # one source',
'gbrain links people/alice-example --all-sources # every source',
+ 'gbrain links people/alice-example --limit 100 # 500 rows per call by default; --cursor <next_cursor> continues, --all reads every row',
],
get_backlinks: [
'gbrain backlinks companies/acme-example',
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index bb999e0552..e1ab8cba46 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -906,6 +906,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
{ since: '0.60.307.0', text: 'A name written only in Katakana (an alias such as デン) no longer links a page that has it inside a longer Katakana word (インシデント, デンタル): the name must stand as a whole Katakana run, so 「デン」, デンに, 喫茶デン and デン・カフェ still link. A short name inside a real Katakana compound is refused too; add the compound as its own alias when it names the entity. Mention links already written that way are counted by `gbrain doctor` (`stale_mentions`) and removed by `gbrain extract links --by-mention --rebuild --source db`.', id: 'katakana_mention_boundaries' },
{ since: '0.60.307.0', text: 'On Windows, cancelling or timing out a job now ends its whole process tree with taskkill: a per-job child and a shell job first get a polite close (`taskkill /T`), then a forced one (`/T /F`) after the grace window, instead of only the direct child being killed. A windowless console program refuses the polite close, so a cancelled Windows shell job now takes up to its 5-second grace window to end. A descendant whose parent already exited is no longer in the tree and is not ended.', id: 'windows_tree_kill' },
+ { since: '0.60.307.0', text: '`get_links` and `get_backlinks` (`gbrain links`, `gbrain backlinks`) now return at most 500 link rows per call instead of every edge of the page. When more match, the last row carries `truncated: true` and `next_cursor`: pass it back as `cursor` (`--cursor`) with the same filters for the next rows, raise `limit` (`--limit`, up to 5000), or use `--all` on the CLI for every row. Remote callers also get a `listing_truncated` notice naming the next call. Rows come in link order, `link_type` and the live/history filter apply before the cap so hidden former relationships never use a row, and each row\'s `context` is cut to 2000 characters (ending in an ellipsis). A cursor from another listing is refused `link_cursor_invalid`. `get_backlinks` with `limit` no longer points at `group: "page"`; it pages the rows with `cursor`.', id: 'link_read_cap' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 9f8e4affad..50559caf30 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -24,13 +24,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
+ 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
- 'capture': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
+ 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--exit-code', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
@@ -50,12 +50,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
- 'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
+ 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -88,19 +88,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--add', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
+ 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
- 'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
+ 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
- 'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--since', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
@@ -137,7 +137,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
};
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
diff --git a/src/core/engine-constants.ts b/src/core/engine-constants.ts
index 1d88bca6cf..db82695f45 100644
--- a/src/core/engine-constants.ts
+++ b/src/core/engine-constants.ts
@@ -46,3 +46,17 @@ export const TRAVERSE_PATH_ROW_CAP = 5000;
* paths (a 12-page clique at depth 5 took 22 s).
*/
export const TRAVERSE_WALK_ROW_CAP = 20000;
+
+/**
+ * Default rows per get_links / get_backlinks call (#6876, decision D4). The
+ * cap is applied by the ops, after every filter and the source/identity merge;
+ * `engine.getLinks` / `getBacklinks` stay complete unless a caller opts into
+ * a page. One place to change it.
+ */
+export const LINK_READ_DEFAULT_LIMIT = 500;
+
+/** Largest `limit` a get_links / get_backlinks call accepts. */
+export const LINK_READ_MAX_LIMIT = 5000;
+
+/** get_links / get_backlinks rows carry at most this much edge context (cut in SQL, ellipsis-terminated). */
+export const LINK_READ_CONTEXT_MAX_CHARS = 2000;
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index 81b767b1fd..bd142543db 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -37,6 +37,36 @@ function temporalWalkFilter(alias: string, opts?: LinkReadScope) {
return opts?.temporal ? trustedSql(`AND ${relationshipFilterSql(alias, { ...opts.temporal, excludePrivate: opts.excludePrivate })}`) : sqlFragment``;
}
+/**
+ * SQL pieces of an opt-in keyset page (LinkReadScope.page, #6876). Without a
+ * page every piece renders master's statement text, so internal callers read
+ * every row. With one, link_type, the keyset bounds and the temporal policy
+ * filter in SQL before LIMIT, and each row carries `link_id`.
+ */
+function linkPageSql(opts?: LinkReadScope) {
+ const page = opts?.page;
+ if (!page) return { context: sqlFragment`l.context`, id: sqlFragment``, where: sqlFragment``, limit: sqlFragment`` };
+ const chars = page.contextChars;
+ const context = chars === undefined
+ ? sqlFragment`l.context`
+ : sqlFragment`CASE WHEN char_length(l.context) > ${chars} THEN left(l.context, ${chars - 1}) || '…' ELSE l.context END AS context`;
+ const rel = page.relationship;
+ const relationship = !rel
+ ? sqlFragment``
+ : rel.keep === 'match'
+ ? sqlFragment` ${temporalWalkFilter('l', { temporal: rel.policy, excludePrivate: opts?.excludePrivate })}`
+ : sqlFragment` ${trustedSql(`AND NOT (${relationshipFilterSql('l', { ...rel.policy, excludePrivate: opts?.excludePrivate })})`)}`;
+ const linkType = page.linkType !== undefined ? sqlFragment` AND l.link_type = ${page.linkType}` : sqlFragment``;
+ const after = page.afterId !== undefined ? sqlFragment` AND l.id > ${page.afterId}` : sqlFragment``;
+ const through = page.throughId !== undefined ? sqlFragment` AND l.id <= ${page.throughId}` : sqlFragment``;
+ return {
+ context,
+ id: sqlFragment`, l.id AS link_id`,
+ where: sqlFragment`${linkType}${after}${through}${relationship}`,
+ limit: page.limit !== undefined ? sqlFragment` LIMIT ${page.limit}` : sqlFragment``,
+ };
+}
+
export async function addLink(
exec: SqlExecutor,
from: string,
@@ -306,6 +336,7 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadSc
const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
const finish = (rows: unknown[]) => finishTemporal(rows, opts);
+ const page = linkPageSql(opts);
// #2200: federated grant scopes ALL THREE page endpoints — from, to, AND
// the origin (the page that authored the edge, surfaced as origin_slug).
// Scoping only from+to would still leak an out-of-grant origin's slug; the
@@ -316,16 +347,16 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadSc
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[]) ${trustedSql(tJoin)}
WHERE f.slug = ${slug} AND f.source_id = ANY(${ids}::text[]) AND t.source_id = ANY(${ids}::text[])
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
@@ -340,32 +371,32 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadSc
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE f.slug = ${slug} AND f.source_id = ${opts.sourceId}
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE f.slug = ${slug}
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
@@ -376,6 +407,7 @@ export async function getBacklinks(exec: ScopedRead, slug: string, opts?: LinkRe
const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
const finish = (rows: unknown[]) => finishTemporal(rows, opts);
+ const page = linkPageSql(opts);
// #2200: federated grant scopes all three endpoints (mirrors getLinks) —
// the referrer (from), the queried page (to), AND the origin — so neither
// a foreign referrer nor a foreign origin slug is disclosed to the caller.
@@ -384,16 +416,16 @@ export async function getBacklinks(exec: ScopedRead, slug: string, opts?: LinkRe
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[]) ${trustedSql(tJoin)}
WHERE t.slug = ${slug} AND t.source_id = ANY(${ids}::text[]) AND f.source_id = ANY(${ids}::text[])
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
@@ -403,32 +435,32 @@ export async function getBacklinks(exec: ScopedRead, slug: string, opts?: LinkRe
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE t.slug = ${slug} AND t.source_id = ${opts.sourceId}
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
- l.link_type, l.context, l.link_source,
+ l.link_type, ${page.context}, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field ${trustedSql(tSel)}
+ l.origin_field ${trustedSql(tSel)}${page.id}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE t.slug = ${slug}
- AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
- ORDER BY l.id
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}${page.where}
+ ORDER BY l.id${page.limit}
`)).rows;
return finish(rows);
}
diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.ts
index e68db901ec..93bd2ebc3c 100644
--- a/src/core/entity-identity.ts
+++ b/src/core/entity-identity.ts
@@ -307,7 +307,11 @@ export async function unionLinksAcrossIdentity(
slug: string,
links: Link[],
direction: 'out' | 'in',
- opts: { sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean; temporal?: import('./link-validity.ts').EdgeTemporalOpts } = {},
+ opts: {
+ sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean; temporal?: import('./link-validity.ts').EdgeTemporalOpts;
+ /** #6876: the caller's keyset page, applied to each member read; `onMemberRead` sees each member's rows before the merge. */
+ page?: import('./link-validity.ts').LinkReadPage; onMemberRead?: (rows: Link[]) => void;
+ } = {},
): Promise<Link[]> {
if (!(await isIdentityUnionEnabled(engine))) return links;
let members: EntityIdentityMember[];
@@ -346,10 +350,12 @@ export async function unionLinksAcrossIdentity(
...(opts.allowedSources?.length ? { sourceIds: opts.allowedSources } : {}),
excludePrivate: opts.excludePrivate,
...(opts.temporal ? { temporal: opts.temporal } : {}),
+ ...(opts.page ? { page: opts.page } : {}),
};
const memberLinks = direction === 'out'
? await engine.getLinks(m.slug, memberScope)
: await engine.getBacklinks(m.slug, memberScope);
+ opts.onMemberRead?.(memberLinks);
for (const l of memberLinks) {
// Federated engine reads span same-slug pages across the grant. Keep
// this identity member's concrete pair, not a same-slug non-member.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5a5436d9dc..f8893ef68a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -356,6 +356,8 @@ export const CODES = {
legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },
legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },
legacy_lock_removal_refused: { class: 'host_only', summary: "`gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local.", why: "The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be confirmed (neither Linux nor macOS, a failed probe, an unrecognised type, a macOS mount without the local flag), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain.", reasons: ['live_holder', 'network_filesystem', 'filesystem_unverified'], docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux or macOS host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside.' },
+ // #6876: get_links / get_backlinks continuations are bound to their listing.
+ link_cursor_invalid: { class: 'caller', summary: "A get_links / get_backlinks cursor was not one this listing returned: it belongs to another slug, direction, source scope or filter set, or is not a cursor.", why: "A cursor is a link-id position bound to the exact listing that issued it; continuing a different listing from it could skip or repeat edges without saying so. Nothing was read.", legacy_error: 'invalid_params', suggestion: 'Restart the listing with the same slug and filters and no cursor, then pass each next_cursor unchanged.', fix: { argv: ['gbrain', 'links', '{slug}'], mcp: { tool: 'get_links', arguments: { slug: '{slug}' } }, consent: [], actor: 'agent', why: 'Restarts the listing from its first page (read-only); pass each next_cursor it returns unchanged.', requires_exclusive: false, verify: { mcp: { tool: 'get_links', arguments: { slug: '{slug}', limit: 1 } } } } },
local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
loops_extraction_skipped: { class: 'unavailable', summary: "A Google sweep or the managed catch-up queued no paid loop extraction; the sync summary's `skipped_reason` says why. Nothing failed and the email pages still imported.", why: "Extraction is gated before any model call: a kill switch, a missing chat provider, the day's spend cap (`loops.extraction_max_usd_per_day`, default $2.00; `spend_cap_zero` means the user set it to 0), or an exclusion label (`g_loops_exclude_labels` / `loops.extraction_exclude_labels`) that did not resolve against the account's labels, which fails closed until a sweep resolves it.", reasons: ['no_candidates', 'extraction_disabled', 'chat_unavailable', 'enqueue_failed', 'daily_spend_cap', 'spend_cap_zero', 'excluded_label', 'excluded_label_unresolved'], docs: 'docs/guides/open-loops.md#two-detectors', suggestion: 'Read the reason. `daily_spend_cap` clears at the next UTC day or when the user raises `loops.extraction_max_usd_per_day`; `excluded_label_unresolved` names the label token to fix in `gbrain sources status <id>` or `gbrain config get loops.extraction_exclude_labels`; the threads are extracted on their next touch or by `gbrain sync --source <id> --full`.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the last sweep\'s loop extraction report with its skipped_reason and the unresolved label tokens.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'loops.extraction_max_usd_per_day'] } } },
diff --git a/src/core/link-validity.ts b/src/core/link-validity.ts
index 891ae1af3d..d12ae110f5 100644
--- a/src/core/link-validity.ts
+++ b/src/core/link-validity.ts
@@ -376,6 +376,26 @@ function recordedMs(v: string | Date | null): number {
/** Link reads that may apply a temporal edge policy. `temporal` absent = every edge, unannotated (reference consumers). */
export interface LinkReadScope extends PageReadScope {
temporal?: EdgeTemporalOpts;
+ /** Opt-in keyset page (get_links / get_backlinks ops); unset reads every row, as internal callers need. */
+ page?: LinkReadPage;
+}
+
+/**
+ * A keyset page of `getLinks` / `getBacklinks` rows in `links.id` order. Each
+ * row then carries `link_id` (the keyset). Every filter runs in SQL so a LIMIT
+ * counts only rows the caller can be shown.
+ */
+export interface LinkReadPage {
+ /** Only rows with links.id above this. */
+ afterId?: number;
+ /** Only rows with links.id at or below this. */
+ throughId?: number;
+ limit?: number;
+ linkType?: string;
+ /** Keep the rows that match the temporal policy, or only the rows it hides. */
+ relationship?: { policy: EdgeTemporalOpts; keep: 'match' | 'hidden' };
+ /** Context longer than this is cut, ending in an ellipsis. */
+ contextChars?: number;
}
export interface EdgeTemporalOpts {
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 24548b0cb5..87a34abc1f 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -1684,7 +1684,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"mutating": false,
"idempotent": true,
"outputRedaction": "retrieval",
- "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Returns up to 500 rows per call (limit, max 5000); a cut list's last row carries truncated: true and next_cursor, which you pass as cursor. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
"params": {
"slug": {
"type": "string",
@@ -1719,6 +1719,19 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"all_sources": {
"type": "boolean",
"description": "Same as source_id __all__."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Rows per call (default 500, max 5000)."
+ },
+ "cursor": {
+ "type": "string",
+ "description": "next_cursor from the previous call (same filters)."
+ },
+ "all": {
+ "type": "boolean",
+ "description": "Local CLI only: every row, paging internally.",
+ "fullSurfaceOnly": true
}
},
"scope": "read",
@@ -1738,7 +1751,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"mutating": false,
"idempotent": true,
"outputRedaction": "retrieval",
- "description": "Links to a page; group:\"page\" pages by referrer, newest first.",
+ "description": "Links to a page, ≤500/call; group:\"page\" by referrer, newest first.",
"params": {
"slug": {
"type": "string",
@@ -1778,11 +1791,16 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"limit": {
"type": "number",
- "description": "Max 500."
+ "description": "≤5000"
},
"cursor": {
"type": "string",
- "description": "Paging."
+ "description": "Next."
+ },
+ "all": {
+ "type": "boolean",
+ "description": "Local CLI only: every row, paging internally.",
+ "fullSurfaceOnly": true
}
},
"scope": "read",
diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.ts
index a7352d463b..8a27477ba8 100644
--- a/src/core/ops/backlinks-paged.ts
+++ b/src/core/ops/backlinks-paged.ts
@@ -1,7 +1,7 @@
/**
- * get_backlinks' entity-recall parameters (`type`, `group`, `limit`,
- * `cursor`). With none of them the op is today's bare `Link[]` read
- * (ops/links.ts readLinkEdges). `type` filters by the referring page's type
+ * get_backlinks' entity-recall parameters (`type`, `group`). Without
+ * `group` the op returns `Link[]` rows paged by `limit` / `cursor`
+ * (ops/links.ts readLinkEdges, ops/link-paging.ts). `type` filters by the referring page's type
* in both modes (a pack-canonical type, or any stored type observed on a
* referrer; `untyped` for untyped pages). `group: "page"` returns
* `{rows, total, truncated, cursor, coverage}`: one row per referring page,
@@ -12,7 +12,6 @@
import { opError, type OperationContext } from './contract.ts';
import type { Link, PageReadPolicy } from '../types.ts';
-import type { Notice } from '../agent-output.ts';
import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';
import {
canonicalRecordTypes, decodeCursor, readPageStatusByRef, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,
@@ -28,11 +27,6 @@ export interface BacklinkPage {
coverage: MentionCoverage;
}
-/** True when the call uses any entity-recall parameter. */
-export function wantsPagedBacklinks(p: Record<string, unknown>): boolean {
- return p.type !== undefined || p.group !== undefined || p.limit !== undefined || p.cursor !== undefined;
-}
-
function parseLimit(p: Record<string, unknown>, fallback: number | undefined): number | undefined {
if (p.limit === undefined) return fallback;
const n = typeof p.limit === 'string' ? Number(p.limit) : p.limit;
@@ -123,43 +117,26 @@ export async function withLinkPageStatus(ctx: OperationContext, policy: () => Pr
}
/**
- * Array mode with `type` and/or `limit`: today's link rows, filtered by the
- * referring page's type and cut at `limit` (a cut is reported with a
- * `listing_truncated` notice naming the paged call).
+ * Array mode with `type`: one page of link rows (ops/links.ts, #6876 keyset
+ * paging), kept when the referring page has that type. The page is cut before
+ * this filter, so a page can hold fewer rows than `limit`; the cursor still
+ * continues the same listing.
*/
export async function filterBacklinkRows(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy, links: Link[]): Promise<Link[]> {
- if (p.cursor !== undefined) {
- throw opError('invalid_params', 'get_backlinks: cursor needs group: "page".', 'Pass group: "page" with the cursor, or omit cursor.');
- }
- const limit = parseLimit(p, undefined);
- let rows = links;
const type = typeof p.type === 'string' && p.type ? p.type : undefined;
- if (type) {
- const resolved = await referrerScope(ctx, String(p.slug), policy);
- if (resolved) await assertKnownType(ctx, resolved.scope, type);
- const keys = [...new Set(links.map(l => `${l.from_source_id}\0${l.from_slug}`))];
- const types = new Map((await ctx.engine.executeRaw<{ source_id: string; slug: string; type: string | null }>(
- `SELECT p.source_id, p.slug, p.type FROM pages p JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON p.source_id = k.s AND p.slug = k.g`,
- [keys.map(k => k.split('\0')[0]), keys.map(k => k.split('\0')[1])])).map(r => [`${r.source_id}\0${r.slug}`, r.type]));
- const packs = new Map<string, Awaited<ReturnType<typeof loadSourcePack>>>();
- const filtered: Link[] = [];
- for (const l of links) {
- if (!packs.has(l.from_source_id)) packs.set(l.from_source_id, await loadSourcePack(ctx.engine, l.from_source_id));
- const stored = types.get(`${l.from_source_id}\0${l.from_slug}`) ?? null;
- if (stored === type || canonicalTypeOf(stored, packs.get(l.from_source_id) ?? null) === type) filtered.push(l);
- }
- rows = filtered;
- }
- if (limit !== undefined && rows.length > limit) {
- const notice: Notice = {
- code: 'listing_truncated', kind: 'info',
- why: `${rows.length} link rows match; ${limit} were returned. For one row per referring page with a cursor, use group: "page".`,
- fix: { mcp: { tool: 'get_backlinks', arguments: { slug: p.slug, ...(p.source_id !== undefined ? { source_id: p.source_id } : {}),
- ...(type ? { type } : {}), group: 'page', limit } }, consent: [], actor: 'agent', requires_exclusive: false,
- why: 'Pages through every referring page, newest first, without dropping rows.' },
- };
- ctx.emitNotice?.(notice);
- rows = rows.slice(0, limit);
+ if (!type) return links;
+ const resolved = await referrerScope(ctx, String(p.slug), policy);
+ if (resolved) await assertKnownType(ctx, resolved.scope, type);
+ const keys = [...new Set(links.map(l => `${l.from_source_id}\0${l.from_slug}`))];
+ const types = new Map((await ctx.engine.executeRaw<{ source_id: string; slug: string; type: string | null }>(
+ `SELECT p.source_id, p.slug, p.type FROM pages p JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON p.source_id = k.s AND p.slug = k.g`,
+ [keys.map(k => k.split('\0')[0]), keys.map(k => k.split('\0')[1])])).map(r => [`${r.source_id}\0${r.slug}`, r.type]));
+ const packs = new Map<string, Awaited<ReturnType<typeof loadSourcePack>>>();
+ const filtered: Link[] = [];
+ for (const l of links) {
+ if (!packs.has(l.from_source_id)) packs.set(l.from_source_id, await loadSourcePack(ctx.engine, l.from_source_id));
+ const stored = types.get(`${l.from_source_id}\0${l.from_slug}`) ?? null;
+ if (stored === type || canonicalTypeOf(stored, packs.get(l.from_source_id) ?? null) === type) filtered.push(l);
}
- return rows;
+ return filtered;
}
diff --git a/src/core/ops/link-paging.ts b/src/core/ops/link-paging.ts
new file mode 100644
index 0000000000..0465c93279
--- /dev/null
+++ b/src/core/ops/link-paging.ts
@@ -0,0 +1,155 @@
+/**
+ * get_links / get_backlinks row paging (#6876). Both ops used to return every
+ * edge of a page. Each call now returns at most `limit` rows (default
+ * LINK_READ_DEFAULT_LIMIT, max LINK_READ_MAX_LIMIT) in `links.id` order and
+ * continues with an opaque `cursor`.
+ *
+ * Every read (each source of a local federated read and each identity
+ * member) is a keyset page `links.id > cursor` with link_type and the
+ * temporal policy applied in SQL, probing `limit + 1` rows. The streams merge
+ * by link id and the cap is applied once, after the merge and the identity
+ * union. A stream that hit its probe row is only complete through its last
+ * row, so the page never reaches past the lowest such id: nothing between two
+ * pages is skipped even when the identity union de-duplicates rows.
+ *
+ * The result stays a bare array (what deployed clients parse), as get_chunks
+ * does: the last row of a cut page carries `truncated: true` and
+ * `next_cursor`, `_meta.pagination` carries the same facts, remote callers
+ * get a `listing_truncated` notice whose fix is the next call, and the local
+ * CLI gets one stderr line. A cursor is bound to the op (direction), slug,
+ * source scope and filters; any other cursor is `link_cursor_invalid`.
+ */
+import { createHash } from 'node:crypto';
+import type { Action } from '../agent-output.ts';
+import type { Link, PageReadPolicy } from '../types.ts';
+import { LINK_READ_DEFAULT_LIMIT, LINK_READ_MAX_LIMIT } from '../engine-constants.ts';
+import { opError, type OperationContext } from './contract.ts';
+import { invalidParam } from './op-fix.ts';
+
+type LinkOp = 'get_links' | 'get_backlinks';
+type PagedLink = Link & { link_id?: number | string };
+
+const CURSOR_PREFIX = 'lk1.';
+/** Params that select the listing: a cursor is bound to them, and a continuation carries them. */
+const LISTING_PARAMS = ['slug', 'link_type', 'status', 'as_of', 'during', 'source_id', 'all_sources', 'type'] as const;
+
+export interface LinkListing {
+ limit: number;
+ afterId?: number;
+ all: boolean;
+ binding: string;
+}
+
+const commandOf = (opName: LinkOp) => (opName === 'get_links' ? 'links' : 'backlinks');
+
+export const linkId = (l: Link): number => Number((l as PagedLink).link_id);
+
+function listingArgs(p: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(LISTING_PARAMS.filter(k => p[k] !== undefined).map(k => [k, p[k]]));
+}
+
+function cliArgs(args: Record<string, unknown>): string[] {
+ const out = [String(args.slug)];
+ for (const [k, v] of Object.entries(args)) {
+ if (k === 'slug') continue;
+ out.push(`--${k.replace(/_/g, '-')}`, ...(v === true ? [] : [String(v)]));
+ }
+ return out;
+}
+
+function restartFix(opName: LinkOp, p: Record<string, unknown>): Action {
+ const args = { ...listingArgs(p), ...(p.limit !== undefined ? { limit: p.limit } : {}) };
+ return {
+ argv: ['gbrain', commandOf(opName), ...cliArgs(args)],
+ mcp: { tool: opName, arguments: args },
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Restarts the listing from its first page with the same filters and no cursor; pass each next_cursor it returns unchanged.',
+ verify: { mcp: { tool: opName, arguments: { ...listingArgs(p), limit: 1 } } },
+ };
+}
+
+function bindingOf(opName: LinkOp, p: Record<string, unknown>, policy: PageReadPolicy): string {
+ const scope = [policy.sourceId ?? null, policy.sourceIds ?? null, policy.excludePrivate === true];
+ return createHash('sha256').update(JSON.stringify([opName, ...LISTING_PARAMS.map(k => p[k] ?? null), ...scope])).digest('hex').slice(0, 16);
+}
+
+function decodeCursor(raw: unknown, binding: string): number | null {
+ if (typeof raw !== 'string' || !raw.startsWith(CURSOR_PREFIX)) return null;
+ try {
+ const c = JSON.parse(Buffer.from(raw.slice(CURSOR_PREFIX.length), 'base64url').toString('utf8')) as { i?: unknown; b?: unknown };
+ return c.b === binding && typeof c.i === 'number' && Number.isSafeInteger(c.i) && c.i >= 0 ? c.i : null;
+ } catch {
+ return null;
+ }
+}
+
+const encodeCursor = (id: number, binding: string) => CURSOR_PREFIX + Buffer.from(JSON.stringify({ i: id, b: binding })).toString('base64url');
+
+/** Validate limit / cursor / all for one link listing. */
+export function parseLinkListing(ctx: OperationContext, opName: LinkOp, p: Record<string, unknown>, policy: PageReadPolicy): LinkListing {
+ let limit = LINK_READ_DEFAULT_LIMIT;
+ if (p.limit !== undefined && p.limit !== null) {
+ const n = typeof p.limit === 'string' ? Number(p.limit) : p.limit;
+ if (!(typeof n === 'number' && Number.isSafeInteger(n) && n >= 1 && n <= LINK_READ_MAX_LIMIT)) {
+ throw invalidParam(ctx, opName, 'limit', `${opName}: limit must be an integer from 1 to ${LINK_READ_MAX_LIMIT}.`, { example: LINK_READ_DEFAULT_LIMIT });
+ }
+ limit = n;
+ }
+ if (p.all === true && ctx.remote !== false) {
+ throw invalidParam(ctx, opName, 'all', `${opName}: all is for the local CLI; page with cursor instead.`,
+ { example: true, fix: restartFix(opName, p) });
+ }
+ const binding = bindingOf(opName, p, policy);
+ if (p.cursor === undefined || p.cursor === null) return { limit, all: p.all === true, binding };
+ const afterId = decodeCursor(p.cursor, binding);
+ if (afterId === null) {
+ throw opError('link_cursor_invalid',
+ `${opName}: cursor is not one this listing returned (another slug, direction, source scope or filter, or not a cursor).`,
+ 'Restart the listing with the same filters and no cursor, then pass each next_cursor unchanged.',
+ { legacy_error: 'invalid_params', fix: restartFix(opName, p) });
+ }
+ return { limit, afterId, all: p.all === true, binding };
+}
+
+/**
+ * One page from the merged streams (sorted by link id, de-duplicated). A
+ * stream that returned its probe row bounds the page at its last id.
+ */
+export function cutLinkPage(streams: Link[][], merged: Link[], limit: number): { rows: Link[]; nextId?: number } {
+ let bound = Infinity;
+ for (const s of streams) if (s.length > limit) bound = Math.min(bound, linkId(s[s.length - 1]));
+ const within = merged.filter(l => linkId(l) <= bound);
+ const rows = within.slice(0, limit);
+ if (within.length > limit) return { rows, nextId: linkId(rows[rows.length - 1]) };
+ return bound === Infinity ? { rows } : { rows, nextId: bound };
+}
+
+/** Pagination meta, the remote notice or the local stderr line; returns the next cursor when the listing continues. */
+export function reportLinkPage(ctx: OperationContext, opName: LinkOp, p: Record<string, unknown>, listing: LinkListing, page: { returned: number; nextId?: number }): string | undefined {
+ const next = page.nextId === undefined ? undefined : encodeCursor(page.nextId, listing.binding);
+ ctx.emitResponseMeta?.('pagination', { limit: listing.limit, returned: page.returned, truncated: next !== undefined, ...(next ? { next_cursor: next } : {}) });
+ if (!next) return undefined;
+ const args = { ...listingArgs(p), ...(p.limit !== undefined ? { limit: p.limit } : {}), cursor: next };
+ if (ctx.remote === false) {
+ ctx.logger.warn(`[gbrain] ${commandOf(opName)}: showing ${page.returned} link rows (limit ${listing.limit}); more exist. ` +
+ `Continue with --cursor ${next}, or pass --all for every row.`);
+ return next;
+ }
+ ctx.emitNotice?.({
+ code: 'listing_truncated', kind: 'info',
+ why: `${page.returned} link rows were returned (limit ${listing.limit}) and more match, so this list is not complete; a missing edge here is not proof it does not exist.`,
+ fix: { mcp: { tool: opName, arguments: args }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Fetches the next rows of the same listing; keep paging until a response has no next_cursor.' },
+ });
+ return next;
+}
+
+/** Drop the keyset column; the last row of a cut page carries truncated + next_cursor. */
+export function finishLinkPage<T extends Link>(rows: T[], nextCursor: string | undefined): T[] {
+ const out = rows.map(r => {
+ const { link_id: _id, ...rest } = r as T & { link_id?: unknown };
+ return rest as T;
+ });
+ if (!nextCursor || out.length === 0) return out;
+ return [...out.slice(0, -1), { ...out[out.length - 1], truncated: true, next_cursor: nextCursor }];
+}
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 631e14b987..842e9d39ef 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -1,5 +1,6 @@
import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';
-import { filterBacklinkRows, readBacklinkPage, wantsPagedBacklinks, withLinkPageStatus } from './backlinks-paged.ts';
+import { filterBacklinkRows, readBacklinkPage, withLinkPageStatus } from './backlinks-paged.ts';
+import { cutLinkPage, finishLinkPage, linkId, parseLinkListing, reportLinkPage } from './link-paging.ts';
/**
* Links + graph operation cluster — pure move from operations.ts (v0.46.x
* tranche 1). MANAGED_LINK_SOURCES stays exported (test suite + operations.ts
@@ -31,11 +32,11 @@ import type { OperationContext } from './contract.ts';
import type { Link, PageReadPolicy } from '../types.ts';
import { ALL_SOURCES } from '../source-id.ts';
import { PageMissingError } from '../engine-errors.ts';
-import { TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from '../engine-constants.ts';
+import { LINK_READ_CONTEXT_MAX_CHARS, LINK_READ_DEFAULT_LIMIT, LINK_READ_MAX_LIMIT, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from '../engine-constants.ts';
// #4224: flag-gated cross-source identity union for the link read ops.
import { unionLinksAcrossIdentity } from '../entity-identity.ts';
import { TEMPORAL_EDGE_PARAMS, STARTER_STATUS_PARAM, STARTER_AS_OF_PARAM, resolveEdgeTemporal, filterTemporalLinks, reportTemporal } from './edge-temporal.ts';
-import { isCalendarDate, relationSemantics, temporalLinkTypes } from '../link-validity.ts';
+import { isCalendarDate, relationSemantics, relationshipFilterSql, temporalLinkTypes, type LinkReadPage } from '../link-validity.ts';
import { writeManualTransitions, removeManualTransitions } from '../link-temporal-apply.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { primeRelationSemantics } from '../link-semantics-pack.ts';
@@ -229,6 +230,9 @@ const LINK_ALL_SOURCES_PARAM = {
type: 'boolean',
description: 'Same as source_id __all__.',
} as const;
+const LINK_LIMIT_PARAM = { type: 'number', description: `Rows per call (default ${LINK_READ_DEFAULT_LIMIT}, max ${LINK_READ_MAX_LIMIT}).` } as const;
+const LINK_CURSOR_PARAM = { type: 'string', description: 'next_cursor from the previous call (same filters).' } as const;
+const LINK_ALL_PARAM = { type: 'boolean', description: 'Local CLI only: every row, paging internally.', fullSurfaceOnly: true } as const;
/**
* #5827: the per-call source scope of a link read (get_links, get_backlinks,
@@ -267,67 +271,78 @@ const linkIdentity = (l: Link) => JSON.stringify([
]);
/**
- * get_links / get_backlinks body. A trusted local unqualified read whose scope
- * widened to the federated set runs the scalar read once per federated source
- * (resolved source first, the set's own order) and merges, de-duplicated on
- * link identity: the scalar branch keeps the cross-source far-endpoint view
- * local callers rely on, which the all-endpoints branch would drop for far
- * pages in non-federated sources. Every other caller runs one read.
+ * get_links / get_backlinks body: one page of a page's edges (#6876,
+ * link-paging.ts). A trusted local unqualified read whose scope widened to
+ * the federated set runs the scalar read once per federated source and
+ * merges, de-duplicated on link identity: the scalar branch keeps the
+ * cross-source far-endpoint view local callers rely on, which the
+ * all-endpoints branch would drop for far pages in non-federated sources.
+ * Every other caller runs one read. Each read is a keyset page with link_type
+ * and the temporal policy in SQL; the cap applies after the merge and the
+ * identity union, and hidden former relationships never count toward it.
*/
async function readLinkEdges(
ctx: OperationContext,
p: Record<string, unknown>,
opName: 'get_links' | 'get_backlinks',
direction: 'out' | 'in',
-): Promise<Link[]> {
+): Promise<{ links: Link[]; nextCursor?: string }> {
const slug = p.slug as string;
const { requested, policy } = await resolveLinkReadScope(ctx, p, opName);
const temporal = await resolveEdgeTemporal(ctx, p, opName);
+ const listing = parseLinkListing(ctx, opName, p, policy);
const linkType = typeof p.link_type === 'string' && p.link_type ? p.link_type : undefined;
- // Rows come back annotated with their relationship status; the policy is
- // applied below so hidden former relationships can be counted and reported.
+ // Rows come back annotated with their relationship status; the policy
+ // itself runs in SQL (and a second read counts what it hid).
const annotate = temporal.disabled ? undefined : { ...temporal, status: 'all' as const, during: undefined };
- const finish = (links: Link[]): Link[] => {
- const typed = linkType ? links.filter(l => l.link_type === linkType) : links;
- const { kept, hidden } = filterTemporalLinks(typed, temporal);
- reportTemporal(ctx, opName, p, temporal, hidden);
- return kept;
- };
+ const filtering = !temporal.disabled && relationshipFilterSql('l', temporal) !== 'TRUE';
const scopes: PageReadPolicy[] = ctx.remote === false && policy.sourceIds
? policy.sourceIds.map((sourceId) => ({ ...policy, sourceIds: undefined, sourceId }))
: [policy];
- const perScope: Link[][] = [];
- for (const sourceOpts of scopes) {
- const readOpts = annotate ? { ...sourceOpts, temporal: annotate } : sourceOpts;
- const links = direction === 'out'
- ? await ctx.engine.getLinks(slug, readOpts)
- : await ctx.engine.getBacklinks(slug, readOpts);
- // #4224: flag-gated identity union — merge edges from the page's identity
- // co-members (entity_identity.union config, default off; pure no-op then).
- // Member visibility never widens past the caller's grant. The scalar base
- // scope (when present) pins group resolution to the page actually read.
- // The engine authorizes the base and every member read before merging;
- // each union contributor must preserve this policy because no final filter runs.
- perScope.push(await unionLinksAcrossIdentity(ctx.engine, slug, links, direction, {
- sourceId: sourceOpts.sourceId,
- allowedSources: sourceOpts.sourceIds,
- excludePrivate: sourceOpts.excludePrivate,
- ...(annotate ? { temporal: annotate } : {}),
- }));
- }
- if (perScope.length === 1) {
- if (perScope[0].length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
- return finish(perScope[0]);
- }
- const seen = new Set<string>();
- const merged = perScope.flat().filter((l) => {
- const key = linkIdentity(l);
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- });
- if (merged.length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
- return finish(merged);
+ const read = async (page: LinkReadPage) => {
+ const streams: Link[][] = [];
+ const merged = new Map<string, Link>();
+ for (const sourceOpts of scopes) {
+ const readOpts = { ...sourceOpts, ...(annotate ? { temporal: annotate } : {}), page };
+ const links = direction === 'out'
+ ? await ctx.engine.getLinks(slug, readOpts)
+ : await ctx.engine.getBacklinks(slug, readOpts);
+ streams.push(links);
+ // #4224: flag-gated identity union — merge edges from the page's identity
+ // co-members (entity_identity.union config, default off; pure no-op then).
+ // Member visibility never widens past the caller's grant. The scalar base
+ // scope (when present) pins group resolution to the page actually read.
+ // The engine authorizes the base and every member read before merging;
+ // each union contributor must preserve this policy because no final filter runs.
+ const unioned = await unionLinksAcrossIdentity(ctx.engine, slug, links, direction, {
+ sourceId: sourceOpts.sourceId,
+ allowedSources: sourceOpts.sourceIds,
+ excludePrivate: sourceOpts.excludePrivate,
+ ...(annotate ? { temporal: annotate } : {}),
+ page,
+ onMemberRead: (rows) => streams.push(rows),
+ });
+ for (const l of unioned) if (!merged.has(linkIdentity(l))) merged.set(linkIdentity(l), l);
+ }
+ return { streams, rows: [...merged.values()].sort((a, b) => linkId(a) - linkId(b)) };
+ };
+ const base: LinkReadPage = { ...(linkType ? { linkType } : {}), contextChars: LINK_READ_CONTEXT_MAX_CHARS };
+ const out: Link[] = [];
+ let hidden = 0;
+ let afterId = listing.afterId;
+ let nextId: number | undefined;
+ do {
+ const { streams, rows } = await read({ ...base, afterId, limit: listing.limit + 1, ...(filtering ? { relationship: { policy: temporal, keep: 'match' as const } } : {}) });
+ const page = cutLinkPage(streams, rows, listing.limit);
+ if (filtering) hidden += (await read({ ...base, afterId, throughId: page.nextId, relationship: { policy: temporal, keep: 'hidden' } })).rows.length;
+ out.push(...page.rows);
+ nextId = page.nextId;
+ afterId = nextId;
+ } while (listing.all && nextId !== undefined);
+ const { kept, hidden: hiddenAfterRead } = filterTemporalLinks(out, temporal);
+ reportTemporal(ctx, opName, p, temporal, hidden + hiddenAfterRead);
+ if (out.length === 0 && hidden === 0 && listing.afterId === undefined) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
+ return { links: kept, nextCursor: reportLinkPage(ctx, opName, p, listing, { returned: kept.length, nextId }) };
}
/**
@@ -379,15 +394,21 @@ const get_links: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: 'List a page\'s outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: "all" for history, during: "2022" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.',
+ description: `List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: "all" for history, during: "2022" for a period). Pass source_id or all_sources to widen. Returns up to ${LINK_READ_DEFAULT_LIMIT} rows per call (limit, max ${LINK_READ_MAX_LIMIT}); a cut list's last row carries truncated: true and next_cursor, which you pass as cursor. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.`,
params: {
slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },
link_type: { type: 'string', description: 'Only this type.' },
...TEMPORAL_EDGE_PARAMS,
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
+ limit: LINK_LIMIT_PARAM,
+ cursor: LINK_CURSOR_PARAM,
+ all: LINK_ALL_PARAM,
+ },
+ handler: async (ctx, p) => {
+ const { links, nextCursor } = await readLinkEdges(ctx, p, 'get_links', 'out');
+ return finishLinkPage(links, nextCursor);
},
- handler: async (ctx, p) => readLinkEdges(ctx, p, 'get_links', 'out'),
scope: 'read',
cliHints: { name: 'links', aliases: ['get_links'], positional: ['slug'] },
};
@@ -397,7 +418,7 @@ const get_backlinks: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: 'Links to a page; group:"page" pages by referrer, newest first.',
+ description: `Links to a page, ≤${LINK_READ_DEFAULT_LIMIT}/call; group:"page" by referrer, newest first.`,
params: {
slug: { type: 'string', description: 'Page slug.', required: true },
status: STARTER_STATUS_PARAM,
@@ -406,14 +427,16 @@ const get_backlinks: Operation = {
all_sources: LINK_ALL_SOURCES_PARAM,
type: { type: 'string', description: 'Referrer type.' },
group: { type: 'string', enum: ['page'], description: 'Per page.' },
- limit: { type: 'number', description: 'Max 500.' },
- cursor: { type: 'string', description: 'Paging.' },
+ limit: { type: 'number', description: `≤${LINK_READ_MAX_LIMIT}` },
+ cursor: { type: 'string', description: 'Next.' },
+ all: LINK_ALL_PARAM,
},
handler: async (ctx, p) => {
if (p.group !== undefined) return readBacklinkPage(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy);
- const links = await readLinkEdges(ctx, p, 'get_backlinks', 'in');
+ const { links, nextCursor } = await readLinkEdges(ctx, p, 'get_backlinks', 'in');
const policy = async () => (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy;
- return withLinkPageStatus(ctx, policy, wantsPagedBacklinks(p) ? await filterBacklinkRows(ctx, p, await policy(), links) : links);
+ const typed = p.type !== undefined ? await filterBacklinkRows(ctx, p, await policy(), links) : links;
+ return finishLinkPage(await withLinkPageStatus(ctx, policy, typed), nextCursor);
},
scope: 'read',
cliHints: { name: 'backlinks', positional: ['slug'] },
diff --git a/test/e2e/link-read-paging-postgres.test.ts b/test/e2e/link-read-paging-postgres.test.ts
new file mode 100644
index 0000000000..e48f8dcbad
--- /dev/null
+++ b/test/e2e/link-read-paging-postgres.test.ts
@@ -0,0 +1,23 @@
+/**
+ * #6876 — Postgres twin of test/link-read-paging.test.ts: the keyset page
+ * SQL (link_type, links.id bounds, the temporal policy before LIMIT, the
+ * bounded context CASE) binds and plans on real Postgres the same as PGLite.
+ *
+ * DATABASE_URL-gated: self-skips without a real Postgres.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';
+import { registerLinkPagingTests, seedLinkPagingFixture } from '../helpers/link-paging-scenarios.ts';
+
+const describePg = hasDatabase() ? describe : describe.skip;
+
+describePg('#6876 link read paging — Postgres', () => {
+ beforeAll(async () => {
+ await setupDB();
+ await seedLinkPagingFixture(getEngine());
+ }, 120_000);
+
+ afterAll(async () => { await teardownDB(); }, 30_000);
+
+ registerLinkPagingTests(getEngine);
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 01b174f80a..52f2341b0a 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 242920,
- "stdoutSha256": "746130fbb9b8f33b5e8f81d8b9377ae133c1f3866c76c891b155f9d50971cb3e",
+ "stdoutBytes": 243688,
+ "stdoutSha256": "8dd9a6403a547142ad8b4dc51498bc3a16db5932be626a755d1a24d246d8f4c3",
"toolNames": [
"remember",
"entity",
@@ -2045,15 +2045,18 @@
"scope": "write"
},
{
- "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Returns up to 500 rows per call (limit, max 5000); a cut list's last row carries truncated: true and next_cursor, which you pass as cursor. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_links",
"parameters": {
+ "all": "boolean?",
"all_sources": "boolean?",
"as_of": "string?",
+ "cursor": "string?",
"during": "string?",
+ "limit": "number?",
"link_type": "string?",
"slug": "string",
"source_id": "string?",
@@ -2062,6 +2065,10 @@
"required_scopes": [],
"schema": {
"properties": {
+ "all": {
+ "description": "Local CLI only: every row, paging internally.",
+ "type": "boolean"
+ },
"all_sources": {
"description": "Same as source_id __all__.",
"type": "boolean"
@@ -2070,10 +2077,18 @@
"description": "YYYY-MM-DD.",
"type": "string"
},
+ "cursor": {
+ "description": "next_cursor from the previous call (same filters).",
+ "type": "string"
+ },
"during": {
"description": "Period: 2022, 2022-03 or 2021..2023.",
"type": "string"
},
+ "limit": {
+ "description": "Rows per call (default 500, max 5000).",
+ "type": "number"
+ },
"link_type": {
"description": "Only this type.",
"type": "string"
@@ -2104,12 +2119,13 @@
"scope": "read"
},
{
- "description": "Links to a page; group:\"page\" pages by referrer, newest first.",
+ "description": "Links to a page, ≤500/call; group:\"page\" by referrer, newest first.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_backlinks",
"parameters": {
+ "all": "boolean?",
"all_sources": "boolean?",
"as_of": "string?",
"cursor": "string?",
@@ -2123,6 +2139,10 @@
"required_scopes": [],
"schema": {
"properties": {
+ "all": {
+ "description": "Local CLI only: every row, paging internally.",
+ "type": "boolean"
+ },
"all_sources": {
"description": "Same as source_id __all__.",
"type": "boolean"
@@ -2132,7 +2152,7 @@
"type": "string"
},
"cursor": {
- "description": "Paging.",
+ "description": "Next.",
"type": "string"
},
"group": {
@@ -2143,7 +2163,7 @@
"type": "string"
},
"limit": {
- "description": "Max 500.",
+ "description": "≤5000",
"type": "number"
},
"slug": {
diff --git a/test/helpers/link-paging-scenarios.ts b/test/helpers/link-paging-scenarios.ts
new file mode 100644
index 0000000000..90d3c7fa71
--- /dev/null
+++ b/test/helpers/link-paging-scenarios.ts
@@ -0,0 +1,208 @@
+/**
+ * #6876 — get_links / get_backlinks row paging scenarios, shared by the PGLite
+ * unit test (test/link-read-paging.test.ts) and its Postgres twin
+ * (test/e2e/link-read-paging-postgres.test.ts): the keyset SQL (link_type,
+ * keyset bounds and the temporal policy before LIMIT, bounded context) must
+ * behave the same on both engines.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { LinkBatchInput } from '../../src/core/engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { ENTITY_IDENTITY_UNION_CONFIG_KEY, linkEntityIdentity } from '../../src/core/entity-identity.ts';
+import { LINK_READ_CONTEXT_MAX_CHARS, LINK_READ_DEFAULT_LIMIT } from '../../src/core/engine-constants.ts';
+
+type Row = Record<string, unknown>;
+const config = { engine: 'pglite' } as never;
+const LOCAL = { remote: false, sourceId: 'default', config };
+const REMOTE = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };
+const FEDERATED = { ...LOCAL, localFederatedSourceIds: ['default', 'second'] };
+const TARGETS = Array.from({ length: 12 }, (_, i) => `targets/t${String(i).padStart(2, '0')}`);
+
+/** N edges from `from` spread over the 12 targets (distinct link types keep each row unique). */
+function fan(from: string, n: number, opts: { reverse?: boolean; prefix?: string } = {}): LinkBatchInput[] {
+ return Array.from({ length: n }, (_, i) => {
+ const other = TARGETS[i % TARGETS.length];
+ const link_type = `${opts.prefix ?? 'k'}${String(Math.floor(i / TARGETS.length)).padStart(3, '0')}`;
+ return { from_slug: opts.reverse ? other : from, to_slug: opts.reverse ? from : other, link_type, context: `edge ${i}`, link_source: 'manual',
+ from_source_id: 'default', to_source_id: 'default' };
+ });
+}
+
+async function put(engine: BrainEngine, slug: string, sourceId = 'default') {
+ await engine.putPage(slug, { type: 'note' as never, title: slug, compiled_truth: `${slug} body`, frontmatter: {} }, { sourceId });
+}
+
+export async function seedLinkPagingFixture(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ('second', 'second', '/tmp/gbrain-6876-second', '{"federated": true}'::jsonb)
+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`);
+ await engine.executeRaw(`UPDATE sources SET config = '{"federated": true}'::jsonb WHERE id = 'default'`);
+ for (const slug of [...TARGETS, 'hubs/at-cap', 'hubs/over-cap', 'hubs/many', 'hubs/typed', 'hubs/wide', 'hubs/backlinked',
+ 'hubs/temporal', 'people/alice-example', 'companies/acme-example', 'fed/hub', 'idn/a', 'idn/b']) await put(engine, slug);
+ for (const slug of ['fed/hub', ...TARGETS]) await put(engine, slug, 'second');
+ await engine.addLinksBatch([
+ ...fan('hubs/at-cap', LINK_READ_DEFAULT_LIMIT),
+ ...fan('hubs/over-cap', LINK_READ_DEFAULT_LIMIT + 1),
+ ...fan('hubs/many', 1203),
+ ...fan('hubs/typed', 700),
+ ...fan('hubs/backlinked', LINK_READ_DEFAULT_LIMIT + 1, { reverse: true }),
+ ]);
+ // Three 'cites' edges after 700 others: the link_type filter runs before the cap.
+ await engine.addLinksBatch(TARGETS.slice(0, 3).map(t => ({ from_slug: 'hubs/typed', to_slug: t, link_type: 'cites', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' })));
+ await engine.addLink('hubs/wide', TARGETS[0], 'w'.repeat(10_000), 'k000', 'manual');
+ // Federation: the same slug in two federated sources, 4 edges each.
+ await engine.addLinksBatch([
+ ...TARGETS.slice(0, 4).map(t => ({ from_slug: 'fed/hub', to_slug: t, link_type: 'f', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' })),
+ ...TARGETS.slice(4, 8).map(t => ({ from_slug: 'fed/hub', to_slug: t, link_type: 'f', link_source: 'manual', from_source_id: 'second', to_source_id: 'second' })),
+ ]);
+ // Identity: idn/a and idn/b are one entity (a scalar read unions same-source members), 5 edges each.
+ await engine.addLinksBatch([
+ ...TARGETS.slice(0, 5).map(t => ({ from_slug: 'idn/a', to_slug: t, link_type: 'i', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' })),
+ ...TARGETS.slice(5, 10).map(t => ({ from_slug: 'idn/b', to_slug: t, link_type: 'i', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' })),
+ ]);
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ await linkEntityIdentity(engine, { entityId: 'thing/idn', slug: 'idn/a', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'thing/idn', slug: 'idn/b', sourceId: 'default' });
+ // Temporal: a live reference edge, then an ENDED works_at (hidden by the
+ // default live read), then two more live edges, in links.id order.
+ await engine.addLink('hubs/temporal', TARGETS[0], 'one', 'k000', 'manual');
+ await engine.addLink('people/alice-example', 'companies/acme-example', 'cto', 'k000', 'manual');
+ const ended = await dispatchToolCall(engine, 'add_link', { from: 'hubs/temporal', to: 'companies/acme-example', link_type: 'works_at', valid_from: '2019-01-01', valid_until: '2020-01-01' }, LOCAL as never);
+ if (ended.isError) throw new Error(`seed add_link failed: ${ended.content[0].text}`);
+ await engine.addLink('hubs/temporal', TARGETS[1], 'two', 'k000', 'manual');
+ await engine.addLink('hubs/temporal', TARGETS[2], 'three', 'k000', 'manual');
+}
+
+async function call(engine: BrainEngine, op: string, args: Record<string, unknown>, opts: Record<string, unknown> = LOCAL) {
+ const r = await dispatchToolCall(engine, op, args, opts as never);
+ return { isError: r.isError === true, text: r.content[0].text, json: r.isError ? null : JSON.parse(r.content[0].text) as Row[], notices: r.content.slice(1).map(c => c.text) };
+}
+
+const key = (r: Row) => `${r.from_source_id}:${r.from_slug}->${r.to_source_id}:${r.to_slug}:${r.link_type}:${r.origin_slug ?? ''}`;
+
+/** Every page of a listing, following next_cursor from the last row. */
+async function pages(engine: BrainEngine, op: string, args: Record<string, unknown>, opts?: Record<string, unknown>): Promise<Row[][]> {
+ const out: Row[][] = [];
+ let cursor: unknown;
+ for (let i = 0; i < 50; i++) {
+ const { json, text, isError } = await call(engine, op, { ...args, ...(cursor ? { cursor } : {}) }, opts);
+ if (isError) throw new Error(text);
+ out.push(json!);
+ const last = json![json!.length - 1];
+ cursor = last?.next_cursor;
+ if (!cursor) return out;
+ expect(last.truncated).toBe(true);
+ }
+ throw new Error('listing did not end');
+}
+
+export function registerLinkPagingTests(getEngine: () => BrainEngine): void {
+ describe('#6876 get_links / get_backlinks paging', () => {
+ test('exactly at the cap: every row, no truncation marker', async () => {
+ const { json } = await call(getEngine(), 'get_links', { slug: 'hubs/at-cap' });
+ expect(json!.length).toBe(LINK_READ_DEFAULT_LIMIT);
+ expect(json!.some(r => 'truncated' in r || 'next_cursor' in r || 'link_id' in r)).toBe(false);
+ });
+
+ test('one over the cap: the cap, a marked last row, and one row on the next page', async () => {
+ const [first, second, ...rest] = await pages(getEngine(), 'get_links', { slug: 'hubs/over-cap' });
+ expect(first.length).toBe(LINK_READ_DEFAULT_LIMIT);
+ expect(first.slice(0, -1).some(r => 'truncated' in r)).toBe(false);
+ expect(second.length).toBe(1);
+ expect(rest).toEqual([]);
+ expect(new Set([...first, ...second].map(key)).size).toBe(LINK_READ_DEFAULT_LIMIT + 1);
+ });
+
+ test('a 1203-edge traversal pages 500/500/203 and returns the complete set once', async () => {
+ const all = await pages(getEngine(), 'get_links', { slug: 'hubs/many' });
+ expect(all.map(p => p.length)).toEqual([500, 500, 203]);
+ const engineRows = await getEngine().getLinks('hubs/many', { sourceId: 'default' });
+ expect(engineRows.length).toBe(1203);
+ expect(all.flat().map(key).sort()).toEqual(engineRows.map(r => key(r as unknown as Row)).sort());
+ });
+
+ test('get_backlinks pages the same way', async () => {
+ const all = await pages(getEngine(), 'get_backlinks', { slug: 'hubs/backlinked' });
+ expect(all.map(p => p.length)).toEqual([500, 1]);
+ expect(new Set(all.flat().map(key)).size).toBe(501);
+ });
+
+ test('an explicit limit pages, and --all (local) returns every row without a marker', async () => {
+ const small = await pages(getEngine(), 'get_links', { slug: 'hubs/many', limit: 400 });
+ expect(small.map(p => p.length)).toEqual([400, 400, 400, 3]);
+ const { json } = await call(getEngine(), 'get_links', { slug: 'hubs/many', all: true, limit: 250 });
+ expect(json!.length).toBe(1203);
+ expect(json!.some(r => 'truncated' in r)).toBe(false);
+ const remote = await call(getEngine(), 'get_links', { slug: 'hubs/many', all: true }, REMOTE);
+ expect(remote.isError).toBe(true);
+ });
+
+ test('link_type filters in SQL before the cap', async () => {
+ const { json } = await call(getEngine(), 'get_links', { slug: 'hubs/typed', link_type: 'cites' });
+ expect(json!.map(r => r.to_slug).sort()).toEqual(TARGETS.slice(0, 3));
+ expect(json!.some(r => 'truncated' in r)).toBe(false);
+ });
+
+ test('a wide context is bounded in the op; the engine read stays complete', async () => {
+ const { json } = await call(getEngine(), 'get_links', { slug: 'hubs/wide' });
+ const context = String(json![0].context);
+ expect(context.length).toBe(LINK_READ_CONTEXT_MAX_CHARS);
+ expect(context.endsWith('…')).toBe(true);
+ expect((await getEngine().getLinks('hubs/wide', { sourceId: 'default' }))[0].context.length).toBe(10_000);
+ });
+
+ test('a hidden former relationship never takes a slot at the page boundary and is counted', async () => {
+ const first = await call(getEngine(), 'get_links', { slug: 'hubs/temporal', limit: 2 }, REMOTE);
+ expect(first.json!.map(r => r.context)).toEqual(['one', 'two']);
+ expect(first.json![1].truncated).toBe(true);
+ expect(first.notices.join('\n')).toContain('former_relationships_hidden');
+ expect(first.notices.join('\n')).toContain('listing_truncated');
+ const second = await call(getEngine(), 'get_links', { slug: 'hubs/temporal', limit: 2, cursor: first.json![1].next_cursor }, REMOTE);
+ expect(second.json!.map(r => r.context)).toEqual(['three']);
+ expect(second.notices.join('\n')).not.toContain('former_relationships_hidden');
+ const history = await call(getEngine(), 'get_links', { slug: 'hubs/temporal', status: 'all' });
+ expect(history.json!.length).toBe(4);
+ });
+
+ test('a local federated read merges the sources by link id and pages without gaps', async () => {
+ const all = await pages(getEngine(), 'get_links', { slug: 'fed/hub', limit: 3 }, FEDERATED);
+ expect(all.map(p => p.length)).toEqual([3, 3, 2]);
+ const rows = all.flat();
+ expect(new Set(rows.map(key)).size).toBe(8);
+ expect(rows.filter(r => r.from_source_id === 'second').length).toBe(4);
+ });
+
+ test('identity union rows join the merged stream; the cap applies after the union', async () => {
+ const all = await pages(getEngine(), 'get_links', { slug: 'idn/a', source_id: 'default', limit: 3 });
+ expect(all.map(p => p.length)).toEqual([3, 3, 3, 1]);
+ const rows = all.flat();
+ expect(new Set(rows.map(key)).size).toBe(10);
+ expect(rows.filter(r => r.from_slug === 'idn/b').length).toBe(5);
+ });
+
+ test('a legacy call without limit keeps its plain array', async () => {
+ const { json } = await call(getEngine(), 'get_links', { slug: 'people/alice-example' });
+ expect(json).toEqual([expect.objectContaining({ from_slug: 'people/alice-example', to_slug: 'companies/acme-example', context: 'cto' })]);
+ expect(Object.keys(json![0])).not.toContain('link_id');
+ expect(Object.keys(json![0])).not.toContain('truncated');
+ });
+
+ test('a foreign or malformed cursor is link_cursor_invalid with a restart fix', async () => {
+ const first = await call(getEngine(), 'get_links', { slug: 'hubs/over-cap' }, REMOTE);
+ const cursor = first.json![first.json!.length - 1].next_cursor as string;
+ for (const args of [
+ { slug: 'hubs/over-cap', cursor: 'not-a-cursor' },
+ { slug: 'hubs/at-cap', cursor },
+ { slug: 'hubs/over-cap', cursor, link_type: 'k000' },
+ ]) {
+ const r = await call(getEngine(), 'get_links', args, REMOTE);
+ expect(r.isError).toBe(true);
+ expect(r.text).toContain('link_cursor_invalid');
+ expect(r.text).toContain('invalid_params');
+ }
+ const backlinks = await call(getEngine(), 'get_backlinks', { slug: 'hubs/over-cap', cursor }, REMOTE);
+ expect(backlinks.text).toContain('link_cursor_invalid');
+ });
+ });
+}
diff --git a/test/link-read-paging.test.ts b/test/link-read-paging.test.ts
new file mode 100644
index 0000000000..9605a7302f
--- /dev/null
+++ b/test/link-read-paging.test.ts
@@ -0,0 +1,24 @@
+/**
+ * #6876 — get_links / get_backlinks return at most 500 rows per call (or
+ * `limit`), continue with a cursor bound to the listing, filter link_type and
+ * the temporal policy in SQL before the cap, merge federated sources and
+ * identity members by link id before the cap, and bound edge context.
+ * Regression: the ops returning every edge of a hub (no LIMIT, JS filters).
+ * Scenarios shared with the Postgres twin (test/e2e/link-read-paging-postgres.test.ts).
+ */
+import { afterAll, beforeAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { registerLinkPagingTests, seedLinkPagingFixture } from './helpers/link-paging-scenarios.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedLinkPagingFixture(engine);
+}, 120_000);
+
+afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);
+
+registerLinkPagingTests(() => engine);