Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): list_pages tells MCP callers when a listing was clamped or truncated (F3b, #5954)

garrytand75bdfaf54f1
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 5b9e8d2ce1..b622f63537 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -36,7 +36,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). 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`.
-- `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. `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. 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.
+- `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. `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. 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`.
- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index 0f9ff300a0..39cb9a506f 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -33,6 +33,7 @@ shape for it.
| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call |
| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose) |
| `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` |
+| `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |
Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS) is a
separate, client-to-server plane. The eval-report `_meta.metric_glossary`
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bcb69c4cd9..8b69d483db 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -39,6 +39,6 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in
src/core/config.ts 1824 ratchet +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 652 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only)
+src/core/ops/pages.ts 659 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts)
src/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part
src/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9d25f43de9..f724555ade 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -285,4 +285,5 @@ export const NOTICE_CODES = {
backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },
empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
+ listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/src/core/ops/list-pages-pagination.ts b/src/core/ops/list-pages-pagination.ts
new file mode 100644
index 0000000000..8e6b3be96c
--- /dev/null
+++ b/src/core/ops/list-pages-pagination.ts
@@ -0,0 +1,79 @@
+/**
+ * list_pages pagination for MCP callers (agent operator contract v1, F3b;
+ * absorbs community PR #5954).
+ *
+ * The handler probes limit+1 rows, so it knows whether rows remain, but its
+ * truncation notice reaches local CLI stderr only and its remote clamp
+ * warning reaches the server log only. Two channels carry the facts to MCP
+ * callers:
+ *
+ * - `_meta.pagination` (structured data, docs/protocol/MCP_META_CHANNELS.md):
+ * `truncated`, the effective `limit`, `clamped_from` when a remote caller's
+ * limit was capped, and `next` — the params that fetch the following page,
+ * every other param unchanged. Under sort=updated_asc `next` is the
+ * lossless (updated_at, slug) keyset; any other sort continues by offset.
+ * - the model-visible `listing_truncated` notice (kind info, never deduped):
+ * `_meta` is not a channel the model sees, so a full page would otherwise
+ * read as a complete listing.
+ */
+import type { Action, Notice } from '../agent-output.ts';
+
+export interface ListPagesPagination {
+ truncated: boolean;
+ limit: number;
+ clamped_from?: number;
+ next?: { sort: 'updated_asc'; updated_after: string; updated_after_slug: string } | { offset: number };
+}
+
+export function listPagesPagination(opts: {
+ truncated: boolean;
+ limit: number;
+ requestedLimit: number | undefined;
+ offset: number | undefined;
+ sort: string | undefined;
+ last: { slug: string; updated_at_iso?: string } | undefined;
+}): ListPagesPagination {
+ const { truncated, limit, requestedLimit, last } = opts;
+ const clamped = requestedLimit !== undefined && Number.isFinite(requestedLimit) && requestedLimit > limit;
+ let next: ListPagesPagination['next'];
+ if (truncated && last) {
+ next = opts.sort === 'updated_asc' && last.updated_at_iso
+ ? { sort: 'updated_asc', updated_after: last.updated_at_iso, updated_after_slug: last.slug }
+ : { offset: (opts.offset ?? 0) + limit };
+ }
+ return {
+ truncated,
+ limit,
+ ...(clamped ? { clamped_from: requestedLimit } : {}),
+ ...(next ? { next } : {}),
+ };
+}
+
+/** Declared list_pages params a continuation call carries over unchanged. */
+const CARRIED_PARAMS = ['type', 'tag', 'sort', 'include_deleted', 'source_id', 'updated_after'] as const;
+
+/**
+ * The `listing_truncated` notice for a truncated result; null when nothing
+ * was dropped. The fix is the exact next call: the caller's declared filter
+ * params plus the `next` continuation (never page titles or text).
+ */
+export function listingTruncatedNotice(pagination: ListPagesPagination, params: Record<string, unknown>): Notice | null {
+ if (!pagination.truncated || !pagination.next) return null;
+ const args: Record<string, unknown> = {};
+ for (const key of CARRIED_PARAMS) if (params[key] !== undefined) args[key] = params[key];
+ Object.assign(args, { limit: pagination.limit }, pagination.next);
+ const clamp = pagination.clamped_from !== undefined ? ` (limit ${pagination.clamped_from} was capped at ${pagination.limit})` : '';
+ const fix: Action = {
+ mcp: { tool: 'list_pages', arguments: args },
+ consent: [],
+ actor: 'agent',
+ why: 'Fetches the next page; every other parameter stays the same. Keep paging until no listing_truncated notice comes back.',
+ requires_exclusive: false,
+ };
+ return {
+ code: 'listing_truncated',
+ kind: 'info',
+ why: `More pages match than the ${pagination.limit} returned${clamp}; this listing is not complete.`,
+ fix,
+ };
+}
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 423666d7b5..df9aa07cbf 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -21,6 +21,7 @@ import { getContentFlag } from '../quarantine.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
+import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagination.ts';
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
import {
@@ -581,6 +582,12 @@ const list_pages: Operation = {
`updated_after_slug=<last row's slug>, or narrow with type/tag.`,
);
}
+ // MCP callers see neither that notice nor the clamp warning (server log):
+ // `_meta.pagination` carries the data, the listing_truncated notice tells the model.
+ const pagination = listPagesPagination({ truncated, limit, requestedLimit, offset, sort, last: pages[pages.length - 1] });
+ ctx.emitResponseMeta?.('pagination', pagination);
+ const truncatedNotice = isLocal ? null : listingTruncatedNotice(pagination, p);
+ if (truncatedNotice) ctx.emitNotice?.(truncatedNotice);
return pages.map(pg => ({
slug: pg.slug,
source_id: pg.source_id,
diff --git a/test/list-pages-truncation.test.ts b/test/list-pages-truncation.test.ts
index 90d0198ee0..284f80f12a 100644
--- a/test/list-pages-truncation.test.ts
+++ b/test/list-pages-truncation.test.ts
@@ -19,6 +19,10 @@
* - remote ctx never writes to stderr (MCP server logs stay clean)
* - the pagination recipe in LIST_PAGES_DESCRIPTION (sort=updated_asc +
* updated_after cursor) actually enumerates every row to completion
+ * - remote callers get the same facts on the `pagination` response meta
+ * (truncated, limit, clamped_from, next), and MCP dispatch adds the
+ * model-visible `listing_truncated` notice while content[0] stays the
+ * bare array (#5954, agent contract v1 F3b)
*
* Runs against PGLite in-memory (both engines share the SQL surface; the
* handler change touches no engine code).
@@ -28,6 +32,8 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from '
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { operations, type OperationContext } from '../src/core/operations.ts';
+import { dispatchToolCall, __resetBackupNoticeForTests } from '../src/mcp/dispatch.ts';
+import type { ListPagesPagination } from '../src/core/ops/list-pages-pagination.ts';
const list_pages = operations.find(o => o.name === 'list_pages')!;
@@ -153,3 +159,99 @@ describe('list_pages truncation signal', () => {
expect(seen.size).toBe(23);
}, 30_000);
});
+
+// The stderr notice above is local-only and the remote clamp warning goes to
+// the server log, so before #5954 a remote caller holding exactly `limit`
+// rows could not tell a full page from a complete listing.
+describe('list_pages pagination meta for remote callers', () => {
+ function remote(params: Record<string, unknown>) {
+ const meta: Record<string, unknown> = {};
+ const notices: unknown[] = [];
+ const ctx = ctxOf({ remote: true, emitResponseMeta: (key, value) => { meta[key] = value; }, emitNotice: n => { notices.push(n); } });
+ return runCapturing(ctx, params).then(({ result }) => ({ result, notices, pagination: meta.pagination as ListPagesPagination }));
+ }
+
+ test('limit below the row count: truncated, with an offset continuation', async () => {
+ await seed(12);
+ const { result, pagination } = await remote({ limit: 10 });
+ expect(result.length).toBe(10);
+ expect(pagination).toEqual({ truncated: true, limit: 10, next: { offset: 10 } });
+ }, 30_000);
+
+ test('limit above the remote cap: clamped_from carries the requested limit', async () => {
+ await seed(101);
+ const { result, pagination } = await remote({ limit: 200 });
+ expect(result.length).toBe(100);
+ expect(pagination).toEqual({ truncated: true, limit: 100, clamped_from: 200, next: { offset: 100 } });
+ }, 60_000);
+
+ test('complete listing: truncated false, no next, no notice', async () => {
+ await seed(5);
+ const { result, pagination, notices } = await remote({ limit: 10 });
+ expect(result.length).toBe(5);
+ expect(pagination).toEqual({ truncated: false, limit: 10 });
+ expect(notices).toEqual([]);
+ }, 30_000);
+
+ test('updated_asc: next is the keyset of the last row', async () => {
+ await seed(12);
+ const { result, pagination } = await remote({ limit: 10, sort: 'updated_asc' });
+ const last = result[result.length - 1];
+ expect(pagination.next).toEqual({ sort: 'updated_asc', updated_after: last.updated_at_iso, updated_after_slug: last.slug });
+ }, 30_000);
+
+ test('following the notice fix until no notice comes back enumerates every row exactly once', async () => {
+ await seed(23);
+ // updated_asc pages a bulk-sync cluster (one shared timestamp) through the
+ // keyset; offset under updated_desc needs distinct timestamps, which has
+ // no tiebreaker.
+ const cases: Array<[Record<string, unknown>, string]> = [
+ [{ sort: 'updated_asc' }, `UPDATE pages SET updated_at = '2026-08-10T12:00:00.000123Z'::timestamptz WHERE slug LIKE 'notes/note-%'`],
+ [{}, `UPDATE pages SET updated_at = now() - (interval '1 minute' * (100 - id)) WHERE slug LIKE 'notes/note-%'`],
+ ];
+ for (const [base, spread] of cases) {
+ await engine.executeRaw(spread);
+ const seen: string[] = [];
+ let params: Record<string, unknown> = { ...base, limit: 10 };
+ for (let guard = 0; guard < 10; guard++) {
+ const { result, notices } = await remote(params);
+ seen.push(...result.map(r => r.slug as string));
+ const notice = notices[0] as { code: string; fix: { mcp: { tool: string; arguments: Record<string, unknown> } } } | undefined;
+ if (!notice) break;
+ expect(notice.code).toBe('listing_truncated');
+ expect(notice.fix.mcp.tool).toBe('list_pages');
+ params = notice.fix.mcp.arguments;
+ }
+ expect(seen.length).toBe(23);
+ expect(new Set(seen).size).toBe(23);
+ }
+ }, 60_000);
+
+ test('local CLI callers get no notice (stderr stays their channel)', async () => {
+ await seed(12);
+ const notices: unknown[] = [];
+ await runCapturing(ctxOf({ remote: false, emitNotice: n => { notices.push(n); } }), { limit: 10 });
+ expect(notices).toEqual([]);
+ }, 30_000);
+
+ test('MCP dispatch: content[0] stays the bare array; the listing_truncated notice names the next call', async () => {
+ __resetBackupNoticeForTests();
+ await seed(12);
+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+ const res = await dispatchToolCall(engine as any, 'list_pages', { limit: 10, type: 'note' }, opts);
+ expect(res.isError).toBeUndefined();
+ expect(JSON.parse(res.content[0].text)).toHaveLength(10);
+ expect(res.content).toHaveLength(2);
+ expect(res.content[1].text.split('\n')[0]).toBe('[gbrain notice listing_truncated kind=info]');
+ expect(res.content[1].text).toContain('fix: list_pages {"type":"note","limit":10,"offset":10}');
+ expect(res.content[1].text).toContain('next: run');
+ expect(res._meta?.pagination).toEqual({ truncated: true, limit: 10, next: { offset: 10 } });
+ // Per-call notice: never deduped, so the second truncated page carries it too.
+ const again = await dispatchToolCall(engine as any, 'list_pages', { limit: 10, type: 'note' }, opts);
+ expect(again.content).toHaveLength(2);
+
+ const complete = await dispatchToolCall(engine as any, 'list_pages', { limit: 20 }, opts);
+ expect(complete.content).toHaveLength(1);
+ expect(complete._meta?.pagination).toEqual({ truncated: false, limit: 20 });
+ }, 30_000);
+});