Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
57.6 KB
Raw Blame

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. validate keeps the producer rule: exit 1 on any parseMarkdown validation error, including YAML_PARSE that ingestion recovers by quoting (those print "importable but not canonical" with the --fix command). --importable switches to the ingestion view through screenImportContent (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 --json lists the paths as targets when 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 one ls-files --stage and one cat-file --batch; a failing blob whose working copy passes says to git add it). --fix runs autoFixFrontmatter then repairRecoverableFrontmatter (brain-writer.ts: safe quote recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; --include-ambiguous adds 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 with writer_coordinator_required whose fix is gbrain repair frontmatter [--source <id>]. audit --json adds recoverability_by_code (imported anyway vs held on import). runFrontmatter(args, io) takes stdin-stream and git-cwd test seams. Pinned by test/frontmatter-cli.test.ts and test/frontmatter-validate-producer.test.ts. #6157: parseMarkdown (markdown.ts yamlBlockError) runs the per-line NESTED_QUOTES heuristic only when the whole block fails to parse, and brain-writer.ts autoFixFrontmatter skips 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, so validate, --fix, lint and repair frontmatter never flag or rewrite valid YAML. A block (or tags/aliases line) with more than MAX_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 via resolveSourceId, the same scalar scope the traverse_graph op gets from sourceScopeOpts); an explicit --source that 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 uses engine.traversePathsDetailed and prints a stderr note when the walk hit TRAVERSE_PATH_ROW_CAP (shallowest edges kept; lower --depth or narrow with --type/--direction); the thin-client path goes through the traverse_graph op, which has no source_id param (the server scopes the walk to the caller's grant): an explicit --source there is rejected with exit 1 (same policy + wording as applyThinClientSourceScope, never silently dropped) and --include-foreign prints a stderr note that it is not forwarded. --hop <link_type>:<object|subject> (repeatable, 1-3) runs a typed chain through runRelationalChain locally or traverse_graph hops on a thin client; it is refused with --type/--depth/--direction, a malformed hop names the fix, and a host that ignored hops (older gbrain, detected via ignoredRemoteParams or a non-chain response) is refused with the upgrade message. Pinned by test/graph-query.test.ts (local) + test/graph-query-thin-client-source-flag.serial.test.ts (thin client; mocks isThinClient + 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. runImport contains NO process.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 typed ImportAbortError (carries exitCode and, for a refused lock admission, the underlying error as cause), so in-process callers — the sync_brain MCP op, autopilot, the Minions import handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's import case catches it and exits e.exitCode. Pinned by test/import-abort-error.test.ts. Human-only output (the info() lines and the end-of-run Import complete summary) goes through slog() from console-prefix.ts — identical to console.log outside a wrap, but an in-process caller in its own --json mode (sync --json → performFullSync → runImport, wrapped in withHumanLogsToStderr) keeps stdout pure JSON; import --json itself sends them to stderr directly. Pinned by test/sync-json-stdout-clean.test.ts (first-sync case) + test/import-json-stdout.test.ts. The --json payload also carries source_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, since runImport adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to default; pinned by the --json payload names … cases in test/import-source-id.test.ts. --source-id <id> (alias --source <id>; passing both with different values aborts) routes pages to the named source (resolved via resolveSourceWithTier() at the boundary; consistent across import, extract, graph-query, sources current; graph-query takes --source <id>). Pinned by test/import-source-id.test.ts. An unscoped import that resolves to tier seed_default runs the default-write assessment through assessDefaultWriteGuardOnce(engine) (memoized per engine — in-process callers such as the sync_brain op, autopilot, and minion sync invoke runImport repeatedly on one engine) and WARNS via formatDefaultWriteWarning(a, '--source-id') when the brain's pages overwhelmingly live outside default — never aborts, since aborting would take an in-process host down mid-call; GBRAIN_ALLOW_DEFAULT_WRITE=1 skips it. Pinned by test/import-default-write-guard-once.test.ts. gbrain import CLI + runImport library entrypoint. Ordinary imports use a path-set progress checkpoint via src/core/import-checkpoint.ts; their runImport path walks all current files, including previously completed paths, through the existing importFile content-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 protected op_checkpoints entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See company-brain ingestion. The walk still applies sortNewestFirst() for embed-cost ordering. A file enters completed: Set<relativePath> only when its processFile returns 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.json delete. 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. The managedBookmark opt (set by performFullSync when runImport is the full-sync engine) suppresses runImport's own sync.last_commit advance so the shared applySyncFailureGate (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 by test/import-checkpoint.test.ts + test/import-resume.test.ts (incl. the SLUG_MISMATCH retry case). collectSyncableFiles' shared emit filter isCollectibleForWalker applies the SAME segment-level pruneDir gate as incremental sync's classifySync — load-bearing for the git ls-files fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it sync --full would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by test/import-git-fastpath-prune.test.ts. runImport opts also carry exclude (glob filter over dir-relative paths, threaded by performFullSync for sync --exclude; warns when every file is excluded — NAV-4) and slugRoot (slug/source_path base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use resumeFilter to skip paths). The --json payload carries, beside the counts, unchanged (content-hash no-ops), malformed_skipped, and failures: [{path, error}] — rethurned per-file failures importFile RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both skipped, anotd errors, are excluded from unchanged, and produce status: "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 by test/import-json-stdout.test.ts. Each --workers child pool connects through connectWithRetry with retryConnectTimeout: true (#5946, see src/core/db.ts). A directory the enclosing git repository ignores (for example a scratch folder under .context/) returns no git ls-files rows, so gitListSyncableFiles (listing through gitLsFiles in src/core/git-visible-files.ts, memoized inside doctor's withGitListingCache) falls back to the filesystem walk when git check-ignore reports 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 to importManagedFiles in batches (nextImportBatch) and accounts each file's settled result, in order, through the same processFile bookkeeping; held paths are skipped before the batch. runImport's onCollected hands over its completed, unaborted walk (root-relative, before --exclude) as a CollectedWalk.

  • src/commands/init-prefer-postgres.ts — runPreferPostgresLadder: the Postgres-first install ladder behind gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json] (the zero-config gbrain init default 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 via supabase-admin.ts — SUPABASE_ACCESS_TOKEN (+ SUPABASE_PROJECT_REF on 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 gbrain needs explicit --allow-create-db); (4) docker via docker-postgres.ts (explicit --allow-docker; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) initPGLite + explicit upgrade-later note. Calls initPostgresCore (typed InitPostgresFailure, no process.exit — the returnable core that makes rung fall-through possible) and reuses db-repair's defaultDeps.probeAccess prober. 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 bare DATABASE_URL (vs the stated-intent GBRAIN_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 surviving gbrain-pgdata volume) 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. --json emits ONE final {status, engine, ladder_rung, url_source} envelope and stdout is EXACTLY that document — withStdoutToStderr reroutes both console.log (Bun writes it to fd 1 directly) and bare process.stdout.write around the inner init cores.

  • src/commands/integrations.ts — recipe install. The resolver-row install fence is keyed by manifest.recipe (gbrain:<recipe>:resolver-rows), so a second copy-into-host-repo recipe never writes a block mislabeled with the first recipe's name. Pinned by test/integrations-install.test.ts. Health-check DSL includes the staleness-aware heartbeat_max_age type: declares the sense's expected cadence (max_age: 48h), and integrations doctor FAILS 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 carries output_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 by test/integrations-heartbeat-max-age.test.ts. Standalone integration recipe management (no DB needed). Exports getRecipeDirs() (trust-tagged recipe sources), SSRF helpers (isInternalUrl, parseOctet, hostnameToOctets, isPrivateIpv4). Only package-bundled recipes are embedded=true; $GBRAIN_RECIPES_DIR and cwd ./recipes/ are untrusted and cannot run command/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 from gbrain doctor (sampled at limit=500) and cmdCheck (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by engine.kind === 'postgres' at the call site so PGLite never enters batch; fallback catch logs at GBRAIN_DEBUG=1. Batch projection is SELECT ... ORDER BY source_id, slug (NOT SELECT 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 use listAllPageRefs() to enumerate (slug, source_id) pairs and thread sourceId to getPage; batch + sequential paths report the same page count on multi-source brains. Help (--help/-h/help after any subcommand) prints usage without running it, and auto / reset-progress take 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 to skipped.

  • src/commands/jobs.ts — gbrain jobs CLI subcommands + gbrain jobs work daemon. jobs-readiness.ts orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After ensureSchema, maybeRunWorkerStartupRecovery(queue, process.env, true) runs for both bare and supervised workers; the final worker ready event publishes readiness, and a worker handed an owner status channel (GBRAIN_WORKER_STATUS_PATH or GBRAIN_WORKER_STATUS_TOKEN, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (GBRAIN_SUPERVISED=1 from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report configuration_blocked and exit WORKER_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) and JOBS_SUBCOMMAND_HELP (work/supervisor/submit/watch/prune) print from a guard at the TOP of runJobs, BEFORE the thin-client refusal and the JOBS_SUBCOMMANDS dispatch — jobs work --help can never start a daemon; only --help/-h are help tokens (bare help can be a job name); cli.ts routes it engine-free via SELF_HELP_WITHOUT_ENGINE + CLI_ONLY_SELF_HELP. formatJobDetail prints 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_at is in JOB_DATE_FIELDS for thin-client rehydration. jobs stats prints a Backpressure (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 shared GBRAIN_WEDGED_QUEUE_WARN_MINUTES threshold — the read-only visibility for maxPending single-flight suppression. Pinned by test/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) wraps worker.start() in try/finally and owns engine lifecycle — calls engine.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 submit surfaces the MinionJobInput retry/backoff/timeout/idempotency surface as flags: --max-stalled, --backoff-type fixed|exponential, --backoff-delay, --backoff-jitter, --timeout-ms, --idempotency-key, --max-waiting (maxPending is deliberately internal-only — no flag; see TODOS). jobs smoke (jobs/smoke.ts) tracks every job it adds to the private smoke queue and discards exactly those (cancel if live, then delete) in one finally on pass, failure, timeout and throw (test/jobs-smoke-cleanup.test.ts); its --sigkill-rescue/--wedge-rescue cases (W4.9) add a probe under its own job name (smoke-sigkill-probe, smoke-wedge-probe), move it to active through queue.claim (the queue protocol trigger refuses a forged transition) and then age only lock_until/started_at (timeout_at=NULL for wedge), so each reaches its rescue verdict. registerBuiltinHandlers always registers subagent + subagent_aggregator (no env flag — ANTHROPIC_API_KEY is the cost gate, trust is via PROTECTED_JOB_NAMES) and loads GBRAIN_PLUGIN_PATH plugins at startup with a loud per-plugin line; shell handler still gated by GBRAIN_ALLOW_SHELL_JOBS=1 (RCE surface). The autopilot-cycle handler forwards job.data.phases to runCycle, validated against ALL_PHASES from src/core/cycle.ts (invalid names filtered; empty/missing falls back to the default cycle); when source_id is set it binds brainDir to that source's local_path (null for a pure-DB source, never the global repo) and checks isSourceInCooldown before runCycle, returning a no-op skipped (not a failure) for a source still in its failure cooldown. The sibling autopilot-global-maintenance handler runs MAINTENANCE_PHASES (mixed ∪ global) once (no sourceId, pull:false) and stamps autopilot.last_global_at only 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. resolveJobPull gives both cycle and standalone sync jobs one positive-polarity pull contract while preserving queued payloads that still carry the inverse legacy noPull key; explicit pull wins. The sync handler resolves sourceId at entry from sources.local_path (mirrors cycle.ts:480) so multi-source brains read the per-source last_commit anchor; concurrency routes through autoConcurrency() in src/core/sync-concurrency.ts (PGLite stays serial); noEmbed default is true. gbrain jobs supervisor status --json adds processing_ready, lowercase processing_state (starting/ready/configuration_blocked, or unknown/stopped without current state), reason_code, blocked_since and worker/child identities without changing running or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes summarizeCrashes() from src/core/minions/handlers/supervisor-audit.ts for parity with gbrain doctor: JSON adds crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy} + clean_exits_24h; human output includes per-cause + clean-exits lines. Pinned by test/job-pull-policy.test.ts and 4 source-grep wiring assertions in test/doctor.test.ts requiring crashes_by_cause + clean_exits_24h= in both doctor.ts and jobs.ts. gbrain jobs watch decouples its two output axes: --json picks FORMAT (human default, never gated on isTTY), --follow picks LOOP (default isTTY && !json). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); --follow opts 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 pure resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard} in src/commands/jobs-watch.ts; the dispatch wires --follow. Pinned by test/jobs-watch-mode.test.ts (format×loop matrix incl. the TTY+--json-one-shot case) + test/e2e/non-tty-output.serial.test.ts (the cmd </dev/null non-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 to runCycle({phases:[name]}) so src/core/cycle.ts stays the single source of truth for phase semantics. The standalone sync handler passes noExtract: true to match runPhaseSync's contract (doctor's remediation plan emitting [sync, extract] would otherwise double-extract). The extract handler routes {stale: true} jobs (submitted by performSync's size-gate defer branch) through extractStaleFromDB scoped to data.sourceId, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from STALE_TIME_BUDGET_MS) when the sweep's budget leaves staleRemaining > 0 with forward progress. parseJobIsolationFlag(args, env?) (--job-isolation, space/= forms, GBRAIN_JOB_ISOLATION fallback, default inline); jobs work resolves the actual selected child and validates its bounded protocol/capability handshake and warns when --max-rss is combined with isolation (watchdog covers the worker only); jobs run-child is 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); the db_dead fatal text is verdict-aware (pool starved vs server unreachable). Generic jobs submit normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit ensureSchema() preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, jobs submit embed-backfill refuses with no_worker_surface and a paste-ready inline embed command before any queue access; --dry-run evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. --follow is 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 MCP submit_job operation applies the same gate (including dry-run), translates the expected refusal to branchable OperationError('no_worker_surface'), and never emits internal_error for this capability miss. The sync handler forwards job.data.github_item ({repo, number, kind}) into performSync for github-kind single-item webhook refreshes. jobs work registers the shell handler always; the startup line names the flag first (--allow-shell-jobs / GBRAIN_ALLOW_SHELL_JOBS=1); jobs start computes allowShellJobs as --allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1' — the same literal handlers/shell.ts and buildChildArgs check. extract-atoms-drain accepts a trusted retryRequestId in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite jobs --follow still requires exclusive owner access. D2: jobs supervisor start --detach writes its payload (event, status:'started', supervisor_pid, pid_file, detached, stderr_log) through writeStdoutFinal; the jobs record declares no json because work/watch/foreground supervisor stream. Start refusals add an envelope under --json (invalid_params exit 2 for an unknown subcommand or bad --health-interval, config_error for PGLite). jobs submit enrich|subagent runs the paid consent gate and stores an authorized spend record on the row; jobs get --json adds spend_basis, spend_why and spend_group; jobs list --group <id> and jobs cancel --group <id> act on one spend group. GBRA-133 2a.4 / #7002: on Postgres, jobs work starts startSyncQueueWake (src/core/minions/sync-queue-wake.ts, given worker.idleWaiter) before worker.start() and stops it in the finally, and calls startWorkerPersistenceConsumer (exported from jobs/work.ts): startPersistenceConsumer at boot through the existing election (service.ts unchanged), so an idle worker runs the persistence consumer, or with persistence.single_consumer on 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 (real jobs work processes). Size ceiling: scripts/module-size-limits.tsv (per-change raise history: git log -p on that file). runJobs resolves help and the thin-client refusal, builds the queue, then dispatches through JOBS_SUBCOMMANDS (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in src/commands/jobs/<sub>.ts (runJobs<Sub>(ctx); parsers, formatters and JobsCommandContext in jobs/shared.ts; maybeRunWorkerStartupRecovery in jobs/work.ts), all re-exported from jobs.ts. Subcommands that register handlers import registerBuiltinHandlers lazily from jobs.ts. registerBuiltinHandlers is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in src/core/minions/handlers/ (see core-minions-1). Registration names and order are pinned by test/jobs-handler-registry-golden.test.ts, which also drives the supervisor's deriveHandlerNames probe.

  • 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-ONLY refreshGatewayEnvFromFilePlane — never a full configureGateway(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_key writes the DB plane, which loadConfigWithEngine() deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). facts-absorb sits in GATEWAY_REFRESH_JOB_NAMES; its handler converts execution-time chat_unavailable in 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 by test/jobs-gateway-refresh.serial.test.ts.

  • src/commands/lint.ts — Page quality linter (catches LLM artifacts, placeholder dates). runLintCore(opts) walks the tree ONCE; --fix applies fixes during that same scan and reports per-page results through the onPageIssues(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. onScanStart fires once with the collected page count for progress wiring. Pinned by test/lint-fix-single-pass.test.ts. On a durability-hardened brain (isDurabilityHardened on the target dir, or the page's directory for a single-file target) every non-dry-run --fix repair is committed path-limited via commitWriteThroughFile right after the writeFileSync — the same contract as put_page write-through, so the cycle, the lint/lint-fix minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by test/cycle-lint-durability.test.ts). Lint rules huge-page (flags pages exceeding content_sanity.bytes_warn) and scraper-junk (flags pages matching any junk pattern). Both reuse assessContent() from src/core/content-sanity.ts so lint, doctor, and ingest share one assessor. lint.ts lifts DB config when ~/.gbrain/ is reachable; falls back to file/env on CI. Pinned by test/lint-content-sanity.test.ts. Rule type-undeclared flags an explicit frontmatter type the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane schema_pack, else file/env config; no resolvable pack skips it; LintOpts.typePack injects it), pinned by test/lint-page-type-vocabulary.test.ts. with src/commands/sources.ts: gbrain lint has a markup-heavy rule (flags pages whose prose-vs-markup ratio exceeds content_sanity.max_markup_ratio, reusing assessContentSanity so lint/gate/scan share one assessor); pinned by test/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 effective content_sanity.junk_disposition + markup config, so an operator previews the gate's verdict before sync. The content-sanity-audit JSONL (src/core/audit/content-sanity-audit.ts) records the quarantine/flag dispositions. On a managed brain (persistence enabled) runLintCore skips 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-fixable managed-write-pending issue with code: 'managed_write_pending', a reason (the coordinator refusal's detail, held_file, canonical_file_missing, revision_changed, not_indexed), the refusal's own rendered fix (never a sync) and the guide link; the run continues (LintResult.write_path / fix_pending / pending_issues, first 50; #5180, test/managed-lint.test.ts on 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 --fix run asks the coordinator (pending canonical_file_missing), otherwise a non-fixable file-removed-during-scan issue with code file_removed_during_scan and a gbrain lint <target> fix; the CLI prints each issue's Fix: command and Docs: link (test/lint-file-removed-during-scan.test.ts). llm-preamble matches 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-fixable fix-not-writable issue (code: 'fix_not_writable', the errno as reason, a user fix naming the permission change or --exclude) counted in fix_pending; the run continues (test/lint-preamble-anchor.test.ts). placeholder-date and empty-section read 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, and empty-section reads 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-created fires only when none of created, event_date, date, published, captured_at, ingested_at parses (parseDateLoose on the parsed frontmatter, never a regex; a block YAML could not read is already frontmatter-yaml-parse) and is never fixable: fixContent no longer promotes a capture timestamp into created (ingest time is not creation time, and the cycle's fix: true lint phase rewrote every native page), so a page serializePageToMarkdown emits stays byte-identical across repeated --fix runs; promoteCreatedFromCapture stays exported, deprecated, for explicit callers.

  • src/commands/maintain.ts — gbrain maintain [--safe] [--dry-run] [--json], --unattended [--runner <name>] (one free upkeep run through src/core/maintenance/run.ts), --status (the upkeep view doctor's unattended_maintenance reads) and --purge (page-purge preview; --yes --expect <hash> applies exactly the previewed set, purgePreviewHash). --safe: stale extraction, then one source-scoped runCycle per source doctor's cycle_freshness names, limited to MAINTAIN_SAFE_PHASES (the step list lives in src/core/maintenance/run.ts and is re-exported here) (free and never hard-deleting: no purge, no paid phase); maintainSafePhases also holds back extract_facts when an embedding provider is available or the decide conflict slot is on and the repair lanes when an embedding provider is available or fences.repair.llm has a model (GST-2246). A source whose cycle throws an item-scoped error is a blocked action with details.code and fix (gbrain dream --source <id>) and later sources still cycle (ItemRun site maintain.cycle_sources); run-scoped errors and item_failures_systemic stop 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 the migrate_embeddings op: planMigrationFlow (plan + verifyMigrationComplete + env presence + un-merged file plane + brain/DB identity via redactPgUrl + concurrent-writer census + reranker plan + in-flight-other marker) and executeMigrationFlow (global gbrain-embedding-migration DbLock → retarget gate under it → all-source embed locks sorted with includeArchived → worst-case authorization under the locks (a cap below it returns refused_budget / op refused with embedding_budget_below_worst_case before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via runEmbedCore({heldLocks, …}) so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as lock_lost → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on verify.complete with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). --status is 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). persistEmbeddingFileConfig writes through loadConfigFileOnly (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: requireConsent with effects paid + destructive; spend.posture=tokenmax covers only the paid part, --json never implies consent, the payload's fix repeats the caller's argv plus --yes; the TTY prompt is interaction.readLine, and the confirm/isTTY test seams map onto ConsentEnv). Spend stays bounded by the durable --max-cost-usd authorization, not the consent cap. Pinned by test/migrate-embeddings-flow.serial.test.ts, test/migrate-embeddings-boundary.serial.test.ts, test/migrate-embeddings-hardening.serial.test.ts. Migration guidance uses renderCanonicalMigrationCommands (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 when migrate.graduation is false). A PGLite → Postgres move routes to src/commands/migrate-graduation.ts (engine graduation) before connect and never reaches this file. Copies the complete source catalog FIRST (copyMigrationSources — every sources row incl. archived rows and sync/routing metadata, ON CONFLICT (id) DO UPDATE, default ordered first) so every page write has a valid pages.source_id FK parent and the target preserves per-source behavior; pages copy afterward: listAllPageRefs lists every live page's (source_id, slug) in one uncapped query, copyMigrationPages reads each body with getPage(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's to_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_url for Postgres, resolved database_path for PGLite) and manifestMatchesTarget requires schema_version === 2 plus a matching target_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, copyMigrationFacts carries 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-pass superseded_by restore (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 a setval bump 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-reassigned page_id; the next extract cycle rebuilds them). copyMigrationConfig then copies EVERY DB-plane config row except the explicit engine-local denylist MIGRATE_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 by test/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: copyPageToTarget forwards the full page row (page_kind, source_path, effective date and its source, import_filename, source_kind/source_uri/ingested_via, ingested_at restored in the timestamp UPDATE), the frontmatter aliases (setPageAliases) and each chunk's code metadata (carryChunkMetadata). A page sealed on the source is queued engine_migration; one the source had not sealed is queued engine_migration_source_unsealed and keeps its verbatim chunks and vectors. Before the config flip, while autopilot is paused, runMigrateEngine runs drainProjections (moved to src/core/page-state/projections.ts; commands/projections.ts re-exports it) on the target for the engine_migration and rebuild_failed reasons, 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 by test/migrate-full-row-projections.serial.test.ts, test/e2e/migrate-full-row-projections-postgres.test.ts and a D2 case in test/e2e/migrate-engine-pglite-to-postgres.test.ts. Open-loop and loop-suppression rows the target refuses (copyMigrationSimpleTable, per-row ItemRun site migrate_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 of skills/migrations/*.md). index.ts lists 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); phaseASchema has a 600s timeout for duplicate-heavy brains; the config check reads auto_link in-process (file/env plane, then the database), never through a gbrain config get child. 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; raises minion_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: true marks an orchestrator that changes nothing on a brain gbrain init just created; fresh-install.ts:recordFreshInstallMigrations (one call in each init engine path, only when init created the database) appends a complete ledger entry with fresh_install: true + installed_version for each, and every other migration lists as pending_fresh_install (src/core/migration-ledger.ts:freshInstallVersion/isPendingFreshInstall) in apply-migrations --list [--json]/--dry-run, get_health.migrations and doctor's minions_migration (an ok/info row with gbrain apply-migrations --yes --no-autopilot-install); stamps never count as forward progress over a real partial. Each flag is proven by test/migrations-fresh-install-audit.serial.test.ts (schema, row counts, config table and GBRAIN_HOME file tree unchanged by the real orchestrator on a keyless init --pglite --no-embedding brain); unit coverage test/migrations-fresh-install.test.ts. shared-content.ts names its read-only next step as phase argv (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 table MIGRATION_OPT_OUT_KEYS in src/core/migration-ledger.ts, pinned to every module's optOut); an explicit off value (false/0/off/no, isMigrationDeclinedValue) puts the migration in the plan's declined bucket (opt-out.ts:readDeclinedMigrations, read before buildPlan; an unreachable brain declines nothing), so the runner never calls its orchestrator, reconcile included, --list [--json] and --dry-run show it declined with opt_out.key, and an explicit --migration <v> refuses migration_declined (exit 3, fix.next: ask_user, gbrain config set <key> true, verify --list --json). migrationLedgerSummary(VERSION, declined) gives get_health.migrations.declined and doctor's minions_migration an ok row with details.declined; with no engine (doctor --fast) the config is unreadable, so minions_migration leaves every MIGRATION_OPT_OUT_KEYS version 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 from partial status. The RUNNER owns all ledger writes — orchestrators return OrchestratorResult and apply-migrations.ts persists a canonical {version, status, phases} shape (orchestrators never call appendCompletedMigration). statusForVersion prefers complete over partial (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_5 with UPDATE backfill) live in src/core/schema-migrations/v014-pages-updated-at-index.ts and v015-minion-jobs-max-stalled-default-5.ts (one file per schema migration; migrate.ts is the runner). in-process.ts exports runMigrateOnlyCore({timeoutMs?}) — single source of truth for "bring schema to head" (configureGateway → createEngine → connect → initSchema → disconnect, idempotent, 600s MIGRATE_ONLY_TIMEOUT_MS guard, throws MigrateOnlyError on no-config / timeout); the orchestrators' 9 schema phases AND init.ts:initMigrateOnly both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with getaddrinfo ENOTFOUND on Windows + bun + Supabase pooler). runGbrainSubprocess is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. v0_13_1.ts is an idempotent no-op since #7814: it records completion and writes no page (it used to stamp validate: false into every page on any brain whose ledger never recorded v0.13.1). Pinned by test/migrations-v0_13_1.test.ts and the upgrade contract test/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 (ledger 0.60.31), two phases. credential_projection: runs runMigrateOnlyCore first (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), then resealCredentialProjections, 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 with held: N and the codes in its detail (doctor text_projection_readiness lists the pages, gbrain repair safe-chunks --source <id> --apply retries them); a run-scoped failure or a systemic one (item_failures_systemic) fails the phase with its code, so the run is partial and gbrain apply-migrations --yes --no-autopilot-install retries it, and re-sealed pages are no longer pending, so a rerun resumes. google_file_modes_notice: googleFileModesNoticePhase from v0_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 (14 PER_TASK_KEYS, including provider-neutral models.contextual_synopsis with legacy-key/env attribution and models.dream.extract_atoms which reports via its own caller-specific resolver — resolveExtractAtomsModelWithSource() in extract-atoms.ts: its own key, then models.tier.utility, then the key-aware utility default, never models.default or GBRAIN_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 from resolveModelDetailed, so a tier key is attributed before models.default. A Nightly quality probe block (JSON nightly_probe; schema_version stays 1) shows the probe's routes from resolveNightlyProbeModelRoutes: reader and extractor with their source, and each judge slot labelled config: models.eval.cross_modal.slot_<x>, panel default or substitute for <default> (no usable provider) — the #4636 substitution run with a silent log against this process's gateway. Its environment_note says availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's ~/.gbrain/env reads 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 in src/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-token gateway.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 via resolveChatProbeTimeoutMs — the recipe touchpoint's default_timeout_ms when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; claude-cli declares 30s because its claude -p subprocess cold start routinely outruns 5s and would false-fail every run as unknown). The reranker reachability probe sends one question with a relevant and an unrelated passage and reports ok only when the relevant one scores higher by more than 0.1; equal, inverted or missing scores are config with a fix naming docs/ai-providers/llama-server-reranker.md step 2 (a broken GGUF conversion answers but ranks at random). Wired into cli.ts dispatch + CLI_ONLY set. A zero-token embedding_config probe runs FIRST, before any chat/expansion probes spend money: probeEmbeddingConfig() reads getEmbeddingModel() + getEmbeddingDimensions() and (for Voyage flexible-dim models) checks isValidVoyageOutputDim(dims) against VOYAGE_VALID_OUTPUT_DIMS. ProbeStatus variant 'config' + optional fix?: string on ProbeResult surface a paste-ready gbrain 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 reads pricing.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} or pricePerMTok) with source and set_at beside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) and thinClient: 'refuse' in the command table. Pinned by test/budget/no-pricing-registration.test.ts.

  • src/commands/orphans.ts — gbrain orphans and MCP find_orphans share 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 remote find_orphans caller'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. --source remains explicit; no new remote privacy parameter. Connector renders (an email/meeting page whose source config.kind is a connector kind) are islanded by construction, so they leave both totals and are reported as connector_renders_excluded (--include-pseudo keeps them); doctor orphan_ratio carries that count in details and prints gbrain extract links --by-mention --source db (plus --source-id when scoped). Pinned by test/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 of gbrain sources purge for the page-level lifecycle. Hard-deletes pages whose deleted_at is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. parsePurgeArgs is strict (the pages purge-deleted row of src/cli/strict-args.ts): --older-than N and --older-than=N both work, and any other token throws invalid_params before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through consentGate (destructive): a TTY prompt, --yes, or exit 3 with the consent payload whose fix is the exact --yes argv and whose preview is --dry-run --json. --retry-parked retries parked tombstones once within --older-than and rename holds; the dry run lists parked, retried and blocked, and the consent names the parked count. The autopilot purge phase calls purgeDeletedPagesCoordinated directly and never asks. pages ghosts [--source <id>] [--json] (#6696 B5, pages-ghosts.ts) lists ghost pages read-only through scanGhostSource. pages status <slug...> (#7179) lives in pages-status.ts. Exports SUBCOMMANDS and printUsage for the help route. Pinned by test/pages-purge-deleted-args.test.ts and the pages purge-deleted consent-table row. Its help points soft-delete and restore at gbrain 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) from listEmbeddingStateRows with reason, chunks, bytes and the state's rendered fix; every state but embedded unless --state names one; --limit 1-1000 (default 50) with complete; an unknown --state or bad --limit throws invalid_params naming the valid values; adds semantic_unsearchable (+keyword_only) and awaiting_sync (held files) (#7193). Test: test/pages-unsearchable.test.ts.