Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(closeout): routing pin reads a generated CLI route table; provider lives beside the CLI; serve installs no process pin

garrytan75ad58e7e210
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 45a4e1b9d7..4557766039 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -347,14 +347,18 @@ export function buildFlagRegistry(root: string = ROOT): Record<string, string[]>
}
/**
- * 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.
+ * A1 render-time routing pin (src/core/fix-routing.ts): the routing flags a
+ * fix naming each CLI-only command carries. Acceptance alone is not evidence
+ * (every command accepts `--brain`/`--source` through UNIVERSAL_FLAGS), so:
+ * - `--brain` when the command opens its brain through the connect terminator
+ * (phase other than `pre-connect`), or its own code reads the global brain
+ * option;
+ * - `--source` when the record declares `routes_source` (its source resolves
+ * through the ambient chain). The declaration needs consumption evidence (the
+ * tight-quoted `'--source'` literal in the command's own code, the
+ * SAFETY_FLAGS rule); a declaration without it fails the generator.
*/
-export function buildRoutingConsumers(root: string = ROOT): Record<string, string[]> {
+export function buildRoutingFlags(root: string = ROOT): Record<string, string[]> {
return buildFlagArtifacts(root).routing;
}
@@ -473,11 +477,15 @@ function buildFlagArtifacts(root: string): { registry: 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'] : []),
+ const record = records.find(r => r.name === command);
+ if (record?.routesSource && !consumes(depthZeroText, '--source')) {
+ throw new Error(`generate-flag-registry: ${command} declares routes_source but its code never reads '--source'`);
+ }
+ const routed = [
+ ...(record?.phase !== 'pre-connect' || /getCliOptions\(\)\.brain|cliOpts\.brain/.test(depthZeroText) ? ['--brain'] : []),
+ ...(record?.routesSource ? ['--source'] : []),
];
- if (consumed.length) routing[command] = consumed;
+ if (routed.length) routing[command] = routed;
}
return { registry, routing };
}
@@ -507,11 +515,11 @@ 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[]> = {
+// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
+// src/core/fix-routing.ts): '--brain' when the command opens its brain (not a
+// pre-connect command, or its code reads the global brain option); '--source'
+// when the command-table record declares routes_source (consumption-checked).
+export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
${render(routing)}
};
`;
diff --git a/scripts/lib/cli-pipeline.ts b/scripts/lib/cli-pipeline.ts
index 0250aa8dd5..e2f2c7b324 100644
--- a/scripts/lib/cli-pipeline.ts
+++ b/scripts/lib/cli-pipeline.ts
@@ -128,6 +128,10 @@ export interface TableRecordShape {
loadSpecifier: string | null;
/** D3: `help` absent → undefined; `() => import('<literal>')` → the literal; any other shape → null. */
helpSpecifier?: string | null;
+ /** The record's `phase` string literal (A1 routing pin: pre-connect commands open no brain through the terminator). */
+ phase?: string;
+ /** A1: `routes_source: true` on the record. */
+ routesSource?: true;
}
/** Every record of CLI_COMMANDS in table order, read by AST (the EO13 literal-load contract). */
@@ -150,6 +154,9 @@ export function readTableRecords(root: string): TableRecordShape[] {
&& init.body.expression.kind === ts.SyntaxKind.ImportKeyword && init.body.arguments.length === 1
&& ts.isStringLiteral(init.body.arguments[0]!) ? init.body.arguments[0].text : null;
const help = prop('help');
- return { name: name.text, loadSpecifier: literalImport(prop('load')?.initializer), ...(help ? { helpSpecifier: literalImport(help.initializer) } : {}) };
+ const phase = prop('phase')?.initializer;
+ const routesSource = prop('routes_source')?.initializer.kind === ts.SyntaxKind.TrueKeyword;
+ return { name: name.text, loadSpecifier: literalImport(prop('load')?.initializer), ...(help ? { helpSpecifier: literalImport(help.initializer) } : {}),
+ ...(phase && ts.isStringLiteral(phase) ? { phase: phase.text } : {}), ...(routesSource ? { routesSource: true as const } : {}) };
});
}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 537d49d3e2..163c39d7f6 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2233 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 334 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice)
+src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
src/core/pglite-engine.ts 2921 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
diff --git a/src/cli.ts b/src/cli.ts
index c07a054ebe..a18f8068f1 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -31,7 +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 { installCliRoutingFor } from './cli/fix-routing-provider.ts';
import { formatVolunteeredPage } from './core/context/volunteer.ts';
import type { Operation, OperationContext } from './core/operations.ts';
import { currentCliWriteWait } from './core/persistence/write-wait.ts';
@@ -300,41 +300,6 @@ 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();
@@ -347,7 +312,7 @@ async function main() {
setCliOptions(cliOpts);
let command = args[0];
- installCliRouting(cliRoutingProvider(() => command, args));
+ installCliRoutingFor(() => command, args);
if (!command || command === '--help' || command === '-h') {
printHelp();
diff --git a/src/cli/fix-routing-provider.ts b/src/cli/fix-routing-provider.ts
new file mode 100644
index 0000000000..cb3c47b2ca
--- /dev/null
+++ b/src/cli/fix-routing-provider.ts
@@ -0,0 +1,54 @@
+/**
+ * A1: the CLI process's routing provider for the render-time pin
+ * (src/core/fix-routing.ts), installed by src/cli.ts once global flags are parsed.
+ */
+import { isThinClient, loadConfig } from '../core/config.ts';
+import { resolveBrainId } from '../core/brain-resolver.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
+import { installCliRouting, recordedSource, routingFlagsFor, type FixRouting } from '../core/fix-routing.ts';
+
+/**
+ * Install the pin for this invocation. `serve` installs nothing: its fixes are rendered per request by
+ * dispatch (the served brain + the request's source), and a long-lived
+ * process must not pin the first request's source onto later ones.
+ */
+export function installCliRoutingFor(currentCommand: () => string | undefined, args: readonly string[]): void {
+ if (currentCommand() === 'serve') return;
+ installCliRouting(cliRoutingProvider(currentCommand, args));
+}
+
+/**
+ * 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.
+ */
+export 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 = resolveBrainId(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 } : {}) };
+ };
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 625c9ebdb3..8e174f5aaf 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -132,58 +132,85 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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'],
+// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
+// src/core/fix-routing.ts): '--brain' when the command opens its brain (not a
+// pre-connect command, or its code reads the global brain option); '--source'
+// when the command-table record declares routes_source (consumption-checked).
+export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
+ 'advisor': ['--brain'],
+ 'agent': ['--brain'],
+ 'anomalies': ['--brain'],
+ 'auth': ['--brain'],
+ 'autopilot': ['--brain'],
+ 'backfill': ['--brain'],
'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'],
+ 'book-mirror': ['--brain'],
+ 'brainstorm': ['--brain'],
+ 'calibration': ['--brain', '--source'],
+ 'call': ['--brain'],
+ 'capture': ['--brain', '--source'],
+ 'code-callees': ['--brain', '--source'],
+ 'code-callers': ['--brain', '--source'],
+ 'code-def': ['--brain', '--source'],
+ 'code-refs': ['--brain', '--source'],
+ 'compile-context': ['--brain', '--source'],
'config': ['--brain'],
- 'connectors': ['--source'],
+ 'connectors': ['--brain'],
+ 'conversation-parser': ['--brain'],
'db-repair': ['--brain'],
- 'decide': ['--source'],
- 'doctor': ['--brain', '--source'],
- 'dream': ['--source'],
- 'edges-backfill': ['--source'],
+ 'decide': ['--brain'],
+ 'doctor': ['--brain'],
+ 'dream': ['--brain', '--source'],
+ 'edges-backfill': ['--brain', '--source'],
'embed': ['--brain', '--source'],
'embeddings': ['--brain'],
- 'enrich': ['--source'],
- 'eval': ['--source'],
- 'export': ['--source'],
+ 'enrich': ['--brain', '--source'],
+ 'eval': ['--brain'],
+ 'export': ['--brain', '--source'],
'extract': ['--brain', '--source'],
- 'facts': ['--source'],
- 'files': ['--source'],
- 'frontmatter': ['--source'],
- 'graph-query': ['--source'],
- 'import': ['--source'],
- 'loops': ['--source'],
- 'mcp': ['--source'],
- 'orphans': ['--source'],
- 'pricing': ['--source'],
+ 'extract-conversation-facts': ['--brain'],
+ 'facts': ['--brain', '--source'],
+ 'features': ['--brain'],
+ 'files': ['--brain', '--source'],
+ 'forget': ['--brain'],
+ 'founder': ['--brain'],
+ 'graph-query': ['--brain', '--source'],
+ 'import': ['--brain', '--source'],
+ 'jobs': ['--brain'],
+ 'loops': ['--brain', '--source'],
+ 'lsd': ['--brain'],
+ 'maintain': ['--brain'],
+ 'mcp': ['--brain'],
+ 'migrate': ['--brain'],
+ 'models': ['--brain'],
+ 'notability-eval': ['--brain'],
+ 'onboard': ['--brain'],
+ 'orphans': ['--brain'],
+ 'pages': ['--brain'],
+ 'pricing': ['--brain'],
'projections': ['--brain'],
+ 'quarantine': ['--brain'],
'recall': ['--brain', '--source'],
- 'reindex': ['--source'],
+ 'reconcile-links': ['--brain'],
+ 'reindex': ['--brain'],
'reindex-code': ['--brain', '--source'],
- 'reindex-frontmatter': ['--source'],
- 'repair': ['--source'],
- 'repos': ['--source'],
- 'schema': ['--source'],
- 'sources': ['--source'],
+ 'reindex-frontmatter': ['--brain'],
+ 'reindex-search-vector': ['--brain'],
+ 'repair': ['--brain'],
+ 'repos': ['--brain'],
+ 'retrieval-upgrade': ['--brain'],
+ 'salience': ['--brain'],
+ 'serve': ['--brain'],
+ 'skillopt': ['--brain'],
+ 'sources': ['--brain'],
+ 'status': ['--brain'],
+ 'storage': ['--brain'],
'sweep': ['--brain', '--source'],
'sync': ['--brain', '--source'],
- 'think': ['--source'],
- 'transcripts': ['--source'],
- 'waiting': ['--source'],
- 'watch': ['--source'],
+ 'takes': ['--brain'],
+ 'think': ['--brain', '--source'],
+ 'transcripts': ['--brain', '--source'],
+ 'waiting': ['--brain', '--source'],
+ 'watch': ['--brain', '--source'],
+ 'whoknows': ['--brain'],
};
diff --git a/src/core/fix-routing.ts b/src/core/fix-routing.ts
index 17b4cdfd2c..3289f0d7b9 100644
--- a/src/core/fix-routing.ts
+++ b/src/core/fix-routing.ts
@@ -8,22 +8,23 @@
* 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).
+ * - `--brain <id>` for commands that route through the brain axis: every
+ * shared op, and CLI-only commands that open their engine through the
+ * connect terminator or read the global brain option.
+ * - `--source <id>` 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 whose command-table
+ * record declares `routes_source`.
+ *
+ * The CLI-only half is generated from the command table and each command's
+ * code (CLI_ROUTING_FLAGS, `bun run build:flag-registry`), so this module never
+ * imports the table (its lazy loaders would pull every command into any bundle
+ * 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.
*/
-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 { CLI_FLAG_REGISTRY, CLI_ROUTING_FLAGS } from './cli-flag-registry.generated.ts';
import { ALL_SOURCES, SOURCE_ID_RE } from './source-id.ts';
export interface FixRouting { brain?: string; source?: string }
@@ -32,29 +33,25 @@ 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);
+/**
+ * Shared-op CLI names (primary + aliases, hidden excluded): every op routes the brain, and `--source`
+ * unless the op owns a `source` param (provenance, not the target source). Called by src/core/operations.ts.
+ */
+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 });
+ }
}
/** 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 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') };
}
const op = opCommands.get(command);
return op ? { brain: true, source: !op.ownsSource } : { brain: false, source: false };
@@ -107,7 +104,7 @@ export function cliRouting(): FixRouting | undefined {
try { return cliProvider?.(); } catch { return undefined; }
}
-/** Test seam: drop the provider and the recorded source. */
+/** Test seam: drop the provider and the recorded source (registered command tables stay). */
export function __resetCliRoutingForTests(): void {
cliProvider = null;
resolvedSource = undefined;
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 60cb82a6e1..183da64120 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -333,8 +333,4 @@ 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)));
+registerOpRoutes(operations); // A1 render-time routing pin (src/core/fix-routing.ts)
diff --git a/test/fix-routing.test.ts b/test/fix-routing.test.ts
index 0f6dbd2a54..c599a5943c 100644
--- a/test/fix-routing.test.ts
+++ b/test/fix-routing.test.ts
@@ -8,13 +8,13 @@
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 { CLI_FLAG_REGISTRY, CLI_ROUTING_FLAGS } 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';
+import { buildRoutingFlags } 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 });
@@ -58,26 +58,23 @@ describe('pinRouting', () => {
});
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);
+ test('every routes_source record pins --source and accepts it; nothing else does', () => {
+ const declared = CLI_COMMANDS.filter(r => r.routes_source).map(r => r.name).sort();
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');
- }
+ for (const name of declared) expect(CLI_FLAG_REGISTRY[name], `${name} accepts --source`).toContain('--source');
+ expect(Object.keys(CLI_ROUTING_FLAGS).filter(k => CLI_ROUTING_FLAGS[k]!.includes('--source')).sort()).toEqual(declared);
});
- 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'));
- }
+ test('every engine-opening command pins --brain; pre-connect ones only when their code reads the brain option', () => {
+ for (const r of CLI_COMMANDS.filter(c => c.phase !== 'pre-connect')) expect(routingFlagsFor(r.name).brain, r.name).toBe(true);
expect(routingFlagsFor('db-repair').brain).toBe(true);
+ expect(routingFlagsFor('embeddings').brain).toBe(true);
expect(routingFlagsFor('apply-migrations').brain).toBe(false);
+ expect(routingFlagsFor('init').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);
+ test('committed routing table matches a fresh generator run (bun run build:flag-registry)', () => {
+ expect(Object.fromEntries(Object.entries(CLI_ROUTING_FLAGS).map(([k, v]) => [k, [...v]]))).toEqual(buildRoutingFlags());
});
});
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index 04b3e60521..519d1dd6b9 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -183,6 +183,7 @@ describe('keyless answers ask before spending (F8/F9)', () => {
describe('F6 hidden-tool hint (owner stdio only)', () => {
test('a tool outside the stdio surface names itself, its CLI equivalent and GBRAIN_SURFACE=full', async () => {
+ // A1: the CLI fix names the served brain explicitly.
const { STARTER_OPS } = await import('../src/mcp/surface.ts');
const allowedOps = new Set(STARTER_OPS);
const stdio = await dispatchToolCall(engine as any, 'get_health', {}, { remote: true, transport: 'stdio', sourceId: 'default', allowedOps, surface: 'starter' });
@@ -190,7 +191,6 @@ 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');
- // 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).