Garry's Opinionated OpenClaw/Hermes Agent Brain
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— thehome_dir_in_worktreecheck: walks up from the gbrain home looking for an enclosing.git(dir or linked-worktree file), warning that agit addfrom the worktree root could stage the brain; stops at $HOME. Both anchors (GBRAIN_HOME,$HOME) arepath.resolve()d before the containment test, so a trailing-slashHOME=/home/user/(a common shell/launchd spelling) cannot make a brain inside a worktree grade ok.isValidGitMarkerstructurally validates a candidate before it counts (a.git/dir must contain HEAD; a.gitfile must start withgitdir:— 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 (thememorable enableout-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the sharedclampRelayCause; child text never lands in a doctor message verbatim) — EXCEPT the documented openclawno_decisive_stepsrejection, 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: truealways rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned bytest/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>-workspacesources, (c) privileged self-registered clients — activeoauth_clientsrows whose scope word-matchesDCR_PRIVILEGED_SCOPES— the DERIVED complementALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES(exported; bound as a$1regex parameter, never interpolated) — and the(read/write)/--scopes read,writecopy is built fromDCR_REGISTRABLE_SCOPES; pinned by the set-equality + per-scope loop intest/doctor-oauth-client-scope-health.test.ts; rows withgrant_revision = 0and nooauth_grant_auditrow withaction = '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 thegbrain auth rescope-client <client_id> --scopes read,write/gbrain auth revoke-client <client_id>remedy; when the audit table orgrant_revisioncolumn is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned bytest/doctor-oauth-client-scope-health.test.ts.src/commands/doctor/checks/postgres-tls.ts—postgres_tls(OPS, afterrls), judged from the client side: the moderesolvePgTlsgives forengine.connectedDatabaseUrl(the config URL only as a fallback).require,allow,verify-caandverify-fullare ok, because the driver refuses a server without TLS;sslmode=disablewarns;sslmode=prefersends 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 withclient_tls: null(a fresh probe is not the engine's socket). APGSSLvalue is TLS to the driver even when it readsdisable(only URL values turn TLS off). The session'spg_stat_sslrow 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 isgbrain 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 intest/e2e/pg-tls-postgres.test.ts).src/commands/doctor/checks/embedding-identity.ts—embedding_identity_unqualified(#6113, BRAIN, right afterembedding_env_override): warns when the DBconfigrowembedding_modelhas no provider prefix (managed fact extraction reads only that row andconfig setrefuses it). The fix is the read-onlygbrain migrate embeddings --to <provider:model> --dry-run, filled fromloadConfig()'s provider-qualifiedembedding_model, or<PROVIDER_MODEL>plus aninputsentry when none is configured;details.target_differsflags 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', afterembeddings):readEmbeddingStateinopsmode on the ops tier,fullotherwise. Warns only on purgeable chunks of pages soft-deleted past the 72h window (deleted_page_chunks_overdue, fixpages purge-deleted) and, on a keyed brain, live pages with body text but no chunks (chunkless_pages_healable, fixembed --stale); the pending backlog isembeddings' warning and quarantined pagesquarantined_pages'. keyword_only, held or in-window deleted chunks and a keyless brain areinfoCheck; ops without a covering index warns withdetails.health: 'unknown'(embedding_state_unknown). Test:test/doctor-embedding-state.test.ts.src/commands/doctor/checks/knowledge-health.ts—facts_extraction_healthreads the last 24 h offacts:absorbrows iningest_log(written bysrc/core/facts/absorb-log.ts) per source and reason (split_part(summary, ':', 1)) and warns when a failure reason reachesfacts.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) andwrite_deferred_unadmitted(writer_lock_unavailablebefore 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 completedfacts-absorbjob for the same page; that warning's fix is the read-onlygbrain 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, anddetails.facts_absorb(incidents_24h,ages_out_at,jobs_still_dead,dead_jobs) adds the current state, thefacts-absorbjobs 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 paidgbrain jobs retry <id>fix (retry_jobover 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): doctortwo_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, aputor a row younger than 30 s, is listed indetails) andconsumers_without_heartbeat(aclaim_phase.ownerpid 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 structuredagentFix(gbrain sources writer status --json) anddoctorVerify; withpersistence.single_consumeroff the overlap is reported as the configured behavior.serve_build_drift(#6696 C6, its ownserveBuildDriftEntry, onelistHostConsumersread, ok on PGLite with no read) compares the live resident rows (not this process) with this binary'sVERSIONthroughcompareWriterVersions(an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" withdetails { count, this_version, owner, older, newer }and afix(actoruser,doctorVerify) whose argv is the installed serve service's restart (systemctl --user restart gbrain-serve.servicewhensystemdUnitPathexists on Linux,launchctl kickstart -k gui/<uid>/com.gbrain.servewhenlaunchdPlistPathexists on macOS;serveBuildDriftCheck'sServiceHostargument injects platform, home and uid) or elsekill <pid>; a newer row is reported in an ok message; no rows namesconsumers_without_heartbeatfor a pre-heartbeat serve. Registered inDOCTOR_CHECK_REGISTRY(the consumer entry, thenserveBuildDriftEntry) beforesearchModeEntryand categorisedopsinsrc/core/doctor-categories.ts. Tests:test/doctor-serve-build-drift.test.ts.src/commands/doctor/checks/runtime-build-skew.ts— #7245: doctorruntime_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 fromjob_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, thengbrain 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 bytest/doctor-runtime-build-skew.test.ts.src/commands/dream-retriage.ts—gbrain dream retriage: re-scores synthesize's list (withConversationPages, #7307) via the sharedrunTriagePass(withmaxMs: 0— operator sweeps run to completion;--limitslices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-deaddream-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 livegbrain_cycle_locksrow suppresses conversion only for queues born at/after itsacquired_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 viacanonicalLookupon the resolved triage model, confirmation aboveSPEND_CONFIRM_USD($5, indream-retriage-constants.ts; unpriced models gate onUNPRICED_CONFIRM_FILES=500) throughrequireConsent(effectpaid;--yes,--max-usd, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload,--jsonnever implying it); the budget (--max-usd, else the derived consent cap) soft-stops via the pass'sshouldStopseam (estimate-based) and bounds the--audit-rejectshalf.--reconcile-queue(opt-in — cancels queued work): selects waiting/delayed/pauseddream:synth-v2:%jobs across ALL queues, parses keys withparseSynthV2Key, then per row, reading THE shared gate (passesTriageGatefromtriage-rescue.ts— threshold pass OR the verified-segment rescue; a hand-rolledscore >= thresholdhere would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate butwaitingin a staledream-inline-*queue → cancel asconverted_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 vsdata.source_iddisagreement → skip +source_mismatch; status re-checked immediately before each cancel (rows turnedactiveare skipped; residual race matches cancelJob's best-effort contract). Legacydream:synth:keys are excluded at the SQL LIKE filter — never candidates.--sourcescopes cancels (other_sourcecounted);--threshold/--since/--force/--dry-run(zero judge calls, zero cancels — cached scores only, uncached files reportneeds_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 carryrescued/verified_segmentsso 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 bytest/dream-retriage.test.ts. With System One S7 on, cached decide verdicts (cache identity fromresolveTriageDecide) count as valid, the slot threshold joins every gate read,runTriagePassgetsdecide, 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 fromdream.tsbefore cycle flag parsing. Thedream_paid_loopdoctor 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 keydream:patterns:source:<id>; doctordream_paid_loopreports that prefix as the key'skey_prefix.src/commands/dream.ts—gbrain dreamCLI; thin alias overrunCycle. 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 throughrunCycle.synthBypassDreamGuard→SynthesizePhaseOpts.bypassDreamGuard→discoverTranscripts({bypassGuard})/readSingleTranscript({bypassGuard}); loud stderr warning at synthesize-phase entry; never auto-applied for--input). Conflict detection:--input+--dateexits 2. ISO date validation.--dry-runruns 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 withdetails.reason: 'no_database'exits 1 with adatabase_errorenvelope (#9608), while a plaingbrain dreamnaming no phase still exits 0; acycle_already_runningskip names the lock holder (pid, host, age) fromreport.lock_holder. Source scope enters the shared 6-tier resolver whenever--source <id>is given ORGBRAIN_SOURCEis 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--sourcefreshness boundary.resolveBrainDirreturnsstring | null(order:--dir→ resolved source'slocal_path→ globalsync.repo_path→ null); a checkout-less postgres/Supabase brain runs DB-only phases (incl.resolve_symbol_edges) and skips the 6 filesystem phases withdetails.reason: 'no_brain_dir';runDreamowns the only hard error (no checkout AND no engine). When--sourceresolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's globalsync.repo_path(would mix scopes). Pinned bytest/dream-postgres.serial.test.ts.--drain [--window <seconds>]for--phase extract_atoms:runDrain()bypasses the pack-gate and runs the single-hold bounded drain fromsrc/core/cycle/extract-atoms-drain.tsunder the samecycleLockIdFor(sourceId)the routine cycle uses (concurrent autopilot tick defers withcycle_already_running), reporting{extracted, skipped, remaining, stopped}.--windowis a hard deadline for starting work (the item in flight finishes). Every stop maps throughdrainOutcome(src/core/cycle/extract-atoms-drain-outcome.ts): exit 0 only forstopped: drainedwithremaining: 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_failurereasonsrate_limit/transient), printing the rerun command (gbrain dream --drain --window <s> [--source <id>]) on stderr and addingresume_commandunder--json; exit 1 for a stop a rerun cannot clear (atom_drain_provider_failurereasonsauth/billing/model_not_found/content_block,atom_drain_no_progressover a counted backlog), printing the registry suggestion as aFix:line and adding the renderedfixinstead ofresume_command.--jsonof any incomplete stop carriesstatus(incompleteorprovider_failure, neverok),retryable,codeandreason;LockUnavailableError→cycle_already_runningskip (also exit 11). Under--json(D2) every path is one document: usage errors areinvalid_paramsenvelopes (exit 2, unknown--phaseincluded), a failed or contained cycle under the guard is acycle_failedenvelope leading with the CycleReport keys, andretriage/reset-keyrefusals are envelopes. Theextract_atoms_backlogdoctor check (computeExtractAtomsBacklogCheck) surfaces the silent pack-gated backlog with the exact--draincommand; pack-gated cycle skips carry a greppablepack_gated:truemarker.dream retriagedispatches onargs[0] === 'retriage'BEFOREparseArgs(its flag set never collides with cycle flags;dream retriage --helpprints subcommand help engine-free per the same IRON RULE).--eval-runopts the process in toGBRAIN_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 intest/embedding-recovery.serial.test.ts(PGLite) and its PostgreSQL wrapper,test/e2e/embedding-recovery-parity.test.ts.--stalefirst callsengine.countChunklessPagesWithContent()(chunkless-page safety net: a page written directly viaputPage— e.g. an enrichment-generated stub — that never went through chunking has ZEROcontent_chunksrows, 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,healChunklessPageschunks them locally (mirrorsembedPage's chunkless branch: samechunkTextcalls overcompiled_truth/timeline) withembedding = NULL, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checksgetChunks.installPageProjectionthen 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 sameEmbedResult.failures/recordFailurepath as every other embed failure and the sweep moves on — it never aborts the whole--stalerun 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 ONEGBRAIN_EMBED_TIME_BUDGET_MSwall-clock budget with the main stale loop (both measure from the sameoverallStartedAt, not two independent 30-minute windows) so a large damaged brain can't run the combined--stalepass unbounded; a budget stop that leaves stale chunks is never silent:src/core/embed-budget-stop.tsrecordsreason: 'time_budget',remaining_staleandresume_command,runEmbedprints the verdict on stdout and the CLI exits 11 (BUDGET_STOP_EXIT_CODE); an abort during healing stops the whole function before falling through toinvalidateStaleSignatureEmbeddings. Pinned bytest/embed-stale-chunkless-pages.serial.test.ts+test/e2e/engine-parity.test.ts. Then--stalecallsengine.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, novector(1536)payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs throughinstallPageEmbeddings. 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 sharedcarryChunkMetadata(chunk, loaded)field list insrc/core/embed-stale.ts—modalityplus 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 bytest/embed-modality-preserved.test.ts. Allconsole.log/console.errorcall sites useslog/serrfromsrc/core/console-prefix.tsso whenrunEmbedCoreruns inside a per-sourcewithSourcePrefixscope (installed by thegbrain sync --allworker 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 stamppages.embedding_signatureinside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (embedPage, used bygbrain 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 callsinvalidateStaleSignatureEmbeddingson a live run so signature-drifted pages flow through the NULL cursor, then stamps each page throughstampIfPageProvenanceCompleteinsrc/core/embed-stale.ts(shared with the minionembed-backfilldrain,embedStaleForSource): the stamp is judged from DB state — every chunk carries an active-column vector whosemodeland vector width match the signature and whoseembedded_text_hashmatchesmd5(chunk_text)— never from the batch subset, becauselistStaleChunkspages 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 --allfully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widenedcountStaleChunks({signature})predicate without NULLing anything.--include-null-signaturelifts the NULL-signature grandfather clause: threadsincludeNullSignature: trueinto the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines'countStaleChunks/sumStaleChunkChars/invalidateStaleSignatureEmbeddingsaccept the flag; predicate becomessig 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 bytest/embedding-migration.test.ts+test/e2e/migrate-embeddings-postgres.test.ts. Embed failures are never silent: all three page paths embed viaembedPageTexts, 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 stayembedding IS NULLfor the next--stalepass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding —embedBatchWithBackoffalready owns 429 backoff). Failed chunk counts land onEmbedResult.failures+ cappedfailure_samples, andsrc/cli.ts's embed case sets a non-zero exit verdict onfailures > 0(mirror of theimporterrors>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 bytest/embed-stale-unavailable-snapshot.serial.test.ts. Pinned bytest/embed-partial-failure-3037.serial.test.ts+test/embed-exit-code-3037.serial.test.ts(real spawned CLI). applies theembed-skipfilter at all 5 stale-chunk sites:runEmbedCore --stale,runEmbedCore --all, theembed-staleMinion helper, plus both engines'listStaleChunks+countStaleChunksviaEMBED_SKIP_SQL_FRAGMENT. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper fromsrc/core/embed-skip.tsis the single implementation — no per-site ad-hoc filter allowed. Pinned bytest/embed-skip.test.ts. both inline sliding-pool sites (embedAllsimple at:458-467andembedAllStalepaginated + AbortSignal at:586-632) callrunSlidingPoolfrom the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry viaembedBatchWithBackoff); byte-equality on progress-event ORDERING is NOT promised. TheGBRAIN_EMBED_CONCURRENCY || 20default is preserved and embed bypassesresolveWorkersWithClampbecause the 20-worker default would otherwise silently change every brain's embed hot path. Pinned bytest/embed-default-concurrency.test.ts(20 page workers on both paths when the env var is unset) andtest/embed-pool-abort.test.ts(an abort stops both page pools from claiming further pages). wires--backgroundas the reference integration for themaybeBackground()helper.gbrain embed --stale --backgroundsubmits as a Minion job, printsjob_id=Nto stdout, exits 0. Composable:JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB.runEmbedCoreaccepts an optionalsignalthreaded down both the--staleand--allpaths (embedAllStale/embedAll/embedPage); each composes it with the internal wall-clock budget viaanySignaland checksisAborted/effectiveSignal.abortedin every per-slug loop, page-claim pool, andembedBatchcall, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned bytest/embed.serial.test.ts. Keyless brains (embedding_disabled: true): the exported pure predicateisKeylessStaleRefusal(args, embeddingDisabled)gates a CLEAN refusal at the top ofrunEmbed— a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chaingbrain sync ... && gbrain embed --stalemust stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 viaEmbeddingDisabledError, mirroring the dispatch precedence where a slugs list wins over stale. Pinned bytest/embed-keyless-guard.test.ts+test/agent-scheduler-contract.test.ts. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (twocountStaleChunkscalls) followed by one liveprobeEmbedderembed call (fromsrc/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 (tempGBRAIN_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 callsengine.invalidateContentDriftEmbeddings(not probe-gated — blast radius is bounded by real content edits) so chunks whoseembedded_text_hashno longer matchesmd5(chunk_text)re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned bytest/embed-stale.test.ts(probe-gate + content-drift blocks). The--stalesingle-flight lock HEARTBEAT (intervalGBRAIN_EMBED_LOCK_HEARTBEAT_MS, default 5 min — test seam) is refresh-bounded per tick: eachrefresh()races a per-tick timeout (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, default 30s viaDEFAULT_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 (beatingguard), a refresh returning false (stolen/released lock) aborts the drain immediately aslock_lost, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort aslock_lostrather 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.--staleprogress (#5968) is exact chunk accounting throughsrc/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 ticksembed.pagesby the delta and forwards the grown total withsetTotal, anddone <= totalholds at every callback.runEmbedCore --stalealso arms the progress-keyed stall watchdog fromsrc/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 returnsreason: 'stall_timeout'. Pinned bytest/embed.serial.test.ts(heartbeat + stall blocks) +test/jobs-embed-stall-wiring.serial.test.ts. Explicit--stale --facts --source IDis a read-only NULL-fact preview;--yes --max-cost-usd Nconsents to bounded execution, not automatic/full-brain repair. Its result prints fromrunEmbedonly without--json; under--jsonthe 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 fromresolveEmbedConcurrencyinsrc/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 throughretryProjectionConflictand 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).--allpasses the sliding pool anonErrorhandler: an error that escapesembedOnePage(its snapshot read runs before the page's own try) counts that page once onresult.failureswith anError 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--staleearly; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) withgbrain embed --stale --images/gbrain sync --fullfor image and media pages. Fix wave 13 P1.18 (#6400):runEmbedtakes the CLI's consent outcome; a finite approvedcap_usdruns the foreground text and--imagespaths underembedCostCap(src/core/embed-cost-cap.ts) and returnsreason: 'cost_cap'(exitBUDGET_STOP_EXIT_CODEfromsrc/cli/commands/embed.ts, which now returns the Authorization fromauthorizeEmbed);--backgroundstores it on the row throughmaybeBackground(...spendAuthorization)(PGLite runs inline, metered).--slugstakes the arguments up to the next flag. Tests:test/embed-max-usd-metered.serial.test.ts,test/e2e/embed-background-cap.test.ts. #6529:runEmbedwith--stale(no--slugs) first runsrunStaleImageSweepFirst(core/embed-stale-images.ts, multimodal installs only) inside the same cost cap and folds it intoEmbedResult.images; the text pass's blocked-projection hint (core/embedding-readiness.ts) then points at that sweep'smissing_samplesinstead of a separate--imagescommand, and atGBRAIN_EMBEDDING_MULTIMODAL=trueor--images/sync --fullon 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 itssearch.*overrides; when the only override is an explicitsearch.reranker.modelrow equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precisegbrain 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 beforefence_integrity). ListslistHeldManagedAtoms(persistence/atom-maintenance.ts): managed atom pages and transcripts held afterMAX_DETERMINISTIC_FAILURESfailed extractions of their current content (codeheld_failed) that no later run completed, each with its last request id, failure,receipt_commandandretry_command. Warns with a paidfix(the reviewedgbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'retry of the first item). Local doctor only;run_doctordoes 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 afterfence_integrity, beforesearch_mode). Groups the live pages with aninput_truncatedreceipt inpage_extraction_stateby pipeline and kind (facts_backstop/head|tail_window,extract_atoms/head|tail_window,conversation_facts/skipped_too_large) with three recentsource:slugsamples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix isgbrain config set cycle.extract_atoms.max_input_chars <n>(ask_user, consentpaid), otherwisefix_unavailable_reason: operator_judgement. Facts-only receipts areokwithseverity: 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 itslimitbeside it, gradeswarn, and names the bound and the rerun or wider command in its message. Used bymulti_source_drift,ghost_pages,missing_recorded_files,conversation_outcomes_stale,maintenance_write_drift,git_convergence,tracked_ownership_marker,orphaned_private_queue,link_resolution_opportunityandfrontmatter_integrity. A capped list that found rows says "at least N" or "N+" withexact: falseinstead. 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 beforesearch_mode). Each run advances the fence census withinGBRAIN_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-dayfences_normalizedtrend with top writers (warns atFENCE_NORMALIZATION_WARN_7D= 20), and the model-repair caps with today's ledger spend.okonly 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-onlygbrain repair fences --source <id>preview for holds, stored pages and files alike; a warn readsreadFenceAutoRepair(detailsauto_repair): while a maintenance run is active andfences.repair.enabledis on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix'sthenis the apply. Model-tier fences say why they wait (fences.repair.llmoff with the command that turns it on, or today's budget spent with the cap command), else the caps.fenceIntegrityCheck(engine, sourceIds?)is theWAVE_CHECKSentry (scoped for a remote caller). Location only. #6278: the check also countsunrenderable_legacy_facts: the activerow_num IS NULLfact 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 suggestsforget_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_factslists, from the same plan, unfenced rows of classic database-only pages thatpersistence.unbound_writekeeps unfenced; when it is the only finding the fix isgbrain config set persistence.unbound_write database_onlywithask_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) addsCheck.skipped_segmented: nand askipped (segmented): nmessage 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, andextract_healthviareadFactsReconcileBacklog'sskipped_segmented; each count is one COUNT query that falls back to 0 on a schema withoutbody_storage. Test:test/large-pages/doctor-skipped-segmented.test.ts(+ Postgres arm).src/commands/doctor/checks/git-convergence.ts—git_convergence(#5063, brain category, aftersync_freshness): for every non-archived filesystem source root plussync.repo_path(connector sources skipped),git status --porcelain -zandrev-list --left-right --count @{u}...HEADagainst 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: trueindetails.roots, #7089) with an agent fixgbrain git commit-push --push-only --keep-checkout --scan-secrets --path <root>(verifygbrain 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 ismirror_read_only) whose commits ahead of upstream touch only.gbrain/access.ymland.gbrain/access.approvedis reported ok at info severity (policy_only_mirror, GST-2634), and amirror_read_onlyroot's fix never suggests a push (mirror_read_onlyindetails.roots); testdoctor-git-convergence-mirror-gst2634.test.ts. Emits nothing when no probed root has an upstream. The same entry emitstracked_ownership_marker(#5186):git ls-files --cachedon each of those checkouts, warn when a pathisPhysicalRootMetadatarecognizes is in the index, with a user-rungit -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.tsbootstrap_push_healthalso warns, instead ofok, when a recent successful push leaves the receipt workspace ahead oforigin/<branch>.scripts/smoke-test.shaccepts a configured database URL (engine statusdb_url_source) and trusts doctorembedding_providerover 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 ofvector_planin commands-2.md). Postgres only: reads the commonest lexeme the planner knows forcontent_chunks.search_vector(pg_stats.most_common_elemswith its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (buildKeywordCountStatement, the builder the engine uses) and times the engine's own boundedcountKeywordPages(term, { timeoutMs: 2000 }); warnscanary_timed_outwhen that count hits its bound andcanary_slowwhen it takes more than half ofsearch.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 namesANALYZE content_chunks); a failing probe reports unknown health.engineKeywordPlanProbe(engine)is the database side;keywordPlanCheck(engine, probe?)takes a fake for tests. Tested intest/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, afterimage_assets). Counts live image pages (page_kind = 'image'), those with noembedding_imagechunk, those with a NULLsource_path, and themanaged_image_sync_unsupportedholds per source, and readsisMultimodalEnabled(). Ok when the brain has no image pages, when every image page has an image vector and asource_pathand 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 namesgbrain embed --stale --imagesandgbrain 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 afterembedding_key_source; not indoctorReportRemote): the provider-use decisiongbrain setuprecorded for this install (localSetupRecordsinsrc/core/setup/local-receipts.ts). A decline (any live receipt; opt-outs win) isok+ infodisabled_by_choice, "skipped by consent", naming the provider key variables present (names only) and carryingproviderConsentFix:gbrain setup <harness> --providers(+--name/--scope project), actoruser, consentpaid+egress, sonext: tell_user_to_run. Accepted is plainok; no receipt is infonot_applicable. The same fix ridesembedding_provider's--probeskip (checks/embedding-health.ts), andprobe-consent.tsauthorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned bytest/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_DEFAULT10000, connect included;entryRunsAtorders ops ⊂ quick ⊂ standard ⊂ deep;cheapTiergives it the ops tier's round-trip connection check and counter-mode embedding state) runs the ops entries plus the entries taggedtier: 'quick'(schema version, the stub-guard entry withsync_failures, queue health, partial embeddings).lastKnownModeturns the store on only for a brain-wide local CLI run (buildChecks(..., { lastKnown: 'cli' })fromrunDoctor) or the refresh job, never under--only,--source, a remote scope,--fixor--tier ops.runDoctorRegistryrecords each entry's outcome (done,expiredwhen it ran out of budget or emitted a budget unknown,not_runwhen the tier skipped a standard entry);withLastKnownwrites the finished entries of a standard or deep run toop_checkpoints(opdoctor-last-known, fingerprint = entry name,completed_keys[0]={ checks, measured_at, elapsed_ms, emits }, one bounded statement, best-effort) andapplyLastKnownreplaces an unfinished entry's checks with its last known ones when they are at mostLAST_KNOWN_MAX_AGE_MS(24 h) old: same status, message prefixedLast known, N ago (...),details.last_known{ measured_at, age_ms, reason: not_in_tier | budget }. The rest are named in onedoctor_last_knownwarning (details.health: 'unknown',unknown_checks), whichtierFieldsexpands intounknown_sections; served checks go tolast_known_sectionsand make the report incomplete. An entry with no result younger thanREFRESH_AFTER_MS(1 h) queues onedoctor-refreshjob 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_ms15 min; none when DB configdoctor.background_refreshisfalse, #7263); the handler (runDoctorRefresh, registered incommands/jobs.ts) runsdoctorRefreshRegistry()(the connection lane plus every standard entry after the connection gate; filesystem entries are recorded only by CLI runs) withREFRESH_ENTRY_BUDGET_MS(600000) per entry inside the overallREFRESH_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-refreshis inDEFAULT_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 lightreadCapacityForecast(null when unreadable: days unknown) andreadLastCompaction; the bands readcachedCapacitySnapshot;capacityVerify()is the verify of every capacity fix (gbrain doctor --only persistence_capacity --jsonplus MCPget_brain_health).readBrainHealthBandsbacks the read-scopeget_brain_healthop: 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.runRemoteDoctorTierbacksrun_doctor'stier: "ops"/only(admin).runScopedRemoteDoctoris the thin client'sgbrain doctor --tier ops/--only <registry check>: it readstools/listand usesrun_doctorwith the parameters, else the bands (BAND_CHECKS), else refusesdoctor_tier_unavailable; it never runs the full remote report in their place.cachedOpsSnapshotserves/admin/api/opsfrom 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'sgbrain repair rename-identityapply (destructive,ask_user,preview_argv,plan_hash;--closeon a managed brain), so unbound classic Postgres pairs get an actionable fix too;gbrain restore <old-slug> --source-id <id> --forceis named as the alternative in its text only whererestore_available !== false, andrestore_unavailable_sourceslists 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); fixgbrain pages purge-deleted --retry-parked --yes(preview--dry-run --json), consent destructive, ask_user. Alsoderived_origin_parked(GST-2689,checkDerivedOriginParked): names each originpersistence/derived-origin-hold.tsparked with the page that blocks it and the reason (details.origins); fix the read-onlygbrain repair visibility --source <id> --slug <blocking page>preview. An origin whose owner purge was held (held_request_id) also getsfinish_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 beforesearch_modeand mirrored indoctorReportRemote: 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_sinceLATERAL walk), the 7-day unlinked share of new facts,no_subjectjudgments and the 7-daylinkedtiers fromfact_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, originconversation, anddetails.conversationnaming the source with the most and its pages, most rows first, up toCONVERSATION_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 judgedno_subjectand conversation rows memoizedconversation_unresolvedexcluded (new_7d.conversation_unresolved); the fix isgbrain facts relink --dry-run; when conversation rows are unlinked the envelopefix(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; testtest/conversation-relink-6764.test.ts) and, once only rows it memoizedconversation_unresolvedremain (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>, inputNthe approved USD, preview--dry-run, consent paid + egress, ask_user; testtest/conversation-facts-unlinked-6764.test.ts), both verified bygbrain 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.fixismanual: no envelopefix, and the message names linking by hand with--entity(testtest/conversation-memo-6764.test.ts). Withoutfact_relink_attemptsthe 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, readsarchiveStatus(no reader run) andtranscripts.archive.last_maintenanceand warns on a harnesstranscripts.archive.stale_days(2) behind the newest session day seen or a reader unread that long (fixgbrain transcripts archive run, orbackfill --from <day>past one run window), on no maintenance pass that long (fixgbrain autopilot --install,persistent_installconsent), on held days, reader and pass errors; no readable sessions is info. Pinned bytest/doctor-transcript-archive-freshness.test.ts.src/commands/doctor/checks/unattended-maintenance.ts—unattended_maintenance(GBRA-438):readUpkeepStatusas 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 withgbrain maintain --unattended(consent: []unless an embedding key and a non-zero cap make it paid); on an overdue braindetails.alternative_fixrendersgbrain maintain --scheduleas the second fix.