Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(loops): our own implementation of the #5939 fix (#5939)
time-attackbc5560b730fb
diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex b1299b18e4..4306205879 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -140,6 +140,52 @@ export async function runWaiting(engine: BrainEngine, args: string[]): Promise<v}}+/**+ * `loops show <id>`: asks open_loops for that one id rather than scanning a+ * listed page, so the loop is found at any status and any recency rank.+ * `--status` / `--type` still narrow, and the source span is the same one+ * `loops list` reads.+ */+async function showLoop(+ engine: BrainEngine,+ rest: string[],+ narrowing: Record<string, unknown>,+ readScope: { sourceId: string },+ json: boolean,+): Promise<void> {+ const token = rest.find((a) => /^\d+$/.test(a));+ const loopId = token === undefined ? NaN : Number(token);+ if (!Number.isSafeInteger(loopId) || loopId < 1) {+ exitCliError(usageError('gbrain loops show needs a loop id of 1 or more.',+ 'Usage: gbrain loops show <id> [--json]. Example: gbrain loops show 42 (`gbrain loops list` prints ids).'), 'loops', { json });+ }+ const { loops } = (await handleToolCall(+ engine,+ 'open_loops',+ { group_by: 'none', id: loopId, ...narrowing },+ readScope,+ )) as { loops: Array<Record<string, unknown>> };+ const loop = loops[0];+ if (loop === undefined) {+ setCliExitVerdict(writeCliError(opError('not_found', `No loop ${loopId} in the sources this command reads.`,+ 'Run `gbrain loops list` to see loop ids.', {+ why: 'A loop in a source this command does not read, or one excluded by --status or --type, is reported the same way as an id that does not exist.',+ fix: { argv: ['gbrain', 'loops', 'list'], consent: [], actor: 'agent', why: 'Prints the loops this command can read, with their ids.', requires_exclusive: false },+ }), 'loops', { json }));+ return;+ }+ if (json) {+ process.stdout.write(JSON.stringify({ ok: true, status: 'ok', loop }, null, 2) + '\n');+ return;+ }+ const due = loop.due_at ? ` due ${String(loop.due_at).slice(0, 10)}` : '';+ process.stdout.write(`#${String(loop.id)} [${String(loop.loop_type)}] ${String(loop.status)}${due}\n${String(loop.summary)}\n`);+ const quote = (loop as { quote?: string }).quote;+ if (quote) process.stdout.write(`> "${quote}"\n`);+ const link = (loop as { deep_link?: string }).deep_link;+ if (link) process.stdout.write(`${link}\n`);+}+export async function runLoops(engine: BrainEngine, args: string[]): Promise<void> {const [sub, ...rest] = args;const json = rest.includes('--json') || args.includes('--json');@@ -164,47 +210,21 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voiif (sub === 'list' || sub === 'show') {const statusIdx = rest.indexOf('--status');const typeIdx = rest.indexOf('--type');- const id = sub === 'show' ? Number(rest.find((a) => /^\d+$/.test(a))) : undefined;- if (id !== undefined && !(Number.isSafeInteger(id) && id > 0)) {- exitCliError(usageError('gbrain loops show needs a positive loop id.',- 'Usage: gbrain loops show <id> [--json]. Example: gbrain loops show 42 (`gbrain loops list` shows ids).'), 'loops', { json });+ const narrowing = {+ ...(statusIdx !== -1 ? { status: rest[statusIdx + 1] } : {}),+ ...(typeIdx !== -1 ? { loop_type: rest[typeIdx + 1] } : {}),+ };+ const readScope = { sourceId: sourceFlag(rest) ?? ALL_SOURCES };+ if (sub === 'show') {+ await showLoop(engine, rest, narrowing, readScope, json);+ return;}- // show looks the id up in the op (any status, any rank), never in the- // listed page: a page holds only the most recent loops of one status.const result = (await handleToolCall(engine,'open_loops',- {- group_by: 'none',- limit: 200,- ...(id !== undefined ? { id } : {}),- ...(statusIdx !== -1 ? { status: rest[statusIdx + 1] } : {}),- ...(typeIdx !== -1 ? { loop_type: rest[typeIdx + 1] } : {}),- },- { sourceId: sourceFlag(rest) ?? ALL_SOURCES },+ { group_by: 'none', limit: 200, ...narrowing },+ readScope,)) as { loops: Array<Record<string, unknown>>; count: number };- if (sub === 'show') {- const loop = result.loops.find((l) => l.id === id);- if (!loop) {- setCliExitVerdict(writeCliError(opError('not_found', `No loop ${id} in the sources this command reads.`,- 'Run `gbrain loops list` to see loop ids.', {- why: 'A loop outside the sources this command reads, or outside an explicit --status or --type, looks the same as a missing loop.',- fix: { argv: ['gbrain', 'loops', 'list'], consent: [], actor: 'agent', why: 'Lists the loops this command can read, with their ids.', requires_exclusive: false },- }), 'loops', { json }));- return;- }- if (json) {- process.stdout.write(JSON.stringify({ ok: true, status: 'ok', loop }, null, 2) + '\n');- return;- }- const due = loop.due_at ? ` due ${String(loop.due_at).slice(0, 10)}` : '';- process.stdout.write(`#${String(loop.id)} [${String(loop.loop_type)}] ${String(loop.status)}${due}\n${String(loop.summary)}\n`);- const quote = (loop as { quote?: string }).quote;- if (quote) process.stdout.write(`> "${quote}"\n`);- const link = (loop as { deep_link?: string }).deep_link;- if (link) process.stdout.write(`${link}\n`);- return;- }if (json) {process.stdout.write(JSON.stringify({ ok: true, status: 'ok', ...result }, null, 2) + '\n');return;diff --git a/src/core/loops/loops-store.ts b/src/core/loops/loops-store.tsindex 1928c0c1d8..deec074aed 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -218,8 +218,11 @@ export interface ListLoopsOpts {status?: LoopStatus;loopType?: LoopType;counterparty?: string;- /** One loop by id. Composes with the other filters, never replaces the source scope. */- id?: number;+ /**+ * Restrict the read to the loop with this primary key. It is ANDed with+ * every other filter, so the source scope above still bounds the result.+ */+ loopId?: number;limit?: number;}@@ -234,7 +237,7 @@ export async function listOpenLoops(AND ($2::text IS NULL OR status = $2)AND ($3::text IS NULL OR loop_type = $3)AND ($4::text IS NULL OR counterparty_slug = $4 OR counterparty_email = $4)- AND ($5::bigint IS NULL OR id = $5)+ AND ($5::bigint IS NULL OR id = $5::bigint)ORDER BY last_activity_at DESC, id DESCLIMIT ${limit}`,[@@ -242,7 +245,7 @@ export async function listOpenLoops(opts.status ?? null,opts.loopType ?? null,opts.counterparty ?? null,- opts.id ?? null,+ opts.loopId === undefined ? null : opts.loopId,],);return rows.map(normalizeRow);diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex a5e0eedf6d..7b0c7cdb58 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -322,8 +322,8 @@ const open_loops: Operation = {'answer as partial and name the held items and their retry command.',params: {group_by: { type: 'string', enum: ['counterparty', 'none'], description: "Default 'counterparty' (ranked groups)." },- status: { type: 'string', enum: ['open', 'done', 'dropped', 'stale'], description: "Default 'open' (no default with `id`)." },- id: { type: 'number', description: 'One loop by id (from a previous open_loops result), at any status unless `status` is given. Stays inside the resolved source scope; returns no text digest.' },+ status: { type: 'string', enum: ['open', 'done', 'dropped', 'stale'], description: "Default 'open', except with `id`, where any status matches." },+ id: { type: 'number', description: 'Fetch the single loop with this id (ids come from earlier open_loops results). Matches any status unless `status` is passed; the source scope still applies, and the grouped view omits `text`.' },loop_type: { type: 'string', enum: ['commitment_owed_by_me', 'commitment_owed_to_me', 'unanswered_inbound', 'unanswered_outbound', 'decision_pending'], description: 'Filter to one loop type.' },counterparty: { type: 'string', description: 'Filter to one counterparty (slug or email).' },limit: { type: 'number', description: 'Grouped: max groups (default 3). Flat: max loops (default 50). The internal fetch is capped at 500 rows; `truncated: true` marks a hit.' },@@ -342,14 +342,9 @@ const open_loops: Operation = {{ def: open_loops.params.as_of, example: '2026-04-03T09:00:00Z' });}const groupBy = (p.group_by as string | undefined) ?? 'counterparty';- // An id names one loop whatever its status, so the 'open' default only- // applies to lists; an explicit status still narrows the lookup.- const id = (p.id ?? undefined) as number | undefined;- if (id !== undefined && !(Number.isSafeInteger(id) && id > 0)) {- throw invalidParam(ctx, 'open_loops', 'id', 'open_loops: id must be a positive integer loop id.',- { def: open_loops.params.id, example: 42 });- }- const status = (p.status as LoopStatus | undefined) ?? (id === undefined ? 'open' : undefined);+ const loopId = requestedLoopId(ctx, p.id);+ let status = (p.status ?? undefined) as LoopStatus | undefined;+ if (status === undefined && loopId === undefined) status = 'open';// Per-call scope via the canonical trust+grant resolver: an MCP caller// whose transport is bound to another source can point this read at the// google source (`source_id`) or, trusted-local, span the brain@@ -398,7 +393,7 @@ const open_loops: Operation = {status,...(p.loop_type ? { loopType: p.loop_type as LoopType } : {}),...(p.counterparty ? { counterparty: p.counterparty as string } : {}),- ...(id !== undefined ? { id } : {}),+ ...(loopId === undefined ? {} : { loopId }),limit: 500,});const freshness = await googleSourceFreshness(ctx, scope);@@ -504,13 +499,26 @@ const open_loops: Operation = {no_google_sources: noGoogleSources,redacted: !trusted,as_of: new Date(nowMs).toISOString(),- // The digest reads as "waiting on you" over open loops; an id lookup- // can hit a closed loop or nothing at all, so it gets no digest.- ...(trusted && id === undefined ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) } : {}),+ ...(trusted && loopId === undefined+ ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) }+ : {}),};},};+/**+ * open_loops `id`: absent or null means a list read. Anything else must be a+ * positive safe integer. The refusal never echoes the raw value. The digest+ * stays off for a lookup because it describes the open list ("waiting on+ * you", "You are clean"), which is false for a closed or missing loop.+ */+function requestedLoopId(ctx: OperationContext, raw: unknown): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === 'number' && Number.isSafeInteger(raw) && raw >= 1) return raw;+ throw invalidParam(ctx, 'open_loops', 'id', 'open_loops: id must be a whole number of 1 or more.',+ { def: open_loops.params.id, example: 42 });+}+function grantedSources(ctx: OperationContext): string[] {const allowed = ctx.auth?.allowedSources;if (allowed && allowed.length > 0) return [...allowed];diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 1783c8f415..06b56e9a2e 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -2433,10 +2433,6 @@ describeBoth('Engine parity — open_loops loops-store round-trip', () => {const closed = await closeOpenLoop(eng, 'lpsrc', first.id, 'done', 'parity-test');const openAfter = await listOpenLoops(eng, { sourceIds: ['lpsrc'], status: 'open' });const doneAfter = await listOpenLoops(eng, { sourceIds: ['lpsrc'], status: 'done' });- // #5870: the id filter binds as bigint on both engines and finds the- // closed row with no status filter; another source's scope never does.- const byId = await listOpenLoops(eng, { sourceIds: ['lpsrc'], id: first.id });- const byIdOtherSource = await listOpenLoops(eng, { sourceIds: ['lpsrc-other'], id: first.id });return {firstCreated: first.created,againCreated: again.created,@@ -2456,9 +2452,6 @@ describeBoth('Engine parity — open_loops loops-store round-trip', () => {closedBy: closed?.closed_by,openAfterCount: openAfter.length,doneAfterCount: doneAfter.length,- byIdSameRow: byId.length === 1 && byId[0].id === first.id,- byIdStatus: byId[0]?.status,- byIdOtherSourceCount: byIdOtherSource.length,};}@@ -2482,9 +2475,42 @@ describeBoth('Engine parity — open_loops loops-store round-trip', () => {expect(pg.closedBy).toBe('parity-test');expect(pg.openAfterCount).toBe(0);expect(pg.doneAfterCount).toBe(1);- expect(pg.byIdSameRow).toBe(true);- expect(pg.byIdStatus).toBe('done');- expect(pg.byIdOtherSourceCount).toBe(0);+ });++ async function lookupById(eng: BrainEngine) {+ const { upsertOpenLoop, closeOpenLoop, listOpenLoops } = await import(+ '../../src/core/loops/loops-store.ts'+ );+ await eng.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('lpid-a', 'lpid-a'), ('lpid-b', 'lpid-b') ON CONFLICT (id) DO NOTHING`,+ [],+ );+ const row = await upsertOpenLoop(eng, {+ sourceId: 'lpid-a',+ dedupKey: 'thread:eeee000000000001:unanswered_inbound',+ loopType: 'unanswered_inbound',+ counterpartyEmail: '[email protected]',+ summary: 'Reply owed to [email protected]',+ evidence: [{ message_id: 'eeee000000000001', quote: 'Any update?' }],+ threadId: 'eeee000000000001',+ detector: 'deterministic_thread',+ });+ await closeOpenLoop(eng, 'lpid-a', row.id, 'dropped', 'parity-lookup');+ const hit = await listOpenLoops(eng, { sourceIds: ['lpid-a'], loopId: row.id });+ return {+ hitIds: hit.map((r) => r.id === row.id),+ hitStatus: hit[0]?.status,+ otherSource: (await listOpenLoops(eng, { sourceIds: ['lpid-b'], loopId: row.id })).length,+ statusMismatch: (await listOpenLoops(eng, { sourceIds: ['lpid-a'], loopId: row.id, status: 'open' })).length,+ beyondInt4: (await listOpenLoops(eng, { sourceIds: ['lpid-a'], loopId: 2 ** 40 })).length,+ };+ }++ test('loopId lookup finds a closed row inside its source and nothing outside, on both engines', async () => {+ const pg = await lookupById(pgEngine);+ const pglite = await lookupById(pgliteEngine);+ expect(pg).toEqual(pglite);+ expect(pg).toEqual({ hitIds: [true], hitStatus: 'dropped', otherSource: 0, statusMismatch: 0, beyondInt4: 0 });});});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 4153eec556..bbb045dfb5 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": 205668,- "stdoutSha256": "96a9c3f7a58c78971bff5f692cbb7ea529c99fbb7c890f63c63b689c8d0c0f76",+ "stdoutBytes": 205725,+ "stdoutSha256": "04098d0530fafd5a3c383de74c002333571950d2be7c6d6e41c792fd71cdecdd","toolNames": ["remember","entity",@@ -6359,7 +6359,7 @@"type": "string"},"id": {- "description": "One loop by id (from a previous open_loops result), at any status unless `status` is given. Stays inside the resolved source scope; returns no text digest.",+ "description": "Fetch the single loop with this id (ids come from earlier open_loops results). Matches any status unless `status` is passed; the source scope still applies, and the grouped view omits `text`.","type": "number"},"include_context": {@@ -6386,7 +6386,7 @@"type": "string"},"status": {- "description": "Default 'open' (no default with `id`).",+ "description": "Default 'open', except with `id`, where any status matches.","enum": ["open","done",diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.tsindex 493a448f4c..6aed76c6e7 100644--- a/test/loops-cli.test.ts+++ b/test/loops-cli.test.ts@@ -337,49 +337,8 @@ describe('runLoops', () => {expect(env.loop.id).toBe(1);});- test('show <id> finds a loop below the 200 most recent and a closed loop, with no --status (#5870)', async () => {- // 205 open loops one hour apart, then one done loop with the newest activity.- await engine.executeRaw(- `INSERT INTO open_loops (source_id, dedup_key, loop_type, counterparty_email, summary, detector, last_activity_at)- SELECT 'default', 'thread:bulk' || g || ':unanswered_inbound', 'unanswered_inbound',- 'p' || g || '@example.com', 'Reply owed to p' || g || '@example.com', 'deterministic_thread',- now() - make_interval(hours => g)- FROM generate_series(1, 205) AS g`,- );- const oldest = Number((await engine.executeRaw<{ id: number }>(- `SELECT id FROM open_loops ORDER BY last_activity_at ASC LIMIT 1`,- ))[0].id);- const { id: doneId } = await upsertOpenLoop(engine, loop());- await closeOpenLoop(engine, 'default', doneId, 'done', 'manual');-- const old = await captured(() => runLoops(engine, ['show', String(oldest)]));- expect(old.out).toContain(`#${oldest} [unanswered_inbound] open`);- expect(old.out).toContain('Reply owed to [email protected]');- expect(old.verdict).toBe(0);-- const done = await captured(() => runLoops(engine, ['show', String(doneId), '--json']));- const env = JSON.parse(done.out) as { ok: boolean; loop: { id: number; status: string } };- expect(env.ok).toBe(true);- expect(env.loop).toMatchObject({ id: doneId, status: 'done' });- expect(done.verdict).toBe(0);-- const doneHuman = await captured(() => runLoops(engine, ['show', String(doneId)]));- expect(doneHuman.out).toContain(`#${doneId} [unanswered_inbound] done`);- expect(doneHuman.verdict).toBe(0);-- // An explicit --status still narrows: the done loop is not open.- const narrowed = await captured(() => runLoops(engine, ['show', String(doneId), '--status', 'open']));- expect(narrowed.err).toContain(`Error [not_found]: No loop ${doneId} in the sources this command reads.`);- expect(narrowed.verdict).toBe(1);- });-- test('show with an unknown id renders not_found with the list fix, verdict 1', async () => {+ test('show with an unknown id sets verdict 1', async () => {const r = await captured(() => runLoops(engine, ['show', '999']));- expect(r.err).toContain('Error [not_found]: No loop 999 in the sources this command reads.');- expect(r.err).toContain('Fix: gbrain loops list');- expect(r.err).toContain('Why: A loop outside the sources this command reads');- expect(r.err).not.toContain('closed loops need --status');- expect(r.out).toBe('');expect(r.verdict).toBe(1);});@@ -428,18 +387,9 @@ describe('runLoops', () => {expect(rows[0].closed_by).toBe('handled in person');});- test.each([[['done']], [['show']], [['show', '0']]])('%p without a positive numeric id hard-exits with usage code 2', async (args) => {- const r = await captured(() => runLoops(engine, args));- expect(r.exitCalled).toBe(2);- expect(r.err).toContain(`Usage: gbrain loops ${args[0]} <id>`);- expect(r.out).toBe('');- });-- test('show without an id renders the invalid_params contract with the usage on the Fix line', async () => {- const r = await captured(() => runLoops(engine, ['show']));+ test('done without a numeric id hard-exits with usage code 2', async () => {+ const r = await captured(() => runLoops(engine, ['done']));expect(r.exitCalled).toBe(2);- expect(r.err).toContain('Error [invalid_params]: gbrain loops show needs a positive loop id.');- expect(r.err).toContain('Fix: Usage: gbrain loops show <id> [--json]. Example: gbrain loops show 42');});test('mute sender writes the suppression row (lowercased) and prints the semantics', async () => {@@ -575,3 +525,115 @@ describe('runLoops', () => {expect(l.verdict).toBe(0);});});++// ── gbrain loops show <id> looks the id up directly (#5870) ─────────────────++describe('loops show by id', () => {+ /**+ * One aged loop (last activity in 2019), then 230 newer fillers, so the aged+ * loop sits below the 200-row page `loops list` prints. A second google+ * source holds one foreign loop.+ */+ async function seedShowFixture(): Promise<{ aged: number; foreign: number }> {+ const { id: aged } = await upsertOpenLoop(engine, loop({+ threadId: 'aaaa000000000001',+ counterpartyEmail: '[email protected]',+ summary: 'Reply owed to [email protected]: "Aged thread"',+ }));+ await engine.executeRaw(+ `UPDATE open_loops SET last_activity_at = '2019-06-01T00:00:00Z' WHERE id = $1`,+ [aged],+ );+ await engine.executeRaw(+ `INSERT INTO open_loops (source_id, detector, loop_type, dedup_key, summary, counterparty_email, last_activity_at)+ SELECT 'default', 'deterministic_thread', 'unanswered_inbound', 'thread:filler-' || n || ':unanswered_inbound',+ 'Filler loop ' || n, 'filler' || n || '@example.com',+ now() - (n || ' minutes')::interval+ FROM generate_series(1, 230) AS n`,+ );+ const googleConfig = { kind: 'google' };+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, last_sync_at) VALUES ($1, $1, $2::jsonb, now()) ON CONFLICT (id) DO NOTHING`,+ ['gx', googleConfig],+ );+ const { id: foreign } = await upsertOpenLoop(engine, loop({+ sourceId: 'gx',+ threadId: 'bbbb000000000002',+ counterpartyEmail: '[email protected]',+ summary: 'Reply owed to [email protected]: "Foreign source"',+ }));+ return { aged, foreign };+ }++ test('an open loop below the 200 most recent is shown, verdict 0', async () => {+ const { aged } = await seedShowFixture();+ const r = await captured(() => runLoops(engine, ['show', String(aged)]));+ expect(r.err).toBe('');+ expect(r.out).toContain(`#${aged} [unanswered_inbound] open`);+ expect(r.out).toContain('"Aged thread"');+ expect(r.verdict).toBe(0);+ expect(r.exitCalled).toBeUndefined();+ });++ test('a dropped loop is shown without --status, in human and --json output', async () => {+ const { aged } = await seedShowFixture();+ await closeOpenLoop(engine, 'default', aged, 'dropped', 'manual');+ const human = await captured(() => runLoops(engine, ['show', String(aged)]));+ expect(human.out).toContain(`#${aged} [unanswered_inbound] dropped`);+ expect(human.verdict).toBe(0);+ const machine = await captured(() => runLoops(engine, ['show', String(aged), '--json']));+ const doc = JSON.parse(machine.out) as { ok: boolean; status: string; loop: { id: number; status: string } };+ expect(doc.ok).toBe(true);+ expect(doc.loop.id).toBe(aged);+ expect(doc.loop.status).toBe('dropped');+ });++ test('--status and --type still narrow a lookup: a mismatch is not_found, verdict 1', async () => {+ const { aged } = await seedShowFixture();+ await closeOpenLoop(engine, 'default', aged, 'done', 'manual');+ const wrongStatus = await captured(() => runLoops(engine, ['show', String(aged), '--status', 'open']));+ expect(wrongStatus.err).toContain(`Error [not_found]: No loop ${aged} in the sources this command reads.`);+ expect(wrongStatus.out).toBe('');+ expect(wrongStatus.verdict).toBe(1);+ const wrongType = await captured(() => runLoops(engine, ['show', String(aged), '--type', 'decision_pending']));+ expect(wrongType.err).toContain('Error [not_found]');+ expect(wrongType.verdict).toBe(1);+ const matching = await captured(() => runLoops(engine, ['show', String(aged), '--status', 'done']));+ expect(matching.out).toContain(`#${aged} [unanswered_inbound] done`);+ expect(matching.verdict).toBe(0);+ });++ test('--source narrows the lookup: a loop in another source is not_found there', async () => {+ const { foreign } = await seedShowFixture();+ const narrowed = await captured(() => runLoops(engine, ['show', String(foreign), '--source', 'default']));+ expect(narrowed.err).toContain(`No loop ${foreign} in the sources this command reads.`);+ expect(narrowed.verdict).toBe(1);+ const home = await captured(() => runLoops(engine, ['show', String(foreign), '--source', 'gx']));+ expect(home.out).toContain(`#${foreign} [unanswered_inbound] open`);+ expect(home.verdict).toBe(0);+ });++ test('a missing id renders not_found with the list fix and no --status advice', async () => {+ await seedShowFixture();+ const r = await captured(() => runLoops(engine, ['show', '424242']));+ expect(r.err).toContain('Error [not_found]: No loop 424242 in the sources this command reads.');+ expect(r.err).toContain('Fix: gbrain loops list');+ expect(r.err).not.toContain('closed loops need --status');+ expect(r.out).toBe('');+ expect(r.verdict).toBe(1);+ });++ test.each([+ ['no id at all', ['show']],+ ['id 0', ['show', '0']],+ ['a negative id', ['show', '-5']],+ ['a fractional id', ['show', '2.5']],+ ['a non-numeric id', ['show', 'abc']],+ ])('%s is a usage error: exit 2, invalid_params, nothing on stdout', async (_label, args) => {+ const r = await captured(() => runLoops(engine, args));+ expect(r.exitCalled).toBe(2);+ expect(r.err).toContain('Error [invalid_params]: gbrain loops show needs a loop id of 1 or more.');+ expect(r.err).toContain('Usage: gbrain loops show <id> [--json]');+ expect(r.out).toBe('');+ });+});diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.tsindex de5848c884..8bb77bd0cb 100644--- a/test/ops-loops.test.ts+++ b/test/ops-loops.test.ts@@ -20,8 +20,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { loopsOperations } from '../src/core/ops/loops.ts';import { operationsByName } from '../src/core/operations.ts';-import { toAgentError } from '../src/core/agent-output.ts';import type { OperationContext } from '../src/core/ops/contract.ts';+import { toAgentError } from '../src/core/agent-output.ts';import {closeOpenLoop,listOpenLoops,@@ -615,113 +615,153 @@ describe('open_loops per-call scope (source_id / all_sources)', () => {});});-describe('open_loops id lookup (#5870)', () => {- interface FlatResult {- loops: Array<{ id: number; status: string; quote?: string }>;+describe('open_loops single-loop lookup by id (#5870)', () => {+ interface LookupFlat {+ loops: Array<{ id: number; status: string; quote?: string; deep_link?: string }>;count: number;- truncated: boolean;redacted: boolean;}- // 501 open loops in g1 one hour apart (the oldest sits past the 500-row- // internal fetch), one done loop in g1, and g2 as a second google source.- async function seed(): Promise<{ oldestOpen: number; done: number }> {+ /**+ * g1: one aged loop (2019) behind 510 newer fillers, so it sits past the+ * op's 500-row internal fetch, plus one loop closed as `stale`.+ * g3: a second google source with one loop the g1-scoped callers must not see.+ */+ async function seedLookup(): Promise<{ aged: number; closed: number; foreign: number }> {+ const googleConfig = { kind: 'google' };await engine.executeRaw(- `INSERT INTO sources (id, name, config, last_sync_at)- VALUES ('g2', 'g2', '{"kind":"google"}'::jsonb, now())- ON CONFLICT (id) DO NOTHING`,+ `INSERT INTO sources (id, name, config, last_sync_at) VALUES ($1, $1, $2::jsonb, now()) ON CONFLICT (id) DO NOTHING`,+ ['g3', googleConfig],);+ const { id: aged } = await upsertOpenLoop(engine, loop({ threadId: 'cccc000000000001', counterpartyEmail: '[email protected]' }));+ await engine.executeRaw(`UPDATE open_loops SET last_activity_at = '2019-06-01T00:00:00Z' WHERE id = $1`, [aged]);await engine.executeRaw(- `INSERT INTO open_loops (source_id, dedup_key, loop_type, counterparty_email, summary, detector, last_activity_at)- SELECT 'g1', 'thread:bulk' || g || ':unanswered_inbound', 'unanswered_inbound',- 'p' || g || '@example.com', 'Reply owed to p' || g || '@example.com', 'deterministic_thread',- now() - make_interval(hours => g)- FROM generate_series(1, 501) AS g`,+ `INSERT INTO open_loops (source_id, detector, loop_type, dedup_key, summary, counterparty_email, last_activity_at)+ SELECT 'g1', 'deterministic_thread', 'unanswered_inbound', 'thread:filler-' || n || ':unanswered_inbound',+ 'Filler loop ' || n, 'filler' || n || '@example.com',+ now() - (n || ' minutes')::interval+ FROM generate_series(1, 510) AS n`,);- const oldestOpen = Number((await engine.executeRaw<{ id: number }>(- `SELECT id FROM open_loops ORDER BY last_activity_at ASC LIMIT 1`,- ))[0].id);- const { id: done } = await upsertOpenLoop(engine, loop());- await closeOpenLoop(engine, 'g1', done, 'done', 'manual');- return { oldestOpen, done };+ const { id: closed } = await upsertOpenLoop(engine, loop({ threadId: 'cccc000000000002', counterpartyEmail: '[email protected]' }));+ await closeOpenLoop(engine, 'g1', closed, 'stale', 'staleness');+ const { id: foreign } = await upsertOpenLoop(engine, loop({ sourceId: 'g3', threadId: 'dddd000000000003', counterpartyEmail: '[email protected]' }));+ return { aged, closed, foreign };}- const granted = (allowedSources: string[]) =>+ const federated = (allowedSources: string[]) =>ctx({ remote: true, sourceId: undefined, auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources } });+ const flat = async (caller: OperationContext, params: Record<string, unknown>) =>+ (await openLoopsOp.handler(caller, { group_by: 'none', ...params })) as LookupFlat;- test.each([- { name: 'a closed loop, no status given', caller: () => ctx(), target: 'done', found: true, quote: 'Can you review the plan?' },- { name: 'an open loop past the 500-row fetch', caller: () => ctx(), target: 'oldestOpen', found: true },- { name: 'an explicit status the loop has', caller: () => ctx(), target: 'done', params: { status: 'done' }, found: true, quote: 'Can you review the plan?' },- { name: 'an explicit status the loop lacks', caller: () => ctx(), target: 'done', params: { status: 'open' }, found: false },- { name: 'an explicit loop_type the loop lacks', caller: () => ctx(), target: 'done', params: { loop_type: 'decision_pending' }, found: false },- { name: 'an explicit counterparty the loop lacks', caller: () => ctx(), target: 'done', params: { counterparty: '[email protected]' }, found: false },- { name: 'a trusted call narrowed to another source', caller: () => ctx(), target: 'done', params: { source_id: 'g2' }, found: false },- { name: 'a remote grant covering the source (redacted)', caller: () => granted(['g1', 'g2']), target: 'done', found: true },- { name: 'a remote grant outside the source', caller: () => granted(['g2']), target: 'done', found: false },- ] as const)('id lookup: $name', async (c) => {- const ids = await seed();- const id = ids[c.target];- const caller = c.caller();- const res = (await openLoopsOp.handler(caller, {- group_by: 'none',- id,- ...('params' in c ? c.params : {}),- })) as FlatResult;- expect(res.loops.map((l) => l.id)).toEqual(c.found ? [id] : []);- expect(res.count).toBe(c.found ? 1 : 0);- expect(res.redacted).toBe(caller.remote !== false);- if (c.found) {- expect(res.loops[0].status).toBe(c.target === 'done' ? 'done' : 'open');- expect(res.loops[0].quote).toBe('quote' in c ? c.quote : undefined);+ test('trusted: a loop past the 500-row fetch comes back alone, with its quote', async () => {+ const { aged } = await seedLookup();+ const res = await flat(ctx(), { id: aged });+ expect(res.loops.map((l) => l.id)).toEqual([aged]);+ expect(res.count).toBe(1);+ expect(res.loops[0].status).toBe('open');+ expect(res.loops[0].quote).toBe('Can you review the plan?');+ });++ test('trusted: a closed (stale) loop is found with no status given', async () => {+ const { closed } = await seedLookup();+ const res = await flat(ctx(), { id: closed });+ expect(res.loops.map((l) => [l.id, l.status])).toEqual([[closed, 'stale']]);+ });++ test('explicit filters still narrow: status, loop_type and counterparty mismatches return nothing', async () => {+ const { closed, aged } = await seedLookup();+ expect((await flat(ctx(), { id: closed, status: 'open' })).count).toBe(0);+ expect((await flat(ctx(), { id: closed, status: 'stale' })).count).toBe(1);+ expect((await flat(ctx(), { id: aged, loop_type: 'commitment_owed_by_me' })).count).toBe(0);+ expect((await flat(ctx(), { id: aged, counterparty: '[email protected]' })).count).toBe(0);+ expect((await flat(ctx(), { id: aged, counterparty: '[email protected]' })).count).toBe(1);+ });++ test('trusted source_id still bounds the lookup: the g3 loop is not visible from g1', async () => {+ const { foreign } = await seedLookup();+ expect((await flat(ctx(), { id: foreign })).count).toBe(0);+ expect((await flat(ctx(), { id: foreign, source_id: 'g3' })).count).toBe(1);+ });++ test('deny: a foreign id reads exactly like a missing id for scalar and federated remote callers', async () => {+ const { foreign } = await seedLookup();+ const asOf = '2026-04-03T09:00:00.000Z';+ for (const caller of [ctx({ remote: true, sourceId: 'g1' }), federated(['g1'])]) {+ for (const group_by of ['none', 'counterparty'] as const) {+ const foreignRes = await openLoopsOp.handler(caller, { group_by, id: foreign, as_of: asOf });+ const missingRes = await openLoopsOp.handler(caller, { group_by, id: foreign + 900_000, as_of: asOf });+ expect(foreignRes).toEqual(missingRes);+ expect((foreignRes as { count: number }).count).toBe(0);+ }}});- test.each([['omitted', {}], ['null', { id: null }]] as const)('id %s: the open default still applies, the closed loop stays out of a list', async (_label, extra) => {- const { done } = await seed();- const res = (await openLoopsOp.handler(ctx(), { group_by: 'none', limit: 500, ...extra })) as FlatResult;- expect(res.loops.map((l) => l.id)).not.toContain(done);- expect(res.loops.every((l) => l.status === 'open')).toBe(true);- expect(res.truncated).toBe(true);+ test('deny: a narrowed grant cannot reach the id through an out-of-grant source_id', async () => {+ const { foreign } = await seedLookup();+ await expect(flat(federated(['g1']), { id: foreign, source_id: 'g3' })).rejects.toMatchObject({ code: 'permission_denied' });+ await expect(flat(ctx({ remote: true, sourceId: 'g1' }), { id: foreign, source_id: 'g3' })).rejects.toMatchObject({ code: 'permission_denied' });});- // Grouped (the default view): the trusted "waiting on you" digest would- // misdescribe a closed loop, and call a missing id "You are clean".- test.each([['a closed loop', true], ['an id with no loop', false]] as const)('grouped id lookup of %s returns its groups and no text digest', async (_label, found) => {- const { done } = await seed();- const id = found ? done : done + 10_000;- const res = (await openLoopsOp.handler(ctx(), { id })) as GroupsResult;- expect(res.groups.flatMap((g) => g.loops.map((l) => l.id))).toEqual(found ? [id] : []);- expect(res.count).toBe(found ? 1 : 0);- expect('text' in res).toBe(false);+ test('deny: an unscoped remote id lookup fails closed', async () => {+ const { aged } = await seedLookup();+ await expect(flat(ctx({ remote: true, sourceId: undefined }), { id: aged })).rejects.toMatchObject({ code: 'permission_denied' });});- test.each([0, -1, 1.5, '7'])('id %p is rejected with invalid_params', async (bad) => {+ test('allow: a grant covering the source finds the loop redacted (no quote, no deep link)', async () => {+ const { foreign } = await seedLookup();+ const res = await flat(federated(['g3']), { id: foreign });+ expect(res.loops.map((l) => l.id)).toEqual([foreign]);+ expect(res.redacted).toBe(true);+ expect(JSON.stringify(res)).not.toContain('"quote"');+ expect(JSON.stringify(res)).not.toContain('"deep_link"');+ });++ test.each([+ ['zero', 0],+ ['negative', -4],+ ['fractional', 3.25],+ ['NaN', Number.NaN],+ ['Infinity', Number.POSITIVE_INFINITY],+ ['past the safe-integer range', 2 ** 53],+ ['a numeric string', '12'],+ ['a boolean', true],+ ['an object', { id: 1 }],+ ])('invalid id (%s) is refused with invalid_params before any read', async (_label, bad) => {await expect(openLoopsOp.handler(ctx(), { id: bad })).rejects.toMatchObject({ code: 'invalid_params' });});- test('a rejected id renders the agent contract without echoing the value', async () => {- const thrown = await openLoopsOp.handler(ctx({ remote: true }), { id: 987654.25 }).catch((e: unknown) => e);+ test('the refusal renders the agent contract and does not echo the rejected value', async () => {+ const thrown = await openLoopsOp.handler(ctx({ remote: true }), { id: 31337.5 }).catch((e: unknown) => e);const env = toAgentError(thrown, { transport: 'stdio', op: 'open_loops', render: {transport: 'stdio', surface: 'full', isCallable: () => true, preapproved: () => false, routing: { brain: 'host', source: 'g1' },} });expect(env).toMatchObject({ code: 'invalid_params', class: 'caller', contract_version: 1 });- expect(env.message).toBe('open_loops: id must be a positive integer loop id.');- expect(env.suggestion).toContain('Pass `id` as a number');+ expect(env.message).toBe('open_loops: id must be a whole number of 1 or more.');expect(env.suggestion).toContain('open_loops {"id": 42}');- expect(JSON.stringify(env)).not.toContain('987654');+ expect(JSON.stringify(env)).not.toContain('31337');});- test('remote: an id outside the grant returns exactly what a missing id returns', async () => {- const { done } = await seed();- const asOf = '2026-04-03T09:00:00.000Z';- for (const group_by of ['none', 'counterparty'] as const) {- const outOfScope = await openLoopsOp.handler(granted(['g2']), { group_by, id: done, as_of: asOf });- const missing = await openLoopsOp.handler(granted(['g2']), { group_by, id: done + 10_000, as_of: asOf });- expect(outOfScope).toEqual(missing);- expect((outOfScope as { count: number }).count).toBe(0);+ test('negative control: id absent or null keeps the list read and its open default', async () => {+ const { closed } = await seedLookup();+ for (const extra of [{}, { id: null }]) {+ const res = await flat(ctx(), { limit: 500, ...extra });+ expect(res.loops.length).toBe(500);+ expect(res.loops.some((l) => l.id === closed)).toBe(false);+ expect(res.loops.every((l) => l.status === 'open')).toBe(true);}});++ test('grouped: a lookup carries no text digest, while the trusted list keeps it', async () => {+ const { closed } = await seedLookup();+ const lookup = (await openLoopsOp.handler(ctx(), { id: closed })) as GroupsResult;+ expect(lookup.groups.flatMap((g) => g.loops.map((l) => l.id))).toEqual([closed]);+ expect(lookup.text).toBeUndefined();+ const missing = (await openLoopsOp.handler(ctx(), { id: closed + 900_000 })) as GroupsResult;+ expect(missing.count).toBe(0);+ expect(missing.text).toBeUndefined();+ const list = (await openLoopsOp.handler(ctx(), {})) as GroupsResult;+ expect(typeof list.text).toBe('string');+ });});describe('loops_close', () => {