Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (4/6)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/commands/frontmatter.ts—gbrain frontmatter validate|generate|audit|install-hook.validatekeeps the producer rule: exit 1 on anyparseMarkdownvalidation error, includingYAML_PARSEthat ingestion recovers by quoting (those print "importable but not canonical" with the--fixcommand).--importableswitches to the ingestion view throughscreenImportContent(exit 1 only for a hold). Inputs: one or more files or directories (every path is checked and each directory walked, a file named twice is checked once, a missing path refuses before anything is checked, and--jsonlists the paths astargetswhen there is more than one),--stdin/-(with optional--path <source-relative path>for the slug check, otherwise reported skipped), or--staged [paths](git index blobs via onels-files --stageand onecat-file --batch; a failing blob whose working copy passes says togit addit).--fixrunsautoFixFrontmatterthenrepairRecoverableFrontmatter(brain-writer.ts: safequoterecoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read;--include-ambiguousadds fold/dup/unclosed proposals and#-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root withwriter_coordinator_requiredwhose fix isgbrain repair frontmatter [--source <id>].audit --jsonaddsrecoverability_by_code(imported anyway vs held on import).runFrontmatter(args, io)takes stdin-stream and git-cwd test seams. Pinned bytest/frontmatter-cli.test.tsandtest/frontmatter-validate-producer.test.ts. #6157:parseMarkdown(markdown.tsyamlBlockError) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, andbrain-writer.tsautoFixFrontmatterskips the NESTED_QUOTES rewrite on a parseable block and keeps a tags/aliases re-quote only when the line reads back as the same value, sovalidate,--fix,lintandrepair frontmatternever flag or rewrite valid YAML. A block (or tags/aliases line) with more thanMAX_FRONTMATTER_YAML_ALIASES(16) aliases outside quotes counts as not parsing and is never rewritten (yamlAliasesWithinLimit; alias-bomb guard,test/frontmatter-alias-bomb.test.ts).src/commands/graph-query.ts—gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (--source/GBRAIN_SOURCE/.gbrain-source/ path match / brain default viaresolveSourceId, the same scalar scope thetraverse_graphop gets fromsourceScopeOpts); an explicit--sourcethat fails to resolve throws.--include-foreign(or--source __all__) drops the scope so the walk spans every source. The foreign-edge footer (N edges to foreign-source pages hidden; pass --include-foreign) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path usesengine.traversePathsDetailedand prints a stderr note when the walk hitTRAVERSE_PATH_ROW_CAP(shallowest edges kept; lower--depthor narrow with--type/--direction); the thin-client path goes through thetraverse_graphop, which has nosource_idparam (the server scopes the walk to the caller's grant): an explicit--sourcethere is rejected with exit 1 (same policy + wording asapplyThinClientSourceScope, never silently dropped) and--include-foreignprints a stderr note that it is not forwarded.--hop <link_type>:<object|subject>(repeatable, 1-3) runs a typed chain throughrunRelationalChainlocally ortraverse_graphhopson a thin client; it is refused with--type/--depth/--direction, a malformed hop names the fix, and a host that ignoredhops(older gbrain, detected viaignoredRemoteParamsor a non-chain response) is refused with the upgrade message. Pinned bytest/graph-query.test.ts(local) +test/graph-query-thin-client-source-flag.serial.test.ts(thin client; mocksisThinClient+callRemoteTool).src/commands/import.ts—gbrain import <path> [--source-id <id> | --source <id>]: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest.runImportcontains NOprocess.exit: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid--workers, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typedImportAbortError(carriesexitCodeand, for a refused lock admission, the underlying error ascause), so in-process callers — thesync_brainMCP op, autopilot, the Minionsimporthandler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI'simportcase catches it and exitse.exitCode. Pinned bytest/import-abort-error.test.ts. Human-only output (theinfo()lines and the end-of-runImport completesummary) goes throughslog()fromconsole-prefix.ts— identical toconsole.logoutside a wrap, but an in-process caller in its own--jsonmode (sync --json→performFullSync→runImport, wrapped inwithHumanLogsToStderr) keeps stdout pure JSON;import --jsonitself sends them to stderr directly. Pinned bytest/sync-json-stdout-clean.test.ts(first-sync case) +test/import-json-stdout.test.ts. The--jsonpayload also carriessource_id, the effective destination the pages were written to (sourceId ?? 'default', identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, sincerunImportadopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through todefault; pinned by the--json payload names …cases intest/import-source-id.test.ts.--source-id <id>(alias--source <id>; passing both with different values aborts) routes pages to the named source (resolved viaresolveSourceWithTier()at the boundary; consistent acrossimport,extract,graph-query,sources current;graph-querytakes--source <id>). Pinned bytest/import-source-id.test.ts. An unscoped import that resolves to tierseed_defaultruns the default-write assessment throughassessDefaultWriteGuardOnce(engine)(memoized per engine — in-process callers such as thesync_brainop, autopilot, and minion sync invokerunImportrepeatedly on one engine) and WARNS viaformatDefaultWriteWarning(a, '--source-id')when the brain's pages overwhelmingly live outsidedefault— never aborts, since aborting would take an in-process host down mid-call;GBRAIN_ALLOW_DEFAULT_WRITE=1skips it. Pinned bytest/import-default-write-guard-once.test.ts.gbrain importCLI +runImportlibrary entrypoint. Ordinary imports use a path-set progress checkpoint viasrc/core/import-checkpoint.ts; theirrunImportpath walks all current files, including previously completed paths, through the existingimportFilecontent-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protectedop_checkpointsentries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See company-brain ingestion. The walk still appliessortNewestFirst()for embed-cost ordering. A file enterscompleted: Set<relativePath>only when itsprocessFilereturns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual~/.gbrain/import-checkpoint.jsondelete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. ThemanagedBookmarkopt (set byperformFullSyncwhenrunImportis the full-sync engine) suppressesrunImport's ownsync.last_commitadvance so the sharedapplySyncFailureGate(src/core/sync-failure-ledger.ts) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned bytest/import-checkpoint.test.ts+test/import-resume.test.ts(incl. the SLUG_MISMATCH retry case).collectSyncableFiles' shared emit filterisCollectibleForWalkerapplies the SAME segment-levelpruneDirgate as incremental sync'sclassifySync— load-bearing for thegit ls-filesfast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without itsync --fullwould import (and resurrect soft-deleted) pages incremental sync excludes. Pinned bytest/import-git-fastpath-prune.test.ts.runImportopts also carryexclude(glob filter over dir-relative paths, threaded byperformFullSyncforsync --exclude; warns when every file is excluded — NAV-4) andslugRoot(slug/source_pathbase for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not useresumeFilterto skip paths). The--jsonpayload carries, beside the counts,unchanged(content-hash no-ops),malformed_skipped, andfailures: [{path, error}]— rethurned per-file failuresimportFileRETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under bothskipped, anotderrors, are excluded fromunchanged, and producestatus: "partial"with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned bytest/import-json-stdout.test.ts. Each--workerschild pool connects throughconnectWithRetrywithretryConnectTimeout: true(#5946, seesrc/core/db.ts). A directory the enclosing git repository ignores (for example a scratch folder under.context/) returns nogit ls-filesrows, sogitListSyncableFiles(listing throughgitLsFilesinsrc/core/git-visible-files.ts, memoized inside doctor'swithGitListingCache) falls back to the filesystem walk whengit check-ignorereports the directory itself ignored; an explicit import of it no longer succeeds with zero files (test/import-ignored-root.test.ts).A managed import hands its files toimportManagedFilesin batches (nextImportBatch) and accounts each file's settled result, in order, through the sameprocessFilebookkeeping; held paths are skipped before the batch.runImport'sonCollectedhands over its completed, unaborted walk (root-relative, before--exclude) as aCollectedWalk.src/commands/init-prefer-postgres.ts—runPreferPostgresLadder: the Postgres-first install ladder behindgbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json](the zero-configgbrain initdefault stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY viasupabase-admin.ts—SUPABASE_ACCESS_TOKEN(+SUPABASE_PROJECT_REFon multi-project accounts, auto-selected on single-project ones) +SUPABASE_DB_PASSWORD(the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or--local-postgres— a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (CREATE DATABASE gbrainneeds explicit--allow-create-db); (4) docker viadocker-postgres.ts(explicit--allow-docker; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5)initPGLite+ explicit upgrade-later note. CallsinitPostgresCore(typedInitPostgresFailure, noprocess.exit— the returnable core that makes rung fall-through possible) and reuses db-repair'sdefaultDeps.probeAccessprober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bareDATABASE_URL(vs the stated-intentGBRAIN_DATABASE_URL) is adopted only when the target is already a gbrain brain or holds no tables at all (classifyDbContent, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a survivinggbrain-pgdatavolume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted.--jsonemits ONE final{status, engine, ladder_rung, url_source}envelope and stdout is EXACTLY that document —withStdoutToStderrreroutes bothconsole.log(Bun writes it to fd 1 directly) and bareprocess.stdout.writearound the inner init cores.src/commands/integrations.ts— recipe install. The resolver-row install fence is keyed bymanifest.recipe(gbrain:<recipe>:resolver-rows), so a secondcopy-into-host-reporecipe never writes a block mislabeled with the first recipe's name. Pinned bytest/integrations-install.test.ts. Health-check DSL includes the staleness-awareheartbeat_max_agetype: declares the sense's expected cadence (max_age: 48h), andintegrations doctorFAILS when the newest heartbeat event is older — the only check type that catches a green-but-dead sense (all others are point-in-time). Not embedded-gated (reads only the local heartbeat file). Recipe frontmatter carriesoutput_paths(repo-relative dirs the collector writes, e.g. calendar-to-brain →daily/calendar/);getConfiguredCollectorOutputs()surfaces them for the db_only-collision check/warning. Pinned bytest/integrations-heartbeat-max-age.test.ts. Standalone integration recipe management (no DB needed). ExportsgetRecipeDirs()(trust-tagged recipe sources), SSRF helpers (isInternalUrl,parseOctet,hostnameToOctets,isPrivateIpv4). Only package-bundled recipes areembedded=true;$GBRAIN_RECIPES_DIRand cwd./recipes/are untrusted and cannot runcommand/http/string health checks.src/commands/integrity.ts—gbrain integrity check|auto|review|extract: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip).scanIntegrity()is the shared library function called fromgbrain doctor(sampled at limit=500) andcmdCheck(full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated byengine.kind === 'postgres'at the call site so PGLite never enters batch; fallbackcatchlogs atGBRAIN_DEBUG=1. Batch projection isSELECT ... ORDER BY source_id, slug(NOTSELECT DISTINCT ON (slug), which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each(source, slug)row independently. Sequential and auto-repair loops uselistAllPageRefs()to enumerate(slug, source_id)pairs and threadsourceIdtogetPage; batch + sequential paths report the same page count on multi-source brains. Help (--help/-h/helpafter any subcommand) prints usage without running it, andauto/reset-progresstake strict arguments (src/cli/strict-args.ts). A segmented page is scanned block by block (bodyLines, fence state and line numbers carried) with inline-identical hits; an unreadable page goes toskipped.src/commands/jobs.ts—gbrain jobsCLI subcommands +gbrain jobs workdaemon.jobs-readiness.tsorchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. AfterensureSchema,maybeRunWorkerStartupRecovery(queue, process.env, true)runs for both bare and supervised workers; the final workerreadyevent publishes readiness, and a worker handed an owner status channel (GBRAIN_WORKER_STATUS_PATHorGBRAIN_WORKER_STATUS_TOKEN, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (GBRAIN_SUPERVISED=1from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults reportconfiguration_blockedand exitWORKER_EXIT_CONFIGURATION, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded:JOBS_HELP(full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) andJOBS_SUBCOMMAND_HELP(work/supervisor/submit/watch/prune) print from a guard at the TOP ofrunJobs, BEFORE the thin-client refusal and theJOBS_SUBCOMMANDSdispatch —jobs work --helpcan never start a daemon; only--help/-hare help tokens (barehelpcan be a job name); cli.ts routes it engine-free viaSELF_HELP_WITHOUT_ENGINE+CLI_ONLY_SELF_HELP.formatJobDetailprints the effective wall-clock budget (Timeout:/Deadline:— 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer;timeout_atis inJOB_DATE_FIELDSfor thin-client rehydration.jobs statsprints aBackpressure (24h)line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the sharedGBRAIN_WEDGED_QUEUE_WARN_MINUTESthreshold — the read-only visibility for maxPending single-flight suppression. Pinned bytest/jobs-subcommand-help.test.ts,test/jobs-format-detail.test.ts,test/jobs-stats-backpressure.serial.test.ts.jobs work(src/commands/jobs/work.ts) wrapsworker.start()in try/finally and owns engine lifecycle — callsengine.disconnect()on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive).jobs submitsurfaces theMinionJobInputretry/backoff/timeout/idempotency surface as flags:--max-stalled,--backoff-type fixed|exponential,--backoff-delay,--backoff-jitter,--timeout-ms,--idempotency-key,--max-waiting(maxPendingis deliberately internal-only — no flag; see TODOS).jobs smoke(jobs/smoke.ts) tracks every job it adds to the privatesmokequeue and discards exactly those (cancel if live, then delete) in onefinallyon pass, failure, timeout and throw (test/jobs-smoke-cleanup.test.ts); its--sigkill-rescue/--wedge-rescuecases (W4.9) add a probe under its own job name (smoke-sigkill-probe,smoke-wedge-probe), move it toactivethroughqueue.claim(the queue protocol trigger refuses a forged transition) and then age onlylock_until/started_at(timeout_at=NULLfor wedge), so each reaches its rescue verdict.registerBuiltinHandlersalways registerssubagent+subagent_aggregator(no env flag —ANTHROPIC_API_KEYis the cost gate, trust is viaPROTECTED_JOB_NAMES) and loadsGBRAIN_PLUGIN_PATHplugins at startup with a loud per-plugin line;shellhandler still gated byGBRAIN_ALLOW_SHELL_JOBS=1(RCE surface). Theautopilot-cyclehandler forwardsjob.data.phasestorunCycle, validated againstALL_PHASESfromsrc/core/cycle.ts(invalid names filtered; empty/missing falls back to the default cycle); whensource_idis set it bindsbrainDirto that source'slocal_path(null for a pure-DB source, never the global repo) and checksisSourceInCooldownbeforerunCycle, returning a no-opskipped(not a failure) for a source still in its failure cooldown. The siblingautopilot-global-maintenancehandler runsMAINTENANCE_PHASES(mixed ∪ global) once (nosourceId,pull:false) and stampsautopilot.last_global_atonly when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible.resolveJobPullgives both cycle and standalone sync jobs one positive-polaritypullcontract while preserving queued payloads that still carry the inverse legacynoPullkey; explicitpullwins. Thesynchandler resolvessourceIdat entry fromsources.local_path(mirrorscycle.ts:480) so multi-source brains read the per-sourcelast_commitanchor; concurrency routes throughautoConcurrency()insrc/core/sync-concurrency.ts(PGLite stays serial);noEmbeddefault istrue.gbrain jobs supervisor status --jsonaddsprocessing_ready, lowercaseprocessing_state(starting/ready/configuration_blocked, orunknown/stoppedwithout current state),reason_code,blocked_sinceand worker/child identities without changingrunningor crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumessummarizeCrashes()fromsrc/core/minions/handlers/supervisor-audit.tsfor parity withgbrain doctor: JSON addscrashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}+clean_exits_24h; human output includes per-cause + clean-exits lines. Pinned bytest/job-pull-policy.test.tsand 4 source-grep wiring assertions intest/doctor.test.tsrequiringcrashes_by_cause+clean_exits_24h=in bothdoctor.tsandjobs.ts.gbrain jobs watchdecouples its two output axes:--jsonpicks FORMAT (human default, never gated on isTTY),--followpicks LOOP (defaultisTTY && !json). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron);--followopts into a continuous stream (human plain per tick, or JSONL with--json); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pureresolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}insrc/commands/jobs-watch.ts; the dispatch wires--follow. Pinned bytest/jobs-watch-mode.test.ts(format×loop matrix incl. the TTY+--json-one-shot case) +test/e2e/non-tty-output.serial.test.ts(thecmd </dev/nullnon-empty-stdout contract). registers 11 Minion handlers:reindex,repair-jsonb,orphans,integrity,purge,synthesize(PROTECTED),patterns(PROTECTED),consolidate(PROTECTED),extract_facts,resolve_symbol_edges,recompute_emotional_weight. Phase wrappers delegate torunCycle({phases:[name]})sosrc/core/cycle.tsstays the single source of truth for phase semantics. The standalonesynchandler passesnoExtract: trueto matchrunPhaseSync's contract (doctor's remediation plan emitting[sync, extract]would otherwise double-extract). Theextracthandler routes{stale: true}jobs (submitted by performSync's size-gate defer branch) throughextractStaleFromDBscoped todata.sourceId, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived fromSTALE_TIME_BUDGET_MS) when the sweep's budget leavesstaleRemaining > 0with forward progress.parseJobIsolationFlag(args, env?)(--job-isolation, space/= forms,GBRAIN_JOB_ISOLATIONfallback, default inline);jobs workresolves the actual selected child and validates its bounded protocol/capability handshake and warns when--max-rssis combined with isolation (watchdog covers the worker only);jobs run-childis the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); thedb_deadfatal text is verdict-aware (pool starved vs server unreachable). Genericjobs submitnormalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicitensureSchema()preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite,jobs submit embed-backfillrefuses withno_worker_surfaceand a paste-ready inline embed command before any queue access;--dry-runevaluates the same read-only feasibility gate and never says “Would submit” for an impossible job.--followis the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCPsubmit_joboperation applies the same gate (including dry-run), translates the expected refusal to branchableOperationError('no_worker_surface'), and never emitsinternal_errorfor this capability miss. Thesynchandler forwardsjob.data.github_item({repo, number, kind}) intoperformSyncfor github-kind single-item webhook refreshes.jobs workregisters the shell handler always; the startup line names the flag first (--allow-shell-jobs/GBRAIN_ALLOW_SHELL_JOBS=1);jobs startcomputesallowShellJobsas--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'— the same literalhandlers/shell.tsandbuildChildArgscheck.extract-atoms-drainaccepts a trustedretryRequestIdin submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLitejobs --followstill requires exclusive owner access. D2:jobs supervisor start --detachwrites its payload (event,status:'started',supervisor_pid,pid_file,detached,stderr_log) throughwriteStdoutFinal; thejobsrecord declares nojsonbecause work/watch/foreground supervisor stream. Start refusals add an envelope under--json(invalid_paramsexit 2 for an unknown subcommand or bad--health-interval,config_errorfor PGLite).jobs submit enrich|subagentruns the paid consent gate and stores anauthorizedspend record on the row;jobs get --jsonaddsspend_basis,spend_whyandspend_group;jobs list --group <id>andjobs cancel --group <id>act on one spend group. GBRA-133 2a.4 / #7002: on Postgres,jobs workstartsstartSyncQueueWake(src/core/minions/sync-queue-wake.ts, givenworker.idleWaiter) beforeworker.start()and stops it in the finally, and callsstartWorkerPersistenceConsumer(exported fromjobs/work.ts):startPersistenceConsumerat boot through the existing election (service.ts unchanged), so an idle worker runs the persistence consumer, or withpersistence.single_consumeron waits beside a live owner and promotes when it stops;engine.disconnect()stops it. Tests:test/pathological/s-7002-worker-consumer.test.ts+ its Postgres twin (realjobs workprocesses). Size ceiling:scripts/module-size-limits.tsv(per-change raise history:git log -pon that file).runJobsresolves help and the thin-client refusal, builds the queue, then dispatches throughJOBS_SUBCOMMANDS(Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand insrc/commands/jobs/<sub>.ts(runJobs<Sub>(ctx); parsers, formatters andJobsCommandContextinjobs/shared.ts;maybeRunWorkerStartupRecoveryinjobs/work.ts), all re-exported fromjobs.ts. Subcommands that register handlers importregisterBuiltinHandlerslazily fromjobs.ts.registerBuiltinHandlersis the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live insrc/core/minions/handlers/(see core-minions-1). Registration names and order are pinned bytest/jobs-handler-registry-golden.test.ts, which also drives the supervisor'sderiveHandlerNamesprobe.src/commands/jobs.ts:refreshGatewayForJob+src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane— long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (reconfigureGatewayWithEngine); (2) FILE-plane config (~/.gbrain/config.json, incl. provider API keys) re-folds per job via the env-ONLYrefreshGatewayEnvFromFilePlane— never a fullconfigureGateway(buildGatewayConfig(loadConfig())), which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart.gbrain config set *_api_keywrites the DB plane, whichloadConfigWithEngine()deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane).facts-absorbsits inGATEWAY_REFRESH_JOB_NAMES; its handler converts execution-timechat_unavailablein a KEYED worker into a typed retryable failure (factsAbsorbShouldRetry) while a keyless worker defers it (JobDeferredError, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned bytest/jobs-gateway-refresh.serial.test.ts.src/commands/lint.ts— Page quality linter (catches LLM artifacts, placeholder dates).runLintCore(opts)walks the tree ONCE;--fixapplies fixes during that same scan and reports per-page results through theonPageIssues(relPath, issues, fixedCount)callback (issues = what remains after this run's fix attempt for the page;fixedCount= fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero.onScanStartfires once with the collected page count for progress wiring. Pinned bytest/lint-fix-single-pass.test.ts. On a durability-hardened brain (isDurabilityHardenedon the target dir, or the page's directory for a single-file target) every non-dry-run--fixrepair is committed path-limited viacommitWriteThroughFileright after thewriteFileSync— the same contract as put_page write-through, so the cycle, thelint/lint-fixminion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned bytest/cycle-lint-durability.test.ts). Lint ruleshuge-page(flags pages exceedingcontent_sanity.bytes_warn) andscraper-junk(flags pages matching any junk pattern). Both reuseassessContent()fromsrc/core/content-sanity.tsso lint, doctor, and ingest share one assessor.lint.tslifts DB config when~/.gbrain/is reachable; falls back to file/env on CI. Pinned bytest/lint-content-sanity.test.ts. Ruletype-undeclaredflags an explicit frontmattertypethe active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-planeschema_pack, else file/env config; no resolvable pack skips it;LintOpts.typePackinjects it), pinned bytest/lint-page-type-vocabulary.test.ts. withsrc/commands/sources.ts:gbrain linthas amarkup-heavyrule (flags pages whose prose-vs-markup ratio exceedscontent_sanity.max_markup_ratio, reusingassessContentSanityso lint/gate/scan share one assessor); pinned bytest/lint-content-sanity.test.ts.gbrain sources audit <id>is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effectivecontent_sanity.junk_disposition+ markup config, so an operator previews the gate's verdict before sync. Thecontent-sanity-auditJSONL (src/core/audit/content-sanity-audit.ts) records the quarantine/flag dispositions. On a managed brain (persistence enabled)runLintCoreskips the legacy filesystem lock and publishes each repair through the persistence coordinator (maintenancePreflight+publishMaintenancePage: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (fileMatchesSnapshot, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixablemanaged-write-pendingissue withcode: 'managed_write_pending', areason(the coordinator refusal's detail,held_file,canonical_file_missing,revision_changed,not_indexed), the refusal's own renderedfix(never a sync) and the guide link; the run continues (LintResult.write_path/fix_pending/pending_issues, first 50; #5180,test/managed-lint.test.tson both engines). A file the scan listed that is gone by its scan read (ENOENT only; other read errors still fail the run) is reported instead of aborting: a managed--fixrun asks the coordinator (pendingcanonical_file_missing), otherwise a non-fixablefile-removed-during-scanissue with codefile_removed_during_scanand agbrain lint <target>fix; the CLI prints each issue'sFix:command andDocs:link (test/lint-file-removed-during-scan.test.ts).llm-preamblematches only a leading run at a body start (file top, after leading frontmatter, or after a whole-page ```markdown wrapper), and repair removes only that run, so a later line that begins like a preamble is never flagged or deleted. A filesystem fix write refused with EACCES/EPERM/EROFS leaves the file unchanged and becomes a non-fixablefix-not-writableissue (code: 'fix_not_writable', the errno asreason, a userfixnaming the permission change or--exclude) counted infix_pending; the run continues (test/lint-preamble-anchor.test.ts).placeholder-dateandempty-sectionread code-masked text (stripCodeBlocks, offset-preserving): a placeholder or a##line inside a fence or inline code is code, an unclosed fence masks to the end of the file, andempty-sectionreads each section's body from the original text, so a section holding only a code block is not empty (test/lint-3958.test.ts). #5433:missing-createdfires only when none ofcreated,event_date,date,published,captured_at,ingested_atparses (parseDateLooseon the parsed frontmatter, never a regex; a block YAML could not read is alreadyfrontmatter-yaml-parse) and is never fixable:fixContentno longer promotes a capture timestamp intocreated(ingest time is not creation time, and the cycle'sfix: truelint phase rewrote every native page), so a pageserializePageToMarkdownemits stays byte-identical across repeated--fixruns;promoteCreatedFromCapturestays exported, deprecated, for explicit callers.src/commands/maintain.ts—gbrain maintain [--safe] [--dry-run] [--json],--unattended [--runner <name>](one free upkeep run throughsrc/core/maintenance/run.ts),--status(the upkeep view doctor'sunattended_maintenancereads) and--purge(page-purge preview;--yes --expect <hash>applies exactly the previewed set,purgePreviewHash).--safe: stale extraction, then one source-scopedrunCycleper source doctor'scycle_freshnessnames, limited toMAINTAIN_SAFE_PHASES(the step list lives insrc/core/maintenance/run.tsand is re-exported here) (free and never hard-deleting: nopurge, no paid phase);maintainSafePhasesalso holds backextract_factswhen an embedding provider is available or the decide conflict slot is on and the repair lanes when an embedding provider is available orfences.repair.llmhas a model (GST-2246). A source whose cycle throws an item-scoped error is ablockedaction withdetails.codeandfix(gbrain dream --source <id>) and later sources still cycle (ItemRun sitemaintain.cycle_sources); run-scoped errors anditem_failures_systemicstop maintain; any blocked action sets exit 1. Tests:test/maintain.test.ts,test/maintenance-unattended.test.ts,test/e2e/maintain-unattended-keyless-pglite.test.ts,test/pathological/a41-maintain-sources.test.ts.src/commands/migrate-embeddings.ts—gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override](alias:gbrain retrieval-upgrade). ONE shared orchestrator for CLI and themigrate_embeddingsop:planMigrationFlow(plan +verifyMigrationComplete+ env presence + un-merged file plane + brain/DB identity viaredactPgUrl+ concurrent-writer census + reranker plan + in-flight-other marker) andexecuteMigrationFlow(globalgbrain-embedding-migrationDbLock → retarget gate under it → all-source embed locks sorted withincludeArchived→ worst-case authorization under the locks (a cap below it returnsrefused_budget/ oprefusedwithembedding_budget_below_worst_casebefore any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain viarunEmbedCore({heldLocks, …})so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS aslock_lost→ reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY onverify.completewith no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion).--statusis read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome).persistEmbeddingFileConfigwrites throughloadConfigFileOnly(never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2:requireConsentwith effectspaid+destructive;spend.posture=tokenmaxcovers only the paid part,--jsonnever implies consent, the payload's fix repeats the caller's argv plus--yes; the TTY prompt is interaction.readLine, and theconfirm/isTTYtest seams map onto ConsentEnv). Spend stays bounded by the durable--max-cost-usdauthorization, not the consent cap. Pinned bytest/migrate-embeddings-flow.serial.test.ts,test/migrate-embeddings-boundary.serial.test.ts,test/migrate-embeddings-hardening.serial.test.ts. Migration guidance usesrenderCanonicalMigrationCommands(src/core/ai/defaults.ts) to keep supported targets and dimensions consistent.src/commands/migrate-engine.ts— Legacy engine copier (gbrain migrate --to pglite, and PGLite → Postgres whenmigrate.graduationisfalse). A PGLite → Postgres move routes tosrc/commands/migrate-graduation.ts(engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (copyMigrationSources— everysourcesrow incl. archived rows and sync/routing metadata,ON CONFLICT (id) DO UPDATE,defaultordered first) so every page write has a validpages.source_idFK parent and the target preserves per-source behavior; pages copy afterward:listAllPageRefslists every live page's(source_id, slug)in one uncapped query,copyMigrationPagesreads each body withgetPage(slug, { sourceId })(a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite(source_id, slug)key. Link copy preserves each row'sto_source_id(falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware:migrationTargetId(config)hashes(engine, locator)(database_urlfor Postgres, resolveddatabase_pathfor PGLite) andmanifestMatchesTargetrequiresschema_version === 2plus a matchingtarget_id— a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links,copyMigrationFactscarries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-passsuperseded_byrestore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (vector/halfvec) the target column has with a NULL-embedding retry on per-row cast failure, and asetvalbump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassignedpage_id; the next extract cycle rebuilds them).copyMigrationConfigthen copies EVERY DB-plane config row except the explicit engine-local denylistMIGRATE_CONFIG_ENGINE_LOCAL_KEYS(engine,version= target-owned schema ledger,embedding_columns+search_embedding_column= physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned bytest/migrate-engine-resume.test.ts(manifest identity) +test/e2e/migrate-engine-sources-postgres.test.ts(source catalog lands before overlapping-slug pages, PGLite → real Postgres) +test/e2e/multi-source-bug-class.test.ts(cross-source links) +test/migrate-engine-completeness.serial.test.ts(facts chains/embeddings/sequence, config copy-all + denylist, summary) +test/migrate-engine-pagination.serial.test.ts(no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. #6286:copyPageToTargetforwards the full page row (page_kind,source_path, effective date and its source,import_filename,source_kind/source_uri/ingested_via,ingested_atrestored in the timestamp UPDATE), the frontmatter aliases (setPageAliases) and each chunk's code metadata (carryChunkMetadata). A page sealed on the source is queuedengine_migration; one the source had not sealed is queuedengine_migration_source_unsealedand keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused,runMigrateEnginerunsdrainProjections(moved tosrc/core/page-state/projections.ts;commands/projections.tsre-exports it) on the target for theengine_migrationandrebuild_failedreasons, keyless; the rebuild keeps chunk ids and vectors whose identity and embedding input match, so the first sync after the flip skips unchanged pages. A failed rebuild blocks the flip with exit 1, like a page that failed to copy. Pinned bytest/migrate-full-row-projections.serial.test.ts,test/e2e/migrate-full-row-projections-postgres.test.tsand a D2 case intest/e2e/migrate-engine-pglite-to-postgres.test.ts. Open-loop and loop-suppression rows the target refuses (copyMigrationSimpleTable, per-rowItemRunsitemigrate_engine.loop_rows) are printed with their id and reason, block the config flip and set exit 1; a run-scoped failure stops the copy (test/pathological/a31-migrate-loop-rows.serial.test.ts). Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.src/commands/migrations/— TS migration registry (compiled into the binary; no runtime walk ofskills/migrations/*.md).index.tslists migrations in semver order.v0_11_0.ts= Minions adoption orchestrator (8 phases).v0_12_0.ts= Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify);phaseASchemahas a 600s timeout for duplicate-heavy brains; the config check readsauto_linkin-process (file/env plane, then the database), never through agbrain config getchild.v0_12_2.ts= JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record).v0_14_0.ts= shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md; raisesminion_jobs.max_stalled's default to 3 only when it is below 3, so it never lowers schema v15's 5). Fresh installs (E8):Migration.fresh_install_noop: truemarks an orchestrator that changes nothing on a braingbrain initjust created;fresh-install.ts:recordFreshInstallMigrations(one call in each init engine path, only when init created the database) appends acompleteledger entry withfresh_install: true+installed_versionfor each, and every other migration lists aspending_fresh_install(src/core/migration-ledger.ts:freshInstallVersion/isPendingFreshInstall) inapply-migrations --list [--json]/--dry-run,get_health.migrationsand doctor'sminions_migration(anok/inforow withgbrain apply-migrations --yes --no-autopilot-install); stamps never count as forward progress over a real partial. Each flag is proven bytest/migrations-fresh-install-audit.serial.test.ts(schema, row counts, config table and GBRAIN_HOME file tree unchanged by the real orchestrator on a keylessinit --pglite --no-embeddingbrain); unit coveragetest/migrations-fresh-install.test.ts.shared-content.tsnames its read-only next step as phaseargv(SHARED_CONTENT_INSPECT_ARGV), which the runner prints and the ledger keeps. #6466 opt-out:Migration.optOut: { key }names a brain-level DB config key (shared-content.ts:shared_skills.migration.enabled, the registry-free tableMIGRATION_OPT_OUT_KEYSinsrc/core/migration-ledger.ts, pinned to every module'soptOut); an explicit off value (false/0/off/no,isMigrationDeclinedValue) puts the migration in the plan'sdeclinedbucket (opt-out.ts:readDeclinedMigrations, read beforebuildPlan; an unreachable brain declines nothing), so the runner never calls its orchestrator, reconcile included,--list [--json]and--dry-runshow itdeclinedwithopt_out.key, and an explicit--migration <v>refusesmigration_declined(exit 3,fix.next: ask_user,gbrain config set <key> true, verify--list --json).migrationLedgerSummary(VERSION, declined)givesget_health.migrations.declinedand doctor'sminions_migrationanokrow withdetails.declined; with no engine (doctor --fast) the config is unreadable, sominions_migrationleaves everyMIGRATION_OPT_OUT_KEYSversion out of its not-run list (#8720). Tests:test/shared-skills-migration-decline-6466.test.ts,test/doctor-fast-declined-migration-8720.test.ts. All orchestrators are idempotent and resumable frompartialstatus. The RUNNER owns all ledger writes — orchestrators returnOrchestratorResultandapply-migrations.tspersists a canonical{version, status, phases}shape (orchestrators never callappendCompletedMigration).statusForVersionpreferscompleteoverpartial(never regresses); 3 consecutive partials → wedged →--force-retry <version>writes a'retry'reset marker. Schema-only migrations v14 (pages_updated_at_index) + v15 (minion_jobs_max_stalled_default_5with UPDATE backfill) live insrc/core/schema-migrations/v014-pages-updated-at-index.tsandv015-minion-jobs-max-stalled-default-5.ts(one file per schema migration;migrate.tsis the runner).in-process.tsexportsrunMigrateOnlyCore({timeoutMs?})— single source of truth for "bring schema to head" (configureGateway→createEngine→connect→initSchema→disconnect, idempotent, 600sMIGRATE_ONLY_TIMEOUT_MSguard, throwsMigrateOnlyErroron no-config / timeout); the orchestrators' 9 schema phases ANDinit.ts:initMigrateOnlyboth delegate to it so schema bring-up can't drift (in-process, so no spawn can die withgetaddrinfo ENOTFOUNDon Windows + bun + Supabase pooler).runGbrainSubprocessis the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error.v0_13_1.tsis an idempotent no-op since #7814: it records completion and writes no page (it used to stampvalidate: falseinto every page on any brain whose ledger never recorded v0.13.1). Pinned bytest/migrations-v0_13_1.test.tsand the upgrade contracttest/upgrade-preserves-pages-7814.slow.test.ts.src/commands/migrations/v0_46_3.ts— idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.src/commands/migrations/v0_60_31.ts— the security fix wave orchestrated migration (ledger0.60.31), two phases.credential_projection: runsrunMigrateOnlyCorefirst (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), thenresealCredentialProjections, provider-free and never embedding; a dry run reports the count; a page whose re-chunk fails item-scoped is held (credential-reseal.ts) and the phase completes withheld: Nand the codes in its detail (doctortext_projection_readinesslists the pages,gbrain repair safe-chunks --source <id> --applyretries them); a run-scoped failure or a systemic one (item_failures_systemic) fails the phase with its code, so the run ispartialandgbrain apply-migrations --yes --no-autopilot-installretries it, and re-sealed pages are no longer pending, so a rerun resumes.google_file_modes_notice:googleFileModesNoticePhasefromv0_60_31-google-file-modes.ts. A brain without config completes with the phase skipped. Agent instructions:skills/migrations/v0.60.31.0.md.src/commands/models.ts—gbrain models [--json]read-only routing dashboard: prints tier defaults (utility/reasoning/deep/subagent), the resolved value for each (re-walking the resolution chain), every per-task override (14PER_TASK_KEYS, including provider-neutralmodels.contextual_synopsiswith legacy-key/env attribution andmodels.dream.extract_atomswhich reports via its own caller-specific resolver —resolveExtractAtomsModelWithSource()inextract-atoms.ts: its own key, thenmodels.tier.utility, then the key-aware utility default, nevermodels.defaultorGBRAIN_MODEL(#6675) — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (default/config: <key>/env: <VAR>) derived fromresolveModelDetailed, so a tier key is attributed beforemodels.default. ANightly quality probeblock (JSONnightly_probe;schema_versionstays 1) shows the probe's routes fromresolveNightlyProbeModelRoutes: reader and extractor with their source, and each judge slot labelledconfig: models.eval.cross_modal.slot_<x>,panel defaultorsubstitute for <default> (no usable provider)— the #4636 substitution run with a silent log against this process's gateway. Itsenvironment_notesays availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's~/.gbrain/envreads as unavailable. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory[newer <family> available: <id>] (gbrain config set ...)hint (JSON:newer_available); version parsing lives insrc/core/ai/anthropic-model-ids.ts(8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default.gbrain models doctor [--skip=<provider>] [--json]fires a 1-tokengateway.chat()probe against each configured chat + expansion model and classifies failures into{model_not_found, auth, rate_limit, network, unknown}. The probe timeout resolves per model viaresolveChatProbeTimeoutMs— the recipe touchpoint'sdefault_timeout_mswhen declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback;claude-clideclares 30s because itsclaude -psubprocess cold start routinely outruns 5s and would false-fail every run asunknown). The reranker reachability probe sends one question with a relevant and an unrelated passage and reportsokonly when the relevant one scores higher by more than 0.1; equal, inverted or missing scores areconfigwith a fix namingdocs/ai-providers/llama-server-reranker.mdstep 2 (a broken GGUF conversion answers but ranks at random). Wired intocli.tsdispatch +CLI_ONLYset. A zero-tokenembedding_configprobe runs FIRST, before any chat/expansion probes spend money:probeEmbeddingConfig()readsgetEmbeddingModel()+getEmbeddingDimensions()and (for Voyage flexible-dim models) checksisValidVoyageOutputDim(dims)againstVOYAGE_VALID_OUTPUT_DIMS.ProbeStatusvariant'config'+ optionalfix?: stringonProbeResultsurface a paste-readygbrain config set ...line in human + JSON output; touchpoint label'embedding_config'joins'chat'and'expansion'.src/commands/pricing.ts—gbrain pricing set <model> --input <usd/1M> --output <usd/1M> | --rate <usd/1M> [--source <url>],pricing list [--json],pricing unset <model>. Each write readspricing.overrides, changes one entry (keyed by the lowercased model; case variants replaced) and writes it back, so other entries survive; an unreadable stored value is refused, never overwritten. Rates must be non-negative finite numbers; $0 is accepted with a stderr warning. Entries keep the parser schema ({input, output}orpricePerMTok) withsourceandset_atbeside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) andthinClient: 'refuse'in the command table. Pinned bytest/budget/no-pricing-registration.test.ts.src/commands/orphans.ts—gbrain orphansand MCPfind_orphansshare islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition for local scans; a remotefind_orphanscaller's scan (scopeInbound) counts only inbound links from referrers inside its scope. Reporting exclusions (shouldExcludeFromOrphanReporting) stay centralized; the scoped live-page denominator excludes the same private/reporting rows.--sourceremains explicit; no new remote privacy parameter. Connector renders (anemail/meetingpage whose sourceconfig.kindis a connector kind) are islanded by construction, so they leave both totals and are reported asconnector_renders_excluded(--include-pseudokeeps them); doctororphan_ratiocarries that count indetailsand printsgbrain extract links --by-mention --source db(plus--source-idwhen scoped). Pinned bytest/orphan-ratio-connector-renders.test.ts. Pages of 100 (--limit/--cursor/--all; bounded listings); one-page results keep the old shape.src/commands/pages.ts—gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]operator escape hatch. Mirror ofgbrain sources purgefor the page-level lifecycle. Hard-deletes pages whosedeleted_atis older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations.parsePurgeArgsis strict (thepages purge-deletedrow ofsrc/cli/strict-args.ts):--older-than Nand--older-than=Nboth work, and any other token throwsinvalid_paramsbefore the engine is touched. The real purge first previews the count and, when anything would be purged, goes throughconsentGate(destructive): a TTY prompt,--yes, or exit 3 with the consent payload whose fix is the exact--yesargv and whose preview is--dry-run --json.--retry-parkedretries parked tombstones once within--older-thanand rename holds; the dry run listsparked,retriedandblocked, and the consent names the parked count. The autopilot purge phase callspurgeDeletedPagesCoordinateddirectly and never asks.pages ghosts [--source <id>] [--json](#6696 B5,pages-ghosts.ts) lists ghost pages read-only throughscanGhostSource.pages status <slug...>(#7179) lives inpages-status.ts. ExportsSUBCOMMANDSandprintUsagefor the help route. Pinned bytest/pages-purge-deleted-args.test.tsand thepages purge-deletedconsent-table row. Its help points soft-delete and restore atgbrain delete|restore <slug> --force(page writes are revisioned).src/commands/pages-unsearchable.ts—gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json](#6696 B3, read-only): one row per (page, embedding state) fromlistEmbeddingStateRowswith reason, chunks, bytes and the state's rendered fix; every state butembeddedunless--statenames one;--limit1-1000 (default 50) withcomplete; an unknown--stateor bad--limitthrowsinvalid_paramsnaming the valid values; addssemantic_unsearchable(+keyword_only) andawaiting_sync(held files) (#7193). Test:test/pages-unsearchable.test.ts.