Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
agent contract: stdio registration and assemble_evidence refusals name their own next step
garrytane1614df0f93c
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 05a5f782c1..1c8f7cca31 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -1,4 +1,2 @@# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>countsrc/commands/book-mirror.ts 1-src/core/search/evidence-delivery.ts 1-src/mcp/dispatch.ts 1diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex ecd2fb6e31..9d5bddf235 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -1082,8 +1082,8 @@ const assemble_evidence: Operation = {if (!Array.isArray(hits) || hits.some(h => typeof h !== 'object' || h === null|| typeof (h as Record<string, unknown>).source_id !== 'string' || typeof (h as Record<string, unknown>).slug !== 'string'|| !Number.isInteger((h as Record<string, unknown>).chunk_id))) {- throw opError('invalid_params', 'hits must be an array of { source_id: string, slug: string, chunk_id: integer }.',- 'Pass the source_id, slug and chunk_id of each search hit. Example: {"hits": [{"source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812}], "return_unit": "page"}');+ throw invalidParam(ctx, 'assemble_evidence', 'hits', 'hits must be an array of { source_id: string, slug: string, chunk_id: integer }.',+ { def: assemble_evidence.params.hits, example: [{ source_id: 'default', slug: 'chat/session-0412', chunk_id: 8812 }] });}const scope = federatedSearchScope(ctx);const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 8cfd4cbdcb..92c60f569c 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -1122,7 +1122,8 @@ export async function resolveFrozenHits(* (default trusted local).*/export async function assembleEvidenceForHits(engine: BrainEngine, input: AssembleEvidenceInput): Promise<AssembleEvidenceOutput> {- if (!Array.isArray(input.hits)) throw new OperationError('invalid_params', 'hits must be an array of { source_id, slug, chunk_id }.');+ if (!Array.isArray(input.hits)) throw new OperationError('invalid_params', 'hits must be an array of { source_id, slug, chunk_id }.',+ 'Pass hits as an array of { source_id, slug, chunk_id } objects, e.g. [{ "source_id": "default", "slug": "notes/a", "chunk_id": 12 }], ranked best first.');if (input.hits.length > MAX_ASSEMBLE_HITS) {throw new OperationError('invalid_params', `hits holds at most ${MAX_ASSEMBLE_HITS} entries (got ${input.hits.length}).`, 'Pass the top-ranked hits only.');}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 11d9a2ba91..d505c6af03 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -851,7 +851,10 @@ export async function dispatchToolCall(}const result = registration? await withVerifiedLocalRegistration(engine, registration, async verified => {- if (!verified.remote) throw new OperationError('permission_denied', 'This registration is not an agent-facing connection.');+ if (!verified.remote) throw opError('permission_denied', 'This registration is not an agent-facing connection.',+ `${name} on this stdio connection needs the agent-facing stdio writer registration, which only the user can create in a terminal on the brain host.`,+ { fix: hostFix(ctx, ['gbrain', 'auth', 'local-writer', 'register', 'stdio', '--dry-run', '--json'],+ 'Previews the agent-facing stdio registration; the user reruns it without --dry-run (with --replace and the complete grant when a registration exists).') });return op.handler(ctx, safeParams);}): await op.handler(ctx, safeParams);diff --git a/test/dispatch-stdio-registration-refusal.test.ts b/test/dispatch-stdio-registration-refusal.test.tsnew file mode 100644index 0000000000..af4e093e0f--- /dev/null+++ b/test/dispatch-stdio-registration-refusal.test.ts@@ -0,0 +1,25 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { copyFileSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { persistenceHome, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-stdio-registration-'));+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('a stdio registration that resolves to the CLI lane names the agent-facing registration the user creates', () => withEnv({ GBRAIN_HOME: home }, async () => {+ await registerLocalWriter(engine, 'cli');+ const cli = readdirSync(persistenceHome()).find(name => name.endsWith('.cli.json'))!;+ copyFileSync(join(persistenceHome(), cli), join(persistenceHome(), cli.replace('.cli.json', '.stdio.json')));+ const result = await dispatchToolCall(engine, 'list_skills', {}, { remote: true, transport: 'stdio', sourceId: 'default' });+ expect(result.isError).toBe(true);+ const envelope = JSON.parse(result.content[0]!.text);+ expect(envelope).toMatchObject({ code: 'permission_denied', fix: { actor: 'user', next: 'tell_user_to_run' } });+ expect(envelope.fix.argv.slice(0, 7)).toEqual(['gbrain', 'auth', 'local-writer', 'register', 'stdio', '--dry-run', '--json']);+ expect(envelope.suggestion).toContain('list_skills on this stdio connection');+}));diff --git a/test/evidence-delivery.test.ts b/test/evidence-delivery.test.tsindex 0bca0096a7..ba0c85eb6a 100644--- a/test/evidence-delivery.test.ts+++ b/test/evidence-delivery.test.ts@@ -25,6 +25,7 @@ import { runThink } from '../src/core/think/index.ts';import { formatDeliverySummary, formatResultsExplain } from '../src/core/search/explain-formatter.ts';import {conversationSignal,+ assembleEvidenceForHits,countEvidenceTokens,deliverEvidence,deliveryVersionSkewWarning,@@ -625,6 +626,16 @@ describe('ops', () => {expect(bad.unresolved).toEqual([0]);});+ test('malformed assemble_evidence hits name the parameter in the caller\'s own syntax', async () => {+ await expect(op('assemble_evidence').handler(ctxOf(), { hits: 'chat/session-1' })).rejects.toMatchObject({+ code: 'invalid_params', suggestion: expect.stringContaining('Pass --hits as a array'),+ });+ await expect(op('assemble_evidence').handler(ctxOf({ remote: true, transport: 'stdio' }), { hits: [{ slug: 'chat/session-1' }] })).rejects.toMatchObject({+ code: 'invalid_params', suggestion: expect.stringContaining('assemble_evidence {"hits": [{"source_id":"default","slug":"chat/session-0412","chunk_id":8812}]}'),+ });+ await expect(assembleEvidenceForHits(engine, { hits: 'x' as never })).rejects.toMatchObject({ code: 'invalid_params', suggestion: expect.stringContaining('"chunk_id": 12') });+ });+test('a fenced-code best hit delivers the page text for return_unit page, not the code chunk', async () => {const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>(`SELECT compiled_truth, timeline FROM pages WHERE slug = 'notes/quokka-code'`);const code = await engine.executeRaw<{ id: number; chunk_index: number; chunk_text: string }>(