Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): find a loop by id at any status and rank in loops show (#5939)
time-attack326a1e142937
diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex 182339a51c..b1299b18e4 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -25,6 +25,8 @@ import type { BrainEngine } from '../core/engine.ts';import { handleToolCall } from '../mcp/server.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { ALL_SOURCES } from '../core/source-id.ts';+import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';+import { opError } from '../core/ops/contract.ts';function sourceFlag(args: string[]): string | undefined {const i = args.indexOf('--source');@@ -162,23 +164,33 @@ 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 });+ }+ // 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 },)) as { loops: Array<Record<string, unknown>>; count: number };if (sub === 'show') {- const id = Number(rest.find((a) => /^\d+$/.test(a)));const loop = result.loops.find((l) => l.id === id);if (!loop) {- console.error(`No loop ${id}. (gbrain loops list shows ids; closed loops need --status done/dropped/stale)`);- setCliExitVerdict(1);+ 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) {diff --git a/src/core/loops/loops-store.ts b/src/core/loops/loops-store.tsindex a33aa00d46..1928c0c1d8 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -218,6 +218,8 @@ 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;limit?: number;}@@ -232,6 +234,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)ORDER BY last_activity_at DESC, id DESCLIMIT ${limit}`,[@@ -239,6 +242,7 @@ export async function listOpenLoops(opts.status ?? null,opts.loopType ?? null,opts.counterparty ?? null,+ opts.id ?? null,],);return rows.map(normalizeRow);diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex da0d1e6c1f..a5e0eedf6d 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -322,7 +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'." },+ 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.' },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.' },@@ -341,7 +342,14 @@ 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';- const status = ((p.status as string | undefined) ?? 'open') as LoopStatus;+ // 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);// 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@@ -390,6 +398,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 } : {}),limit: 500,});const freshness = await googleSourceFreshness(ctx, scope);@@ -495,7 +504,9 @@ const open_loops: Operation = {no_google_sources: noGoogleSources,redacted: !trusted,as_of: new Date(nowMs).toISOString(),- ...(trusted ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) } : {}),+ // 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) } : {}),};},};diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 72d4d5b3f2..1783c8f415 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -2433,6 +2433,10 @@ 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,@@ -2452,6 +2456,9 @@ 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,};}@@ -2475,6 +2482,9 @@ 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);});});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex a7dbe801f3..f9d4d21078 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": 204538,- "stdoutSha256": "14baa283cc6c3428ec4ab5205ee7a23660cb9c516c8bea96dbb84f8e421d5f3c",+ "stdoutBytes": 204822,+ "stdoutSha256": "9a26bd923b7df9ef6f736b0e32860aa43ca0ae13db09459e9b3e9f8da1b73b4a","toolNames": ["remember","entity",@@ -6308,6 +6308,7 @@"as_of": "string?","counterparty": "string?","group_by": "string?",+ "id": "number?","include_context": "boolean?","limit": "number?","loop_type": "string?",@@ -6337,6 +6338,10 @@],"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.",+ "type": "number"+ },"include_context": {"description": "Attach the counterparty entity card per group (trusted local only). Default true.","type": "boolean"@@ -6361,7 +6366,7 @@"type": "string"},"status": {- "description": "Default 'open'.",+ "description": "Default 'open' (no default with `id`).","enum": ["open","done",diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.tsindex 30c511bbd2..493a448f4c 100644--- a/test/loops-cli.test.ts+++ b/test/loops-cli.test.ts@@ -28,6 +28,7 @@ import {} from '../src/core/cli-force-exit.ts';import {addSuppression,+ closeOpenLoop,listOpenLoops,loadSuppressions,upsertOpenLoop,@@ -336,8 +337,49 @@ describe('runLoops', () => {expect(env.loop.id).toBe(1);});- test('show with an unknown id sets verdict 1', async () => {+ 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 () => {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);});@@ -386,9 +428,18 @@ describe('runLoops', () => {expect(rows[0].closed_by).toBe('handled in person');});- test('done without a numeric id hard-exits with usage code 2', async () => {- const r = await captured(() => runLoops(engine, ['done']));+ 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']));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 () => {diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.tsindex d1e7989704..de22a6ab66 100644--- a/test/ops-loops.test.ts+++ b/test/ops-loops.test.ts@@ -20,8 +20,10 @@ 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 {+ closeOpenLoop,listOpenLoops,loadSuppressions,upsertOpenLoop,@@ -613,6 +615,115 @@ 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 }>;+ 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 }> {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, last_sync_at)+ VALUES ('g2', 'g2', '{"kind":"google"}'::jsonb, now())+ ON CONFLICT (id) DO NOTHING`,+ );+ 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`,+ );+ 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 granted = (allowedSources: string[]) =>+ ctx({ remote: true, sourceId: undefined, auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources } });++ 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.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);+ });++ // 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.each([0, -1, 1.5, '7'])('id %p is rejected with invalid_params', async (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);+ 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.suggestion).toContain('open_loops {"id": 42}');+ expect(JSON.stringify(env)).not.toContain('987654');+ });++ 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);+ }+ });+});+describe('loops_close', () => {test('closes an open loop; the second close reports not_found_or_already_closed', async () => {const { id } = await upsertOpenLoop(engine, loop());