Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
55.1 KB
Raw Blame

Key files: Commands (2/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/doctor/checks/home-worktree.ts — the home_dir_in_worktree check: walks up from the gbrain home looking for an enclosing .git (dir or linked-worktree file), warning that a git add from the worktree root could stage the brain; stops at $HOME. Both anchors (GBRAIN_HOME, $HOME) are path.resolve()d before the containment test, so a trailing-slash HOME=/home/user/ (a common shell/launchd spelling) cannot make a brain inside a worktree grade ok. isValidGitMarker structurally validates a candidate before it counts (a .git/ dir must contain HEAD; a .git file must start with gitdir: — git itself rejects anything else), and invalid candidates CONTINUE the walk so a valid repo higher up still warns. Cheap (stat + read, no subprocess) — runs on every doctor invocation including --fast.

  • src/commands/doctor/checks/integrations-memorable.ts — memorable_relay_health (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives --fast/--scope. Rung ladder: gate off → quiet ok; enabled WITHOUT the gbrain disclosure stamp → FAIL naming the exact fix (the memorable enable out-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the shared clampRelayCause; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw no_decisive_steps rejection, which becomes an ok-with-note (expected_openclaw_rejection, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (codex_hooks_never_fired — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (out_of_band_settable: true always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by test/doctor-memorable.test.ts.

  • src/commands/doctor/checks/routing-federation.ts — checkOauthClientScopeHealth (oauth_client_scope_health, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty <name>-workspace sources, (c) privileged self-registered clients — active oauth_clients rows whose scope word-matches DCR_PRIVILEGED_SCOPES — the DERIVED complement ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES (exported; bound as a $1 regex parameter, never interpolated) — and the (read/write) / --scopes read,write copy is built from DCR_REGISTRABLE_SCOPES; pinned by the set-equality + per-scope loop in test/doctor-oauth-client-scope-health.test.ts; rows with grant_revision = 0 and no oauth_grant_audit row with action = 'register' (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the gbrain auth rescope-client <client_id> --scopes read,write / gbrain auth revoke-client <client_id> remedy; when the audit table or grant_revision column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by test/doctor-oauth-client-scope-health.test.ts.

  • src/commands/doctor/checks/postgres-tls.ts — postgres_tls (OPS, after rls), judged from the client side: the mode resolvePgTls gives for engine.connectedDatabaseUrl (the config URL only as a fallback). require, allow, verify-ca and verify-full are ok, because the driver refuses a server without TLS; sslmode=disable warns; sslmode=prefer sends one SSLRequest probe (probeServerTls) and warns when the answer is no or the session reads unencrypted, since the driver falls back to plaintext silently; otherwise it is ok with client_tls: null (a fresh probe is not the engine's socket). A PGSSL value is TLS to the driver even when it reads disable (only URL values turn TLS off). The session's pg_stat_ssl row is detail only: behind a pooler it describes the pooler's hop to the database. Ok on a loopback host, nothing on PGLite. The fix asks the user; verify is gbrain doctor --only postgres_tls. postgresTlsCheck(url, session, env, preferAnswer) is the pure half (test/doctor-postgres-tls.test.ts; real servers and a TLS-client pooler in test/e2e/pg-tls-postgres.test.ts).

  • src/commands/doctor/checks/embedding-identity.ts — embedding_identity_unqualified (#6113, BRAIN, right after embedding_env_override): warns when the DB config row embedding_model has no provider prefix (managed fact extraction reads only that row and config set refuses it). The fix is the read-only gbrain migrate embeddings --to <provider:model> --dry-run, filled from loadConfig()'s provider-qualified embedding_model, or <PROVIDER_MODEL> plus an inputs entry when none is configured; details.target_differs flags a configured model with another name (applying it switches models). Applying re-embeds active facts (paid, user's call). The free relabel is parked (TODOS). Test: test/doctor-embedding-identity-unqualified.test.ts.

  • src/commands/doctor/checks/embedding-state.ts — embedding_state (#6696 B3, BRAIN, tier: 'ops', opsPglite: 'not_applicable', after embeddings): readEmbeddingState in ops mode on the ops tier, full otherwise. Warns only on purgeable chunks of pages soft-deleted past the 72h window (deleted_page_chunks_overdue, fix pages purge-deleted) and, on a keyed brain, live pages with body text but no chunks (chunkless_pages_healable, fix embed --stale); the pending backlog is embeddings' warning and quarantined pages quarantined_pages'. keyword_only, held or in-window deleted chunks and a keyless brain are infoCheck; ops without a covering index warns with details.health: 'unknown' (embedding_state_unknown). Test: test/doctor-embedding-state.test.ts.

  • src/commands/doctor/checks/knowledge-health.ts — facts_extraction_health reads the last 24 h of facts:absorb rows in ingest_log (written by src/core/facts/absorb-log.ts) per source and reason (split_part(summary, ':', 1)) and warns when a failure reason reaches facts.absorb_warn_threshold (default 10) in a source. Two reasons are not failures and never count: write_pending_accepted (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and write_deferred_unadmitted (writer_lock_unavailable before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed facts-absorb job for the same page; that warning's fix is the read-only gbrain sources writer status --source <id> --json. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and details.facts_absorb (incidents_24h, ages_out_at, jobs_still_dead, dead_jobs) adds the current state, the facts-absorb jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid gbrain jobs retry <id> fix (retry_job over MCP, asks first). Tests: test/doctor-facts-absorb-contention-6778.test.ts, test/facts-absorb-publish-wait-6778.test.ts, test/doctor-facts-absorb-history-6761.test.ts.

  • src/commands/doctor/checks/persistence-consumers.ts — #6317 (B3, T1c): doctor two_consumers_on_host (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a put or a row younger than 30 s, is listed in details) and consumers_without_heartbeat (a claim_phase.owner pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured agentFix (gbrain sources writer status --json) and doctorVerify; with persistence.single_consumer off the overlap is reported as the configured behavior. serve_build_drift (#6696 C6, its own serveBuildDriftEntry, one listHostConsumers read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's VERSION through compareWriterVersions (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with details { count, this_version, owner, older, newer } and a fix (actor user, doctorVerify) whose argv is the installed serve service's restart (systemctl --user restart gbrain-serve.service when systemdUnitPath exists on Linux, launchctl kickstart -k gui/<uid>/com.gbrain.serve when launchdPlistPath exists on macOS; serveBuildDriftCheck's ServiceHost argument injects platform, home and uid) or else kill <pid>; a newer row is reported in an ok message; no rows names consumers_without_heartbeat for a pre-heartbeat serve. Registered in DOCTOR_CHECK_REGISTRY (the consumer entry, then serveBuildDriftEntry) before searchModeEntry and categorised ops in src/core/doctor-categories.ts. Tests: test/doctor-serve-build-drift.test.ts.

  • src/commands/doctor/checks/runtime-build-skew.ts — #7245: doctor runtime_build_skew (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), skipping a row this process can prove dead (consumerRowProvablyDead: an old serve stopped on SIGTERM can leave its row renewed for 30 s, GST-2688), worker parents from the worker registry (version, install_root), the supervisor from its PID file (readSupervisorBuild), and job-child builds from job_build_skew: history on the newest 500 jobs of the last 24 h while their worker pid lives. Fails on 2+ builds, warns when only an install differs; fix: ask, then gbrain upgrade --restart-only; the message names the manual restart: serve (restartArgv, exported from persistence-consumers.ts), else the supervisor (gbrain jobs supervisor stop), else a worker pid. Output: pids and versions only. Pinned by test/doctor-runtime-build-skew.test.ts.

  • src/commands/dream-retriage.ts — gbrain dream retriage: re-scores synthesize's list (withConversationPages, #7307) via the shared runTriagePass (with maxMs: 0 — operator sweeps run to completion; --limit slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead dream-inline-* queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live gbrain_cycle_locks row suppresses conversion only for queues born at/after its acquired_at; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via canonicalLookup on the resolved triage model, confirmation above SPEND_CONFIRM_USD ($5, in dream-retriage-constants.ts; unpriced models gate on UNPRICED_CONFIRM_FILES=500) through requireConsent (effect paid; --yes, --max-usd, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, --json never implying it); the budget (--max-usd, else the derived consent cap) soft-stops via the pass's shouldStop seam (estimate-based) and bounds the --audit-rejects half. --reconcile-queue (opt-in — cancels queued work): selects waiting/delayed/paused dream:synth-v2:% jobs across ALL queues, parses keys with parseSynthV2Key, then per row, reading THE shared gate (passesTriageGate from triage-rescue.ts — threshold pass OR the verified-segment rescue; a hand-rolled score >= threshold here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but waiting in a stale dream-inline-* queue → cancel as converted_for_resubmit (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless --cancel-unmatched; key-source vs data.source_id disagreement → skip + source_mismatch; status re-checked immediately before each cancel (rows turned active are skipped; residual race matches cancelJob's best-effort contract). Legacy dream:synth: keys are excluded at the SQL LIKE filter — never candidates. --source scopes cancels (other_source counted); --threshold/--since/--force/--dry-run (zero judge calls, zero cancels — cached scores only, uncached files report needs_triage). --audit-rejects <n> re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry rescued/verified_segments so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by test/dream-retriage.test.ts. With System One S7 on, cached decide verdicts (cache identity from resolveTriageDecide) count as valid, the slot threshold joins every gate read, runTriagePass gets decide, and the spend estimate prices Jev windows (estimateTriageDecideUsd).

  • src/commands/dream-reset-key.ts — gbrain dream reset-key <base-key> persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); gbrain dream reset-key --list [--json] lists tripped keys with counts and reset commands. Dispatched from dream.ts before cycle flag parsing. The dream_paid_loop doctor check (src/commands/doctor/checks/dream-breaker.ts) warns on keys at the limit through the same counter. Its help names the per-source patterns key dream:patterns:source:<id>; doctor dream_paid_loop reports that prefix as the key's key_prefix.

  • src/commands/dream.ts — gbrain dream CLI; thin alias over runCycle. Flags: --dry-run, --json, --phase <name>, --pull, --dir <path>, --input <file> (ad-hoc transcript, implies --phase synthesize), --date YYYY-MM-DD, --from <d> --to <d> (backfill range), --unsafe-bypass-dream-guard (plumbed through runCycle.synthBypassDreamGuard → SynthesizePhaseOpts.bypassDreamGuard → discoverTranscripts({bypassGuard}) / readSingleTranscript({bypassGuard}); loud stderr warning at synthesize-phase entry; never auto-applied for --input). Conflict detection: --input + --date exits 2. ISO date validation. --dry-run runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a phase named by --phase (or implied by --input) that skips with details.reason: 'no_database' exits 1 with a database_error envelope (#9608), while a plain gbrain dream naming no phase still exits 0; a cycle_already_running skip names the lock holder (pid, host, age) from report.lock_holder. Source scope enters the shared 6-tier resolver whenever --source <id> is given OR GBRAIN_SOURCE is set (a null explicit falls through to tier 2: validated + assertSourceExists, so an invalid/unknown env value is a clean exit 1; the __all__ sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the --source freshness boundary. resolveBrainDir returns string | null (order: --dir → resolved source's local_path → global sync.repo_path → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. resolve_symbol_edges) and skips the 6 filesystem phases with details.reason: 'no_brain_dir'; runDream owns the only hard error (no checkout AND no engine). When --source resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global sync.repo_path (would mix scopes). Pinned by test/dream-postgres.serial.test.ts. --drain [--window <seconds>] for --phase extract_atoms: runDrain() bypasses the pack-gate and runs the single-hold bounded drain from src/core/cycle/extract-atoms-drain.ts under the same cycleLockIdFor(sourceId) the routine cycle uses (concurrent autopilot tick defers with cycle_already_running), reporting {extracted, skipped, remaining, stopped}. --window is a hard deadline for starting work (the item in flight finishes). Every stop maps through drainOutcome (src/core/cycle/extract-atoms-drain-outcome.ts): exit 0 only for stopped: drained with remaining: 0; exit 11 (BUDGET_STOP_EXIT_CODE) for a retryable stop (atom_drain_incomplete: window, deadline, lock, batch cap, budget, a null count; atom_drain_provider_failure reasons rate_limit/transient), printing the rerun command (gbrain dream --drain --window <s> [--source <id>]) on stderr and adding resume_command under --json; exit 1 for a stop a rerun cannot clear (atom_drain_provider_failure reasons auth/billing/model_not_found/content_block, atom_drain_no_progress over a counted backlog), printing the registry suggestion as a Fix: line and adding the rendered fix instead of resume_command. --json of any incomplete stop carries status (incomplete or provider_failure, never ok), retryable, code and reason; LockUnavailableError → cycle_already_running skip (also exit 11). Under --json (D2) every path is one document: usage errors are invalid_params envelopes (exit 2, unknown --phase included), a failed or contained cycle under the guard is a cycle_failed envelope leading with the CycleReport keys, and retriage / reset-key refusals are envelopes. The extract_atoms_backlog doctor check (computeExtractAtomsBacklogCheck) surfaces the silent pack-gated backlog with the exact --drain command; pack-gated cycle skips carry a greppable pack_gated:true marker. dream retriage dispatches on args[0] === 'retriage' BEFORE parseArgs (its flag set never collides with cycle flags; dream retriage --help prints subcommand help engine-free per the same IRON RULE). --eval-run opts the process in to GBRAIN_DECIDE_SLOTS (enableDecideEvalOverride) for eval harnesses; consent, egress and the daily cap still apply.

  • src/commands/embed.ts — gbrain embed [--stale|--all] [--slugs ...]. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in test/embedding-recovery.serial.test.ts (PGLite) and its PostgreSQL wrapper, test/e2e/embedding-recovery-parity.test.ts. --stale first calls engine.countChunklessPagesWithContent() (chunkless-page safety net: a page written directly via putPage — e.g. an enrichment-generated stub — that never went through chunking has ZERO content_chunks rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, healChunklessPages chunks them locally (mirrors embedPage's chunkless branch: same chunkText calls over compiled_truth/timeline) with embedding = NULL, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks getChunks. installPageProjection then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same EmbedResult.failures/recordFailure path as every other embed failure and the sweep moves on — it never aborts the whole --stale run before the normal stale-chunk pass even starts). listChunklessPagesWithContent's default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors --catch-up (removes its cap entirely, matching the main loop below), and otherwise shares ONE GBRAIN_EMBED_TIME_BUDGET_MS wall-clock budget with the main stale loop (both measure from the same overallStartedAt, not two independent 30-minute windows) so a large damaged brain can't run the combined --stale pass unbounded; a budget stop that leaves stale chunks is never silent: src/core/embed-budget-stop.ts records reason: 'time_budget', remaining_stale and resume_command, runEmbed prints the verdict on stdout and the CLI exits 11 (BUDGET_STOP_EXIT_CODE); an abort during healing stops the whole function before falling through to invalidateStaleSignatureEmbeddings. Pinned by test/embed-stale-chunkless-pages.serial.test.ts + test/e2e/engine-parity.test.ts. Then --stale calls engine.countStaleChunks() (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, engine.listStaleChunks() returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no vector(1536) payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through installPageEmbeddings. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared carryChunkMetadata(chunk, loaded) field list in src/core/embed-stale.ts — modality plus the code fields (language, symbol_name, symbol_type, start_line). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by test/embed-modality-preserved.test.ts. All console.log/console.error call sites use slog/serr from src/core/console-prefix.ts so when runEmbedCore runs inside a per-source withSourcePrefix scope (installed by the gbrain sync --all worker pool) every line carries the [<source-id>] prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp pages.embedding_signature inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (embedPage, used by gbrain embed <slug> AND sync's post-import embed step) and the full-re-embed path (embedAll) stamp per page when every chunk embedded cleanly. The stale path (embedAllStale) first calls invalidateStaleSignatureEmbeddings on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through stampIfPageProvenanceComplete in src/core/embed-stale.ts (shared with the minion embed-backfill drain, embedStaleForSource): the stamp is judged from DB state — every chunk carries an active-column vector whose model and vector width match the signature and whose embedded_text_hash matches md5(chunk_text) — never from the batch subset, because listStaleChunks pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; embed --all fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened countStaleChunks({signature}) predicate without NULLing anything. --include-null-signature lifts the NULL-signature grandfather clause: threads includeNullSignature: true into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' countStaleChunks/sumStaleChunkChars/invalidateStaleSignatureEmbeddings accept the flag; predicate becomes sig IS NULL OR sig <> current). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by test/embedding-migration.test.ts + test/e2e/migrate-embeddings-postgres.test.ts. Embed failures are never silent: all three page paths embed via embedPageTexts, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-AITransientError, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay embedding IS NULL for the next --stale pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — embedBatchWithBackoff already owns 429 backoff). Failed chunk counts land on EmbedResult.failures + capped failure_samples, and src/cli.ts's embed case sets a non-zero exit verdict on failures > 0 (mirror of the import errors>0 guard). In --stale, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by test/embed-stale-unavailable-snapshot.serial.test.ts. Pinned by test/embed-partial-failure-3037.serial.test.ts + test/embed-exit-code-3037.serial.test.ts (real spawned CLI). applies the embed-skip filter at all 5 stale-chunk sites: runEmbedCore --stale, runEmbedCore --all, the embed-stale Minion helper, plus both engines' listStaleChunks + countStaleChunks via EMBED_SKIP_SQL_FRAGMENT. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from src/core/embed-skip.ts is the single implementation — no per-site ad-hoc filter allowed. Pinned by test/embed-skip.test.ts. both inline sliding-pool sites (embedAll simple at :458-467 and embedAllStale paginated + AbortSignal at :586-632) call runSlidingPool from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via embedBatchWithBackoff); byte-equality on progress-event ORDERING is NOT promised. The GBRAIN_EMBED_CONCURRENCY || 20 default is preserved and embed bypasses resolveWorkersWithClamp because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by test/embed-default-concurrency.test.ts (20 page workers on both paths when the env var is unset) and test/embed-pool-abort.test.ts (an abort stops both page pools from claiming further pages). wires --background as the reference integration for the maybeBackground() helper. gbrain embed --stale --background submits as a Minion job, prints job_id=N to stdout, exits 0. Composable: JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB. runEmbedCore accepts an optional signal threaded down both the --stale and --all paths (embedAllStale/embedAll/embedPage); each composes it with the internal wall-clock budget via anySignal and checks isAborted/effectiveSignal.aborted in every per-slug loop, page-claim pool, and embedBatch call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by test/embed.serial.test.ts. Keyless brains (embedding_disabled: true): the exported pure predicate isKeylessStaleRefusal(args, embeddingDisabled) gates a CLEAN refusal at the top of runEmbed — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain gbrain sync ... && gbrain embed --stale must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via EmbeddingDisabledError, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by test/embed-keyless-guard.test.ts + test/agent-scheduler-contract.test.ts. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two countStaleChunks calls) followed by one live probeEmbedder embed call (from src/core/embed-stale.ts; validates a real vector whose dims match the signature's trailing :<dims>) must succeed before anything is NULLed, so a misresolved config (temp GBRAIN_HOME → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls engine.invalidateContentDriftEmbeddings (not probe-gated — blast radius is bounded by real content edits) so chunks whose embedded_text_hash no longer matches md5(chunk_text) re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by test/embed-stale.test.ts (probe-gate + content-drift blocks). The --stale single-flight lock HEARTBEAT (interval GBRAIN_EMBED_LOCK_HEARTBEAT_MS, default 5 min — test seam) is refresh-bounded per tick: each refresh() races a per-tick timeout (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, default 30s via DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (beating guard), a refresh returning false (stolen/released lock) aborts the drain immediately as lock_lost, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as lock_lost rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. --stale progress (#5968) is exact chunk accounting through src/core/embed-stale-progress.ts: onProgress(done, total, embedded) carries cumulative stale chunks against a total that grows by heal splits, behind-cursor rows and re-entries, the CLI ticks embed.pages by the delta and forwards the grown total with setTotal, and done <= total holds at every callback. runEmbedCore --stale also arms the progress-keyed stall watchdog from src/core/embed-stall.ts (GBRAIN_EMBED_STALL_ABORT_SECONDS, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns reason: 'stall_timeout'. Pinned by test/embed.serial.test.ts (heartbeat + stall blocks) + test/jobs-embed-stall-wiring.serial.test.ts. Explicit --stale --facts --source ID is a read-only NULL-fact preview; --yes --max-cost-usd N consents to bounded execution, not automatic/full-brain repair. Its result prints from runEmbed only without --json; under --json the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from resolveEmbedConcurrency in src/core/embed-concurrency.ts (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through retryProjectionConflict and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a [page_projection_conflict] failure sample with the envelope's next step (test/embedding-recovery.serial.test.ts). --all passes the sliding pool an onError handler: an error that escapes embedOnePage (its snapshot read runs before the page's own try) counts that page once on result.failures with an Error embedding <slug> stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); test/embed-partial-failure-3037.serial.test.ts. #6223: pages still blocked after bounded projection recovery no longer end --stale early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with gbrain embed --stale --images / gbrain sync --full for image and media pages. Fix wave 13 P1.18 (#6400): runEmbed takes the CLI's consent outcome; a finite approved cap_usd runs the foreground text and --images paths under embedCostCap (src/core/embed-cost-cap.ts) and returns reason: 'cost_cap' (exit BUDGET_STOP_EXIT_CODE from src/cli/commands/embed.ts, which now returns the Authorization from authorizeEmbed); --background stores it on the row through maybeBackground(...spendAuthorization) (PGLite runs inline, metered). --slugs takes the arguments up to the next flag. Tests: test/embed-max-usd-metered.serial.test.ts, test/e2e/embed-background-cap.test.ts. #6529: runEmbed with --stale (no --slugs) first runs runStaleImageSweepFirst (core/embed-stale-images.ts, multimodal installs only) inside the same cost cap and folds it into EmbedResult.images; the text pass's blocked-projection hint (core/embedding-readiness.ts) then points at that sweep's missing_samples instead of a separate --images command, and at GBRAIN_EMBEDDING_MULTIMODAL=true or --images / sync --full on a text-only install.

  • src/commands/doctor/checks/search-eval.ts — search, model, and AI-config health checks. checkSearchMode (search_mode) reports the resolved mode and its search.* overrides; when the only override is an explicit search.reranker.model row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise gbrain config unset search.reranker.model — never a --reset, which would also wipe every other tuned search knob.

  • src/commands/doctor/checks/atom-holds.ts — extract_atoms_held_failed (#6325, BRAIN, registered before fence_integrity). Lists listHeldManagedAtoms (persistence/atom-maintenance.ts): managed atom pages and transcripts held after MAX_DETERMINISTIC_FAILURES failed extractions of their current content (code held_failed) that no later run completed, each with its last request id, failure, receipt_command and retry_command. Warns with a paid fix (the reviewed gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}' retry of the first item). Local doctor only; run_doctor does not include it. Tests: test/managed-atoms-retry.test.ts.

  • src/commands/doctor/checks/extraction-input.ts — extraction_input_truncated (large pages A7, BRAIN, registered after fence_integrity, before search_mode). Groups the live pages with an input_truncated receipt in page_extraction_state by pipeline and kind (facts_backstop/head|tail_window, extract_atoms/head|tail_window, conversation_facts/skipped_too_large) with three recent source:slug samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is gbrain config set cycle.extract_atoms.max_input_chars <n> (ask_user, consent paid), otherwise fix_unavailable_reason: operator_judgement. Facts-only receipts are ok with severity: info, readiness_state: degraded (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: test/extraction-watermark-facts.test.ts, test/extraction-watermark-atoms.test.ts, test/conversation-facts-oversized-sidecar.test.ts.

  • src/commands/doctor/bounded-unknown.ts — #7145: boundUnknownDetails(bound) returns { health: 'unknown', reason: 'bound', bound, exact: false }, the details shape a doctor check uses when it stopped at its own bound (files, time, rows, roots, sample) before it could say clear; the check adds its limit beside it, grades warn, and names the bound and the rerun or wider command in its message. Used by multi_source_drift, ghost_pages, missing_recorded_files, conversation_outcomes_stale, maintenance_write_drift, git_convergence, tracked_ownership_marker, orphaned_private_queue, link_resolution_opportunity and frontmatter_integrity. A capped list that found rows says "at least N" or "N+" with exact: false instead. Tests: test/doctor-bound-unknown-7145.test.ts, test/doctor-capped-counts-7145.test.ts, test/doctor-unknown-reads-7145.test.ts.

  • src/commands/doctor/checks/fence-integrity.ts — fence_integrity (#6188, BRAIN, registered before search_mode). Each run advances the fence census within GBRAIN_DOCTOR_FENCE_TIMEOUT_MS (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day fences_normalized trend with top writers (warns at FENCE_NORMALIZATION_WARN_7D = 20), and the model-repair caps with today's ledger spend. ok only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only gbrain repair fences --source <id> preview for holds, stored pages and files alike; a warn reads readFenceAutoRepair (details auto_repair): while a maintenance run is active and fences.repair.enabled is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's then is the apply. Model-tier fences say why they wait (fences.repair.llm off with the command that turns it on, or today's budget spent with the cap command), else the caps. fenceIntegrityCheck(engine, sourceIds?) is the WAVE_CHECKS entry (scoped for a remote caller). Location only. #6278: the check also counts unrenderable_legacy_facts: the active row_num IS NULL fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (planUnfencedFacts + auditUnadoptableFacts) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests forget_fact, and when it is the only finding its fix carries no command (next: report) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: unbound_legacy_facts lists, from the same plan, unfenced rows of classic database-only pages that persistence.unbound_write keeps unfenced; when it is the only finding the fix is gbrain config set persistence.unbound_write database_only with ask_user. Test: test/doctor-fence-integrity.test.ts, test/extract-facts-unfenced-rows.test.ts. Wave B decision #10: withSkippedSegmented(check, n) (src/commands/doctor/check-fix.ts) adds Check.skipped_segmented: n and a skipped (segmented): n message tail (unchanged at n = 0) to every check whose scan reads whole bodies: oversized_pages, scraper_junk_pages, markdown_body_completeness, link_resolution_opportunity, fence_integrity (segmented pages without a walked checkout file), core_memory, and extract_health via readFactsReconcileBacklog's skipped_segmented; each count is one COUNT query that falls back to 0 on a schema without body_storage. Test: test/large-pages/doctor-skipped-segmented.test.ts (+ Postgres arm).

  • src/commands/doctor/checks/git-convergence.ts — git_convergence (#5063, brain category, after sync_freshness): for every non-archived filesystem source root plus sync.repo_path (connector sources skipped), git status --porcelain -z and rev-list --left-right --count @{u}...HEAD against the local upstream ref, never a fetch, each call bounded at 5 s, at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (stranded: true in details.roots, #7089) with an agent fix gbrain git commit-push --push-only --keep-checkout --scan-secrets --path <root> (verify gbrain doctor --only git_convergence); bindings map to their toplevel, and tracked files modified under such a durable source root warn the same way (uncommitted_pages, #7091) with an ask-user commit, then that push; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. A read-only mirror root (every source has sync off, and the upstream has no publishable push URL or every source is mirror_read_only) whose commits ahead of upstream touch only .gbrain/access.yml and .gbrain/access.approved is reported ok at info severity (policy_only_mirror, GST-2634), and a mirror_read_only root's fix never suggests a push (mirror_read_only in details.roots); test doctor-git-convergence-mirror-gst2634.test.ts. Emits nothing when no probed root has an upstream. The same entry emits tracked_ownership_marker (#5186): git ls-files --cached on each of those checkouts, warn when a path isPhysicalRootMetadata recognizes is in the index, with a user-run git -C <root> rm --cached <paths> fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. bootstrap-checks.ts bootstrap_push_health also warns, instead of ok, when a recent successful push leaves the receipt workspace ahead of origin/<branch>. scripts/smoke-test.sh accepts a configured database URL (engine status db_url_source) and trusts doctor embedding_provider over raw OpenAI/Voyage keys. Tests: doctor-git-convergence-5063.test.ts, persistence-git-removal-push-7089.test.ts (stranded roots, both engines), doctor-ownership-marker.test.ts, bootstrap-doctor-checks.test.ts, smoke-test-worker.test.ts.

  • src/commands/doctor/checks/keyword-plan.ts — keyword_plan (#6495, OPS, wave check with operator resolution; the keyword-side twin of vector_plan in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for content_chunks.search_vector (pg_stats.most_common_elems with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (buildKeywordCountStatement, the builder the engine uses) and times the engine's own bounded countKeywordPages(term, { timeoutMs: 2000 }); warns canary_timed_out when that count hits its bound and canary_slow when it takes more than half of search.keyword_statement_timeout_ms, naming the knob with its range (1000-60000), the fail-open to the vector arm (keyword_arm_failed), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (pg_class.reltuples) and without planner statistics (it names ANALYZE content_chunks); a failing probe reports unknown health. engineKeywordPlanProbe(engine) is the database side; keywordPlanCheck(engine, probe?) takes a fake for tests. Tested in test/doctor-keyword-plan-6495.test.ts (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).

  • src/commands/doctor/checks/image-embedding-coverage.ts — image_embedding_coverage (#6529, brain category, after image_assets). Counts live image pages (page_kind = 'image'), those with no embedding_image chunk, those with a NULL source_path, and the managed_image_sync_unsupported holds per source, and reads isMultimodalEnabled(). Ok when the brain has no image pages, when every image page has an image vector and a source_path and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names gbrain embed --stale --images and gbrain sync --no-pull --source <id> for the holds. Read-only; no paid call. Test: test/doctor-image-embedding-coverage.test.ts.

  • src/commands/doctor/checks/provider-consent.ts — provider_consent (OPS, engine-free filesystem lane right after embedding_key_source; not in doctorReportRemote): the provider-use decision gbrain setup recorded for this install (localSetupRecords in src/core/setup/local-receipts.ts). A decline (any live receipt; opt-outs win) is ok + info disabled_by_choice, "skipped by consent", naming the provider key variables present (names only) and carrying providerConsentFix: gbrain setup <harness> --providers (+ --name/--scope project), actor user, consent paid+egress, so next: tell_user_to_run. Accepted is plain ok; no receipt is info not_applicable. The same fix rides embedding_provider's --probe skip (checks/embedding-health.ts), and probe-consent.ts authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by test/doctor-provider-consent.serial.test.ts (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).

  • src/commands/doctor/last-known.ts — the quick tier's last known results (#7142). --tier quick (budget.ts: QUICK_BUDGET_MS_DEFAULT 10000, connect included; entryRunsAt orders ops ⊂ quick ⊂ standard ⊂ deep; cheapTier gives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries tagged tier: 'quick' (schema version, the stub-guard entry with sync_failures, queue health, partial embeddings). lastKnownMode turns the store on only for a brain-wide local CLI run (buildChecks(..., { lastKnown: 'cli' }) from runDoctor) or the refresh job, never under --only, --source, a remote scope, --fix or --tier ops. runDoctorRegistry records each entry's outcome (done, expired when it ran out of budget or emitted a budget unknown, not_run when the tier skipped a standard entry); withLastKnown writes the finished entries of a standard or deep run to op_checkpoints (op doctor-last-known, fingerprint = entry name, completed_keys[0] = { checks, measured_at, elapsed_ms, emits }, one bounded statement, best-effort) and applyLastKnown replaces an unfinished entry's checks with its last known ones when they are at most LAST_KNOWN_MAX_AGE_MS (24 h) old: same status, message prefixed Last known, N ago (...), details.last_known { measured_at, age_ms, reason: not_in_tier | budget }. The rest are named in one doctor_last_known warning (details.health: 'unknown', unknown_checks), which tierFields expands into unknown_sections; served checks go to last_known_sections and make the report incomplete. An entry with no result younger than REFRESH_AFTER_MS (1 h) queues one doctor-refresh job on Postgres (idempotency key per hour, maxWaiting: 1, priority 10 so sync, the autopilot cycles, global maintenance, embed backfill and loops extract claim first, timeout_ms 15 min; none when DB config doctor.background_refresh is false, #7263); the handler (runDoctorRefresh, registered in commands/jobs.ts) runs doctorRefreshRegistry() (the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) with REFRESH_ENTRY_BUDGET_MS (600000) per entry inside the overall REFRESH_BUDGET_MS (10 min, passed as --budget-ms: past it no entry starts and the running one is cut, so the job completes with what it measured and the rest waits for the next slot) and queues nothing itself. doctor-refresh is in DEFAULT_LONG_JOB_NAMES (minions/lanes.ts). Tests: test/doctor-refresh-7263.test.ts, test/doctor-quick-tier-7142.test.ts (+ test/e2e/doctor-quick-tier-7142-postgres.test.ts).

  • src/commands/doctor/brain-health-bands.ts + remote-tier.ts + ops-snapshot.ts, src/core/doctor-remote-tier.ts, src/core/persistence/capacity-view.ts — the ops tier for agents and remote clients (#6696 B2). readCapacityView (for /admin/api/ops) reads the counter rows, capacityDiagnostics, the light readCapacityForecast (null when unreadable: days unknown) and readLastCompaction; the bands read cachedCapacitySnapshot; capacityVerify() is the verify of every capacity fix (gbrain doctor --only persistence_capacity --json plus MCP get_brain_health). readBrainHealthBands backs the read-scope get_brain_health op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. runRemoteDoctorTier backs run_doctor's tier: "ops" / only (admin). runScopedRemoteDoctor is the thin client's gbrain doctor --tier ops / --only <registry check>: it reads tools/list and uses run_doctor with the parameters, else the bands (BAND_CHECKS), else refuses doctor_tier_unavailable; it never runs the full remote report in their place. cachedOpsSnapshot serves /admin/api/ops from one ops run a minute. Tests: test/doctor-ops-remote-6696.test.ts.

  • src/commands/doctor/checks/rename-identity-downgrades.ts — rename_identity_downgrades (#6729): warn while a downgraded rename record is open (sync-identity-downgrades.ts), naming up to 5 pairs with their facts and links; fix = the first pair's gbrain repair rename-identity apply (destructive, ask_user, preview_argv, plan_hash; --close on a managed brain), so unbound classic Postgres pairs get an actionable fix too; gbrain restore <old-slug> --source-id <id> --force is named as the alternative in its text only where restore_available !== false, and restore_unavailable_sources lists the rest.

  • src/commands/doctor/checks/purge-parks.ts — purge_parked_pages (#6741 C): names parked purges with their last error (only this version's parks, isParked); fix gbrain pages purge-deleted --retry-parked --yes (preview --dry-run --json), consent destructive, ask_user. Also derived_origin_parked (GST-2689, checkDerivedOriginParked): names each origin persistence/derived-origin-hold.ts parked with the page that blocks it and the reason (details.origins); fix the read-only gbrain repair visibility --source <id> --slug <blocking page> preview. An origin whose owner purge was held (held_request_id) also gets finish_argv (gbrain delete <slug> --purge --source-id <id>, a new request), named in the message, which finishes it at once.

  • src/commands/doctor/checks/unlinked-facts.ts — unlinked_facts (#5836), registered before search_mode and mirrored in doctorReportRemote: per the doctor's source scope (--source, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (idx_facts_since LATERAL walk), the 7-day unlinked share of new facts, no_subject judgments and the 7-day linked tiers from fact_relink_attempts, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (cli:extract-conversation-facts*, #6764: count, origin conversation, and details.conversation naming the source with the most and its pages, most rows first, up to CONVERSATION_FIX_SLUGS = 50), origins and 7-day write-time inferred links by tier (entity inferred from <tier> context, bare or after —). Warns when over 25% of at least 20 new facts are unlinked, facts judged no_subject and conversation rows memoized conversation_unresolved excluded (new_7d.conversation_unresolved); the fix is gbrain facts relink --dry-run; when conversation rows are unlinked the envelope fix (details.conversation.fix) is, for rows the free conversation relink has not tried, gbrain facts relink --conversation --source <id> --slugs <csv> (preview --dry-run, consent none, actor agent, host operator remotely; test test/conversation-relink-6764.test.ts) and, once only rows it memoized conversation_unresolved remain (a memo that a page created later re-arms unless the reason is memoized, core/facts/conversation-memo.ts), a bounded re-extraction of those pages not yet re-extracted on their current content (gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>, input N the approved USD, preview --dry-run, consent paid + egress, ask_user; test test/conversation-facts-unlinked-6764.test.ts), both verified by gbrain doctor --only unlinked_facts --json, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, details.conversation.fix is manual: no envelope fix, and the message names linking by hand with --entity (test test/conversation-memo-6764.test.ts). Without fact_relink_attempts the relink figures are null and nothing is excluded. Non-user facts are skipped (#7270). Tests: test/doctor-unlinked-facts.test.ts, test/relink-attribution-7270.test.ts.

  • src/commands/doctor/checks/transcript-archive.ts — transcript_archive_freshness (GST-2768, brain category): off is ok and reads nothing; on, reads archiveStatus (no reader run) and transcripts.archive.last_maintenance and warns on a harness transcripts.archive.stale_days (2) behind the newest session day seen or a reader unread that long (fix gbrain transcripts archive run, or backfill --from <day> past one run window), on no maintenance pass that long (fix gbrain autopilot --install, persistent_install consent), on held days, reader and pass errors; no readable sessions is info. Pinned by test/doctor-transcript-archive-freshness.test.ts.

  • src/commands/doctor/checks/unattended-maintenance.ts — unattended_maintenance (GBRA-438): readUpkeepStatus as a check; off and autopilot-owned are ok, a brain under 48h with no run is info, a run older than 48h, a step failing 3 runs in a row or an item serve parked (details.parked) warns with gbrain maintain --unattended (consent: [] unless an embedding key and a non-zero cap make it paid); on an overdue brain details.alternative_fix renders gbrain maintain --schedule as the second fix.