Garry's Opinionated OpenClaw/Hermes Agent Brain
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): onePageStatusper slug (at most 200) in thesources resolve-pathstate vocabulary (searchable,pending_embedding,chunkless,keyword_only,quarantined,empty,missing,page_deleted) withsearchabletrue/'keyword'/false, the page's chunks andunembedded(no vector in the active column),embedding_hold(a held or capped budget row that applies perbudgetRowAppliesFilter),hold(the Git sync hold on its file fromreadGitHold, keyed by the source-root path under the source's slug mode),source_path,in_synced_commit(the file is insources.last_commit; null without a Git checkout here) andwhy+fix; top levellast_commit,head,at_head,embeddings_enabled. The state is the worst classifier row fromlistEmbeddingStateRowsnarrowed byslugs(quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks readpending_embedding, not keyword_only, and its fix isheldApproveAction(ask_user, preview first, never a spend). A sync hold'sgitHoldFixwins over every other fix; otherwiseembeddingStateFix, none forsearchable,missing,page_deletedor 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 localsources writer status|failures|claim|transfer(failures: Managed sync bookkeeping) andauth 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--probeacquires/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.tscovers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses.retry-effects <source> --request-id <original-uuid> --dry-run --jsonpreviews 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.tsownstransfer prepare|accept|cancel:cancel <source> --expected-epoch <n>(intentwriter_transfer_cancel,--dry-runpreviews) runscancelWriterTransferinownership.tson the owner host under the coordination lock andFOR UPDATE, requiresdrainingat that epoch, returns the worktree toactiveand clears the prepared manifest while keeping the epoch, so an accept bound to it refuseswriter_transfer_conflict. Prepare stampsprepared_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.reportPersistenceCliErrorowns the write exit verdict (writeErrorExitCodeinpersistence/write-wait.ts: pending exits 10 withpoll_command, 0 with--accept-pendingunless the receipt carriesdiagnostic.owner); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting.runDeferredPersistenceCommanddrains/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.tsexcludes 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, andpoll_commandplus thePoll: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 viasetCliExitVerdict, neverprocess.exit). Never connects an engine — works when the DB won't open and when auto-repair is disabled.--dry-runis strictly read-only. Consent (C2) isconsentGate(src/core/consent-cli.ts):destructive, bound to aplan_hashover the data dir, WAL segment names and a stale postmaster.pid (--dry-run --jsonreports it; approval is--yes --expect <plan_hash>, a bare--yesre-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 addsrestore_command. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline).src/commands/reinit-pglite.tsasks the same way (destructive, plan bound to the brain path and target model/width, the.bakrestore command in the risk text; the.bakcollision is refused before asking). The real run validates BEFORE locking (acquireLockmkdirs the data dir — a typo'd--pathmust not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a livegbrain serveis called out), refuses a reaped acquisition (refused_reaped_lock— no--forceby design: force-removing.gbrain-lockwould reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned bytest/pglite-repair-command.serial.test.ts.--legacy-lockroutes tosrc/commands/pglite-repair-legacy-lock.ts(runLegacyLockRepair):--dry-runprintsinspectLegacyLock(src/core/pglite-legacy-lock.ts) withapply_argv, risk and user_message; apply takesacquireKernelLockOnly(5 s; busy →pglite_busyreasontimeout), re-inspects under it, refuseslegacy_lock_removal_refused(live_holder/network_filesystem/filesystem_unverified, fix = the preview), asksconsentGate(destructive, plan hash bound to the legacy lock; a changed lock refusespreview_changed), inspects again after consent (refusal or a changed plan hash refuses;consentEnv/probeare test seams), then applies and prints the receipt. Pinned bytest/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].--jsonemits 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.tsentry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the cleanunavailableerror). 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.listrendersformatRecipeTableagainst the SAME env the gateway actually sees (buildGatewayConfig(cfg).env, file-plane keys folded in) so the STATUS column matches whatproviders testand init would report. The pureformatEnvOutput(recipe, env)renders required keys, setup hints and endpoints;explain --jsonreturns the recipe capability matrix without exposing key values. Pinned bytest/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;backfillis dispatched bysrc/cli/commands/trust.ts).runOwnerActionpreviews, asks for the typed token when the action raises trust, then applies bound to the preview;review --accept-allneeds 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 underpendingwith its poll command instead ofnot 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, ormaybeDelegateTrust(called fromsrc/cli.tsbefore connecting) routes through a resident PGLite owner's administration socket with the prompt in the invoking CLI (DX-2); itstrust_applycall waitsOWNER_APPLY_TIMEOUT_MS(90 s: the release door's 60 sDOOR_WAIT_MSplus 30 s,src/core/trust/release-publish.ts).confirmTierCrossingAcceptsputs tier-crossingdecide proposals acceptthrough the same rule;quarantine release|dropare aliases (src/cli/commands/quarantine.ts). Refusals render throughwriteCliError(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]paginateslistPagesand reports quarantined (HIDDEN) pages, optionally alsocontent_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--forcesetsGBRAIN_NO_SANITY=1for 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 effectivecontent_sanityconfig thresholds--applywill use, idempotent (skips already-marked pages),--applyre-imports withforceRechunkto set markers + (for quarantine) drop chunks. Dispatched incli.ts. Pinned bytest/quarantine-cli.test.ts. #6259:clearreads one snapshot (page, tags, revision) and, on a managed brain, publishes throughsubmitPageMutationwith thatexpected_revision(a concurrent edit is arevision_conflict, a pending receipt is reported as pending);--forcewrites aquarantine_override(seesrc/core/quarantine-override.ts) instead of disabling the gate, never mutationforce.scan --applyrefuseswriter_coordinator_requiredon a managed brain.scandoes not re-check a segmented page (it would hold the whole body as one string): it lists it inskipped(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— thegbrain recallCLI (facts-first by default; local engine or thin-client). Its help (RECALL_HELP, printed before the engine viaSELF_HELP_WITHOUT_ENGINE) names--questionfor 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 throughrunRecallVerb, with a stderr note; brains with embeddings keep their output and get a--questionhint (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 withoutfacts_orderprints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, eachrelevanceandfacts_degraded(test/recall-question-cli.test.ts). A malformed--limit(not a positive safe integer, or missing) throwsinvalid_paramsfromparseFlags, so the CLI exits 2 throughrenderCliError: the v1 envelope under--jsonwithwhyand afixthat reruns the same argv with--limit 50, and the Error/Fix/Why lines otherwise (test/recall-limit-envelope.test.ts).--sinceparses withparseSinceParam(src/core/facts/since-parse.ts, the parser the recall op uses); an unreadable or missing--sincevalue and a--session/--session-idwith no ID throwinvalid_paramsfromparseFlags(the bad value echoed, the accepted grammar inwhy) instead of dropping the bound (#6944,test/recall-bounds-envelope.test.ts).--since-last-runon a local brain pages oldest-first throughlistFactsKeyset(fetchCursorPage;recallNarrowinginengine-sql/facts.tsgives it the entity, session, grep and audit-row filterslistFactsSinceuses).advanceCursorrecords a full--limitwindow withwritePagedCursor(the newest delivered row's(created_at, id);readRecallCursorinsrc/core/recall-cursor-state.tstrusts it only when it matcheslast_run_iso; stillschema_version: 1), so the next run resumes after it; a caught-up run writes the wall-clock start. Thin-client and--supersessionskeep the newest-N window and warn on stderr when it is full (#6945,test/recall-since-last-run-overflow.test.ts, thin warning intest/recall-budget-policy-thin-cli.test.ts). Optional--budget-policy facts_first|query_firstroutes 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-idnarrows 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.--sincecomposes with entity and session in one query before LIMIT, on event time unless--since-last-run. Local--grepis passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only--supersessionskeeps the client-side filter. Pinned bytest/recall-grep-local-cli.test.ts. Pinned bytest/facts-recall-since-composition.test.ts,test/recall-budget-policy-transports.test.ts,test/recall-budget-policy-thin-cli.test.ts, andtest/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 frontmatteraliases:predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatteraliases:(written viaengine.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; walkslistAllPageRefs(cheap cross-source enumeration),--sourcenarrows. 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 inbody_not_scanned; a per-pagepage_body_segmentedrefusal is listed inskipped. Pinned bytest/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 fromdrainConcurrencyinpage-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 thesealableimage pages throughpage-state/image-seal.ts;--limitcaps pages tried.--dry-runprints 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;--jsonis the fullProjectionDrainResult. Under a resident it asks the resident for its counts (projection_status) andresidentDrainActionbuilds doctor's two-step stop/drain/restart Action (requires_exclusiveon 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, orprojection_owner_residentwhen a process holds the selected PGLite brain, checked withpersistenceConfigForBrainbefore 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).residentDrainStepsgives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests:projection-drain.test.ts(both engines viatest/e2e/projection-drain-postgres.test.ts),projections-drain-cli.serial.test.ts,projection-image-drain.test.ts(both engines viatest/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 livepage_kind = 'code'pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes.--forcerebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route inreindex-code-delegate.ts. Cost-preview model field readsgetEmbeddingModelName()from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge insiderunReindexCode(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 tovoyage:voyage-code-3; suppress withGBRAIN_NO_CODE_MODEL_NUDGE=1,--no-embed, or--json. PureshouldNudgeCodeModel(bareName)returns a taggedNudgeDecisionunion (takes the bare model name, emits qualifiedvoyage:voyage-code-3for the paste-readygbrain config setline). Consent (C2): the cost preview feedsconsentGate(effectpaid);--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 offis the explicit uncapped choice. The owner-delegated path asks the same way (default cap). Pinned bytest/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--forceis 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 torunBackfillCommand(engine, args)insrc/commands/backfill.tsand any future command dispatched from cli.ts's engine-connected switch. Pinned bytest/reindex-frontmatter-connect.test.ts(library path) andtest/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 storedeffective_date/effective_date_sourcewould change, scoped by--sourceand--slug-prefixthroughbackfillEffectiveDate'ssourceIdfilter) and hashes it; the dry run reports thatplan_hash. An apply asks throughrequireConsent(effectdestructive, bound to the plan:--yes --expect <plan_hash>; a changed row ispreview_changed) and writes only the approved ids (onlyIds).--jsonnever implies consent: non-interactive without approval changes nothing, returnsstatus: 'confirmation_required'and exits 3 with the consent payload. Scoped walks never read or write the orchestrator's brain-wide checkpoint. Pinned bytest/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]. Walkscontent_chunks WHERE embedding_multimodal IS NULL, batches viaembedMultimodalSafe(partial-failure-aware), persists. Lock viatryAcquireDbLock(360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY.GBRAIN_NO_REEMBED=1bypass. Checkpoint at~/.gbrain/reindex-multimodal-checkpoint.jsonfor 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 frompg_indexesand runsREINDEX INDEXon each (REINDEX INDEX CONCURRENTLYon Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs insidewithHnswBuildMemory(vector-index.ts), which sizes PGLite'smaintenance_work_memto the graph or refuses withpglite_vector_index_too_large. The PGLite WAL-repair notice (buildWalRepairNotice) andgbrain pglite-repairname it, because a WAL reset does not rebuild indexes (#4616). Tests:test/embedding-zero-norm-4616.serial.test.tson both engines.src/commands/reindex-search-vector.ts—gbrain reindex-search-vector [--dry-run] [--yes] [--json]. Escape hatch for changingGBRAIN_FTS_LANGUAGEafter theconfigurable_fts_languagemigration has run (the migration shows applied and is skipped): recreatesupdate_page_search_vector+update_chunk_search_vectorwith the configured language throughpageSearchVectorTriggerFnSql/chunkSearchVectorTriggerFnSql(fts-language.ts; CREATE OR REPLACE resets their pinnedsearch_path = pg_catalog, public, so the command then runsFUNCTION_SEARCH_PATH_HARDENING_SQLfromsrc/core/function-search-path.tsto putpg_tempback last, #7632; keep that call after the recreate) — then backfillspagesandcontent_chunksthroughsrc/core/search-vector-backfill.tsin id-keyset batches ofBACKFILL_BATCH_SIZE(5000). Pages: an UPDATE-to-self ofidreads each batch (RETURNING id, timeline, knowledge_revision; row locks only for that statement), the timeline is sanitized withsanitizeRemoteBodyas the seal does, and oneUPDATE … FROM unnest(…)writessearch_vectorthroughpageSearchVectorSql(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 viaUPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id. It then replacesidx_facts_fts(v237) under the language throughensureFactsFtsIndex(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 phasesreindex_search_vector.pages/.chunksthrough the shared progress reporter (stderr). Consent gate (agent operator wave C2):requireConsent(effectdestructive, not plan-bound: derived index, the undo is a re-run under the previous language) —--yesor a TTY prompt;--jsonnever implies it, and a refusal changes nothing, returnsstatus: 'confirmation_required'and exits 3 with the consent payload. Interrupted-run safety: stampsfts.reindex_in_progress(= target language, key exported asFTS_REINDEX_MARKER_KEYfromfts-language.ts) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor underbackfill.fts_pages.last_id/backfill.fts_content_chunks.last_id(thecheckpointKeyconvention frombackfill-base.ts), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not oneengine.transaction()(whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned bytest/reindex-search-vector.serial.test.tsandtest/reindex-search-vector-pages.serial.test.ts.src/commands/init-mode-picker.ts— install-time mode recommendation and mandatory operator choice.recommendModeForrecommendstokenmaxwith a chat key,balancedwith a ready reranker and no chat key, andconservativefor a Haiku subagent or when neither exists;resolveModePickerInputsreads keys throughmergedProviderEnv(so~/.gbrain/config.jsonkeys count) and the reranker throughrerankerReadiness.gbrain init --search-mode <mode>(searchModeChoiceFromArgs) records the operator's choice, suppresses the first-runsearch_modeask and refuses on a brain with another mode unless--force; picker choices recordsearch.mode_source: auto, explicit onesoperator. Reasons, the[AGENT]banner and the cost matrix come fromsrc/core/search/mode-advice.ts. Pinned bytest/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 bycommands/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 staticEMBEDDING_MIGRATION_RECOVERYis shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered bytest/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.unattendedPlanis the--safelist plusbookkeeping_gc, split into one global item (brain-wide phases, once per window undergbrain-cycle), one item per source and, while the conversation archive resolves on, a lasttranscript_archiveitem (runArchiveMaintenance; its errors are awarnstep, never a failed pass); cycles run withstamp: 'none'anddeferFactEmbeddingon a keyed brain.runUnattendedMaintenancenever throws: preflight skips (maintenance_disabled,engine_degraded,migrations_pending,maintenance_owned_by_autopilotwhenautopilot.last_global_atis under 48h old,write_capacity_backpressure,cycle_already_running) exit 0; a failed step records its code (exit 1 formaintain) and three same-code failures back the step off to once a week. A budgeted run parks an item its budget stoppedUPKEEP_PARK_AFTER_SLICES(30) times, inparked(a foreground abort never counts; skipped by budgeted runs for the rest of the round, rerun each new round, by an unbudgeted run or byretryParked, a serve's first idle run;readUpkeepStatusstateparkedwarns); testtest/maintenance-park-gbra438.test.ts. The embedding step runs undermaintenance.embed_daily_usd(default $1 per UTC day, 0 = off; spend inmaintenance.embed_spend), one runner at a time (MAINTENANCE_EMBED_LOCK_ID; a busy lock skips it asembed_running). The record ismaintenance.last_run(database config, so repo-less brains have one).readUpkeepStatusis the one view behind--statusand 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.runIdleUpkeeprunsrunUnattendedMaintenanceas runnerservewithIDLE_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,onForegroundRequestor shutdown aborts it.armIdleUpkeepis the HTTP serve's idle timer:mcpForegroundMiddleware(insrc/core/foreground-activity.ts, mounted on POST/mcpafter the bearer check byserve-http-mcp.ts) marks each authenticated/mcpPOST 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 aCHECKPOINTstep.maintain-schedule.tsis routed engine-free fromsrc/cli/main.ts:--schedule(consentpersistent_install,--dry-runpreview) writes a wrapper and a launchd plist, systemd user service and timer, or a# gbrain-maintaincrontab line (pure renderers, every 6 hours); Windows and containers refuseschedule_unsupported;--unscheduleremoves it. A scheduled--unattended --runner schedulerun exits 0maintenance_owned_by_servewhile 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 (extractStaleFromDBsignal), so a slice stops between 25-page batches, andrunExtractFactsyields 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).