Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(list_pages): expose the engine's keyset cursor so documented paging is lossless (#5641)
garrytan1bd9d0e9cabf
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 620499e86b..469c9a7f33 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 insrc/core/config.ts 1813 ratchet +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 mergesrc/core/bootstrap/harness.ts 2674 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)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 626 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+src/core/ops/pages.ts 643 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; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_isosrc/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= partsrc/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/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 1ec46b7cb1..471c9c9832 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -63,8 +63,10 @@ export const LIST_PAGES_DESCRIPTION ="with sort=updated_desc instead of semantic search. " +"Default 50 rows; remote callers are capped at 100 (local CLI callers' explicit " +"limits are honored). A result with exactly `limit` rows may be truncated. " +- "For exhaustive listing, page with sort=updated_asc + " +- "updated_after=<last row's updated_at> until a page returns fewer rows than the limit.";+ "For exhaustive listing, page with updated_after=<last row's updated_at_iso> + " ++ "updated_after_slug=<last row's slug> until a page returns fewer rows than the " ++ "limit (the keyset forces sort=updated_asc; a bare updated_after cursor skips " ++ "rows sharing the cursor timestamp).";export const QUERY_DESCRIPTION ="Hybrid search with vector + keyword + multi-query expansion. " +diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex fb8db50b55..e28d2b6ba8 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -448,7 +448,11 @@ const list_pages: Operation = {// v0.29 — surface filter that already exists on PageFilters.updated_after: {type: 'string',- description: 'ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value.',+ description: 'ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value. Bare (without updated_after_slug) this is LOSSY across rows sharing one timestamp — a bulk sync stamps one now() across a transaction; pair with updated_after_slug to page exactly.',+ },+ updated_after_slug: {+ type: 'string',+ description: "Keyset cursor slug: pass the last row's slug together with updated_after set to that row's updated_at_iso (column precision — a millisecond-rounded value re-selects same-millisecond rows). Resumes strictly after (updated_at, slug) and forces sort=updated_asc.",},sort: {type: 'string',@@ -473,9 +477,19 @@ const list_pages: Operation = {// Engines also whitelist via PAGE_SORT_SQL but defending here keeps// unsupported strings from reaching the SQL layer.const rawSort = p.sort as string | undefined;- const sort = rawSort && (LIST_PAGES_SORT_VALUES as readonly string[]).includes(rawSort)+ let sort = rawSort && (LIST_PAGES_SORT_VALUES as readonly string[]).includes(rawSort)? (rawSort as ListPagesSort): undefined;+ // The keyset is only coherent under updated_asc's (updated_at, slug) total order.+ const updatedAfter = typeof p.updated_after === 'string' ? p.updated_after : undefined;+ const updatedAfterSlug = typeof p.updated_after_slug === 'string' ? p.updated_after_slug : undefined;+ if (updatedAfterSlug !== undefined && updatedAfter === undefined) {+ throw new OperationError('invalid_params', "list_pages: updated_after_slug requires updated_after (the cursor row's updated_at_iso).");+ }+ const updatedAfterKeyset = updatedAfter !== undefined && updatedAfterSlug !== undefined+ ? { updatedAt: updatedAfter, slug: updatedAfterSlug }+ : undefined;+ if (updatedAfterKeyset) sort = 'updated_asc';// v0.34.1 (#861 — P0 leak seal): thread the auth'd client's source scope// into the listPages filter so an OAuth client scoped to src-A cannot// enumerate src-B pages. Pre-fix, ctx.sourceId / ctx.auth?.allowedSources@@ -535,7 +549,8 @@ const list_pages: Operation = {limit: limit + 1,offset,includeDeleted: (p.include_deleted as boolean) === true,- updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,+ updated_after: updatedAfterKeyset ? undefined : updatedAfter,+ updatedAfterKeyset,sort,excludePrivate,...scope,@@ -553,8 +568,9 @@ const list_pages: Operation = {if (truncated && isLocal && (requestedLimit === undefined || requestedLimit > limit)) {console.error(`[list_pages] output truncated at ${limit} rows (default 50). ` +- `Pass an explicit limit, page through with sort=updated_asc + ` +- `updated_after=<last row's updated_at>, or narrow with type/tag.`,+ `Pass an explicit limit, page through with ` ++ `updated_after=<last row's updated_at_iso> + ` ++ `updated_after_slug=<last row's slug>, or narrow with type/tag.`,);}return pages.map(pg => ({@@ -563,6 +579,7 @@ const list_pages: Operation = {type: pg.type,title: pg.title,updated_at: pg.updated_at,+ updated_at_iso: pg.updated_at_iso,...(pg.deleted_at ? { deleted_at: pg.deleted_at } : {}),}));},diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 4101d592b2..ed38991991 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": 203354,- "stdoutSha256": "c8950fdaf4565dfc46c9f17fd7707b39c7bdbdd3776d416b50f25f4d61ca79f8",+ "stdoutBytes": 204066,+ "stdoutSha256": "3c12fd9788be297eb16608c792f997e1e45951814a3e89be4aec058219bc7376","toolNames": ["remember","entity",@@ -472,7 +472,7 @@}},{- "description": "List pages with optional filters. For 'what's recent / what did I touch this week' questions, use list_pages with sort=updated_desc instead of semantic search. Default 50 rows; remote callers are capped at 100 (local CLI callers' explicit limits are honored). A result with exactly `limit` rows may be truncated. For exhaustive listing, page with sort=updated_asc + updated_after=<last row's updated_at> until a page returns fewer rows than the limit.",+ "description": "List pages with optional filters. For 'what's recent / what did I touch this week' questions, use list_pages with sort=updated_desc instead of semantic search. Default 50 rows; remote callers are capped at 100 (local CLI callers' explicit limits are honored). A result with exactly `limit` rows may be truncated. For exhaustive listing, page with updated_after=<last row's updated_at_iso> + updated_after_slug=<last row's slug> until a page returns fewer rows than the limit (the keyset forces sort=updated_asc; a bare updated_after cursor skips rows sharing the cursor timestamp).","name": "list_pages","parameters": {"include_deleted": "boolean?",@@ -482,7 +482,8 @@"source_id": "string?","tag": "string?","type": "string?",- "updated_after": "string?"+ "updated_after": "string?",+ "updated_after_slug": "string?"},"schema": {"properties": {@@ -521,7 +522,11 @@"type": "string"},"updated_after": {- "description": "ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value.",+ "description": "ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value. Bare (without updated_after_slug) this is LOSSY across rows sharing one timestamp — a bulk sync stamps one now() across a transaction; pair with updated_after_slug to page exactly.",+ "type": "string"+ },+ "updated_after_slug": {+ "description": "Keyset cursor slug: pass the last row's slug together with updated_after set to that row's updated_at_iso (column precision — a millisecond-rounded value re-selects same-millisecond rows). Resumes strictly after (updated_at, slug) and forces sort=updated_asc.","type": "string"}},diff --git a/test/list-pages-keyset-cursor-op.test.ts b/test/list-pages-keyset-cursor-op.test.tsnew file mode 100644index 0000000000..570114986a--- /dev/null+++ b/test/list-pages-keyset-cursor-op.test.ts@@ -0,0 +1,129 @@+/**+ * list_pages keyset cursor (updated_after + updated_after_slug).+ *+ * The engine has carried PageFilters.updatedAfterKeyset since v0.45.7, but+ * the op never exposed it, and the documented pagination recipe+ * (sort=updated_asc + updated_after=<last row's updated_at>) is lossy: the+ * strict `updated_at > value` predicate skips every row SHARING the cursor+ * timestamp — and a bulk sync stamps one now() across a transaction, so a+ * >limit same-timestamp cluster is exactly the shape real brains produce.+ * With such a cluster the bare cursor cannot make progress at all.+ *+ * Pins, at the op-handler layer (engine listPages surface unchanged):+ * - a >limit same-timestamp cluster pages to completion via the keyset+ * (fails pre-fix: the bare recipe returns 0 rows after page one)+ * - the cursor resumes STRICTLY after (updated_at, slug): same-ts rows+ * with a greater slug are returned, the cursor row itself is not+ * - the keyset supersedes the bare updated_after filter semantics+ * - the keyset forces sort=updated_asc (a caller-passed sort is ignored —+ * the cursor is only coherent under that total order)+ * - composes with the type filter across rows with DIFFERING types+ * - updated_after_slug without updated_after fails loudly+ * - output rows carry updated_at_iso (column precision), the value the+ * next page's updated_after must be built from — a JS Date is+ * millisecond-truncated and re-selects same-millisecond rows+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';++const list_pages = operations.find(o => o.name === 'list_pages')!;++let engine: PGLiteEngine;++const TS = '2026-08-10T12:00:00.000123Z';+const CLUSTER = 7; // > limit 3 used below: unpageable with a bare cursor++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 1; i <= CLUSTER; i++) {+ await engine.putPage(`notes/sync-${i}`, {+ type: i % 2 === 0 ? 'note' : 'reference',+ title: `Synced ${i}`,+ compiled_truth: `Body ${i}.`,+ timeline: '',+ });+ }+ // One identical timestamp across the whole cluster — the bulk-sync shape.+ await engine.executeRaw(+ `UPDATE pages SET updated_at = '${TS}'::timestamptz WHERE slug LIKE 'notes/sync-%'`,+ );+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++function ctxOf(): OperationContext {+ return {+ engine: engine as any,+ config: {} as any,+ logger: console as any,+ dryRun: false,+ remote: false,+ sourceId: 'default',+ };+}++type Row = { slug: string; updated_at_iso: string; type: string };+const run = (params: Record<string, unknown>) =>+ list_pages.handler(ctxOf(), params) as Promise<Row[]>;++describe('list_pages keyset cursor', () => {+ test('a >limit same-timestamp cluster pages to completion', async () => {+ const seen: string[] = [];+ let cursor: { updated_after?: string; updated_after_slug?: string } = {};+ for (let guard = 0; guard < 10; guard++) {+ const rows = await run({ limit: 3, sort: 'updated_asc', ...cursor });+ seen.push(...rows.map(r => r.slug));+ if (rows.length < 3) break;+ const last = rows[rows.length - 1];+ cursor = { updated_after: last.updated_at_iso, updated_after_slug: last.slug };+ }+ expect(seen.sort()).toEqual(+ Array.from({ length: CLUSTER }, (_, i) => `notes/sync-${i + 1}`).sort(),+ );+ expect(new Set(seen).size).toBe(CLUSTER); // no row twice+ });++ test('resumes strictly after (updated_at, slug): greater-slug rows in, cursor row out', async () => {+ const rows = await run({+ updated_after: TS, updated_after_slug: 'notes/sync-3', limit: 100,+ });+ const slugs = rows.map(r => r.slug);+ expect(slugs).not.toContain('notes/sync-3');+ expect(slugs).toContain('notes/sync-4'); // same ts, greater slug — bare updated_after drops it+ expect(slugs).toContain('notes/sync-7');+ });++ test('bare updated_after stays the (documented-lossy) strict filter', async () => {+ const rows = await run({ updated_after: TS, sort: 'updated_asc', limit: 100 });+ expect(rows.map(r => r.slug).filter(s => s.startsWith('notes/sync-'))).toEqual([]);+ });++ test('keyset forces sort=updated_asc over a caller-passed sort', async () => {+ const rows = await run({+ updated_after: TS, updated_after_slug: 'notes/sync-1', sort: 'updated_desc', limit: 2,+ });+ // Under the forced total order the next rows after sync-1 are sync-2, sync-3.+ expect(rows.map(r => r.slug)).toEqual(['notes/sync-2', 'notes/sync-3']);+ });++ test('composes with the type filter across rows with differing types', async () => {+ const rows = await run({+ updated_after: TS, updated_after_slug: 'notes/sync-2', type: 'note', limit: 100,+ });+ // Cursor sits on sync-2 (a 'note'); remaining notes are the even slugs after it.+ expect(rows.map(r => r.slug)).toEqual(['notes/sync-4', 'notes/sync-6']);+ });++ test('updated_after_slug without updated_after fails loudly', async () => {+ await expect(run({ updated_after_slug: 'notes/sync-1' })).rejects.toThrow(/requires updated_after/);+ });++ test('output rows carry updated_at_iso at column precision', async () => {+ const rows = await run({ sort: 'updated_asc', limit: 1 });+ expect(rows[0].updated_at_iso).toBe(TS); // microseconds survive (.000123Z)+ });+});diff --git a/test/list-pages-truncation.test.ts b/test/list-pages-truncation.test.tsindex 2b8bf124ea..90d0198ee0 100644--- a/test/list-pages-truncation.test.ts+++ b/test/list-pages-truncation.test.ts@@ -86,7 +86,7 @@ describe('list_pages truncation signal', () => {expect(result.length).toBe(50);expect(warnings.length).toBe(1);expect(warnings[0]).toContain('truncated at 50 rows');- expect(warnings[0]).toContain('sort=updated_asc');+ expect(warnings[0]).toContain('updated_after_slug');}, 30_000);test('explicit honored limit: no warning even when more rows exist', async () => {