Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(closeout): HTTP renders pin only thin-client-sendable source ids; exclusive-fix journey expects the pin

garrytane8e2977be286
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1516662c90..a87be2a0a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -156,7 +156,7 @@ Scripts that parse exit codes or `--json` output should read the [behavior chang
#### Closeout
-- Explicit routing is now central: gbrain appends `--brain` and `--source` to every gbrain command in a fix when it renders it, using the brain and source the failing call acted on, and keeps flags a fix already names. Which commands take which flag comes from the command table and each command's code (`CLI_ROUTING_FLAGS`, generated by `bun run build:flag-registry`). Over HTTP the ids stay and paths are still stripped; a thin client pins nothing.
+- Explicit routing is now central: gbrain appends `--brain` and `--source` to every gbrain command in a fix when it renders it, using the brain and source the failing call acted on, and keeps flags a fix already names. Which commands take which flag comes from the command table and each command's code (`CLI_ROUTING_FLAGS`, generated by `bun run build:flag-registry`). Over HTTP only the source id is pinned, where a thin client can send it (a mount id is host topology, and a thin client refuses `--brain`); a thin client pins nothing of its own.
- `gbrain doctor --remediation-plan` is read-only on an outdated brain: it connects without migrating and reports the pending migrations as a notice.
- Delegated write errors (`capture`, `forget`, `call` and the persistence lane) keep their legacy JSON keys and add `code`, `fix`, `docs_cmd`, `class`, `retryable` and `contract_version`, as every other `--json` error does. A lost acknowledgment from the local persistence owner reports `owner_unavailable` and points at the write receipt instead of `internal_error`.
- A missing table (`get_job_stats`, search stats) no longer says "run apply-migrations" while its fix says "run doctor": the suggestion now quotes the fix.
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index 0a98e6737d..adf0a8558a 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -627,9 +627,11 @@ command table marks `routes_source`). gbrain appends them when it renders the
fix, before any bare `--`, and keeps flags the fix already carries. So you can
run the fix later from another directory, or under a different `GBRAIN_BRAIN_ID`,
`GBRAIN_SOURCE`, `.gbrain-mount` or `.gbrain-source`, and it still acts on the
-intended brain. Over HTTP the ids stay (they are not sensitive); paths are
-stripped as everywhere else. A thin client pins nothing: it has no local mounts
-and its remote scopes the source.
+intended brain. Over HTTP only the source id is pinned, and only where a thin
+client can send it (an op with a `source_id` scope, or a command the brain
+host's operator runs): a mount id is host topology, and a thin client refuses
+`--brain`. Paths are stripped as everywhere else. A thin client pins nothing of
+its own: it has no local mounts and its remote scopes the source.
`next` is computed when gbrain renders the fix for your connection: from the
effects, the actor, the transport, which tools you can call and the user's
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 057eb110e2..527280843f 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -227,7 +227,7 @@ function renderVerify(v: Action['verify'], ctx: RenderContext): RenderedAction['
if (!v) return undefined;
const mcp = v.mcp && ctx.isCallable(v.mcp.tool) ? v.mcp : undefined;
if (!v.argv && !mcp) return undefined;
- return { ...(v.argv ? { argv: pinRouting(v.argv, ctx.routing) } : {}), ...(mcp ? { mcp } : {}) };
+ return { ...(v.argv ? { argv: pinRouting(v.argv, ctx.routing, { remote: ctx.transport === 'http' }) } : {}), ...(mcp ? { mcp } : {}) };
}
/** Render an Action for the caller's surface. Key order is part of the v1 goldens. */
@@ -242,7 +242,8 @@ export function renderAction(a: Action, ctx: RenderContext): RenderedAction {
const effective: Action = { ...a, mcp, actor };
const userMessage = a.user_message ?? (relay ? `Call the ${relay.tool} tool over MCP with ${JSON.stringify(relay.arguments)}; this command line cannot call it.` : undefined);
const verify = renderVerify(a.verify, ctx);
- const argv = a.argv ? pinRouting(a.argv, ctx.routing) : undefined;
+ const remote = { remote: ctx.transport === 'http' };
+ const argv = a.argv ? pinRouting(a.argv, ctx.routing, remote) : undefined;
const out: RenderedAction = {
...(argv ? { argv, command: shellQuote(argv) } : {}),
...(mcp ? { mcp } : {}),
@@ -256,7 +257,7 @@ export function renderAction(a: Action, ctx: RenderContext): RenderedAction {
requires_exclusive: a.requires_exclusive,
...(a.inputs?.length ? { inputs: a.inputs } : {}),
...(a.plan_hash ? { plan_hash: a.plan_hash } : {}),
- ...(a.preview_argv ? { preview_argv: pinRouting(a.preview_argv, ctx.routing) } : {}),
+ ...(a.preview_argv ? { preview_argv: pinRouting(a.preview_argv, ctx.routing, remote) } : {}),
...(a.then ? { then: renderAction(a.then, ctx) } : {}),
};
return out;
diff --git a/src/core/fix-routing.ts b/src/core/fix-routing.ts
index 3289f0d7b9..c762691e7b 100644
--- a/src/core/fix-routing.ts
+++ b/src/core/fix-routing.ts
@@ -22,7 +22,8 @@
* that renders a fix); the op half is registered by src/core/operations.ts.
*
* Flags already present are kept as written; the pin goes before a bare `--`
- * so it can never land in the positional lane.
+ * so it can never land in the positional lane. Over HTTP only the source id is
+ * pinned (a mount id is host topology; a thin client refuses `--brain`).
*/
import { CLI_FLAG_REGISTRY, CLI_ROUTING_FLAGS } from './cli-flag-registry.generated.ts';
import { ALL_SOURCES, SOURCE_ID_RE } from './source-id.ts';
@@ -33,7 +34,7 @@ const BRAIN_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
const pinnableSource = (s: string) => SOURCE_ID_RE.test(s) || s === ALL_SOURCES;
const SOURCE_SELECTORS = ['--source', '--source-id', '--all-sources', '--sources'];
-const opCommands = new Map<string, { ownsSource: boolean }>();
+const opCommands = new Map<string, { ownsSource: boolean; scopesSourceId: boolean }>();
/**
* Shared-op CLI names (primary + aliases, hidden excluded): every op routes the brain, and `--source`
@@ -42,27 +43,35 @@ const opCommands = new Map<string, { ownsSource: boolean }>();
export function registerOpRoutes(ops: Iterable<{ params: Record<string, unknown>; cliHints?: { name?: string; aliases?: readonly string[]; hidden?: boolean } }>): void {
for (const op of ops) {
if (!op.cliHints?.name || op.cliHints.hidden) continue;
- for (const name of [op.cliHints.name, ...(op.cliHints.aliases ?? [])]) opCommands.set(name, { ownsSource: 'source' in op.params });
+ for (const name of [op.cliHints.name, ...(op.cliHints.aliases ?? [])]) {
+ opCommands.set(name, { ownsSource: 'source' in op.params, scopesSourceId: 'source_id' in op.params });
+ }
}
}
-/** The routing flags a command accepts AND routes through (see the module comment). */
-export function routingFlagsFor(command: string): { brain: boolean; source: boolean } {
+/**
+ * The routing flags a command accepts AND routes through (see the module comment).
+ * `remote` (an HTTP render): a mount id is host topology, so `--brain` is never
+ * pinned there, and `--source` only where a thin client can send it (an op with a
+ * `source_id` scope, or a CLI command the brain host's operator runs).
+ */
+export function routingFlagsFor(command: string, opts: { remote?: boolean } = {}): { brain: boolean; source: boolean } {
const accepted = CLI_FLAG_REGISTRY[command];
if (accepted) {
const routed = CLI_ROUTING_FLAGS[command] ?? [];
- return { brain: accepted.includes('--brain') && routed.includes('--brain'), source: accepted.includes('--source') && routed.includes('--source') };
+ return { brain: !opts.remote && accepted.includes('--brain') && routed.includes('--brain'), source: accepted.includes('--source') && routed.includes('--source') };
}
const op = opCommands.get(command);
- return op ? { brain: true, source: !op.ownsSource } : { brain: false, source: false };
+ if (!op) return { brain: false, source: false };
+ return { brain: !opts.remote, source: !op.ownsSource && (!opts.remote || op.scopesSourceId) };
}
const hasFlag = (head: readonly string[], flag: string) => head.some(a => a === flag || a.startsWith(`${flag}=`));
/** Append the missing routing flags to one gbrain argv (before a bare `--`). Non-gbrain argv pass through. */
-export function pinRouting(argv: readonly string[], routing: FixRouting | undefined): string[] {
+export function pinRouting(argv: readonly string[], routing: FixRouting | undefined, opts: { remote?: boolean } = {}): string[] {
if (!routing || argv[0] !== 'gbrain' || argv.length < 2) return [...argv];
- const flags = routingFlagsFor(argv[1]!);
+ const flags = routingFlagsFor(argv[1]!, opts);
const end = argv.indexOf('--');
const head = end === -1 ? argv : argv.slice(0, end);
const add: string[] = [];
diff --git a/test/agent-journey-recovery.serial.test.ts b/test/agent-journey-recovery.serial.test.ts
index 160e66fadc..c945846e34 100644
--- a/test/agent-journey-recovery.serial.test.ts
+++ b/test/agent-journey-recovery.serial.test.ts
@@ -279,12 +279,13 @@ describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {
}, 120_000);
afterAll(() => { rmSync(home, { recursive: true, force: true }); });
- const exclusive: Array<{ label: string; args: () => string[]; done: (r: GbResult) => void }> = [
- { label: 'import --no-embed', args: () => ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'],
+ // `pin`: the A1 routing flags the rendered fix appends (apply-migrations always acts on the host config, so none).
+ const exclusive: Array<{ label: string; args: () => string[]; pin: string[]; done: (r: GbResult) => void }> = [
+ { label: 'import --no-embed', args: () => ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'], pin: ['--brain', 'host'],
done: r => expect(oneDocument(r, 'import').imported).toBe(2) },
- { label: 'doctor --remediate (approved)', args: () => ['doctor', '--remediate', '--yes', '--target-score', '50', '--json'],
+ { label: 'doctor --remediate (approved)', args: () => ['doctor', '--remediate', '--yes', '--target-score', '50', '--json'], pin: ['--brain', 'host'],
done: r => expect(oneDocument(r, 'doctor --remediate').exit_status).toBe(0) },
- { label: 'apply-migrations', args: () => ['apply-migrations', '--yes', '--no-autopilot-install', '--json'],
+ { label: 'apply-migrations', args: () => ['apply-migrations', '--yes', '--no-autopilot-install', '--json'], pin: [],
done: r => expect(oneDocument(r, 'apply-migrations').status).not.toBe('failed') },
];
@@ -302,7 +303,7 @@ describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {
expect(fix.argv).toEqual(['kill', String(owner.pid)]);
expect(fix.actor).toBe('user');
expect(fix.next).toBe('tell_user_to_run');
- expect(fix.then?.argv).toEqual(['gbrain', ...args]);
+ expect(fix.then?.argv).toEqual(['gbrain', ...args, ...row.pin]);
expect(fix.then?.next).toBe('run');
// Step one: the user stops the owning session. Step two: the agent runs `then` as given.
await owner.close();
@@ -323,7 +324,7 @@ describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {
expect((report.checks as Check[]).filter(c => c.status === 'fail').map(c => c.name)).toEqual([]);
const connection = (report.checks as Check[]).find(c => c.name === 'connection')!;
expect(connection.fix?.argv).toEqual(['kill', String(owner.pid)]);
- expect(connection.fix?.then?.argv).toEqual(['gbrain', 'doctor', '--json']);
+ expect(connection.fix?.then?.argv).toEqual(['gbrain', 'doctor', '--json', '--brain', 'host']);
expect((report.checks as Check[]).filter(c => c.status === 'warn' && !c.fix?.argv).map(c => c.name)).toEqual([]);
} finally { await owner.close(); }
}, 300_000);
diff --git a/test/fix-routing.test.ts b/test/fix-routing.test.ts
index c599a5943c..9ad6313a20 100644
--- a/test/fix-routing.test.ts
+++ b/test/fix-routing.test.ts
@@ -96,11 +96,16 @@ describe('render-time pin', () => {
expect(env.suggestion).toContain('gbrain get a --brain teambrain --source wiki');
});
- test('HTTP keeps the target ids (non-sensitive) and still strips paths', () => {
+ test('HTTP keeps only the source id (no mount topology), where a thin client can send it, and still strips paths', () => {
const http: RenderContext = { ...cli, transport: 'http' };
const env = toAgentError(opError('invalid_params', 'bad', 'Fix it.', { fix: read(['gbrain', 'import', '/home/alice-example/notes']) }), { transport: 'http', render: http });
- expect(env.fix?.argv).toEqual(['gbrain', 'import', '<path>', '--brain', 'teambrain', '--source', 'wiki']);
+ expect(env.fix?.argv).toEqual(['gbrain', 'import', '<path>', '--source', 'wiki']);
expect(JSON.stringify(env)).not.toContain('/home/alice-example');
+ expect(JSON.stringify(env)).not.toContain('teambrain');
+ expect(renderAction(read(['gbrain', 'get', 'a']), http).argv).toEqual(['gbrain', 'get', 'a', '--source', 'wiki']);
+ // write-request has no source_id scope: a thin client would refuse an explicit --source there.
+ expect(renderAction(read(['gbrain', 'write-request', '--', 'x']), http).argv).toEqual(['gbrain', 'write-request', '--', 'x']);
+ expect(renderAction(read(['gbrain', 'doctor', '--json']), http).argv).toEqual(['gbrain', 'doctor', '--json']);
});
test('cliRenderContext reads the installed CLI routing; the first resolved source wins', () => {