Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(orphans): find_orphans pages (limit/offset/count_only), filters by a granted source, and names each row's source and type (#5891); enable its conformance case
garrytan37bb8d79e7f9
diff --git a/src/commands/orphans.ts b/src/commands/orphans.tsindex 52673a5bf6..48aeb79b06 100644--- a/src/commands/orphans.ts+++ b/src/commands/orphans.ts@@ -37,6 +37,9 @@ export interface OrphanPage {slug: string;title: string;domain: string;+ /** #5891: the page's source and type, so a federated caller can tell rows apart. */+ source_id?: string;+ type?: string | null;}export interface OrphanResult {@@ -188,6 +191,8 @@ export async function findOrphans(slug: row.slug,title: row.title,domain: deriveDomain(row.domain, row.slug),+ ...(row.source_id !== undefined ? { source_id: row.source_id } : {}),+ ...(row.type !== undefined ? { type: row.type } : {}),}));const excluded = allOrphans.length - policyKept.length;diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex dc66a4550e..531d973183 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -6,10 +6,14 @@*/import type { Operation } from './contract.ts';-import { readPolicyOpts } from './context.ts';+import { assertSourceInCallerScope, readPolicyOpts } from './context.ts';+import { OperationError } from './contract.ts';// --- Orphans ---+const ORPHANS_DEFAULT_LIMIT = 100;+const ORPHANS_MAX_LIMIT = 1000;+const find_orphans: Operation = {name: 'find_orphans',outputRedaction: 'retrieval',@@ -23,6 +27,16 @@ const find_orphans: Operation = {type: 'string',description: "#4524: orphan definition — 'islanded' (default; agrees with get_health.orphan_pages and doctor) or 'inbound' (legacy: no inbound links, even when the page links out).",},+ source_id: {+ type: 'string',+ description: 'Only orphans from this source (it must be inside your source grant). Each row carries source_id and type.',+ },+ limit: {+ type: 'number',+ description: `Rows per page (default ${ORPHANS_DEFAULT_LIMIT}, max ${ORPHANS_MAX_LIMIT}); total_orphans counts every orphan and next_offset names the next page.`,+ },+ offset: { type: 'number', description: 'Skip the first N orphans (ordered by source_id, then slug).' },+ count_only: { type: 'boolean', description: 'Return the totals with no rows.' },},scope: 'read',handler: async (ctx, p) => {@@ -39,14 +53,24 @@ const find_orphans: Operation = {// source-bound OAuth client's scope — a read leak in the v0.34.1// source-isolation class. Local CLI callers route through `gbrain// orphans --source` instead (ctx.remote === false → empty scope here).- const scope = await readPolicyOpts(ctx);+ // #5891: a named source narrows the caller's scope and never widens it.+ const named = p.source_id === undefined ? undefined : String(p.source_id);+ if (named !== undefined) assertSourceInCallerScope(ctx, named);+ const scope = named !== undefined ? await readPolicyOpts(ctx, { sourceId: named }) : await readPolicyOpts(ctx);+ const limit = p.limit === undefined ? ORPHANS_DEFAULT_LIMIT : Number(p.limit);+ const offset = p.offset === undefined ? 0 : Number(p.offset);+ if (!Number.isInteger(limit) || limit < 1 || limit > ORPHANS_MAX_LIMIT || !Number.isInteger(offset) || offset < 0) {+ throw new OperationError('invalid_params', `find_orphans: limit must be 1-${ORPHANS_MAX_LIMIT} and offset a non-negative integer`);+ }const result = await findOrphans(ctx.engine, {includePseudo: (p.include_pseudo as boolean) || false,...(mode ? { mode } : {}),...scope,});-- return result;+ const ordered = [...result.orphans].sort((a, b) =>+ (a.source_id ?? '').localeCompare(b.source_id ?? '') || a.slug.localeCompare(b.slug));+ const next = offset + limit < ordered.length ? offset + limit : null;+ return { ...result, orphans: p.count_only === true ? [] : ordered.slice(offset, offset + limit), limit, offset, next_offset: p.count_only === true ? null : next };},cliHints: { name: 'orphans', hidden: true },};diff --git a/test/fixtures/write-contract-conformance-cases.ts b/test/fixtures/write-contract-conformance-cases.tsindex 334c5523d3..cd8b869f0f 100644--- a/test/fixtures/write-contract-conformance-cases.ts+++ b/test/fixtures/write-contract-conformance-cases.ts@@ -35,7 +35,7 @@ interface Transport {}interface Fixture { engine: BrainEngine; transports: () => Promise<Transport[]>; }-const OPERATIONS = ['get_page', 'put_page', 'edit_page', 'get_write_request', 'remember', 'recall'];+const OPERATIONS = ['get_page', 'put_page', 'edit_page', 'get_write_request', 'remember', 'recall', 'find_orphans'];const page = (body: string) => `---\ntitle: Conformance example\ntype: note\n---\n\n${body}\n`;const reply = (result: ToolResult): Reply => ({ isError: result.isError === true, body: JSON.parse(result.content[0]!.text), status: requestLogStatusForResult(result) });@@ -219,8 +219,25 @@ export function writeContractConformanceCases(databaseUrl?: string) {});}, 180_000);- // #5891 lands after fix wave 7 (find_orphans is shared with doctor orphan_ratio).- test.todo('find_orphans source filter stays inside the caller grant (#5891, AFTER-FW7)', () => {});+ test('find_orphans source filter stays inside the caller grant over stdio and HTTP (#5891)', async () => {+ await withFixture(databaseUrl, async ({ engine, transports }) => {+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other-example','other-example') ON CONFLICT DO NOTHING");+ await engine.putPage('people/other-orphan', { type: 'person', title: 'Other orphan', compiled_truth: 'Alone in another source.' }, { sourceId: 'other-example' });+ for (const transport of await transports()) {+ const slug = `people/${transport.name}-orphan`;+ expect((await transport.call('put_page', { slug, content: `---\ntitle: Orphan\ntype: person\n---\n\nAlone.\n`, request_id: randomUUID() })).isError).toBe(false);+ const own = await transport.call('find_orphans', { source_id: 'default', limit: 1000 });+ expect({ transport: transport.name, isError: own.isError }).toEqual({ transport: transport.name, isError: false });+ const rows = own.body.orphans as Array<{ slug: string; source_id: string }>;+ expect(rows.map(row => row.slug)).toContain(slug);+ expect(rows.every(row => row.source_id === 'default')).toBe(true);+ const other = await transport.call('find_orphans', { source_id: 'other-example' });+ expect({ transport: transport.name, other }).toMatchObject({ other: { isError: true, body: { error: 'not_found' } } });+ const unfiltered = await transport.call('find_orphans', { limit: 1000 });+ expect((unfiltered.body.orphans as Array<{ source_id: string }>).some(row => row.source_id === 'other-example')).toBe(false);+ }+ });+ }, 180_000);test('auth rescope-token: explicit empty allowed_operations, sources and takes holders deny all over HTTP; reset restores the default', async () => {await withFixture(databaseUrl, async ({ engine, transports }) => {const http = (await transports()).find(transport => transport.name === 'http')!;diff --git a/test/orphans-paging-5891.test.ts b/test/orphans-paging-5891.test.tsnew file mode 100644index 0000000000..d135e42827--- /dev/null+++ b/test/orphans-paging-5891.test.ts@@ -0,0 +1,67 @@+/**+ * #5891: find_orphans returned every orphan in one response (2.3 MB on a+ * 23k-page multi-source brain) with no way to page, filter by source, or tell+ * which source a row came from. The op now pages (limit/offset, next_offset),+ * has count_only, filters by a source inside the caller's grant, and each row+ * carries source_id and type.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';++let engine: PGLiteEngine;+const op = operations.find(o => o.name === 'find_orphans')!;+const ctx = (over: Record<string, unknown> = {}) => ({+ engine, config: { engine: 'pglite' as const }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, ...over,+}) as never;+type Result = { orphans: Array<{ slug: string; source_id?: string; type?: string | null }>; total_orphans: number; limit: number; offset: number; next_offset: number | null };+const call = async (c: never, p: Record<string, unknown>) => op.handler(c, p) as Promise<Result>;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('src-b', 'src-b') ON CONFLICT DO NOTHING");+ for (let i = 0; i < 5; i++) {+ await engine.putPage(`people/a-${i}`, { type: 'person', title: `A ${i}`, compiled_truth: 'Body.' }, { sourceId: 'default' });+ }+ for (let i = 0; i < 3; i++) {+ await engine.putPage(`companies/b-${i}`, { type: 'company', title: `B ${i}`, compiled_truth: 'Body.' }, { sourceId: 'src-b' });+ }+}, 60_000);+afterAll(async () => { await engine.disconnect(); });++describe('find_orphans paging and source filter (#5891)', () => {+ test('pages through every orphan in a stable order with next_offset; rows carry source_id and type', async () => {+ const local = ctx({ remote: false });+ const first = await call(local, { limit: 3 });+ expect(first.total_orphans).toBe(8);+ expect(first.orphans).toHaveLength(3);+ expect(first.next_offset).toBe(3);+ expect(first.orphans[0]).toMatchObject({ slug: 'people/a-0', source_id: 'default', type: 'person' });+ const rest = await call(local, { limit: 3, offset: 3 });+ const last = await call(local, { limit: 3, offset: 6 });+ expect(last.next_offset).toBeNull();+ const all = [...first.orphans, ...rest.orphans, ...last.orphans].map(r => `${r.source_id}:${r.slug}`);+ expect(new Set(all).size).toBe(8);+ expect(all.slice(-3)).toEqual(['src-b:companies/b-0', 'src-b:companies/b-1', 'src-b:companies/b-2']);+ });++ test('the default page is bounded and count_only returns totals with no rows', async () => {+ const result = await call(ctx({ remote: false }), {});+ expect(result.limit).toBe(100);+ const counted = await call(ctx({ remote: false }), { count_only: true });+ expect(counted.orphans).toEqual([]);+ expect(counted.total_orphans).toBe(8);+ await expect(call(ctx({ remote: false }), { limit: 0 })).rejects.toThrow('limit must be');+ });++ test('source_id narrows inside the grant and never widens it', async () => {+ const federated = ctx({ remote: true, sourceId: 'default', auth: { token: 't', clientId: 'c', scopes: ['read'], sourceId: 'default', allowedSources: ['default', 'src-b'] } });+ const onlyB = await call(federated, { source_id: 'src-b' });+ expect(onlyB.orphans.map(r => r.source_id)).toEqual(['src-b', 'src-b', 'src-b']);+ const bound = ctx({ remote: true, sourceId: 'default', auth: { token: 't', clientId: 'c', scopes: ['read'], sourceId: 'default' } });+ await expect(call(bound, { source_id: 'src-b' })).rejects.toThrow('Unknown source: src-b');+ expect((await call(bound, {})).orphans.every(r => r.source_id === 'default')).toBe(true);+ });+});