Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
32.8 KB
Raw Blame

Key files: Commands (4/6, continued)

Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/commands/pages-status.ts — gbrain pages status <slug...> [--source <id>] [--json] (#7179, read-only, CLI only): one PageStatus per slug (at most 200) in the sources resolve-path state vocabulary (searchable, pending_embedding, chunkless, keyword_only, quarantined, empty, missing, page_deleted) with searchable true/'keyword'/false, the page's chunks and unembedded (no vector in the active column), embedding_hold (a held or capped budget row that applies per budgetRowAppliesFilter), hold (the Git sync hold on its file from readGitHold, keyed by the source-root path under the source's slug mode), source_path, in_synced_commit (the file is in sources.last_commit; null without a Git checkout here) and why + fix; top level last_commit, head, at_head, embeddings_enabled. The state is the worst classifier row from listEmbeddingStateRows narrowed by slugs (quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks read pending_embedding, not keyword_only, and its fix is heldApproveAction (ask_user, preview first, never a spend). A sync hold's gitHoldFix wins over every other fix; otherwise embeddingStateFix, none for searchable, missing, page_deleted or pending on a brain keyless by choice. Strict arguments (invalid_params, exit 2); a page that is not searchable exits 0. Test: test/pages-status-7179.test.ts.

  • src/commands/persistence-admin.ts + src/core/persistence/{admin-contract,administration,transfer-administration}.ts — trusted local sources writer status|failures|claim|transfer (failures: Managed sync bookkeeping) and auth local-writer list|register|revoke. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status --probe acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. test/persistence-administration.test.ts covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. retry-effects <source> --request-id <original-uuid> --dry-run --json previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (--dry-run) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. transfer-administration.ts owns transfer prepare|accept|cancel: cancel <source> --expected-epoch <n> (intent writer_transfer_cancel, --dry-run previews) runs cancelWriterTransfer in ownership.ts on the owner host under the coordination lock and FOR UPDATE, requires draining at that epoch, returns the worktree to active and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses writer_transfer_conflict. Prepare stamps prepared_at. Test: test/pathological/c5-writer-transfer-cancel.test.ts (both engines).

  • src/commands/persistence-delegate.ts — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. reportPersistenceCliError owns the write exit verdict (writeErrorExitCode in persistence/write-wait.ts: pending exits 10 with poll_command, 0 with --accept-pending unless the receipt carries diagnostic.owner); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. runDeferredPersistenceCommand drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. scripts/generate-flag-registry.ts excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: test/persistence-cli-delegation.test.ts. #6255: a pending receipt's envelope carries the receipt fix, and poll_command plus the Poll: line are that same argv.

  • src/commands/pglite-repair.ts — gbrain pglite-repair: the manual surface for WAL repair (--dry-run | --yes | --json | --path <dir>; CLI_ONLY + SELF_HELP; returns an exit code via setCliExitVerdict, never process.exit). Never connects an engine — works when the DB won't open and when auto-repair is disabled. --dry-run is strictly read-only. Consent (C2) is consentGate (src/core/consent-cli.ts): destructive, bound to a plan_hash over the data dir, WAL segment names and a stale postmaster.pid (--dry-run --json reports it; approval is --yes --expect <plan_hash>, a bare --yes re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the .wal-repair-backup-<ts> folder, restoreCommand's undo) is on stderr, in the payload and the dry run; the receipt adds restore_command. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). src/commands/reinit-pglite.ts asks the same way (destructive, plan bound to the brain path and target model/width, the .bak restore command in the risk text; the .bak collision is refused before asking). The real run validates BEFORE locking (acquireLock mkdirs the data dir — a typo'd --path must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live gbrain serve is called out), refuses a reaped acquisition (refused_reaped_lock — no --force by design: force-removing .gbrain-lock would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by test/pglite-repair-command.serial.test.ts. --legacy-lock routes to src/commands/pglite-repair-legacy-lock.ts (runLegacyLockRepair): --dry-run prints inspectLegacyLock (src/core/pglite-legacy-lock.ts) with apply_argv, risk and user_message; apply takes acquireKernelLockOnly (5 s; busy → pglite_busy reason timeout), re-inspects under it, refuses legacy_lock_removal_refused (live_holder / network_filesystem / filesystem_unverified, fix = the preview), asks consentGate (destructive, plan hash bound to the legacy lock; a changed lock refuses preview_changed), inspects again after consent (refusal or a changed plan hash refuses; consentEnv / probe are test seams), then applies and prints the receipt. Pinned by test/pathological/c3-pglite-legacy-lock.test.ts.

  • src/commands/protocol.ts — gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]. --json emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev .ts entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean unavailable error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.

  • src/commands/providers.ts — gbrain providers list | test [--touchpoint T] [--model ID] | env <id> | explain [--json]: provider-recipe discovery + smoke-testing over the recipe registry. list renders formatRecipeTable against the SAME env the gateway actually sees (buildGatewayConfig(cfg).env, file-plane keys folded in) so the STATUS column matches what providers test and init would report. The pure formatEnvOutput(recipe, env) renders required keys, setup hints and endpoints; explain --json returns the recipe capability matrix without exposing key values. Pinned by test/providers.test.ts.

  • src/commands/publish.ts — Deterministic brain page publisher (code+skill pair, zero LLM calls)

  • src/commands/trust.ts — gbrain trust review|confirm|release|drop|revert|explain|allow|disable (#5575 DX-7; backfill is dispatched by src/cli/commands/trust.ts). runOwnerAction previews, asks for the typed token when the action raises trust, then applies bound to the preview; review --accept-all needs a filter and takes one confirmation (DX-15); an item whose write is still pending (a managed release that outlived the door's wait) is listed under pending with its poll command instead of not applied, and the run exits 1 when any item failed, else 10 when any is pending (0 with --accept-pending, except a pending item whose receipt names a stale owner; GBRA-248). The backend is the local engine, or maybeDelegateTrust (called from src/cli.ts before connecting) routes through a resident PGLite owner's administration socket with the prompt in the invoking CLI (DX-2); its trust_apply call waits OWNER_APPLY_TIMEOUT_MS (90 s: the release door's 60 s DOOR_WAIT_MS plus 30 s, src/core/trust/release-publish.ts). confirmTierCrossingAccepts puts tier-crossing decide proposals accept through the same rule; quarantine release|drop are aliases (src/cli/commands/quarantine.ts). Refusals render through writeCliError (exit 3 for consent refusals).

  • src/commands/quarantine.ts — gbrain quarantine <list|clear|scan> operator surface for the content-quality gate. list [--json] [--include-flagged] paginates listPages and reports quarantined (HIDDEN) pages, optionally also content_flag (FLAGGED, searchable) pages. clear <slug> [--force] [--no-embed] [--json] drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless --force sets GBRAIN_NO_SANITY=1 for that one import. scan [--limit N] [--apply] [--no-embed] [--json] re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective content_sanity config thresholds --apply will use, idempotent (skips already-marked pages), --apply re-imports with forceRechunk to set markers + (for quarantine) drop chunks. Dispatched in cli.ts. Pinned by test/quarantine-cli.test.ts. #6259: clear reads one snapshot (page, tags, revision) and, on a managed brain, publishes through submitPageMutation with that expected_revision (a concurrent edit is a revision_conflict, a pending receipt is reported as pending); --force writes a quarantine_override (see src/core/quarantine-override.ts) instead of disabling the gate, never mutation force. scan --apply refuses writer_coordinator_required on a managed brain. scan does not re-check a segmented page (it would hold the whole body as one string): it lists it in skipped (page_body_segmented) and goes on. It is a router (QUARANTINE_SUBCOMMANDS, printUsage). Tests: test/quarantine-override.serial.test.ts, test/quarantine-cli.test.ts.

  • src/commands/recall.ts — the gbrain recall CLI (facts-first by default; local engine or thin-client). Its help (RECALL_HELP, printed before the engine via SELF_HELP_WITHOUT_ENGINE) names --question for natural-language questions. Cat 41 run 4: keylessQuestionFallback — on a brain whose fact recall is keyword-only (factRecallIsKeywordOnly, src/core/facts/keyword-only.ts: embedding opted out or no provider), a multi-word positional that matched no entity and no fact text (#4720's fallback) is ranked as a question through runRecallVerb, with a stderr note; brains with embeddings keep their output and get a --question hint (test/recall-keyless-question-fallback.test.ts). --question <q> (or --question=<q>) is the question, never an entity: it routes through the recall op like --budget-policy (thin clients call the remote recall, an answer without facts_order prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each relevance and facts_degraded (test/recall-question-cli.test.ts). A malformed --limit (not a positive safe integer, or missing) throws invalid_params from parseFlags, so the CLI exits 2 through renderCliError: the v1 envelope under --json with why and a fix that reruns the same argv with --limit 50, and the Error/Fix/Why lines otherwise (test/recall-limit-envelope.test.ts). --since parses with parseSinceParam (src/core/facts/since-parse.ts, the parser the recall op uses); an unreadable or missing --since value and a --session/--session-id with no ID throw invalid_params from parseFlags (the bad value echoed, the accepted grammar in why) instead of dropping the bound (#6944, test/recall-bounds-envelope.test.ts). --since-last-run on a local brain pages oldest-first through listFactsKeyset (fetchCursorPage; recallNarrowing in engine-sql/facts.ts gives it the entity, session, grep and audit-row filters listFactsSince uses). advanceCursor records a full --limit window with writePagedCursor (the newest delivered row's (created_at, id); readRecallCursor in src/core/recall-cursor-state.ts trusts it only when it matches last_run_iso; still schema_version: 1), so the next run resumes after it; a caught-up run writes the wall-clock start. Thin-client and --supersessions keep the newest-N window and warn on stderr when it is full (#6945, test/recall-since-last-run-overflow.test.ts, thin warning in test/recall-budget-policy-thin-cli.test.ts). Optional --budget-policy facts_first|query_first routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no --grep/--supersessions/--session-id narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. --since composes with entity and session in one query before LIMIT, on event time unless --since-last-run. Local --grep is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only --supersessions keeps the client-side filter. Pinned by test/recall-grep-local-cli.test.ts. Pinned by test/facts-recall-since-composition.test.ts, test/recall-budget-policy-transports.test.ts, test/recall-budget-policy-thin-cli.test.ts, and test/recall-budget-policy-thin.serial.test.ts.

  • src/commands/reindex-aliases.ts — gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]: backfills the free-text alias layer for EXISTING pages whose frontmatter aliases: predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter aliases: (written via engine.setPageAliases) and, for linkable entity pages, rewrites the derived title-subject and declared rows (writeDerivedAliases, coordinated on managed brains). Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks listAllPageRefs (cheap cross-source enumeration), --source narrows. A segmented linkable page derives from its body read back as strings (materializedPage); one over the single-string ceiling gets frontmatter and subject aliases only, as its streamed import did, and is listed in body_not_scanned; a per-page page_body_segmented refusal is listed in skipped. Pinned by test/search/reindex-aliases.test.ts.

  • src/commands/projections.ts + src/cli/commands/projections.ts — gbrain projections drain [--dry-run] [--limit <n>] [--concurrency <n>] [--json] (#5401). --concurrency (#9192, Postgres only) sets how many pages rebuild at once on their own pooled connections: default from drainConcurrency in page-state/rebuild-estimate.ts (4, fewer on a small pool), at most the pool size less 2, refused above that; a refused or dropped connection narrows the width by one (stderr names it) without failing the drain, and PGLite rebuilds one page at a time. The drain order is pending rows search does not answer for, then image seals, then pending rows still answering from their pre-upgrade index. Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried), then (#6803, media: true) seals the sealable image pages through page-state/image-seal.ts; --limit caps pages tried. --dry-run prints every class count and the rows a drain takes (formatDrainPreview); the summary (formatDrainResult) lists the classes left with their next step and never says the backlog is empty while any remain; --json is the full ProjectionDrainResult. Under a resident it asks the resident for its counts (projection_status) and residentDrainAction builds doctor's two-step stop/drain/restart Action (requires_exclusive on the drain). Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or projection_owner_resident when a process holds the selected PGLite brain, checked with persistenceConfigForBrain before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). residentDrainSteps gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: projection-drain.test.ts (both engines via test/e2e/projection-drain-postgres.test.ts), projections-drain-cli.serial.test.ts, projection-image-drain.test.ts (both engines via test/e2e/projection-image-drain-postgres.test.ts).

  • src/commands/reindex-code.ts — gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]. Walks live page_kind = 'code' pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. --force rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in reindex-code-delegate.ts. Cost-preview model field reads getEmbeddingModelName() from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside runReindexCode (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist {'voyage-code-3'}, case-insensitive bare match), prints a recommendation to switch to voyage:voyage-code-3; suppress with GBRAIN_NO_CODE_MODEL_NUDGE=1, --no-embed, or --json. Pure shouldNudgeCodeModel(bareName) returns a tagged NudgeDecision union (takes the bare model name, emits qualified voyage:voyage-code-3 for the paste-ready gbrain config set line). Consent (C2): the cost preview feeds consentGate (effect paid); --yes, --max-cost <usd>, a preapproval or tokenmax authorize it, otherwise exit 3 with the consent payload. Without a user cap the run gets the derived cap, except under tokenmax (tokenmaxUncappedEnv: stays uncapped); --max-cost off is the explicit uncapped choice. The owner-delegated path asks the same way (default cap). Pinned by test/ai/voyage-code-3-recipe.test.ts, test/reindex-code-nudge.serial.test.ts, test/reindex-code-model-source.serial.test.ts (IRON-RULE guard for the cost-preview model source). --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow. Without managed persistence, reindexCodeProjection (src/core/persistence/projection-reindex.ts) re-reads and re-prepares a page whose install lost to another installer (skipped when it is now sealed and --force is off); a conflict that outlasts the retries is a per-page failure carrying [page_projection_conflict] and the re-run step (test/page-projection-code-recovery.test.ts).

  • src/commands/reindex-frontmatter.ts — gbrain reindex-frontmatter. reindexFrontmatterCli(engine, args) takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to runBackfillCommand(engine, args) in src/commands/backfill.ts and any future command dispatched from cli.ts's engine-connected switch. Pinned by test/reindex-frontmatter-connect.test.ts (library path) and test/reindex-frontmatter-pglite-spawn.test.ts (CLI dispatch seam, both commands). Consent (agent operator wave C3): every run first previews one selection (the rows whose stored effective_date/effective_date_source would change, scoped by --source and --slug-prefix through backfillEffectiveDate's sourceId filter) and hashes it; the dry run reports that plan_hash. An apply asks through requireConsent (effect destructive, bound to the plan: --yes --expect <plan_hash>; a changed row is preview_changed) and writes only the approved ids (onlyIds). --json never implies consent: non-interactive without approval changes nothing, returns status: 'confirmation_required' and exits 3 with the consent payload. Scoped walks never read or write the orchestrator's brain-wide checkpoint. Pinned by test/reindex-frontmatter-consent.test.ts (two-source scope, binding).

  • src/commands/reindex-multimodal.ts — gbrain reindex --multimodal [--limit N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]. Walks content_chunks WHERE embedding_multimodal IS NULL, batches via embedMultimodalSafe (partial-failure-aware), persists. Lock via tryAcquireDbLock (360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY. GBRAIN_NO_REEMBED=1 bypass. Checkpoint at ~/.gbrain/reindex-multimodal-checkpoint.json for resume. Auto-flip prompt at coverage=100% completion (TTY: interactive; non-TTY: stderr hint with a paste-ready command).

  • src/commands/reindex-vectors.ts — gbrain reindex --vectors [--dry-run] [--json] (dispatched from cli.ts beside --aliases). Lists every HNSW index in the current schema from pg_indexes and runs REINDEX INDEX on each (REINDEX INDEX CONCURRENTLY on Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs inside withHnswBuildMemory (vector-index.ts), which sizes PGLite's maintenance_work_mem to the graph or refuses with pglite_vector_index_too_large. The PGLite WAL-repair notice (buildWalRepairNotice) and gbrain pglite-repair name it, because a WAL reset does not rebuild indexes (#4616). Tests: test/embedding-zero-norm-4616.serial.test.ts on both engines.

  • src/commands/reindex-search-vector.ts — gbrain reindex-search-vector [--dry-run] [--yes] [--json]. Escape hatch for changing GBRAIN_FTS_LANGUAGE after the configurable_fts_language migration has run (the migration shows applied and is skipped): recreates update_page_search_vector + update_chunk_search_vector with the configured language through pageSearchVectorTriggerFnSql/chunkSearchVectorTriggerFnSql (fts-language.ts; CREATE OR REPLACE resets their pinned search_path = pg_catalog, public, so the command then runs FUNCTION_SEARCH_PATH_HARDENING_SQL from src/core/function-search-path.ts to put pg_temp back last, #7632; keep that call after the recreate) — then backfills pages and content_chunks through src/core/search-vector-backfill.ts in id-keyset batches of BACKFILL_BATCH_SIZE (5000). Pages: an UPDATE-to-self of id reads each batch (RETURNING id, timeline, knowledge_revision; row locks only for that statement), the timeline is sanitized with sanitizeRemoteBody as the seal does, and one UPDATE … FROM unnest(…) writes search_vector through pageSearchVectorSql (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id. It then replaces idx_facts_fts (v237) under the language through ensureFactsFtsIndex (src/core/facts/fts-index.ts): the new index is built beside the old one (CONCURRENTLY on Postgres) and renamed into place, so writes never wait and search keeps an index (no row rewrite). Both stream phases reindex_search_vector.pages/.chunks through the shared progress reporter (stderr). Consent gate (agent operator wave C2): requireConsent (effect destructive, not plan-bound: derived index, the undo is a re-run under the previous language) — --yes or a TTY prompt; --json never implies it, and a refusal changes nothing, returns status: 'confirmation_required' and exits 3 with the consent payload. Interrupted-run safety: stamps fts.reindex_in_progress (= target language, key exported as FTS_REINDEX_MARKER_KEY from fts-language.ts) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under backfill.fts_pages.last_id / backfill.fts_content_chunks.last_id (the checkpointKey convention from backfill-base.ts), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one engine.transaction() (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by test/reindex-search-vector.serial.test.ts and test/reindex-search-vector-pages.serial.test.ts.

  • src/commands/init-mode-picker.ts — install-time mode recommendation and mandatory operator choice. recommendModeFor recommends tokenmax with a chat key, balanced with a ready reranker and no chat key, and conservative for a Haiku subagent or when neither exists; resolveModePickerInputs reads keys through mergedProviderEnv (so ~/.gbrain/config.json keys count) and the reranker through rerankerReadiness. gbrain init --search-mode <mode> (searchModeChoiceFromArgs) records the operator's choice, suppresses the first-run search_mode ask and refuses on a brain with another mode unless --force; picker choices record search.mode_source: auto, explicit ones operator. Reasons, the [AGENT] banner and the cost matrix come from src/core/search/mode-advice.ts. Pinned by test/init-mode-picker.test.ts.

  • src/core/embedding-migration-cli.ts — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by commands/migrate-embeddings.ts). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.

  • test/migrate-embeddings-recovery-cli.serial.test.ts — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static EMBEDDING_MIGRATION_RECOVERY is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by test/migrate-embeddings-op-contract.serial.test.ts. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.

  • src/core/maintenance/run.ts + src/core/maintenance/status.ts — GBRA-438 free unattended upkeep. unattendedPlan is the --safe list plus bookkeeping_gc, split into one global item (brain-wide phases, once per window under gbrain-cycle), one item per source and, while the conversation archive resolves on, a last transcript_archive item (runArchiveMaintenance; its errors are a warn step, never a failed pass); cycles run with stamp: 'none' and deferFactEmbedding on a keyed brain. runUnattendedMaintenance never throws: preflight skips (maintenance_disabled, engine_degraded, migrations_pending, maintenance_owned_by_autopilot when autopilot.last_global_at is under 48h old, write_capacity_backpressure, cycle_already_running) exit 0; a failed step records its code (exit 1 for maintain) and three same-code failures back the step off to once a week. A budgeted run parks an item its budget stopped UPKEEP_PARK_AFTER_SLICES (30) times, in parked (a foreground abort never counts; skipped by budgeted runs for the rest of the round, rerun each new round, by an unbudgeted run or by retryParked, a serve's first idle run; readUpkeepStatus state parked warns); test test/maintenance-park-gbra438.test.ts. The embedding step runs under maintenance.embed_daily_usd (default $1 per UTC day, 0 = off; spend in maintenance.embed_spend), one runner at a time (MAINTENANCE_EMBED_LOCK_ID; a busy lock skips it as embed_running). The record is maintenance.last_run (database config, so repo-less brains have one). readUpkeepStatus is the one view behind --status and doctor. Tests: test/maintenance-unattended.test.ts (both engines).

  • src/core/maintenance/idle.ts + src/commands/maintain-schedule.ts — GBRA-438 PR 2, the upkeep runners. runIdleUpkeep runs runUnattendedMaintenance as runner serve with IDLE_UPKEEP_BUDGET_MS (3 s) when upkeep is on and due (upkeepDue); the stdio serve calls it from its idle tick after the sweep, in the same in-flight slot, and stdin data, onForegroundRequest or shutdown aborts it. armIdleUpkeep is the HTTP serve's idle timer: mcpForegroundMiddleware (in src/core/foreground-activity.ts, mounted on POST /mcp after the bearer check by serve-http-mcp.ts) marks each authenticated /mcp POST foreground, so a 401 never counts (#9484), the first tick only opens the window, one run at a time. A finished round on PGLite ends with a CHECKPOINT step. maintain-schedule.ts is routed engine-free from src/cli/main.ts: --schedule (consent persistent_install, --dry-run preview) writes a wrapper and a launchd plist, systemd user service and timer, or a # gbrain-maintain crontab line (pure renderers, every 6 hours); Windows and containers refuse schedule_unsupported; --unschedule removes it. A scheduled --unattended --runner schedule run exits 0 maintenance_owned_by_serve while a live serve holds the brain (PGLite lock holder, or the CLI socket on Postgres). Tests: test/serve-idle-upkeep-gbra438.test.ts, test/maintenance-idle-gbra438.test.ts (both engines, two serves on one brain), test/maintain-schedule-gbra438.test.ts, test/e2e/serve-idle-upkeep-keyless-pglite.test.ts. The cycle hands its signal to the repo-less stale link drain (extractStaleFromDB signal), so a slice stops between 25-page batches, and runExtractFacts yields a macrotask every 50 pages of its walk, so a timer or stdin can trip the abort mid-walk on PGLite. Bench: scripts/bench/serve-upkeep-latency.ts (tool-call latency during idle upkeep on a keyless repo-less PGLite brain, against a sweep-only baseline).