Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(closeout): A1/DX-7 central render-time --brain/--source pin for every CLI fix

garrytan7ede913d5950
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index c5b24a5274..8b27a3302d 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -59,9 +59,13 @@ gbrain returns (`isError: true`, the envelope shown parsed):
"gbrain",
"list",
"--sort",
- "updated"
+ "updated",
+ "--brain",
+ "host",
+ "--source",
+ "default"
],
- "command": "gbrain list --sort updated",
+ "command": "gbrain list --sort updated --brain host --source default",
"mcp": {
"tool": "list_pages",
"arguments": {
@@ -112,7 +116,7 @@ stdout (`--json`):
"error": "confirmation_required",
"code": "confirmation_required",
"message": "doctor --remediate needs the user's approval before it runs; nothing was changed.",
- "suggestion": "Ask the user: Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed? If they agree, run: gbrain doctor --remediate --max-usd 0.60 --yes",
+ "suggestion": "Ask the user: Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed? If they agree, run: gbrain doctor --remediate --max-usd 0.60 --yes --brain host",
"effects": [
"paid"
],
@@ -128,9 +132,11 @@ stdout (`--json`):
"--remediate",
"--max-usd",
"0.60",
- "--yes"
+ "--yes",
+ "--brain",
+ "host"
],
- "command": "gbrain doctor --remediate --max-usd 0.60 --yes",
+ "command": "gbrain doctor --remediate --max-usd 0.60 --yes --brain host",
"consent": [
"paid"
],
@@ -143,7 +149,9 @@ stdout (`--json`):
"gbrain",
"doctor",
"--remediation-plan",
- "--json"
+ "--json",
+ "--brain",
+ "host"
]
},
"preview": {
@@ -151,9 +159,11 @@ stdout (`--json`):
"gbrain",
"doctor",
"--remediation-plan",
- "--json"
+ "--json",
+ "--brain",
+ "host"
],
- "command": "gbrain doctor --remediation-plan --json"
+ "command": "gbrain doctor --remediation-plan --json --brain host"
},
"preapprove_argv": [
"gbrain",
@@ -181,15 +191,15 @@ risk: Spends up to the cap on embedding calls; no data is deleted.
consent: paid
actor: agent
next: ask_user
-if_yes: gbrain doctor --remediate --max-usd 0.60 --yes — To stop asking for runs under a limit the user picks: gbrain config set consent.preapprove.paid.max_usd_per_run '<usd>'
-if_no: Nothing runs; nothing was changed. To look first (read-only): gbrain doctor --remediation-plan --json
+if_yes: gbrain doctor --remediate --max-usd 0.60 --yes --brain host — To stop asking for runs under a limit the user picks: gbrain config set consent.preapprove.paid.max_usd_per_run '<usd>'
+if_no: Nothing runs; nothing was changed. To look first (read-only): gbrain doctor --remediation-plan --json --brain host
[SHOW USER]
Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?
[/SHOW USER]
[/AGENT]
```
-Nothing ran and the command exited 3. The agent reads `fix.next: ask_user`, relays `user_message` ("Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?") and stops. It may offer the read-only preview `gbrain doctor --remediation-plan --json`. Only after the user agrees does it run `gbrain doctor --remediate --max-usd 0.60 --yes`. Passing `--yes` on its own would be a consent violation even though gbrain cannot tell the difference.
+Nothing ran and the command exited 3. The agent reads `fix.next: ask_user`, relays `user_message` ("Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?") and stops. It may offer the read-only preview `gbrain doctor --remediation-plan --json --brain host`. Only after the user agrees does it run `gbrain doctor --remediate --max-usd 0.60 --yes --brain host`. Passing `--yes` on its own would be a consent violation even though gbrain cannot tell the difference.
### 3. An empty recall with a notice: `tell_user_to_run`
@@ -212,12 +222,12 @@ gbrain returns these content blocks:
```text
[gbrain notice empty_retrieval kind=info]
why: No pages matched. Search ran keyword-only because embeddings are not configured.
-fix: gbrain doctor --json
+fix: gbrain doctor --json --brain host
next: tell_user_to_run
user_message: I found no notes on that topic. Your brain searches keywords only right now.
```
-`content[0]` is still the bare array `[]`; the second block is the notice. The agent does not tell the user "you have no notes on that". It relays `user_message` ("I found no notes on that topic. Your brain searches keywords only right now."). `fix.next` is `tell_user_to_run` because the fix is the user's to run (`gbrain doctor --json`) in their terminal, so the agent offers it rather than running it.
+`content[0]` is still the bare array `[]`; the second block is the notice. The agent does not tell the user "you have no notes on that". It relays `user_message` ("I found no notes on that topic. Your brain searches keywords only right now."). `fix.next` is `tell_user_to_run` because the fix is the user's to run (`gbrain doctor --json --brain host`) in their terminal, so the agent offers it rather than running it.
### 4. First run on a keyless brain: one decision bundle, `ask_user` (journey)
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 7f36889d95..45a4e1b9d7 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -343,6 +343,22 @@ export function segmentDispatchBlocks(fnSrc: string): Map<string, string> {
/** @param root repository root; a fixture tree in tests (test/cli-synthetic-command.test.ts). */
export function buildFlagRegistry(root: string = ROOT): Record<string, string[]> {
+ return buildFlagArtifacts(root).registry;
+}
+
+/**
+ * Routing flags each CLI-only command CONSUMES, as opposed to merely accepts
+ * (every command accepts `--brain`/`--source` through UNIVERSAL_FLAGS). A1's
+ * render-time routing pin (src/core/fix-routing.ts) appends `--source` only to
+ * commands with consumption evidence (the tight-quoted `'--source'` literal in
+ * the command's own code, the SAFETY_FLAGS rule) and `--brain` to pre-connect
+ * commands only when their code reads the global brain option.
+ */
+export function buildRoutingConsumers(root: string = ROOT): Record<string, string[]> {
+ return buildFlagArtifacts(root).routing;
+}
+
+function buildFlagArtifacts(root: string): { registry: Record<string, string[]>; routing: Record<string, string[]> } {
// CLI_ONLY membership: one record per command in the command table
// (src/cli/command-table.ts), read by AST so the generator never executes
// the table.
@@ -393,6 +409,7 @@ export function buildFlagRegistry(root: string = ROOT): Record<string, string[]>
new RegExp(`['"\`]${flag}['"\`]`).test(text);
const registry: Record<string, string[]> = {};
+ const routing: Record<string, string[]> = {};
for (const command of commands) {
const parts = blocks.get(command) ?? [];
const flags = new Set<string>(UNIVERSAL_FLAGS);
@@ -456,15 +473,21 @@ export function buildFlagRegistry(root: string = ROOT): Record<string, string[]>
if (flags.has(f) && !consumes(depthZeroText, f)) flags.delete(f);
}
registry[command] = [...flags].sort();
+ const consumed = [
+ ...(/getCliOptions\(\)\.brain|cliOpts\.brain/.test(depthZeroText) ? ['--brain'] : []),
+ ...(consumes(depthZeroText, '--source') ? ['--source'] : []),
+ ];
+ if (consumed.length) routing[command] = consumed;
}
- return registry;
+ return { registry, routing };
}
-export function renderRegistryModule(registry: Record<string, string[]>): string {
- const entries = Object.keys(registry)
+export function renderRegistryModule(registry: Record<string, string[]>, routing: Record<string, string[]> = {}): string {
+ const render = (map: Record<string, string[]>) => Object.keys(map)
.sort()
- .map(cmd => ` '${cmd}': [${registry[cmd].map(f => `'${f}'`).join(', ')}],`)
+ .map(cmd => ` '${cmd}': [${map[cmd].map(f => `'${f}'`).join(', ')}],`)
.join('\n');
+ const entries = render(registry);
return `// AUTO-GENERATED by scripts/generate-flag-registry.ts — do not edit by hand.
// Regenerate: bun run build:flag-registry
// Freshness + drift pinned by test/cli-flag-validation.test.ts (#2185).
@@ -483,13 +506,21 @@ export function renderRegistryModule(registry: Record<string, string[]>): string
export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
${entries}
};
+
+// Routing flags a command CONSUMES (A1 render-time pin, src/core/fix-routing.ts):
+// '--source' when the command's own code reads the tight-quoted literal,
+// '--brain' when it reads the global brain option. Acceptance alone (every
+// command accepts both) is not evidence the flag routes anything.
+export const CLI_ROUTING_FLAG_CONSUMERS: Record<string, readonly string[]> = {
+${render(routing)}
+};
`;
}
if (import.meta.main) {
- const registry = buildFlagRegistry();
+ const { registry, routing } = buildFlagArtifacts(ROOT);
const outPath = join(ROOT, 'src/core/cli-flag-registry.generated.ts');
- writeFileSync(outPath, renderRegistryModule(registry));
+ writeFileSync(outPath, renderRegistryModule(registry, routing));
const n = Object.keys(registry).length;
const total = Object.values(registry).reduce((a, v) => a + v.length, 0);
console.log(`wrote ${outPath} (${n} commands, ${total} flag entries)`);
diff --git a/src/cli.ts b/src/cli.ts
index 3576b1ac55..c07a054ebe 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -31,6 +31,7 @@ import type { AIGatewayConfig } from './core/ai/types.ts';
import type { BrainEngine } from './core/engine.ts';
import { operations, OperationError } from './core/operations.ts';
import { resolveSourceIdEngineFree } from './core/source-resolver.ts';
+import { installCliRouting, recordedSource, routingFlagsFor, type FixRouting } from './core/fix-routing.ts';
import { formatVolunteeredPage } from './core/context/volunteer.ts';
import type { Operation, OperationContext } from './core/operations.ts';
import { currentCliWriteWait } from './core/persistence/write-wait.ts';
@@ -299,6 +300,41 @@ function maybeEmitUpdateMarker(command: string): void {
}
}
+/**
+ * A1: the routing every CLI-surface fix in this invocation pins
+ * (src/core/fix-routing.ts). Brain: the id connectEngine resolves (flag →
+ * GBRAIN_BRAIN_ID → .gbrain-mount → mount path → host). Source: the first
+ * source the invocation resolved through the ambient chain, else the
+ * engine-free tiers for a command that routes `--source`. A thin client pins
+ * nothing: it has no local mounts (`--brain` is refused there) and its remote
+ * scopes the source.
+ */
+function cliRoutingProvider(currentCommand: () => string | undefined, args: readonly string[]): () => FixRouting | undefined {
+ let base: { thin: boolean; brain?: string; source?: string } | null = null;
+ return () => {
+ if (!base) {
+ const thin = isThinClient(loadConfig());
+ let brain: string | undefined;
+ let source: string | undefined;
+ if (!thin) {
+ try { brain = resolveBrainIdForDbMarker(getCliOptions().brain); } catch { /* unresolvable: no brain pin */ }
+ const cmd = currentCommand();
+ if (cmd && routingFlagsFor(cmd).source) {
+ const end = args.indexOf('--');
+ const head = end === -1 ? args : args.slice(0, end);
+ const i = head.findIndex(a => a === '--source' || a.startsWith('--source='));
+ const explicit = i === -1 ? null : head[i]!.startsWith('--source=') ? head[i]!.slice('--source='.length) : head[i + 1] ?? null;
+ try { source = resolveSourceIdEngineFree(explicit) ?? undefined; } catch { /* invalid: no source pin */ }
+ }
+ }
+ base = { thin, brain, source };
+ }
+ if (base.thin) return undefined;
+ const source = recordedSource() ?? base.source;
+ return { ...(base.brain ? { brain: base.brain } : {}), ...(source ? { source } : {}) };
+ };
+}
+
async function main() {
// cwd-.env quarantine → ~/.gbrain/.env → #3688 guardrails loader (fail-closed).
await runCliPreflight();
@@ -311,6 +347,7 @@ async function main() {
setCliOptions(cliOpts);
let command = args[0];
+ installCliRouting(cliRoutingProvider(() => command, args));
if (!command || command === '--help' || command === '-h') {
printHelp();
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 430f48c649..dde67a87fd 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -101,6 +101,13 @@ interface CliCommandBase {
startup?: 'observational';
/** Honours a bare `--` as end of options (positionals after it are never flags). */
end_of_options?: true;
+ /**
+ * A1: the command's target source resolves through the ambient chain
+ * (`--source` → GBRAIN_SOURCE → .gbrain-source → …), so a fix naming it
+ * carries `--source <id>` (src/core/fix-routing.ts). Requires consumption
+ * evidence in the generated registry (test/fix-routing.test.ts).
+ */
+ routes_source?: true;
/** D3: lazy curated help module. */
help?: () => Promise<{ help: CliHelpSpec }>;
}
@@ -217,20 +224,20 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// codes). Without this the generic stub hides it.
// thin client: cathedral-5: compiled views read the LOCAL brain (thin clients have no engine to
// compile from; remote-brain support is a filed follow-up).
- { name: 'compile-context', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/compile-context.ts') },
+ { name: 'compile-context', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/compile-context.ts') },
{ name: 'smoke-test', phase: 'pre-connect', thinClient: 'none', load: () => import('./commands/smoke-test.ts') },
// selfHelp: #4152: dream ships its own printHelp AND the `dream retriage --help` subverb help
// (dispatched engine-free before parseArgs). The generic stub would hide both — `gbrain dream
// retriage --help` printed the one-line dream stub instead of the retriage contract (outside-voice
// CX9).
// thin client: v0.31.1 (CDX-2 op coverage matrix): more local-only commands
- { name: 'dream', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/dream.ts') },
+ { name: 'dream', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/dream.ts') },
// System One decide: local CLI only (calibrate, receipts and proposals are trusted-local); help and a
// key-only probe answer without a brain, so the module opens its own engine.
{ name: 'decide', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/decide.ts') },
// #5836 facts relink: trusted local CLI only (publishes onto the host's entity pages through the write
// coordinator); help answers without a brain, so the module opens its own engine.
- { name: 'facts', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/facts.ts') },
+ { name: 'facts', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/facts.ts') },
// #5401: projections drain refuses a resident-held PGLite brain before any engine opens, so the
// module opens its own engine. Trusted local CLI only (not an operation).
{ name: 'projections', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/projections.ts') },
@@ -239,21 +246,21 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: v0.39.3.0 WARN-5: capture's detailed HELP constant (src/commands/capture.ts:90+) was
// unreachable because the dispatcher's generic short-circuit (printCliOnlyHelp at :204-208) fired
// before runCapture saw --help. brainstorm + lsd were already in the set; capture was the holdout.
- { name: 'capture', phase: 'pre-connect-own-engine', thinClient: 'none', selfHelp: true, dispatchedBy: 'deferred-persistence', load: () => import('../commands/persistence-delegate.ts') },
+ { name: 'capture', phase: 'pre-connect-own-engine', thinClient: 'none', selfHelp: true, dispatchedBy: 'deferred-persistence', routes_source: true, load: () => import('../commands/persistence-delegate.ts') },
{ name: 'forget', phase: 'pre-connect-own-engine', thinClient: 'none', dispatchedBy: 'deferred-persistence', load: () => import('../commands/persistence-delegate.ts') },
{ name: 'call', phase: 'pre-connect-own-engine', thinClient: 'refuse', dispatchedBy: 'deferred-persistence', load: () => import('../commands/persistence-delegate.ts') },
// Post-connect: dispatched by dispatchConnectedCommand after connectEngine(), in master switch order.
{ name: 'mcp', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/mcp.ts') },
- { name: 'import', phase: 'post-connect', thinClient: 'none', json: 'document', help: () => import('./help/import.ts'), load: () => import('./commands/import.ts') },
- { name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/export.ts') },
- { name: 'files', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/files.ts') },
- { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/embed.ts') },
+ { name: 'import', phase: 'post-connect', thinClient: 'none', json: 'document', help: () => import('./help/import.ts'), routes_source: true, load: () => import('./commands/import.ts') },
+ { name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/export.ts') },
+ { name: 'files', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/files.ts') },
+ { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/embed.ts') },
{ name: 'serve', phase: 'post-connect', thinClient: 'refuse', help: () => import('./help/serve.ts'), load: () => import('./commands/serve.ts') },
// thin client: Agent-bootstrap [CX2-5]: the maintenance sweep runs against the LOCAL engine (the
// serve-resident sweep's trusted CLI entry). On a thin client it would fabricate a scratch PGLite
// and sweep nothing anyone reads. `bootstrap` and `hook` are deliberately NOT here (ENG-2).
- { name: 'sweep', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/sweep.ts') },
+ { name: 'sweep', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/sweep.ts') },
// thin client: scratch-DB audit: `config` get/set operate on the host brain's config plane (DB
// rows / host file-plane). On a thin client they fabricated an ephemeral local PGLite (full
// migration replay per call) and read/wrote config nobody would ever see. NOTE: `jobs` is
@@ -284,20 +291,20 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: v0.37 fix wave (Lane D.4 + CDX2-12): sync's --no-embed flag was unreachable via help
// because the dispatcher's generic CLI-only short-circuit fired before runSync could print its own
// usage block. Adding `sync` here routes `gbrain sync --help` into runSync.
- { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/sync.ts') },
+ { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/sync.ts') },
// selfHelp: #3834: extract ships detailed help for its mode-specific flags. Keep the generic
// CLI-only stub from hiding that contract.
- { name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/extract.ts') },
+ { name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/extract.ts') },
// selfHelp: v0.41.11.0 — extract-conversation-facts ships its own detailed HELP describing segment
// splitting + checkpointing + budget caps + the unified types config story. Route around the
// generic short-circuit.
{ name: 'extract-conversation-facts', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/extract-conversation-facts.ts') },
// selfHelp: v0.41.39 (#1700) — enrich ships its own detailed HELP (ordering, budget best-effort
// caveat, provenance, --reenrich-after). Route around the stub.
- { name: 'enrich', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/enrich.ts') },
+ { name: 'enrich', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/enrich.ts') },
{ name: 'features', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/features.ts') },
{ name: 'autopilot', phase: 'post-connect', thinClient: 'none', help: () => import('./help/autopilot.ts'), load: () => import('./commands/autopilot.ts') },
- { name: 'graph-query', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/graph-query.ts') },
+ { name: 'graph-query', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/graph-query.ts') },
{ name: 'reconcile-links', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/reconcile-links.ts') },
// selfHelp: gbrain repair prints REPAIR_HELP (kinds + dry-run/apply contract).
// thin client: Wave 2 repair core: repairs publish coordinated writes on the brain host.
@@ -311,7 +318,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'status', phase: 'post-connect', thinClient: 'none', help: () => import('./help/status.ts'), load: () => import('./commands/status.ts') },
{ name: 'advisor', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/advisor.ts') },
{ name: 'conversation-parser', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/conversation-parser.ts') },
- { name: 'edges-backfill', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/edges-backfill.ts') },
+ { name: 'edges-backfill', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/edges-backfill.ts') },
// CLI_ONLY: #2035 class (wired the #3502 way): `case 'whoknows'` had a live handler (runWhoknows:
// ranked table, per-factor explain, thin-client routing) that was shadowed by find_experts'
// non-hidden cliHints. The op hint is now hidden (ops/insights.ts); this entry makes the richer
@@ -323,10 +330,10 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: v0.41.20.0 skillopt's detailed HELP constant lives in src/core/skillopt/help.ts;
// --help routes there via the dispatcher.
{ name: 'skillopt', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/skillopt.ts') },
- { name: 'calibration', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/calibration.ts') },
+ { name: 'calibration', phase: 'post-connect', thinClient: 'none', routes_source: true, load: () => import('./commands/calibration.ts') },
// selfHelp: cathedral-4: transcripts ships its own HELP (the ingest import lane + the v0.29 recent
// reader). Without this the generic stub hides both.
- { name: 'transcripts', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/transcripts.ts') },
+ { name: 'transcripts', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/transcripts.ts') },
{ name: 'models', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/models.ts') },
// selfHelp: `gbrain takes --help` printed the generic one-line stub, so the nine subcommands
// (add/update/supersede/resolve/scorecard/calibration/revisit/ extract/search) were undiscoverable
@@ -340,8 +347,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'takes', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/takes.ts') },
{ name: 'onboard', phase: 'post-connect', thinClient: 'none', help: () => import('./help/onboard.ts'), load: () => import('./commands/onboard.ts') },
{ name: 'founder', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/founder.ts') },
- { name: 'think', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/think.ts') },
- { name: 'recall', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/recall.ts') },
+ { name: 'think', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/think.ts') },
+ { name: 'recall', phase: 'post-connect', thinClient: 'none', routes_source: true, load: () => import('./commands/recall.ts') },
// CLI_ONLY: v0.42.58 (#2035 class, caught by the handleCliOnly reachability sweep): full handler
// at `case 'notability-eval'` but never dispatchable.
{ name: 'notability-eval', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/notability-eval.ts') },
@@ -353,8 +360,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// pointer circular and those subcommands undiscoverable from the CLI in either direction.
{ name: 'sources', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/sources.ts') },
// CLI_ONLY: Open-loop engine CLI (engine-bound; trusted-local op dispatch).
- { name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/waiting.ts') },
- { name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/loops.ts') },
+ { name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/waiting.ts') },
+ { name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/loops.ts') },
// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with the
// per-subcommand usage; keep the generic short-circuit from hiding it.
{ name: 'connectors', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connectors.ts') },
@@ -371,16 +378,16 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get the
// volunteer_context MCP op instead.
- { name: 'watch', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/watch.ts') },
+ { name: 'watch', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/watch.ts') },
{ name: 'storage', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/storage.ts') },
- { name: 'code-def', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/code-def.ts') },
- { name: 'code-refs', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/code-refs.ts') },
- { name: 'reindex-code', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/reindex-code.ts') },
+ { name: 'code-def', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/code-def.ts') },
+ { name: 'code-refs', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/code-refs.ts') },
+ { name: 'reindex-code', phase: 'post-connect', thinClient: 'none', routes_source: true, load: () => import('./commands/reindex-code.ts') },
{ name: 'reindex-search-vector', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/reindex-search-vector.ts') },
{ name: 'reindex-frontmatter', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/reindex-frontmatter.ts') },
{ name: 'backfill', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/backfill.ts') },
- { name: 'code-callers', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/code-callers.ts') },
- { name: 'code-callees', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/code-callees.ts') },
+ { name: 'code-callers', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/code-callers.ts') },
+ { name: 'code-callees', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/code-callees.ts') },
{ name: 'repos', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/repos.ts') },
];
diff --git a/src/commands/db-repair.ts b/src/commands/db-repair.ts
index 7deb1020e3..324b9043f3 100644
--- a/src/commands/db-repair.ts
+++ b/src/commands/db-repair.ts
@@ -49,6 +49,7 @@ import {
} from '../core/config.ts';
import { HOST_BRAIN_ID, loadMounts } from '../core/brain-registry.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
+import { getCliOptions } from '../core/cli-options.ts';
import { connectWithRetry } from '../core/db.ts';
import { createEngine } from '../core/engine-factory.ts';
import { deriveSessionPoolerUrl } from '../core/connection-manager.ts';
@@ -379,7 +380,7 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDe
return refuse(opts.json, 2, '--undo-last-rewrite requires --yes.', 'invalid_params', 'Example: gbrain db-repair --yes --undo-last-rewrite');
}
- const brainId = resolveBrainId(null);
+ const brainId = resolveBrainId(getCliOptions().brain);
// A mount outage must never repair — or rewrite — the HOST config.
if (brainId !== HOST_BRAIN_ID) {
@@ -387,8 +388,8 @@ export async function runDbRepair(args: string[], deps: DbRepairDeps = defaultDe
return refuse(opts.json, 1,
`db-repair targets the host brain, but this context resolves to mount '${brainId}'` +
(mount ? ` (engine ${mount.engine}, ${mount.database_url ? 'url: ' + redactPgUrl(mount.database_url) : 'path: ' + (mount.database_path ?? '?')})` : '') +
- `.\nMount-targeted repair is not supported yet — fix that brain on its host, or unset GBRAIN_BRAIN_ID/.gbrain-mount to repair the host brain.`,
- 'config_error', 'Run db-repair on the mounted brain\'s host, or unset GBRAIN_BRAIN_ID / remove .gbrain-mount to repair the host brain.');
+ `.\nMount-targeted repair is not supported yet — fix that brain on its host, or pass --brain host to repair the host brain.`,
+ 'config_error', 'Run db-repair on the mounted brain\'s host, or pass --brain host (or unset GBRAIN_BRAIN_ID / remove .gbrain-mount) to repair the host brain.');
}
const cfg = loadConfig();
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 1eb4671cff..20c494f4df 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -21,6 +21,7 @@ import { classifyPgAccessError, formatDbAccessMarker } from './pg-access-classif
import { redactConnectionInfo } from './audit/redact-connection-info.ts';
import { redactUrlsInText } from './url-redact.ts';
import { recordAgentContractEvent } from './agent-contract-log.ts';
+import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';
export const CONTRACT_VERSION = 1 as const;
@@ -99,6 +100,8 @@ export interface RenderContext {
isCallable(opName: string): boolean;
preapproved(effects: Effect[], estUsd?: number | null): boolean;
principal?: string;
+ /** A1: the brain/source the failing call acted on; renderAction pins them into gbrain argv (src/core/fix-routing.ts). */
+ routing?: FixRouting;
}
export interface AgentErrorContext {
@@ -122,7 +125,8 @@ export interface NoticeSink { emitNotice(n: Notice): void }
/** The trusted local CLI: no MCP tool is callable from a shell, nothing is preapproved unless A4 says so. */
export function cliRenderContext(overrides: Partial<RenderContext> = {}): RenderContext {
- return { transport: 'cli', isCallable: () => false, preapproved: () => false, ...overrides };
+ const routing = cliRouting();
+ return { transport: 'cli', isCallable: () => false, preapproved: () => false, ...(routing ? { routing } : {}), ...overrides };
}
// ── text safety ────────────────────────────────────────────────────────────
@@ -222,7 +226,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: v.argv } : {}), ...(mcp ? { mcp } : {}) };
+ return { ...(v.argv ? { argv: pinRouting(v.argv, ctx.routing) } : {}), ...(mcp ? { mcp } : {}) };
}
/** Render an Action for the caller's surface. Key order is part of the v1 goldens. */
@@ -232,8 +236,9 @@ export function renderAction(a: Action, ctx: RenderContext): RenderedAction {
const actor: Actor = cliOnlyOnMcp ? (ctx.transport === 'http' ? 'host_admin' : 'user') : a.actor;
const effective: Action = { ...a, mcp, actor };
const verify = renderVerify(a.verify, ctx);
+ const argv = a.argv ? pinRouting(a.argv, ctx.routing) : undefined;
const out: RenderedAction = {
- ...(a.argv ? { argv: a.argv, command: shellQuote(a.argv) } : {}),
+ ...(argv ? { argv, command: shellQuote(argv) } : {}),
...(mcp ? { mcp } : {}),
consent: a.consent,
actor,
@@ -245,7 +250,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: a.preview_argv } : {}),
+ ...(a.preview_argv ? { preview_argv: pinRouting(a.preview_argv, ctx.routing) } : {}),
...(a.then ? { then: renderAction(a.then, ctx) } : {}),
};
return out;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 265233a9ae..625c9ebdb3 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -44,7 +44,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],
- 'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--probe', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
+ 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
@@ -131,3 +131,59 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--types', '--url', '--yes'],
};
+
+// Routing flags a command CONSUMES (A1 render-time pin, src/core/fix-routing.ts):
+// '--source' when the command's own code reads the tight-quoted literal,
+// '--brain' when it reads the global brain option. Acceptance alone (every
+// command accepts both) is not evidence the flag routes anything.
+export const CLI_ROUTING_FLAG_CONSUMERS: Record<string, readonly string[]> = {
+ 'agent': ['--source'],
+ 'auth': ['--brain', '--source'],
+ 'backup': ['--brain'],
+ 'cache': ['--source'],
+ 'calibration': ['--source'],
+ 'capture': ['--source'],
+ 'claw-test': ['--source'],
+ 'code-callees': ['--source'],
+ 'code-callers': ['--source'],
+ 'code-def': ['--source'],
+ 'code-refs': ['--source'],
+ 'compile-context': ['--source'],
+ 'config': ['--brain'],
+ 'connectors': ['--source'],
+ 'db-repair': ['--brain'],
+ 'decide': ['--source'],
+ 'doctor': ['--brain', '--source'],
+ 'dream': ['--source'],
+ 'edges-backfill': ['--source'],
+ 'embed': ['--brain', '--source'],
+ 'embeddings': ['--brain'],
+ 'enrich': ['--source'],
+ 'eval': ['--source'],
+ 'export': ['--source'],
+ 'extract': ['--brain', '--source'],
+ 'facts': ['--source'],
+ 'files': ['--source'],
+ 'frontmatter': ['--source'],
+ 'graph-query': ['--source'],
+ 'import': ['--source'],
+ 'loops': ['--source'],
+ 'mcp': ['--source'],
+ 'orphans': ['--source'],
+ 'pricing': ['--source'],
+ 'projections': ['--brain'],
+ 'recall': ['--brain', '--source'],
+ 'reindex': ['--source'],
+ 'reindex-code': ['--brain', '--source'],
+ 'reindex-frontmatter': ['--source'],
+ 'repair': ['--source'],
+ 'repos': ['--source'],
+ 'schema': ['--source'],
+ 'sources': ['--source'],
+ 'sweep': ['--brain', '--source'],
+ 'sync': ['--brain', '--source'],
+ 'think': ['--source'],
+ 'transcripts': ['--source'],
+ 'waiting': ['--source'],
+ 'watch': ['--source'],
+};
diff --git a/src/core/consent.ts b/src/core/consent.ts
index fba4078dfe..fbeb8bd4d5 100644
--- a/src/core/consent.ts
+++ b/src/core/consent.ts
@@ -298,7 +298,7 @@ export function confirmationPayload(req: ConsentRequest, ctx: RenderContext): Co
est_usd: req.est_usd ?? null,
user_message: req.user_message,
fix: rendered,
- preview: req.preview_argv ? { argv: req.preview_argv, command: shellQuote(req.preview_argv) } : null,
+ preview: rendered.preview_argv ? { argv: rendered.preview_argv, command: shellQuote(rendered.preview_argv) } : null,
...(req.plan_hash ? { plan_hash: req.plan_hash } : {}),
...(paid && !destructive ? { preapprove_argv: preapprovalCommand(PREAPPROVE_PAID_MAX_USD_PER_RUN, '<usd>') } : {}),
docs_cmd: ['gbrain', 'errors', 'confirmation_required'],
diff --git a/src/core/fix-routing.ts b/src/core/fix-routing.ts
new file mode 100644
index 0000000000..17b4cdfd2c
--- /dev/null
+++ b/src/core/fix-routing.ts
@@ -0,0 +1,115 @@
+/**
+ * A1 explicit routing for every CLI fix (docs/designs/AGENT_OPERATOR_WAVE.md,
+ * DX-7): a rendered `fix.argv` names the brain and source the failing call
+ * acted on, so the agent can run it later from another directory or under a
+ * different GBRAIN_BRAIN_ID / GBRAIN_SOURCE / .gbrain-mount / .gbrain-source
+ * and still act on the intended brain.
+ *
+ * The pin is applied once, at render time (`renderAction`), to every gbrain
+ * argv in the action (`argv`, `preview_argv`, `verify.argv`, `then`):
+ *
+ * - `--brain <id>` is appended for commands that route through the brain axis:
+ * every shared op, every CLI-only command that opens its engine through the
+ * connect terminator (phase other than `pre-connect`), and pre-connect
+ * commands whose own code reads the global brain option
+ * (CLI_ROUTING_FLAG_CONSUMERS, generated).
+ * - `--source <id>` is appended for commands whose target source resolves
+ * through the ambient chain: every shared op (makeContext's resolver; ops
+ * that own a `source` param are excluded) and CLI-only commands that declare
+ * `routes_source` in the command table (each one consumes `--source` per the
+ * generated registry; test/fix-routing.test.ts pins that).
+ *
+ * Flags already present are kept as written; the pin goes before a bare `--`
+ * so it can never land in the positional lane.
+ */
+import { CLI_COMMANDS, type CliCommandRecord } from '../cli/command-table.ts';
+import { CLI_FLAG_REGISTRY, CLI_ROUTING_FLAG_CONSUMERS } from './cli-flag-registry.generated.ts';
+import { ALL_SOURCES, SOURCE_ID_RE } from './source-id.ts';
+
+export interface FixRouting { brain?: string; source?: string }
+
+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'];
+
+let cliRecords: Map<string, CliCommandRecord> | null = null;
+const opCommands = new Map<string, { ownsSource: boolean }>();
+
+/** Shared-op CLI names (primary + aliases) and whether the op owns a `source` param (then --source is not routing). */
+export function registerOpRoutes(entries: Iterable<readonly [cliName: string, ownsSource: boolean]>): void {
+ for (const [name, ownsSource] of entries) opCommands.set(name, { ownsSource });
+}
+
+function record(command: string): CliCommandRecord | undefined {
+ cliRecords ??= new Map(CLI_COMMANDS.map(r => [r.name, r]));
+ return cliRecords.get(command);
+}
+
+/** The routing flags a command accepts AND routes through (see the module comment). */
+export function routingFlagsFor(command: string): { brain: boolean; source: boolean } {
+ const rec = record(command);
+ if (rec) {
+ const accepted = CLI_FLAG_REGISTRY[command] ?? [];
+ const consumed = CLI_ROUTING_FLAG_CONSUMERS[command] ?? [];
+ return {
+ brain: accepted.includes('--brain') && (rec.phase !== 'pre-connect' || consumed.includes('--brain')),
+ source: accepted.includes('--source') && rec.routes_source === true,
+ };
+ }
+ const op = opCommands.get(command);
+ return op ? { brain: true, source: !op.ownsSource } : { brain: false, source: false };
+}
+
+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[] {
+ if (!routing || argv[0] !== 'gbrain' || argv.length < 2) return [...argv];
+ const flags = routingFlagsFor(argv[1]!);
+ const end = argv.indexOf('--');
+ const head = end === -1 ? argv : argv.slice(0, end);
+ const add: string[] = [];
+ if (flags.brain && routing.brain && BRAIN_ID_RE.test(routing.brain) && !hasFlag(head, '--brain')) add.push('--brain', routing.brain);
+ if (flags.source && routing.source && pinnableSource(routing.source) && !SOURCE_SELECTORS.some(f => hasFlag(head, f))) {
+ add.push('--source', routing.source);
+ }
+ if (add.length === 0) return [...argv];
+ return end === -1 ? [...argv, ...add] : [...argv.slice(0, end), ...add, ...argv.slice(end)];
+}
+
+// ── the CLI process's resolved routing ─────────────────────────────────────
+
+let cliProvider: (() => FixRouting | undefined) | null = null;
+let resolvedSource: string | undefined;
+let recording = false;
+
+/**
+ * Installed by src/cli.ts once global flags are parsed: the default routing
+ * for every CLI-surface render in this process (cliRenderContext). Also turns
+ * on source recording, so the first source this invocation resolves through
+ * the ambient chain becomes the pinned source.
+ */
+export function installCliRouting(provider: () => FixRouting | undefined): void {
+ cliProvider = provider;
+ recording = true;
+}
+
+/** Called by the source resolver: the first source an invocation resolves is the one its fixes pin. */
+export function noteResolvedSource(sourceId: string): void {
+ if (recording && resolvedSource === undefined && pinnableSource(sourceId)) resolvedSource = sourceId;
+}
+
+export function recordedSource(): string | undefined {
+ return resolvedSource;
+}
+
+export function cliRouting(): FixRouting | undefined {
+ try { return cliProvider?.(); } catch { return undefined; }
+}
+
+/** Test seam: drop the provider and the recorded source. */
+export function __resetCliRoutingForTests(): void {
+ cliProvider = null;
+ resolvedSource = undefined;
+ recording = false;
+}
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 46e6ea75f6..60cb82a6e1 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -13,6 +13,7 @@ export { MEMORY_VERBS_VERSION };
import type { Operation } from './ops/contract.ts';
import { withOutputRedaction } from './search/output-redaction.ts';
+import { registerOpRoutes } from './fix-routing.ts';
// Re-exports: the full previously-exported foundation surface of this module.
// The formerly file-private helpers (enforceSubagentSlugFence, slugUnderSubagentFence,
@@ -332,3 +333,8 @@ for (const op of operations) {
export const operationsByName = Object.fromEntries(
operations.map(op => [op.name, op]),
) as Record<string, Operation>;
+
+// A1 render-time routing pin: which CLI names are shared ops, and whether
+// their `--source` is an op param (provenance) rather than the target source.
+registerOpRoutes(operations.filter(op => op.cliHints?.name && !op.cliHints.hidden)
+ .flatMap(op => [op.cliHints!.name!, ...(op.cliHints!.aliases ?? [])].map(name => [name, 'source' in op.params] as const)));
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 8a1fe3cb6f..6e71037018 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -20,6 +20,7 @@ import type { ExplicitReadBinding } from './ops/contract.ts';
import { isSourceFederated, parseSourceConfig } from './sources-load.ts';
import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';
import { isTrustedDotfile, realpathOrResolve, realpathOrResolveAsync } from './path-confine.ts';
+import { noteResolvedSource } from './fix-routing.ts';
// Re-export so scope-resolution call sites can import the sentinel from
// either module (#1712).
@@ -151,6 +152,17 @@ export async function resolveSourceId(
// Local IPC already evaluated the client's flag/env/dotfile tiers. The
// owner's environment must never redirect that client's unscoped request.
opts: { skipLocalSignals?: boolean } = {},
+): Promise<string> {
+ const id = await resolveSourceIdChain(engine, explicit, cwd, opts);
+ if (!opts.skipLocalSignals) noteResolvedSource(id);
+ return id;
+}
+
+async function resolveSourceIdChain(
+ engine: BrainEngine,
+ explicit: string | null | undefined,
+ cwd: string,
+ opts: { skipLocalSignals?: boolean },
): Promise<string> {
// 1. Explicit flag wins. The __all__ sentinel passes through verbatim
// (#1712) — it is not a source id, so it skips both the regex and
@@ -757,6 +769,16 @@ export async function resolveSourceWithTier(
engine: BrainEngine,
explicit: string | null | undefined,
cwd: string = process.cwd(),
+): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
+ const resolved = await resolveSourceWithTierChain(engine, explicit, cwd);
+ noteResolvedSource(resolved.source_id);
+ return resolved;
+}
+
+async function resolveSourceWithTierChain(
+ engine: BrainEngine,
+ explicit: string | null | undefined,
+ cwd: string,
): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
// 1. Explicit flag wins. __all__ sentinel passes through verbatim (#1712).
if (explicit) {
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index c7539afda8..2a5775cc9a 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -12,6 +12,7 @@ import { operations, OperationError, enforceBoundClientOpAllowList, opError } fr
import type { OperationContext, AuthInfo } from '../core/operations.ts';
import { loadConfig } from '../core/config.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
+import { getCliOptions } from '../core/cli-options.ts';
import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';
import { cliRenderContext, orderNotices, redactForTransport, renderNotice, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';
import { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';
@@ -58,6 +59,14 @@ function configuredDbUrlForClassify(): string | null {
}
return cachedClassifyUrl;
}
+/** The brain this process serves: `serve --brain` / GBRAIN_BRAIN_ID / .gbrain-mount / host. */
+function servedBrainId(): string | undefined {
+ try {
+ return resolveBrainId(getCliOptions().brain);
+ } catch {
+ return undefined;
+ }
+}
let cachedClassifyBrainId: string | null | undefined;
function brainIdForClassify(): string | undefined {
if (cachedClassifyBrainId === undefined) {
@@ -502,7 +511,11 @@ export function dispatchRenderContext(opts: DispatchOpts): RenderContext {
const transport = opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http';
const surface = opts.surface ?? 'full';
const byName = new Map(operations.map(op => [op.name, op]));
+ // A1: CLI fixes name the served brain and the request's source (ids only; the HTTP pass strips paths).
+ const brain = servedBrainId();
+ const routing = { ...(brain ? { brain } : {}), ...(opts.sourceId ? { source: opts.sourceId } : {}) };
return {
+ routing,
transport,
surface,
isCallable: (opName: string) => {
diff --git a/test/agent-contract-goldens.test.ts b/test/agent-contract-goldens.test.ts
index ff312cf312..860cbafc4e 100644
--- a/test/agent-contract-goldens.test.ts
+++ b/test/agent-contract-goldens.test.ts
@@ -17,20 +17,24 @@ import {
toolErrorResult, toolResultWithNotices, withAgentSiblings, type Notice, type RenderContext,
} from '../src/core/agent-output.ts';
import { opError, OperationError } from '../src/core/ops/contract.ts';
+import '../src/core/operations.ts'; // registers shared-op CLI names for the A1 routing pin, as every gbrain process does
import { confirmationPayload } from '../src/core/consent.ts';
import { withEnv } from './helpers/with-env.ts';
const DIR = join(import.meta.dir, 'fixtures', 'agent-contract', 'v1');
const UPDATE = process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1';
+// A1: every surface renders with the brain/source the call acted on; CLI argv carry them explicitly.
+const routing = { brain: 'host', source: 'default' };
const stdio: RenderContext = {
transport: 'stdio',
surface: 'full',
isCallable: (op) => op !== 'get_health',
preapproved: () => false,
+ routing,
};
const http: RenderContext = { ...stdio, transport: 'http', principal: 'client-example' };
-const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false };
+const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false, routing };
let base = '';
beforeAll(() => { __setDocsRefForTests('master'); base = docsUrl('').replace(/\/$/, ''); });
diff --git a/test/agent-journey-recovery.serial.test.ts b/test/agent-journey-recovery.serial.test.ts
index cb38c0341e..160e66fadc 100644
--- a/test/agent-journey-recovery.serial.test.ts
+++ b/test/agent-journey-recovery.serial.test.ts
@@ -246,6 +246,29 @@ describe('H1b: recovery from another directory with conflicting ambient brain/so
const verify = expectJsonContract(await gb(host, ['doctor', '--only', 'timeline_history', '--json']), 'verify on host');
expect((verify.checks as Check[]).find(c => c.name === 'timeline_history')?.status).toBe('ok');
}, 600_000);
+
+ test('a generic fix (no site-specific routing) is pinned at render time and acts on host/default from elsewhere', async () => {
+ const notes = writeNotes(join(root, 'gone'), 1, 'route-gone');
+ expect((await gb(host, ['import', notes, '--no-embed', '--json'])).exitCode).toBe(0);
+ await withBrain(host, engine => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ "UPDATE pages SET deleted_at = now() WHERE source_id = 'default' AND slug = 'route-gone-1'"), TEST_WRITE_ATTRIBUTION)));
+ // The op handler's fix is `gbrain get <slug> --include-deleted`; the brain and source come only from the render-time pin.
+ const missing = await gb(host, ['get', 'route-gone-1', '--json']);
+ expect(missing.exitCode).toBe(1);
+ const doc = expectJsonContract(missing, 'get on a soft-deleted page');
+ expect(doc.code).toBe('page_not_found');
+ const fix = doc.fix as Fix;
+ expect(fix.argv).toEqual(['gbrain', 'get', 'route-gone-1', '--include-deleted', '--brain', 'host', '--source', 'default']);
+ expect(fix.command).toBe(shellQuote(fix.argv!));
+ expect(doc.suggestion).toContain(fix.command!);
+ const ran = await gb(host, fix.argv!.slice(1), { cwd: work, env: ambient() });
+ expect(ran.exitCode, ran.stderr.slice(-1500)).toBe(0);
+ expect(ran.stdout).toContain(`The ${MARKER} 1.`);
+ // Control: the same command without the pin follows the ambient settings to the wrong brain/source.
+ const unpinned = await gb(host, ['get', 'route-gone-1', '--include-deleted'], { cwd: work, env: ambient() });
+ expect(unpinned.exitCode).not.toBe(0);
+ expect(unpinned.stdout).not.toContain(MARKER);
+ }, 300_000);
});
describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {
diff --git a/test/fix-routing.test.ts b/test/fix-routing.test.ts
new file mode 100644
index 0000000000..0f6dbd2a54
--- /dev/null
+++ b/test/fix-routing.test.ts
@@ -0,0 +1,122 @@
+/**
+ * A1 / DX-7: every CLI fix carries explicit --brain/--source routing, pinned
+ * once at render time (src/core/fix-routing.ts via renderAction). The journey
+ * proof (a pinned fix run from another directory under conflicting ambient
+ * settings acts on the intended brain) lives in
+ * test/agent-journey-recovery.serial.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import '../src/core/operations.ts';
+import { CLI_COMMANDS } from '../src/cli/command-table.ts';
+import { CLI_FLAG_REGISTRY, CLI_ROUTING_FLAG_CONSUMERS } from '../src/core/cli-flag-registry.generated.ts';
+import {
+ __resetCliRoutingForTests, cliRouting, installCliRouting, noteResolvedSource, pinRouting, recordedSource, routingFlagsFor,
+} from '../src/core/fix-routing.ts';
+import { cliRenderContext, renderAction, toAgentError, type Action, type RenderContext } from '../src/core/agent-output.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { buildRoutingConsumers } from '../scripts/generate-flag-registry.ts';
+
+const routing = { brain: 'teambrain', source: 'wiki' };
+const read = (argv: string[], extra: Partial<Action> = {}): Action => ({ argv, consent: [], actor: 'agent', why: 'x', requires_exclusive: false, ...extra });
+
+afterEach(() => __resetCliRoutingForTests());
+
+describe('pinRouting', () => {
+ test('shared ops get --brain and --source, before a bare --', () => {
+ expect(pinRouting(['gbrain', 'get', 'notes/a', '--include-deleted'], routing))
+ .toEqual(['gbrain', 'get', 'notes/a', '--include-deleted', '--brain', 'teambrain', '--source', 'wiki']);
+ expect(pinRouting(['gbrain', 'write-request', '--', '--yes'], routing))
+ .toEqual(['gbrain', 'write-request', '--brain', 'teambrain', '--source', 'wiki', '--', '--yes']);
+ });
+
+ test('flags already present are kept; any source selector suppresses the source pin', () => {
+ expect(pinRouting(['gbrain', 'get', 'a', '--brain=host'], routing)).toEqual(['gbrain', 'get', 'a', '--brain=host', '--source', 'wiki']);
+ expect(pinRouting(['gbrain', 'sync', '--source', 'other'], routing)).toEqual(['gbrain', 'sync', '--source', 'other', '--brain', 'teambrain']);
+ for (const sel of ['--source-id', '--all-sources', '--sources']) {
+ expect(pinRouting(['gbrain', 'search', 'q', sel], routing)).toEqual(['gbrain', 'search', 'q', sel, '--brain', 'teambrain']);
+ }
+ // A routing flag that only appears after `--` is a positional, not a selector.
+ expect(pinRouting(['gbrain', 'get', '--', '--source'], routing)).toEqual(['gbrain', 'get', '--brain', 'teambrain', '--source', 'wiki', '--', '--source']);
+ });
+
+ test('brain-wide and engine-free commands: doctor gets --brain only; init, errors and non-gbrain argv are untouched', () => {
+ expect(pinRouting(['gbrain', 'doctor', '--json'], routing)).toEqual(['gbrain', 'doctor', '--json', '--brain', 'teambrain']);
+ expect(pinRouting(['gbrain', 'init', '--pglite', '--no-embedding'], routing)).toEqual(['gbrain', 'init', '--pglite', '--no-embedding']);
+ expect(pinRouting(['gbrain', 'errors', 'no_brain'], routing)).toEqual(['gbrain', 'errors', 'no_brain']);
+ expect(pinRouting(['kill', '1234'], routing)).toEqual(['kill', '1234']);
+ expect(pinRouting(['gbrain', 'get', 'a'], undefined)).toEqual(['gbrain', 'get', 'a']);
+ });
+
+ test('an op whose --source is its own param (provenance) gets --brain only', () => {
+ expect(routingFlagsFor('timeline-add')).toEqual({ brain: true, source: false });
+ expect(pinRouting(['gbrain', 'timeline-add', 'a', '2026-01-01', 'x'], routing)).toEqual(['gbrain', 'timeline-add', 'a', '2026-01-01', 'x', '--brain', 'teambrain']);
+ });
+
+ test('malformed ids are never interpolated', () => {
+ expect(pinRouting(['gbrain', 'get', 'a'], { brain: '--yes', source: 'a b' })).toEqual(['gbrain', 'get', 'a']);
+ });
+});
+
+describe('routing table agrees with the command table and the generated registry', () => {
+ test('every routes_source command accepts and consumes --source', () => {
+ const declared = CLI_COMMANDS.filter(r => r.routes_source).map(r => r.name);
+ expect(declared.length).toBeGreaterThan(10);
+ for (const name of declared) {
+ expect(CLI_FLAG_REGISTRY[name], `${name} accepts --source`).toContain('--source');
+ expect(CLI_ROUTING_FLAG_CONSUMERS[name], `${name} consumes --source`).toContain('--source');
+ }
+ });
+
+ test('pre-connect commands pin --brain only with consumption evidence', () => {
+ for (const r of CLI_COMMANDS.filter(c => c.phase === 'pre-connect')) {
+ expect(routingFlagsFor(r.name).brain, r.name).toBe((CLI_ROUTING_FLAG_CONSUMERS[r.name] ?? []).includes('--brain'));
+ }
+ expect(routingFlagsFor('db-repair').brain).toBe(true);
+ expect(routingFlagsFor('apply-migrations').brain).toBe(false);
+ });
+
+ test('committed routing map matches a fresh generator run (bun run build:flag-registry)', () => {
+ const fresh = buildRoutingConsumers();
+ expect(Object.fromEntries(Object.entries(CLI_ROUTING_FLAG_CONSUMERS).map(([k, v]) => [k, [...v]]))).toEqual(fresh);
+ });
+});
+
+describe('render-time pin', () => {
+ const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false, routing };
+
+ test('argv, command, preview_argv, verify.argv and then are pinned; suggestion quotes the pinned command', () => {
+ const r = renderAction(read(['gbrain', 'sync', '--no-pull'], {
+ preview_argv: ['gbrain', 'sync', '--dry-run'],
+ verify: { argv: ['gbrain', 'doctor', '--only', 'sync_freshness', '--json'] },
+ then: read(['gbrain', 'embed', '--stale']),
+ }), cli);
+ expect(r.argv).toEqual(['gbrain', 'sync', '--no-pull', '--brain', 'teambrain', '--source', 'wiki']);
+ expect(r.command).toBe('gbrain sync --no-pull --brain teambrain --source wiki');
+ expect(r.preview_argv).toEqual(['gbrain', 'sync', '--dry-run', '--brain', 'teambrain', '--source', 'wiki']);
+ expect(r.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'sync_freshness', '--json', '--brain', 'teambrain']);
+ expect(r.then?.argv).toEqual(['gbrain', 'embed', '--stale', '--brain', 'teambrain', '--source', 'wiki']);
+ const env = toAgentError(opError('invalid_params', 'bad', 'Try again.', { fix: read(['gbrain', 'get', 'a']) }), { transport: 'cli', render: cli });
+ expect(env.suggestion).toContain('gbrain get a --brain teambrain --source wiki');
+ });
+
+ test('HTTP keeps the target ids (non-sensitive) 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(JSON.stringify(env)).not.toContain('/home/alice-example');
+ });
+
+ test('cliRenderContext reads the installed CLI routing; the first resolved source wins', () => {
+ expect(cliRenderContext().routing).toBeUndefined();
+ installCliRouting(() => ({ brain: 'host', ...(recordedSource() ? { source: recordedSource() } : {}) }));
+ noteResolvedSource('wiki');
+ noteResolvedSource('other');
+ expect(cliRouting()).toEqual({ brain: 'host', source: 'wiki' });
+ expect(renderAction(read(['gbrain', 'get', 'a']), cliRenderContext()).argv).toEqual(['gbrain', 'get', 'a', '--brain', 'host', '--source', 'wiki']);
+ });
+
+ test('without an installed CLI routing the resolver records nothing (MCP servers, library callers)', () => {
+ noteResolvedSource('wiki');
+ expect(recordedSource()).toBeUndefined();
+ });
+});
diff --git a/test/fixtures/agent-contract/v1/bare-array-result.json b/test/fixtures/agent-contract/v1/bare-array-result.json
index 7f931e3006..5c9ee9a7b1 100644
--- a/test/fixtures/agent-contract/v1/bare-array-result.json
+++ b/test/fixtures/agent-contract/v1/bare-array-result.json
@@ -6,7 +6,7 @@
},
{
"type": "text",
- "text": "[gbrain notice empty_retrieval kind=info]\nwhy: No pages matched. Search ran keyword-only because embeddings are not configured.\nfix: gbrain doctor --json\nnext: {{next}}\nuser_message: I found no notes on that topic. Your brain searches keywords only right now."
+ "text": "[gbrain notice empty_retrieval kind=info]\nwhy: No pages matched. Search ran keyword-only because embeddings are not configured.\nfix: gbrain doctor --json --brain host\nnext: {{next}}\nuser_message: I found no notes on that topic. Your brain searches keywords only right now."
}
],
"_meta": {
@@ -19,9 +19,11 @@
"argv": [
"gbrain",
"doctor",
- "--json"
+ "--json",
+ "--brain",
+ "host"
],
- "command": "gbrain doctor --json",
+ "command": "gbrain doctor --json --brain host",
"consent": [],
"actor": "user",
"why": "Doctor reports which capability is missing and how to enable it.",
diff --git a/test/fixtures/agent-contract/v1/confirmation-required.json b/test/fixtures/agent-contract/v1/confirmation-required.json
index 34e0f511cb..3cdc5adf67 100644
--- a/test/fixtures/agent-contract/v1/confirmation-required.json
+++ b/test/fixtures/agent-contract/v1/confirmation-required.json
@@ -3,7 +3,7 @@
"error": "confirmation_required",
"code": "confirmation_required",
"message": "doctor --remediate needs the user's approval before it runs; nothing was changed.",
- "suggestion": "Ask the user: Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed? If they agree, run: gbrain doctor --remediate --max-usd 0.60 --yes",
+ "suggestion": "Ask the user: Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed? If they agree, run: gbrain doctor --remediate --max-usd 0.60 --yes --brain host",
"effects": [
"paid"
],
@@ -19,9 +19,11 @@
"--remediate",
"--max-usd",
"0.60",
- "--yes"
+ "--yes",
+ "--brain",
+ "host"
],
- "command": "gbrain doctor --remediate --max-usd 0.60 --yes",
+ "command": "gbrain doctor --remediate --max-usd 0.60 --yes --brain host",
"consent": [
"paid"
],
@@ -33,7 +35,9 @@
"gbrain",
"doctor",
"--remediation-plan",
- "--json"
+ "--json",
+ "--brain",
+ "host"
]
},
"preview": {
@@ -41,9 +45,11 @@
"gbrain",
"doctor",
"--remediation-plan",
- "--json"
+ "--json",
+ "--brain",
+ "host"
],
- "command": "gbrain doctor --remediation-plan --json"
+ "command": "gbrain doctor --remediation-plan --json --brain host"
},
"preapprove_argv": [
"gbrain",
diff --git a/test/fixtures/agent-contract/v1/error-with-fix.json b/test/fixtures/agent-contract/v1/error-with-fix.json
index b1bf8435e7..2bb3bf65c3 100644
--- a/test/fixtures/agent-contract/v1/error-with-fix.json
+++ b/test/fixtures/agent-contract/v1/error-with-fix.json
@@ -2,7 +2,7 @@
"content": [
{
"type": "text",
- "text": "{\n \"error\": \"invalid_params\",\n \"code\": \"invalid_params\",\n \"message\": \"Unknown sort 'bogus'.\",\n \"suggestion\": \"Use one of: updated, created, title. Next: list_pages {\\\"sort\\\":\\\"updated\\\"}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#invalid_params\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"list\",\n \"--sort\",\n \"updated\"\n ],\n \"command\": \"gbrain list --sort updated\",\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\"\n }\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"updated is the default sort.\",\n \"verify\": {\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\",\n \"limit\": 1\n }\n }\n },\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"invalid_params\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
+ "text": "{\n \"error\": \"invalid_params\",\n \"code\": \"invalid_params\",\n \"message\": \"Unknown sort 'bogus'.\",\n \"suggestion\": \"Use one of: updated, created, title. Next: list_pages {\\\"sort\\\":\\\"updated\\\"}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#invalid_params\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"list\",\n \"--sort\",\n \"updated\",\n \"--brain\",\n \"host\",\n \"--source\",\n \"default\"\n ],\n \"command\": \"gbrain list --sort updated --brain host --source default\",\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\"\n }\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"updated is the default sort.\",\n \"verify\": {\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\",\n \"limit\": 1\n }\n }\n },\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"invalid_params\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
}
],
"isError": true
diff --git a/test/fixtures/agent-contract/v1/error-with-notices.json b/test/fixtures/agent-contract/v1/error-with-notices.json
index fd58172ca0..c4b9fbdcd4 100644
--- a/test/fixtures/agent-contract/v1/error-with-notices.json
+++ b/test/fixtures/agent-contract/v1/error-with-notices.json
@@ -2,7 +2,7 @@
"content": [
{
"type": "text",
- "text": "{\n \"error\": \"unavailable\",\n \"code\": \"unavailable\",\n \"message\": \"Semantic search is unavailable.\",\n \"suggestion\": \"Keyword search still works. Next: run_doctor {}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#unavailable\",\n \"reason\": \"embeddings_disabled\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"doctor\",\n \"--json\"\n ],\n \"command\": \"gbrain doctor --json\",\n \"mcp\": {\n \"tool\": \"run_doctor\",\n \"arguments\": {}\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"Doctor reports what is missing or failing on the brain host.\",\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"unavailable\"\n ],\n \"class\": \"unavailable\",\n \"retryable\": false,\n \"notices\": [\n {\n \"code\": \"backup_coverage\",\n \"kind\": \"safety\",\n \"why\": \"Two sources have no backup.\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"backup\",\n \"--json\"\n ],\n \"command\": \"gbrain backup --json\",\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Shows which assets are not backed up.\",\n \"requires_exclusive\": false\n },\n \"user_message\": \"Some of your notes are not backed up. Want me to show you which ones?\",\n \"contract_version\": 1\n }\n ],\n \"contract_version\": 1\n}"
+ "text": "{\n \"error\": \"unavailable\",\n \"code\": \"unavailable\",\n \"message\": \"Semantic search is unavailable.\",\n \"suggestion\": \"Keyword search still works. Next: run_doctor {}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#unavailable\",\n \"reason\": \"embeddings_disabled\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"doctor\",\n \"--json\",\n \"--brain\",\n \"host\"\n ],\n \"command\": \"gbrain doctor --json --brain host\",\n \"mcp\": {\n \"tool\": \"run_doctor\",\n \"arguments\": {}\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"Doctor reports what is missing or failing on the brain host.\",\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"unavailable\"\n ],\n \"class\": \"unavailable\",\n \"retryable\": false,\n \"notices\": [\n {\n \"code\": \"backup_coverage\",\n \"kind\": \"safety\",\n \"why\": \"Two sources have no backup.\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"backup\",\n \"--json\",\n \"--brain\",\n \"host\"\n ],\n \"command\": \"gbrain backup --json --brain host\",\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Shows which assets are not backed up.\",\n \"requires_exclusive\": false\n },\n \"user_message\": \"Some of your notes are not backed up. Want me to show you which ones?\",\n \"contract_version\": 1\n }\n ],\n \"contract_version\": 1\n}"
}
],
"isError": true
diff --git a/test/fixtures/agent-contract/v1/nested-legacy-error.json b/test/fixtures/agent-contract/v1/nested-legacy-error.json
index 00cd2cd7c8..89f8196044 100644
--- a/test/fixtures/agent-contract/v1/nested-legacy-error.json
+++ b/test/fixtures/agent-contract/v1/nested-legacy-error.json
@@ -10,9 +10,13 @@
"argv": [
"gbrain",
"code-def",
- "--help"
+ "--help",
+ "--brain",
+ "host",
+ "--source",
+ "default"
],
- "command": "gbrain code-def --help",
+ "command": "gbrain code-def --help --brain host --source default",
"consent": [],
"actor": "agent",
"why": "Shows the required symbol argument.",
diff --git a/test/fixtures/agent-contract/v1/notice-block.txt b/test/fixtures/agent-contract/v1/notice-block.txt
index 705927dc6f..515dbcfc1a 100644
--- a/test/fixtures/agent-contract/v1/notice-block.txt
+++ b/test/fixtures/agent-contract/v1/notice-block.txt
@@ -1,5 +1,5 @@
[gbrain notice empty_retrieval kind=info]
why: No pages matched. Search ran keyword-only because embeddings are not configured.
-fix: gbrain doctor --json
+fix: gbrain doctor --json --brain host
next: {{next}}
user_message: I found no notes on that topic. Your brain searches keywords only right now.
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index 716e0aa807..04b3e60521 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -190,14 +190,15 @@ describe('F6 hidden-tool hint (owner stdio only)', () => {
expect(env.code).toBe('unknown_tool');
expect(env.suggestion).toContain('get_health exists, but this server runs the starter tool surface');
expect(env.suggestion).toContain('GBRAIN_SURFACE=full');
- expect(env.fix.command).toBe('gbrain doctor --json');
+ // A1: the CLI fix names the served brain explicitly.
+ expect(env.fix.command).toBe('gbrain doctor --json --brain host');
expect(env.fix.next).toBe('tell_user_to_run');
// HTTP keeps the opaque envelope (no existence oracle).
const http = await dispatchToolCall(engine as any, 'get_health', {}, { remote: true, transport: 'http', sourceId: 'default', allowedOps, surface: 'starter' });
const opaque = JSON.parse(http.content[0].text);
expect(opaque.code).toBe('unknown_tool');
expect(opaque.suggestion).not.toContain('exists');
- expect(opaque.fix?.command).not.toBe('gbrain doctor --json');
+ expect(opaque.fix?.command).not.toBe('gbrain doctor --json --brain host');
});
});