Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: match the B3a CHANGELOG and key-files to the reverted entry-point change

garrytanbf7ce35d4fb8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24924ea28f..af2351b4af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
- `src/core/engine-scope-store.ts` (new) and `src/core/engine-scope.ts`: `withLocalScope` (exported from `gbrain/engine-open`) and `needsEngineScope`. `gateway.ts` and `anthropic-key.ts` refuse an unscoped call with the new registered code `engine_scope_required` (its fix names `withEngineScope`); `engine_scope_missing` keeps meaning a provider the engine lacks. The hatch that let `configureGateway` open unscoped calls is gone, and `configureGatewayIfUninitialized` stays a no-op for them.
-- `src/cli.ts`, `src/commands/serve.ts`, `serve-http.ts` and `jobs.ts` enter the local scope at their entry points; `serve-http-mcp.ts` runs each `POST /mcp` and `minions/worker.ts` each job in its engine's scope; `hybridSearch`, `hybridSearchCached`, `importFromContent`, `importFromFile`, `importCodeFile` and `importImageFile` re-enter their engine's scope when called outside it, so a local engine's search inside an embedded engine's scope uses the process gateway and work they defer keeps their scope. `withEngineScope` enters its scope even before the first embedded engine opens, so a call scoped then keeps it.
+- `src/cli.ts`, `src/commands/serve.ts`, `serve-http.ts` and `jobs.ts` enter the local scope at their entry points; `serve-http-mcp.ts` runs each `POST /mcp` and `minions/worker.ts` each job in its engine's scope; `hybridSearch`, `hybridSearchCached`, `importFromContent`, `importFromFile`, `importCodeFile` and `importImageFile` re-enter their engine's scope when called outside it, so a local engine's search inside an embedded engine's scope uses the process gateway. `withEngineScope` enters its scope even before the first embedded engine opens, so a call scoped then keeps it.
- `src/core/engine-construct.ts` (new): `openEngine` builds its engine without the `createEngine` usage-stack entry and gives it a sink of its own (`registerEngineChatUsageSink`), so its usage is never the process fallback and a file-backed PGLite `reconnect()` no longer drops it (#8499).
- `src/core/ai/engine-gateway.ts`: the shrink factor, the once-per-model `no_key` rerank audit row and the structured-output rejection memory live on each gateway state, and an embedded engine's cached query embeddings are dropped at disconnect (#8499 item 2). `settings.cache_namespace` tags them with the namespace and a hash of the provider ids, base URLs and key fingerprints instead, never the key.
- `src/core/search/private-visibility.ts`: `visibility.honor_aliases` and `search.remote_private_pages` read on an embedded engine are kept per engine (keyed by `engineKey`) and decide inside its scope; a read in no scope while an embedded engine is open takes the strict policy; the CLI's process-wide lean-private rule is unchanged. An unscoped rerank refusal skips as `no_key` and writes no failure row.
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 05dc14b398..c422f6283d 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.
- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. `fitMatryoshkaPrefix(recipe, modelId, vector, expected)` (PR #5921, wave 14): when the recipe's embedding touchpoint declares the model in `matryoshka` (`{ native, prefixes }`, folded ids; `recipes/nvidia.ts` declares Nemotron-3-Embed-8B at 4096 with 1024/2048) and the provider answered at the native width for a listed target, the vector is sliced from the start and L2-normalized before `gateway.embedSubBatch`'s dim-mismatch check; every other vector returns untouched, an overflowing norm is refused, a zero or non-finite prefix falls to the per-item screen. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).
-- `src/core/ai/engine-gateway.ts` + `src/core/engine-scope.ts` (GBRA-283 B2) — the AI gateway of an engine `openEngine` opened. `engineGatewayInput(settings)` builds its `AIGatewayConfig` from `settings.ai` (provider id → `apiKey`/`baseUrl`, folded into the recipe's key env name and `base_urls` or the native `*_BASE_URL`) and `settings.embedding`, never `process.env` or `~/.gbrain/config.json`; `scopedGatewayState` keeps one state (config, model clients, a query-cache tag, batch-shrink, no-key and structured-output memory) per held settings object, so a disconnect drops it; `settings.cache_namespace` tags that engine's cached query embeddings instead (B3a). `engineProviderProblem` refuses claude-cli and recipes with `resolveOpenAICompatConfig` (Azure). `gateway.ts` reads `gw()` (that state in an embedded engine's scope, else the process state `configureGateway` writes) and `configFor(recipe, touchpoint)` refuses `engine_scope_missing` before any call to a provider the engine lacks; a call with no scope while the process holds an open embedded engine refuses `engine_scope_required` (`refuseUnscoped`) whatever `configureGateway` set; discovery and `configureGatewayIfUninitialized` skip engine states, and `anthropic-key.ts` answers the scoped engine's own key. `withEngineScope(engine, fn)` (AsyncLocalStorage, `engine-scope-store.ts`; entered even before the first embedded engine opens) is entered by every operation handler (`operation-load.ts`), each persistence consumer (`persistence/service.ts`), minion jobs, `POST /mcp`, and `hybridSearch` and the import paths (`needsEngineScope`: any engine other than the scoped one); `withLocalScope(fn)` marks a call for the process gateway (the CLI, `serve` and `jobs` enter it); `embeddedEngineInScope` resolves through `engineKey`. `engine-construct.ts` builds an engine without the process chat-usage sink (`createEngine` adds it), so `openEngine` registers a sink of its own. Pinned by `test/engine-gateway.test.ts` and `test/engine-scope-required.test.ts` (refusals, two engines, transaction/proxy/degraded sharing, a byte-identical process gateway for other engines, a canary key absent from errors, logs, doctor and read-back).
+- `src/core/ai/engine-gateway.ts` + `src/core/engine-scope.ts` (GBRA-283 B2) — the AI gateway of an engine `openEngine` opened. `engineGatewayInput(settings)` builds its `AIGatewayConfig` from `settings.ai` (provider id → `apiKey`/`baseUrl`, folded into the recipe's key env name and `base_urls` or the native `*_BASE_URL`) and `settings.embedding`, never `process.env` or `~/.gbrain/config.json`; `scopedGatewayState` keeps one state (config, model clients, a query-cache tag, batch-shrink, no-key and structured-output memory) per held settings object, so a disconnect drops it; `settings.cache_namespace` tags that engine's cached query embeddings instead (B3a). `engineProviderProblem` refuses claude-cli and recipes with `resolveOpenAICompatConfig` (Azure). `gateway.ts` reads `gw()` (that state in an embedded engine's scope, else the process state `configureGateway` writes) and `configFor(recipe, touchpoint)` refuses `engine_scope_missing` before any call to a provider the engine lacks; a call with no scope while the process holds an open embedded engine refuses `engine_scope_required` (`refuseUnscoped`) whatever `configureGateway` set; discovery and `configureGatewayIfUninitialized` skip engine states, and `anthropic-key.ts` answers the scoped engine's own key. `withEngineScope(engine, fn)` (AsyncLocalStorage, `engine-scope-store.ts`; entered even before the first embedded engine opens) is entered by every operation handler (`operation-load.ts`), each persistence consumer (`persistence/service.ts`), minion jobs, `POST /mcp`, and `hybridSearch` and the import paths (`needsEngineScope`: once an embedded engine has opened, any engine other than the scoped one); `withLocalScope(fn)` marks a call for the process gateway (the CLI, `serve` and `jobs` enter it); `embeddedEngineInScope` resolves through `engineKey`. `engine-construct.ts` builds an engine without the process chat-usage sink (`createEngine` adds it), so `openEngine` registers a sink of its own. Pinned by `test/engine-gateway.test.ts` and `test/engine-scope-required.test.ts` (refusals, two engines, transaction/proxy/degraded sharing, a byte-identical process gateway for other engines, a canary key absent from errors, logs, doctor and read-back).
- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`). #6816: `providerContentBlockReason` also returns `claude_cli_usage_policy` for the claude-cli adapter's usage-policy refusal (`ClaudeCliProcessError`, no `apiErrorStatus`, `claude-cli reported error: API Error:` prefix, the AUP link and a refusal phrase: `CLAUDE_CLI_REFUSAL_RE`); `test/claude-cli-refusal-6816.test.ts`.