Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(config): embedding_disabled is dual-plane and config get/show report the effective schema_pack (#5253)
time-attack17882ba72908
diff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.mdindex fde411da22..08b6cb3c82 100644--- a/docs/architecture/schema-packs.md+++ b/docs/architecture/schema-packs.md@@ -60,6 +60,8 @@ gbrain schema use <pack> # activate a pack (writes ~/.gbrain/config.json)which takes precedence over the file setting written by `gbrain schema use`.Use `gbrain config unset schema_pack` to remove that database override, then`gbrain schema active` to confirm the resolved pack and its selection tier.+`gbrain config get schema_pack` and `gbrain config show` report the same+resolved pack and name its tier.Authoring + discovery verbs:diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 05c404fe9d..bb908e2ad4 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -46,7 +46,7 @@<a id="pglite-aborted"></a>**PGLite crashes at startup with `RuntimeError: Aborted()` (often right after a macOS upgrade)?** Not a macOS incompatibility — the OS-upgrade reboot killed gbrain mid-write and tore the data dir's WAL. gbrain repairs this automatically on the next command (data preserved, backup kept); if auto-repair is disabled or skipped, run `gbrain pglite-repair --dry-run` to diagnose and `gbrain pglite-repair --yes` to repair in place. Full recovery ladder (repair → rebuild → engine switch) in [`docs/ENGINES.md` — Troubleshooting: startup abort](../ENGINES.md#troubleshooting-startup-abort-runtimeerror-aborted) and [`docs/INSTALL.md`](../INSTALL.md#pglite-crashes-at-startup-runtimeerror-aborted).-<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.+<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. `gbrain config get embedding_disabled` reports whether embedding is off and which plane says so (the config file and the database setting; `true` on either turns it off); `gbrain config set embedding_disabled true|false` and `gbrain config unset embedding_disabled` change both, and the `init --force --embedding-model` enable path clears both. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.**`gbrain doctor` warns `default_source_local_path`?** Your `default` source has no `local_path` AND that null pointer is provably breaking write-through (the repo fallback is another source's own working tree, or file-backed default pages have no resolvable root). A null `local_path` on its own is the designed fallback topology and reports ok. The repair is a pointer update, never a file move: `gbrain sources set-path default <path>` prints the prior value before changing it and refuses a path that nests inside or swallows another source's tree (exit 6; `--force` bypasses). **Say to your agent:** *"Run a brain health check and fix what you find"* — the maintain skill runs `gbrain doctor` and applies the printed repair.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex fe1ee6649d..89c87249a8 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 2932 ratchet +1 System One v1 evals: search arms clasrc/core/search/hybrid.ts 1586 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 keysrc/core/types.ts 2210 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)-src/commands/init.ts 1876 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)+src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)diff --git a/src/commands/config.ts b/src/commands/config.tsindex ea52887179..c3e255465c 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -133,6 +133,85 @@ const MEMORY_DUAL_PLANE_KEYS: ReadonlySet<string> = new Set(* shared-declared brain never gets the enable-nudge advisory. */const BRAIN_AUDIENCE_KEY = 'brain.audience';+/** `embedding_disabled` is dual-plane too: the DB row is authoritative (a+ * mounted brain has no other plane) and the host's file mirror keeps the+ * engine-free readers in step. Runtime gates treat `true` on EITHER plane as+ * disabled, so set and unset always write both and `get` reports that+ * effective value. */+const EMBEDDING_DISABLED_KEY = 'embedding_disabled';++async function setEmbeddingDisabled(engine: BrainEngine, value: string): Promise<void> {+ const normalized = value.trim().toLowerCase();+ if (normalized !== 'true' && normalized !== 'false') {+ console.error(`[config] ${EMBEDDING_DISABLED_KEY} must be true or false (got '${value}'). Nothing was written.`);+ process.exit(1);+ }+ const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');+ const hostPlane = await hostBrainSelected();+ const cfg = loadConfigFileOnly();+ if (hostPlane && cfg) {+ if (normalized === 'true') cfg.embedding_disabled = true;+ else delete cfg.embedding_disabled;+ saveConfig(cfg);+ }+ try {+ await engine.setConfig(EMBEDDING_DISABLED_KEY, normalized);+ } catch (e) {+ console.error(`[config] ERROR: ${hostPlane ? 'file plane written but ' : ''}the DB-plane write failed (${e instanceof Error ? e.message : String(e)}).`);+ console.error(`[config] The planes now disagree and embedding stays off while either says true — re-run this command once the database is reachable.`);+ process.exit(1);+ }+ console.log(`Set ${EMBEDDING_DISABLED_KEY} = ${normalized} (${hostPlane ? 'file + db planes' : 'db plane only — mounted brain'})`);+ if (normalized === 'false' && cfg && !cfg.embedding_model?.trim()) {+ const { embeddingEnablement } = await import('../core/readiness.ts');+ const { shellQuote } = await import('../core/agent-output.ts');+ const fix = embeddingEnablement({ ...cfg, embedding_disabled: false });+ if (fix.argv) console.log(`No embedding model is configured yet. Turn on semantic search (pages and facts are kept): ${shellQuote(fix.argv)}`);+ }+}++async function unsetEmbeddingDisabled(engine: BrainEngine): Promise<void> {+ const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');+ const cfg = loadConfigFileOnly();+ const fileHad = (await hostBrainSelected()) && cfg !== null && EMBEDDING_DISABLED_KEY in cfg;+ if (fileHad) {+ delete cfg!.embedding_disabled;+ saveConfig(cfg!);+ }+ const dbDeleted = await engine.unsetConfig(EMBEDDING_DISABLED_KEY);+ if (!fileHad && dbDeleted === 0) {+ console.error(`Config key not found: ${EMBEDDING_DISABLED_KEY}`);+ process.exit(1);+ }+ console.log(`Unset ${EMBEDDING_DISABLED_KEY} (${[fileHad ? 'file plane' : null, dbDeleted > 0 ? 'db plane' : null].filter(Boolean).join(' + ')})`);+}++/** The effective `embedding_disabled` and where it comes from; null when neither plane holds it. */+async function effectiveEmbeddingDisabled(engine: BrainEngine): Promise<{ value: boolean; note: string } | null> {+ const file = loadConfig()?.embedding_disabled;+ const db = await engine.getConfig(EMBEDDING_DISABLED_KEY);+ if (file === undefined && db === null) return null;+ const value = file === true || db === 'true';+ const planes = `file: ${file === undefined ? 'unset' : String(file)}, db: ${db ?? 'unset'}`;+ const agree = db === null || file === undefined || String(file === true) === db;+ return { value, note: agree+ ? `effective value (${planes}); either plane's true turns embedding off`+ : `planes disagree (${planes}); embedding stays off while either says true. Re-sync: gbrain config set ${EMBEDDING_DISABLED_KEY} <true|false>` };+}++const SCHEMA_PACK_SOURCE_LABEL: Record<string, string> = {+ env: 'GBRAIN_SCHEMA_PACK env', 'db-config': 'db plane (gbrain config set schema_pack)', 'gbrain-yml': 'gbrain.yml',+ 'home-config': 'file plane (~/.gbrain/config.json)', default: 'built-in default',+};++/** The brain-wide schema pack the runtime resolves (the same tiers `gbrain schema active` uses). */+async function effectiveSchemaPack(engine: BrainEngine): Promise<{ value: string; note: string }> {+ const { readDbSchemaPack } = await import('../core/schema-pack/engine-resolution.ts');+ const { resolveActivePackNameOnly } = await import('../core/schema-pack/load-active.ts');+ const resolution = resolveActivePackNameOnly({ cfg: loadConfig(), remote: false, dbConfig: await readDbSchemaPack(engine) });+ return { value: resolution.pack_name, note: `${SCHEMA_PACK_SOURCE_LABEL[resolution.source] ?? resolution.source}; the tier gbrain schema active resolves` };+}+/** Ambient-writeback posture re-stamp (red-team review, this wave): the* engine-free bootstrap-harness renderer reads `memory.visibility_posture`* from the file mirror, previously refreshed ONLY by `config set memory.*` —@@ -536,6 +615,36 @@ export async function tryRunConfigThinClient(args: string[]): Promise<boolean> {return false;}+/** `config show`: file/env values, with the effective DB-aware value for the dual-plane keys. */+async function showConfig(engine: BrainEngine): Promise<void> {+ const config = loadConfig();+ if (!config) {+ console.error('No config found. Run: gbrain init');+ process.exit(1);+ }+ console.log('GBrain config:');+ const effective: Record<string, { value: unknown; note: string }> = {};+ try {+ effective.schema_pack = await effectiveSchemaPack(engine);+ const disabled = await effectiveEmbeddingDisabled(engine);+ if (disabled) effective[EMBEDDING_DISABLED_KEY] = disabled;+ } catch { /* DB plane unreadable: show the file/env values alone */ }+ const shown = { ...config } as Record<string, unknown>;+ for (const [k, e] of Object.entries(effective)) shown[k] = e.value;+ for (const [k, v] of Object.entries(shown)) {+ if (effective[k]) { console.log(` ${k}: ${String(v)} (${effective[k]!.note})`); continue; }+ // #575: objects interpolated into the template literal printed+ // `[object Object]` — render them as JSON instead. Sensitive keys+ // stay redacted whether the value is a string or an object.+ const display = typeof v === 'string'+ ? redactConfigValue(k, v)+ : v !== null && typeof v === 'object'+ ? (isSensitiveConfigKey(k) ? '***' : JSON.stringify(v))+ : v;+ console.log(` ${k}: ${display}`);+ }+}+export async function runConfig(engine: BrainEngine, args: string[]) {const action = args[0];@@ -551,23 +660,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {}if (action === 'show') {- const config = loadConfig();- if (!config) {- console.error('No config found. Run: gbrain init');- process.exit(1);- }- console.log('GBrain config:');- for (const [k, v] of Object.entries(config)) {- // #575: objects interpolated into the template literal printed- // `[object Object]` — render them as JSON instead. Sensitive keys- // stay redacted whether the value is a string or an object.- const display = typeof v === 'string'- ? redactConfigValue(k, v)- : v !== null && typeof v === 'object'- ? (isSensitiveConfigKey(k) ? '***' : JSON.stringify(v))- : v;- console.log(` ${k}: ${display}`);- }+ await showConfig(engine);return;}@@ -632,6 +725,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {console.error('Usage: gbrain config unset <key> | --pattern <prefix>');process.exit(1);}+ if (key === EMBEDDING_DISABLED_KEY) {+ await unsetEmbeddingDisabled(engine);+ return;+ }if (MEMORY_DUAL_PLANE_KEYS.has(key) || key === BRAIN_AUDIENCE_KEY) {// Dual-plane delete, mirroring the dual-plane set: file mirror AND the// authoritative DB row both go. "Not found" only when neither had it.@@ -747,6 +844,16 @@ export async function runConfig(engine: BrainEngine, args: string[]) {const key = positionals[1];const value = positionals[2];+ if (action === 'get' && (key === EMBEDDING_DISABLED_KEY || key === 'schema_pack')) {+ const effective = key === 'schema_pack' ? await effectiveSchemaPack(engine) : await effectiveEmbeddingDisabled(engine);+ if (!effective) {+ console.error(`Config key not found: ${key}`);+ process.exit(1);+ }+ console.log(String(effective.value));+ console.error(`[config] source: ${effective.note}`);+ return;+ }if (action === 'get' && key) {// #2120: `get` used to read only the DB plane, so a runtime-effective key// in ~/.gbrain/config.json (or env) reported not-found. Resolve the way@@ -843,6 +950,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {// Ambient-writeback keys DUAL-WRITE (OV2-5): file mirror first (the// engine-free readers' plane), then the authoritative DB row. A DB// failure leaves the planes briefly diverged — reported, not hidden.+ if (key === EMBEDDING_DISABLED_KEY) {+ await setEmbeddingDisabled(engine, value);+ return;+ }if (key === BRAIN_AUDIENCE_KEY) {// Dual-plane like memory.* (WP8): the engine-free harness lane gates// its enable-nudge advisory on the file-plane declared audience.diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex b60d4b0915..6b1b1cb47b 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -872,12 +872,11 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf// background block so we never queue a job that can only fail. stderr only;// stdout stays empty like every other embed outcome (embed has no JSON// result surface — do not invent one here).- if (isKeylessStaleRefusal(args, loadConfig()?.embedding_disabled)) {- process.stderr.write(- '[embed] Embeddings are disabled on this brain (keyless install). '- + 'Nothing to backfill; keyword search keeps working. '- + 'Enable later: set embedding_model via gbrain config, then re-run gbrain init with the force flag.\n',- );+ const keylessConfig = loadConfig();+ if (isKeylessStaleRefusal(args, keylessConfig?.embedding_disabled)) {+ const enable = (await import('../core/readiness.ts')).embeddingEnablement(keylessConfig!).argv ?? ['gbrain', 'init', '--force', '--embedding-model', '<provider:model>'];+ process.stderr.write('[embed] Embeddings are disabled on this brain (keyless install). Nothing to backfill; keyword search keeps working. '+ + `Turn on semantic search (pages and facts are kept): ${(await import('../core/agent-output.ts')).shellQuote(enable)}\n`);return {embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0,pages_processed: 0, failures: 0, failure_samples: [], dryRun: false,diff --git a/src/commands/embeddings.ts b/src/commands/embeddings.tsindex 8efce0a697..1fc34a61cd 100644--- a/src/commands/embeddings.ts+++ b/src/commands/embeddings.ts@@ -129,6 +129,7 @@ async function enable(opts: EnableOpts): Promise<Record<string, unknown>> {fileCfg.embedding_dimensions = width;delete fileCfg.embedding_disabled;saveConfig(fileCfg);+ await engine.unsetConfig('embedding_disabled');const queuedChunks = await engine.countStaleChunks();const queuedFacts = (await countStaleFactEmbeddings(engine, opts.model, width)).count;return {diff --git a/src/commands/init.ts b/src/commands/init.tsindex 32cf1542f5..5f6ce82798 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -1228,6 +1228,7 @@ export async function initPGLite(opts: {// disables embedding at runtime.if (!opts.aiOpts?.noEmbedding && resolvedModel && resolvedDim) {delete config.embedding_disabled;+ await engine.unsetConfig('embedding_disabled');}// PR1: new installs publish their skill catalog over MCP by default// (existing config wins on re-init, so a prior opt-out is preserved).@@ -1566,6 +1567,7 @@ export async function initPostgresCore(opts: {// disables embedding at runtime.if (!opts.aiOpts?.noEmbedding && resolvedModel && resolvedDim) {delete config.embedding_disabled;+ await engine.unsetConfig('embedding_disabled');}// PR1: new installs publish their skill catalog over MCP by default// (existing config wins on re-init, so a prior opt-out is preserved).diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 14164c2b1c..ba1eaa8a10 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--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'],'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],- 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],+ 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--harness', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--url', '--wait', '--workers', '--yes'],@@ -60,7 +60,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],- 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],'feedback': ['--brain', '--help', '--json', '--page', '--source'],'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],@@ -114,7 +114,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],- 'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--harness', '--help', '--http', '--json', '--log-full-params', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--tools-json', '--url', '--yes'],+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],diff --git a/test/config-embedding-disabled-planes.test.ts b/test/config-embedding-disabled-planes.test.tsnew file mode 100644index 0000000000..d4357329c3--- /dev/null+++ b/test/config-embedding-disabled-planes.test.ts@@ -0,0 +1,85 @@+/**+ * #5253 + B-NEW-1/2/3: `embedding_disabled` and `schema_pack` report and+ * change the value the runtime uses. Authoring gate: (1) protects the+ * keyless-to-keyed journey through the real CLI (`config unset`, `set+ * true|false`, `init --force --embedding-model`), the effective `schema_pack`+ * in `config get`/`show`, and the one enablement command every keyless hint+ * names; (2) fails when `unset` reports not-found for the init sentinel, when+ * `set false` is shadowed by the file plane, when the enable path leaves a DB+ * row that keeps write-path embedding off, or when `config get schema_pack`+ * reports a value `schema active` does not use; (3) config-get-plane tests+ * use stubs and never cross planes; (4) no production seam (real subprocess,+ * isolated GBRAIN_HOME, no provider keys).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const CLI = join(import.meta.dir, '../src/cli.ts');++describe('embedding_disabled and schema_pack config planes', () => {+ let home: string;+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-config-planes-'));+ const init = await cli(['init', '--pglite', '--no-embedding']);+ expect(init.code).toBe(0);+ }, 120_000);+ afterAll(() => rmSync(home, { recursive: true, force: true }));++ async function cli(args: string[]) {+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0',+ GBRAIN_SKIP_UPGRADE_CHECK: '1', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined, GBRAIN_SCHEMA_PACK: undefined,+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined,+ GEMINI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: home, env, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { stdout: stdout.trim(), stderr, code };+ }+ const fileConfig = () => JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')) as Record<string, unknown>;++ test('a keyless embed names the one enablement command', async () => {+ const run = await cli(['embed', '--stale']);+ expect(run.stderr).toContain('Turn on semantic search (pages and facts are kept): gbrain init --force --embedding-model');+ expect(run.stderr).not.toContain('set embedding_model via gbrain config');+ }, 60_000);++ test('unset removes the init sentinel', async () => {+ expect(fileConfig().embedding_disabled).toBe(true);+ const run = await cli(['config', 'unset', 'embedding_disabled']);+ expect({ code: run.code, stdout: run.stdout }).toEqual({ code: 0, stdout: 'Unset embedding_disabled (file plane)' });+ expect('embedding_disabled' in fileConfig()).toBe(false);+ expect((await cli(['config', 'get', 'embedding_disabled'])).code).toBe(1);+ }, 60_000);++ test('set true and set false move both planes and get reports the runtime value', async () => {+ expect((await cli(['config', 'set', 'embedding_disabled', 'true'])).code).toBe(0);+ expect(fileConfig().embedding_disabled).toBe(true);+ expect((await cli(['config', 'get', 'embedding_disabled'])).stdout).toBe('true');+ expect((await cli(['config', 'set', 'embedding_disabled', 'false'])).code).toBe(0);+ expect('embedding_disabled' in fileConfig()).toBe(false);+ expect((await cli(['config', 'get', 'embedding_disabled'])).stdout).toBe('false');+ expect((await cli(['config', 'set', 'embedding_disabled', 'maybe'])).code).toBe(1);+ }, 60_000);++ test('the enable path clears both planes', async () => {+ expect((await cli(['config', 'set', 'embedding_disabled', 'true'])).code).toBe(0);+ const force = await cli(['init', '--force', '--embedding-model', 'voyage:voyage-4', '--embedding-dimensions', '1024',+ '--path', join(home, '.gbrain', 'brain.pglite')]);+ expect({ code: force.code, stderr: force.stderr }).toMatchObject({ code: 0 });+ expect(fileConfig()).toMatchObject({ embedding_model: 'voyage:voyage-4', embedding_dimensions: 1024 });+ const get = await cli(['config', 'get', 'embedding_disabled']);+ expect({ code: get.code, stdout: get.stdout }).toEqual({ code: 1, stdout: '' });+ }, 120_000);++ test('config get and show report the schema pack the runtime resolves', async () => {+ expect((await cli(['config', 'set', 'schema_pack', 'gbrain-creator'])).code).toBe(0);+ expect(fileConfig().schema_pack).not.toBe('gbrain-creator');+ const active = await cli(['schema', 'active']);+ expect(active.stdout).toContain('Active pack: gbrain-creator');+ const get = await cli(['config', 'get', 'schema_pack']);+ expect(get.stdout).toBe('gbrain-creator');+ expect(get.stderr).toContain('db plane');+ expect((await cli(['config', 'show'])).stdout).toContain('schema_pack: gbrain-creator');+ }, 60_000);+});