Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(list): list_pages projects listing columns only, never page bodies (#5154 mitigation)

garrytan0a37ed8eb6ec
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 252fb91347..884624b5f3 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -30,7 +30,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. `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.
- `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/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 61aa7dd52f..67137f6374 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -380,8 +380,12 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
const sortKey = filters?.sort && PAGE_SORT_SQL[filters.sort] ? filters.sort : 'updated_desc';
const orderBy = trustedSql(PAGE_SORT_SQL[sortKey]);
+ const columns = filters?.listColumnsOnly === true
+ ? sqlFragment`p.id, p.source_id, p.slug, p.type, p.page_kind, p.title, p.created_at, p.updated_at, p.deleted_at,
+ p.effective_date, p.effective_date_source, ''::text AS compiled_truth, ''::text AS timeline, '{}'::jsonb AS frontmatter`
+ : sqlFragment`p.*`;
const { rows } = await exec.run(sqlFragment`
- SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p
+ SELECT ${columns}, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p
${tagJoin}
WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index fb8db50b55..024d841494 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -538,6 +538,7 @@ const list_pages: Operation = {
updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
sort,
excludePrivate,
+ listColumnsOnly: true,
...scope,
});
const truncated = rows.length > limit;
diff --git a/src/core/types.ts b/src/core/types.ts
index 2f8702db94..7cddbe30d0 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -376,6 +376,13 @@ export interface PageFilters {
* (search/private-visibility.ts) in BOTH engines.
*/
excludePrivate?: boolean;
+ /**
+ * #5154: select only the listing columns (identity, type, title, dates).
+ * `compiled_truth` and `timeline` come back as '' and `frontmatter` as {},
+ * so a listing never detoasts or ships page bodies. Only for callers that
+ * read none of those fields (list_pages).
+ */
+ listColumnsOnly?: boolean;
}
/** v0.26.5 — opts for getPage / softDeletePage / restorePage. */
diff --git a/test/list-pages-columns-5154.test.ts b/test/list-pages-columns-5154.test.ts
new file mode 100644
index 0000000000..d50a313324
--- /dev/null
+++ b/test/list-pages-columns-5154.test.ts
@@ -0,0 +1,63 @@
+/**
+ * #5154 mitigation: list_pages reads only listing columns, so a listing never
+ * detoasts or ships page bodies. Proven with column privileges: a role that
+ * cannot read `compiled_truth`/`timeline` can still list, while a body-reading
+ * projection is refused.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const listPages = operations.find(o => o.name === 'list_pages')!;
+
+const ctx = (): OperationContext => ({
+ engine: engine as any,
+ config: {} as any,
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+} as OperationContext);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const slug of ['notes/alpha-example', 'notes/beta-example']) {
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: `${'body '.repeat(5000)}\n`, timeline: '- 2026-01-01: event' }, { sourceId: 'default' });
+ }
+ const columns = await engine.executeRaw<{ column_name: string }>(
+ "SELECT column_name FROM information_schema.columns WHERE table_name = 'pages' AND column_name NOT IN ('compiled_truth', 'timeline')");
+ await engine.executeRaw('CREATE ROLE list_columns_reader');
+ await engine.executeRaw('GRANT SELECT ON ALL TABLES IN SCHEMA public TO list_columns_reader');
+ await engine.executeRaw('REVOKE SELECT ON pages FROM list_columns_reader');
+ await engine.executeRaw(`GRANT SELECT (${columns.map(c => `"${c.column_name}"`).join(', ')}) ON pages TO list_columns_reader`);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.executeRaw('RESET ROLE').catch(() => {});
+ await engine.disconnect();
+});
+
+test('list_pages succeeds without read access to page bodies', async () => {
+ await engine.executeRaw('SET ROLE list_columns_reader');
+ try {
+ await expect(engine.executeRaw('SELECT compiled_truth FROM pages LIMIT 1')).rejects.toThrow(/permission denied/);
+ const rows = await listPages.handler(ctx(), { sort: 'slug', limit: 10 }) as Array<{ slug: string; type: string; title: string }>;
+ expect(rows.map(r => r.slug)).toEqual(['notes/alpha-example', 'notes/beta-example']);
+ expect(rows.every(r => r.type === 'note')).toBe(true);
+ } finally {
+ await engine.executeRaw('RESET ROLE');
+ }
+});
+
+test('full listPages still returns bodies for callers that need them', async () => {
+ const pages = await engine.listPages({ sort: 'slug', limit: 10 });
+ expect(pages[0]!.compiled_truth).toContain('body body');
+ expect(pages[0]!.timeline).toContain('2026-01-01');
+ const listed = await engine.listPages({ sort: 'slug', limit: 10, listColumnsOnly: true });
+ expect(listed.map(p => p.slug)).toEqual(pages.map(p => p.slug));
+ expect(listed[0]!.compiled_truth).toBe('');
+ expect(listed[0]!.frontmatter).toEqual({});
+});