Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
48.3 KB
Raw Blame

Key files: Commands (1/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/apply-migrations.ts and src/commands/migrations/v0_11_0.ts — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit --force-retry recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Phase F (v0_11_0-install.ts) reinstalls only an existing autopilot. Every run except --list and --dry-run holds the orchestration lock (src/core/migration-orchestration-lock.ts) from before its first ledger write through its final status: a Postgres TTL lease row gbrain-apply-migrations in gbrain_cycle_locks (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on <datastore>.gbrain-migrations.lock, separate from the datastore lock so orchestrators still open the datastore. A second runner prints another apply-migrations is running (host …, pid …) and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before process.exit. Tests: apply-migrations-safety.serial.test.ts, apply-migrations-orchestration-lock.test.ts, e2e/apply-migrations-orchestration-lock.test.ts and e2e/migration-preview-safety.test.ts. D2 (json: 'document'): every --json path is one single-line document (status unconfigured/dry_run/listed/ok/partial/up_to_date, plan, previews, results[], retry_markers, schema); a non-zero exit is one envelope leading with those keys (invalid_params exit 2, migration_failed with reasons, migrations_pending with schema_pending, database_error for --require-db, migrations_running exit 75, migration_lease_lost exit 1 with lease). #6089: the run never exits 0 with the schema behind (src/commands/apply-migrations-schema.ts); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: assertHeld raises MigrationLeaseLostError (migration_lease_lost, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of migrations_running; tests e2e/migration-lease-lost.test.ts. A4: Migration.effects (v0.11.0: persistent_install, its Phase F autopilot install) is asked through consentGate before the orchestrator runs (skipped under --no-autopilot-install or on PGLite); --yes, --non-interactive (mapped to persistent_install only), a preapproval or a TTY yes authorize, otherwise exit 3. applyMigrations() returns {exitCode, failure} for in-process callers (post-upgrade); runApplyMigrations() exits. Child CLIs use cliChildStdio(). Tests: test/cli-json-commands.test.ts. the plan adds pending_fresh_install (unrun setup work on a brain gbrain init created; runs like pending, reported as expected work, never as a failed upgrade); --list --json prints one row per migration (fresh_install: true on init stamps) plus next.argv when work remains and a wedged[] entry (version, fix.argv --force-retry <v>) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, forwardProgressPast in src/core/migration-ledger.ts; a superseded wedge is listed as wedged_superseded in the plan and is history; a v0.53.0 wedge whose latest row records apply_migrations_pending still owes host work, hostWorkOwedForVersion (other migrations set that flag on ordinary partials and keep the forward-progress rule), is never superseded: it is listed as wedged_host_work with the read-only --migration <v> --dry-run --json inspect as its fix plus each conflicting source's code and next step (owedConflicts), never --force-retry; nothing reruns it, the notice skips it once superseded, and it fails a run only when no newer migration ran past it; tests migration-host-work-owed.test.ts) never reports up to date: it fails migrations_pending reason wedged (exit 1, fix next: ask_user, verify --list --json), so post-upgrade exits non-zero and gbrain upgrade prints Migrations: wedged; tests apply-migrations-wedged-6696.test.ts; every wedged-migration message (run envelope, --list, stderr, gbrain upgrade) points at the migration's partial rows in this brain's migrations/completed.jsonl (phases[].detail, if present) through wedgedLedgerHint (src/core/migration-ledger.ts); a phase's argv prints as its next step. v0.11.0 Phase F (src/commands/migrations/v0_11_0-install.ts) installs the autopilot only for the brain's sync.repo_path; without one it installs nothing, is skipped with the exact install command (the default source's local_path, else <REPO_PATH>), records an autopilot-install-needs-repo pending host-work item, and the migration completes; doctor's minions_migration line (src/commands/doctor/checks/autopilot-install-pending.ts) carries that argv (persistent_install) until an autopilot is installed for this brain. Phase F records a reason code on those outcomes (no_repo_path, autopilot_already_installed, install_failed). clearRepoPathWedge writes a retry marker (reason phase_f_no_repo_path) before the plan when every partial behind a v0.11.0 wedge failed only the install phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's sync.repo_path is unset, so Phase F would now skip; with it set, or any other wedge, the --force-retry advice stands. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit --force-retry recovers a historical false-complete record. Every run except --list and --dry-run holds the orchestration lock (src/core/migration-orchestration-lock.ts) from before its first ledger write through its final status: a Postgres TTL lease row gbrain-apply-migrations in gbrain_cycle_locks (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on <datastore>.gbrain-migrations.lock, separate from the datastore lock so orchestrators still open the datastore. A second runner prints another apply-migrations is running (host …, pid …) and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before process.exit. Tests: apply-migrations-safety.serial.test.ts, apply-migrations-orchestration-lock.test.ts, e2e/apply-migrations-orchestration-lock.test.ts and e2e/migration-preview-safety.test.ts.

  • src/commands/migrations/run-engine.ts — one PGLite engine for consecutive migrations of an apply-migrations run (each open starts an embedded Postgres, about 130 ms). withRunEngineSession wraps the locked run; setRunEngineSharing enables sharing for the opt-out read, each migration flagged sharesRunEngine (v0.11.0, v0.14.0, v0.22.4, v0.28.0, v0.53.0) and the post-orchestrator schema check, and disabling it (before an unflagged migration, --list, --dry-run or a consent prompt) closes the engine. connectMigrationEngine returns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always). releaseRunEngine closes it before a gbrain child that needs the brain (v0.11.0's jobs smoke). A fresh setup's migration child opens the brain three times instead of eight (counting the jobs smoke child); the ledger it writes is pinned by test/fixtures/goldens/setup/fresh-setup-migration-ledger.json. Tests: test/migrations-run-engine.test.ts.

  • src/commands/apply-migrations-schema.ts — #6089 schema half of the apply-migrations exit contract. connectAtSchemaVersion connects the configured brain and reads config.version (pre-flight, --force-schema); the post-orchestrator check opens it through connectMigrationEngine. checkSchemaAfterOrchestrators re-reads the version after the orchestrators ran: on Postgres only when the pre-flight connected; on PGLite in-process once the orchestrators released the datastore (the pre-flight stays skipped, #1100; never a child process), applying the schema migrations under --yes/--non-interactive; a busy PGLite datastore is rethrown. schemaPendingError builds migrations_pending with reason not_applied (fix reruns with --yes), still_behind (after an authorized run) or schema_unreadable (both fix next: report with gbrain doctor --json as verify, never another --yes), each naming the pending schema versions. reportDatabaseUnreachable keeps an unreachable Postgres non-fatal but prints the GBRAIN_DB_ACCESS <reason> marker. Tests: test/apply-migrations-schema-exit.test.ts (PGLite, unreachable Postgres, post-upgrade, postinstall) and test/e2e/apply-migrations-schema-exit.test.ts (Postgres).

  • src/commands/agent-logs.ts — gbrain agent logs <job> [--follow] [--since]. Merges JSONL heartbeat audit + subagent_messages into a chronological timeline. parseSince accepts ISO-8601 or relative (5m, 1h, 2d). Transcript tail renders only for terminal jobs.

  • src/commands/agent-register.ts — gbrain agent register <name> --harness claude-code|codex|opencode|openclaw: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — registerScopedClient (auth.ts), exchangeClientCredentials, the mcp-registration argv builders, renderCodexHttpServerBlock, openclawThinClientBlock — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane ANY($1::text[])) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE engine.transaction (name-scoped pg_advisory_xact_lock → duplicate-name pre-check → ensureWorkspaceSource create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → registerScopedClient with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (probeServeHealth + the unconditional SCOPES_MIN_SERVE_VERSION floor line): a probe-PROVEN pre-scopes serve REFUSES registration (serve_too_old) unless --allow-old-serve — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying probe_note + serve_warning from the probe; secrets redacted unless --show-token). Presets: daily-driver (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' *-workspace scratch sources — a workspace named explicitly in --federated-read is still granted, and the print counts the exclusions) and coding-agent (write-isolated derived <name>-workspace DB-only source; requires --federated-read); both default the client to the full surface (S0/D4) — pass --surface starter|verbs at registration for a capped harness, or narrow per client via gbrain auth rescope-client. Always writes token_ttl (default 30 days — the server default is 1 hour and would kill a pasted config). --url|--port required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on auth register-client. --reissue <client-id> rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by test/agent-register.test.ts.

  • src/commands/agent.ts — gbrain agent run|logs|register dispatcher. run submits subagent (or N children + 1 aggregator) under {allowProtectedSubmit: true}; single-entry --fanout-manifest short-circuits; children get on_child_fail: 'continue' + max_stalled: 3; --follow is the default on TTY (streams logs + polls waitForCompletion in parallel; Ctrl-C detaches, does not cancel). logs delegates to agent-logs.ts; register lazy-imports agent-register.ts. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the -- terminator (agent run -- --help submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real run/logs invocations refuse with an init hint.

  • src/commands/anomalies.ts — gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]: cohort-level activity outliers. Calls engine.findAnomalies(opts). Two cohort kinds: tag, type. At most 20 page_slugs per cohort (page_slugs_complete: false; local --all lists all; test/anomalies-bounded-7246.test.ts).

  • src/commands/auth.ts — token management. gbrain auth create/list/revoke/test for legacy bearer tokens (revoke-client runs an atomic DELETE...RETURNING on oauth_clients; FK ON DELETE CASCADE on oauth_tokens.client_id and oauth_codes.client_id purges every active token + auth code in one transaction; process.exit(1) on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in access_tokens; OAuth clients in oauth_clients; legacy tokens with no scopes grant grandfather to read+write+admin on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. --member without --scopes mints MEMBER_TOKEN_SCOPES (read,write). Every SQL site routes through sqlQueryForEngine(engine) from src/core/sql-query.ts (and executeRawJsonb for the takes-holders permissions JSONB column) so gbrain auth works against PGLite; the takes-holders write goes through executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}]) which round-trips with jsonb_typeof = 'object'. register-client accepts --source <id> (write authority, scalar), --federated-read <S1,S2,...> (read scope, array), and --token-ttl <seconds> (per-client access-token TTL persisted to oauth_clients.token_ttl, bounds TOKEN_TTL_MIN_SECONDS=60 to TOKEN_TTL_MAX_SECONDS=7,776,000/90d) and prints the resolved Write source + Federated reads; clients without a source_id backfill to 'default' via migration v60. The registration core is the exported registerScopedClient(sql, engine, name, parsed, opts) — exit-free, print-free, injected-handle (engine-bound callers like agent register pass the dispatcher's engine; a second withConfiguredSql engine self-deadlocks PGLite's single-writer lock), returns a RegisteredClient data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer formatRegisterClientOutput is a BYTE-PINNED contract (connect.ts's defaultRegisterOAuthClient regex-scrapes Client ID:/Client Secret: from it in production) — pinned by test/auth-register-client-output-pin.test.ts. preflightOauthClientColumns(sql) probes information_schema.columns for the optional columns (token_ttl, surface, federated_read, source_id, deleted_at) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as RegisteredClient.skipped with an apply-migrations hint. gbrain auth clients [--usage] [--days N] [--json] lists clients with scopes, per-client surface, write source (source_id), federated reads (federated_read) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); clientOperationsView reports four distinct operation states (SQL NULL = operations: "all" with includes_future_operations: true and a re-pin fix naming auth rescope --client <id> --operations <list> or --profile; [] = deny-all; an explicit list; unavailable when the schema predates allowed_operations) and marks soft-revoked clients (deleted_at) revoked with no fix (test/auth-clients-operations.test.ts, both engines); tokenLifetimeClampedClients reads the migration's clamp_token_ttl / shorten_access_tokens audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (token_lifetime_clamped in --json); the TOKEN_TTL_* bounds are re-exported from src/core/grants/model.ts; --usage joins op-call counts and coverage via src/core/mcp-usage.ts. The bare gbrain auth create <name> form (no --takes-holders) mints a token via the exported pure parseAuthCreateArgs(rest). Pinned by test/auth-create-args.test.ts + test/auth-register-client-args.test.ts. F3: gbrain auth rescope (runRescope) is the one grant editor for tokens (--token/--id) and OAuth clients (--client), with a bare-name resolver, --migrate-legacy [--dry-run], and refusals printed as JSON on stdout under --json; rescope-token, rescope-client and permissions set-takes-holders are aliases routed through it.

  • src/commands/autopilot-retry-global.ts — gbrain autopilot --retry-global [--phase <name>] [--json] (GBRA-130 A-10): clears retry_at on the backed-off phase streaks in autopilot.global_maintenance.progress (one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a running autopilot-global-maintenance job, whose next progress save can restore the back-off. Test: test/pathological/a10-global-maintenance-stamp.test.ts.

  • src/commands/autopilot-pause.ts — engine-free gbrain autopilot pause [--reason <text>] / resume: writes or removes the operator marker autopilot-operator-paused (autopilotOperatorPauseMarkerPath in src/core/autopilot-paths.ts, with autopilotPaused() and autopilotPauseReason()). The daemon loop and job workers honor it like the migration hold; --install (and so gbrain upgrade) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: test/autopilot-operator-pause.test.ts.

  • src/commands/autopilot.ts — gbrain autopilot --install: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity pull value from automaticSyncPull (src/core/persistence/automatic-sync-policy.ts): a parsed remote_url on an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes detectTini() from src/core/minions/spawn-helpers.ts, resolved once at startup. Composes a ChildWorkerSupervisor instance for spawn-and-respawn with --max-rss 2048 and soft maxCrashes: 5, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. --status --json adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; it also adds global_maintenance, the daemon's latest stall verdict (readGlobalMaintenanceVerdict in src/core/minions/global-maintenance-stall.ts, null when absent or older than a day), and a non-ok verdict turns exit 0 into 1 (autopilotStatusExitCode(state, stalled)); see the owner-specific repair guide. onMaxCrashesExceeded routes through autopilot's own shutdown('max_crashes') so the autopilot lockfile gets cleaned up. shutdown() drains via childSupervisor.killChild('SIGTERM') + awaitChildExit(35_000). Pinned by test/autopilot-fanout-wiring.test.ts and test/autopilot-supervisor-wiring.test.ts (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, --max-rss 2048 in argv, maxCrashes: 5 literal, shutdown-via-callback, no workerProc reference). tick body invokes runNightlyQualityProbe when cfg.autopilot.nightly_quality_probe.enabled === true (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — runNightlyQualityProbe's internal shouldRunNightly (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via logError and does NOT bump consecutiveErrors (probe failure is informational, never crashes the loop). Default max_usd cap = 5. Pinned by test/autopilot-nightly-probe-wiring.test.ts. per-source extract_atoms auto-drain. Postgres-only block after the freshness fan-out: gated on autopilot.auto_drain.enabled (default true) AND !packDeclaresPhase(engine,'extract_atoms') (the silent-backlog condition) AND per-source countExtractAtomsBacklog > threshold (default 25) AND a daily cap floor(max_usd_per_day / ~$0.30). Enumerates loadAllSources. Submits the PROTECTED extract-atoms-drain job ({allowProtectedSubmit:true}) with a UTC-day time-sloted idempotency key autopilot-extract-atoms-drain:<src.id>:<utcDay> (a static key would block the source after the first job completed). src/core/minions/protected-names.ts lists extract-atoms-drain; src/commands/jobs.ts registers the handler (thin wrapper over runExtractAtomsDrainForSource, LockUnavailableError → {deferred:true}; a provider_failure result throws formatDrainProviderFailure(result) — batches/remaining plus the drain's sanitized last_error — so the dead-lettered job's error_text names the cause, e.g. a missing provider key); src/core/config.ts carries the autopilot.auto_drain.* config keys + the autopilot. key prefix. The queued drain's window and timeout_ms are co-stamped by resolveAutopilotAutoDrainBounds (autopilot-timeout.ts): the deadline is at least the window plus twice the gateway's AI_CHAT_TIMEOUT_MS plus 60 s, because the drain hard-stops at its job deadline (#5809) and checks the window only between items; the window is clamped (min 1 s, logged auto_drain_window_clamped) to fit the 30-min anchor (1140 s at the default chat timeout); a longer interval-derived deadline wins. Pinned by test/extract-atoms-drain-handler.test.ts, test/autopilot-auto-drain-wiring.test.ts, test/autopilot-auto-drain-dispatch.test.ts. federated-brain co-existence + launchd hygiene. (1) LOCK_PATH resolves via gbrainPath('autopilot.lock') so it honors GBRAIN_HOME (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; src/core/autopilot-lock.ts checks liveness and the process command before takeover. looksLikeGbrainAutopilotCommand recognizes quoted or unquoted cli.ts / cli.js / cli.mjs paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by test/autopilot-lock.test.ts; they are not native Windows process-probe validation. (2) exported classifyReconnectError(err) returns 'recoverable' | 'unrecoverable'; unrecoverable causes process.exit(0) so launchd backs off instead of looping config.database_url undefined. (3) exported pure generateLaunchdPlist(wrapperPath, home) sets ThrottleInterval=300 so launchd respects the exit-0 backoff. Pinned by test/autopilot-lock-path.test.ts + test/autopilot-reconnect-classifier.test.ts. targeted-submit loop instead of blanket autopilot-cycle dispatch. Each tick: cheap engine.getHealth() (single SQL count) + computeRecommendations(), then route by shape — score >= 95 AND no plan AND <60min since last full → sleep; score >= 95 AND >=60min → submit autopilot-cycle (60-min floor exercises phase-coupling invariants on healthy brains); plan <= 3 steps AND est <5min → submit individual handlers; plan large OR score < 70 → submit full autopilot-cycle. The gbrain-cycle lock ensures targeted submissions and the full cycle can't run concurrently. maxWaiting: 1 per submit closes the queue-fan-out vector. daemon env lane: writeWrapperScript additively sources <gbrainDir>/env (honors GBRAIN_HOME) after the shell profiles with a set -a wrap so dotenv-style KEY=value lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes GBRAIN_HOME — the wrapper bakes it AFTER sourcing). Exported pure chatBootWarning(chatAvailable, gbrainDir) derives both remediation paths from the passed dir and prints via console.log at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model isAvailable('chat') probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run---install remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd try-restarts after enable --now, cron/container print a residual-process notice instead of auto-killing. Pinned by test/autopilot-install.test.ts (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, guardAutopilotEngine refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by test/autopilot-transaction-fence.test.ts. #5195: install, status and uninstall act on one brain's job, named by resolveAutopilotJob() in src/core/autopilot-paths.ts (default brain: the shared names; any other brain: <name>-<suffix> from the random install id in <brain>/.gbrain/autopilot-install-id, with move/copy semantics); crontab lines carry # gbrain-autopilot:<suffix>; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by --status as needs_reinstall: legacy_shared_job; replacing or removing a job whose wrapper runs another live brain is refused (autopilot_job_owned_by_other_brain). Job-definition reads, legacy replacement and the --status job report live in src/commands/autopilot/jobs.ts. --install without --repo uses sync.repo_path, else the default source's local_path (src/commands/autopilot/install-repo.ts), and refuses when neither is set; pinned by test/autopilot-install-repo-fallback-6755.test.ts. Pinned by test/autopilot-install-id.test.ts and test/e2e/autopilot-multi-brain.serial.test.ts. GBRA-133 PR 2a additions: commit-notifier.md.

  • src/commands/autopilot-refusals.ts — GBRA-438: autopilot --install's PGLite and no-repo refusals as autopilot_pglite_daemon / autopilot_no_repo errors whose fix points at gbrain maintain --status. Size ceiling: scripts/module-size-limits.tsv. The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. runAutopilot is a mode table (AUTOPILOT_MODES: --install, --uninstall, --status, --pause/--resume, --retry-global; first match wins) that otherwise lazily imports the daemon: autopilot-daemon.ts (runAutopilotDaemon: boot, lock, managed worker, shutdown and the tick loop over an explicit AutopilotDaemonState; steps probeDatabaseOrReconnect, probeNoWorkerPeer, runInlineCycle, adaptiveInterval; readTickHealth (autopilot-health.ts, #7236): one bounded read per tick), autopilot-dispatch.ts (dispatchAutopilotTick: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through autopilotTargetedSteps in autopilot-remediation-policy.ts, which drops manual-only steps) and autopilot-probes.ts (nightly quality and conversation-parser probes; the quality probe's resolveNightlyProbeModelRoutesForDaemon runs refreshGatewayForJob's two gateway calls (inlined: importing jobs.ts would grant its flags to autopilot in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from NIGHTLY_PROBE_FIXTURES, the embedded assets, and the quality probe passes its cap source and pricing.overrides as resolveBudgetPolicy). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.

  • src/commands/autopilot-dispatch.ts — one autopilot tick's submissions (dispatchAutopilotTick): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. After the brain-wide maintenance dispatch on the full-cycle branch it writes the stall verdict file (recordGlobalMaintenanceStallStatus, GBRA-130 C-6) that autopilot --status reads; a failed write is logged (global_maintenance_verdict_failed under --json) and leaves the previous verdict to expire. The auto-drain (dispatchAutoDrain → submitAutoDrains) runs on Postgres only, unless autopilot.auto_drain.enabled is false, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected extract-atoms-drain job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (autopilot.auto_drain.max_usd_per_day / the per-attempt cycle.extract_atoms.budget_usd estimate) counts attempts, not jobs (autoDrainUnitsToday: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with structural_refusal:. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in AUTO_DRAIN_NEXT_KIND_KEY (autopilot.auto_drain.next_kind) across ticks and days; a source whose writer preflight would refuse (atomDrainOwnerRefusal) is skipped with a logged reason; connector sources need no local_path and submit no repoPath. Tests: test/autopilot-auto-drain*.test.ts, test/e2e/autopilot-auto-drain-dispatch.test.ts. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp sources.config.last_extract_atoms_at (stampExtractAtomsRun in src/core/cycle/extract-atoms-stamp.ts, which also builds the doctor warning), and the extract_atoms_backlog doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run. autopilot.git_pull (#6451, wave 15 P7.2): automaticGitPullDisabled in core/persistence/automatic-sync-policy.ts is read first by automaticSyncPull, so a non-truthy value queues every remote source's sync with pull: false before any persistence read; dispatchFreshnessSyncs prints one git_pull: off line (git_pull_disabled NDJSON event under --json) per tick while it is off. Pinned by test/autopilot-git-pull-optout-6451.test.ts. GBRA-133 PR 2a additions: commit-notifier.md. #7239: readSyncRefusalHolds holds a source's freshness sync after a refused sync job for the failure cooldown of its refusal count (freshness_sync_refused).

  • src/commands/backup.ts — trusted local gbrain backup status|check: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see docs/operations/backup-check.md and test/backup-cli.serial.test.ts. backup create|restore failures render the agent-operator contract (storage_error, fix gbrain doctor --json) with the legacy ok/reason/message/retryable JSON keys; a message-less thrown value is described only by its bounded name/code/errno (backupFailureMessage), never String(object).

  • src/commands/backlinks.ts — Back-link checker and fixer (enforces Iron Law). fix (and fix --dry-run) refuses once, before the scan, when the directory is a managed canonical worktree (isManagedFilesystemPath from src/core/persistence/filesystem-guard.ts, the predicate assertManagedFilesystemWrite uses), instead of skipping every page one by one; check still runs (#5341). Repair-inserted references land as UNDATED rows (- Referenced in [Title](../path)) in a dedicated ## Referenced by section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. insertBacklinkEntry(content, bodyStart, entry) never touches bytes before bodyStart, locates the timeline boundary via findTimelineSplitIndex (existing timeline sentinels take precedence over bare ## Timeline/## History headings), appends to an existing ## Referenced by section or creates one above the timeline, and is CRLF-tolerant; insertTimelineEntry is an alias for existing import sites. buildBacklinkEntry(sourceTitle, sourcePath) takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency). findBacklinkGaps is a streaming two-pass scan (#6438): pass 1 reads each .md once and keeps only its slug, title and candidate people//companies/ targets (display name included; substrings are detached from the page body so JSC cannot pin it), pass 2 reads each referenced existing target once and records which sources it already credits, pass 3 emits the gaps in the pre-streaming order with the #967 per-source dedupe; the working set is the file being read plus that metadata, never the corpus. findBacklinkGapsAsync is the same scan yielding to the event loop every BACKLINKS_YIELD_EVERY files so the progress heartbeat and the minion RSS watchdog run mid-scan; runBacklinksCore uses it and returns the gap list in BacklinksResult.gaps, which the CLI prints instead of walking a second time. Pinned by test/backlinks-gap-parity.test.ts (golden captured from the single-pass walker), test/backlinks-yield.test.ts and test/backlinks-memory.slow.test.ts (isolated-process RSS slope).

  • src/commands/book-mirror.ts — gbrain book-mirror --chapters-dir <path> --slug <slug> [flags]. Submits N read-only subagent jobs (one per chapter; allowed_tools: ['get_page', 'search']), waits for all via waitForCompletion, reads each child's job.result, assembles two-column markdown CLI-side, writes a single operator-trust put_page to media/books/<slug>-personalized.md. Trust narrowing happens at the tool-allowlist layer (subagents can't call put_page) so untrusted EPUB content can't prompt-inject any people page. Asks for consent before submitting (exit 3 with the consent payload without --yes/--max-usd/a preapproval) and stores the authorization on every chapter job as one spend group (of = chapters) whose total the worker enforces; prints the submit summary (group, kept authorizations, reused rows). Per-chapter idempotency keys (book-mirror:<slug>:ch-<N>) for retry-friendly re-runs. Final publication captures its page revision and request UUID before providers run; a pending or failed receipt prevents a false written report and preserves the request ID for inspection. Partial-failure: assembles completed chapters + a ## Failed chapters section. Pinned by test/book-mirror.test.ts (9 cases).

  • src/commands/capture.ts + src/commands/serve-http.ts + src/core/{operations,import-file,types,utils,facts/absorb-log,brainstorm/{orchestrator,error-classify},scope,postgres-engine,pglite-engine}.ts — ingestion hardening. Capture frontmatter merge via mergeCaptureFrontmatter (uses shared data-only data-frontmatter, preserving metadata beyond parseMarkdown); /ingest null-guard + outer try/catch envelope with !res.headersSent guard; dedup via separate normalize-for-hash (normalizeForHash strips BOM/CRLF/whitespace/NFKC) + body-after-frontmatter-strip on the DB hash (excludes captured_at + ingested_at so capture-cli timestamp variations don't invalidate the chunk cache); friendly pages_source_id_fk rewrite via maybeRewriteSourceFkError on BOTH local + thin-client callRemoteTool catch blocks; facts:absorb 'No database connection' suppression via typed instanceof GBrainError && e.problem check + first-occurrence stack-trace info log (module-scoped _hasLoggedDisconnectedFactsAbsorb flag, test seam _resetFactsAbsorbDisconnectedFlagForTests); CLI help discoverability (capture in CLI_ONLY_SELF_HELP + pre-engine-bind --help short-circuit in handleCliOnly + a BRAIN section in printHelp); binary-file guard via detectBinaryNullByte(buf) first-8KB NUL scan on --file (Buffer-read, no encoding) and --stdin (readStdinBuffer accumulator); provenance write-through — put_page accepts 3 optional params (source_kind, source_uri, ingested_via; ingested_at server-stamped) + trust gate (when ctx.remote !== false IGNORE client params, server stamps mcp:put_page, fail-closed) + COALESCE-preserve UPDATE semantics (omitting params on a later put_page preserves prior values; first-write-wins); /admin/api/register-client scopes normalization via normalizeScopesInput(raw: unknown) in src/core/scope.ts (accepts string/string[]/missing; rejects ['read write'] space-in-element shape, non-string elements, empty array, unknown scopes; deduped + sorted); brainstorm timeout surfacing via an orchestrator-level try/catch at runBrainstorm entry (single-point wrap covers every internal SQL site, classifies SQLSTATE 57014 via postgres.js .code / .sqlState / message fallback into StructuredAgentError code brainstorm_timeout with a hint covering all 3 PG cancel sub-causes); read-path surfaces all 4 provenance columns via getPage projection + rowToPage 3-state optional read + Page interface; canonical source resolver routes capture through resolveSourceWithTier(engine, parsed.source, cwd); thin-client --source rejection (server-side OAuth client registration owns source scope); the source_kind taxonomy is closed (capture-cli | put_page | mcp:put_page | webhook | file-watcher | inbox-folder | cron-scheduler), --source maps to source_id only. Tests: test/capture-build-content.test.ts, test/capture-runcapture.test.ts, test/put-page-provenance.test.ts, test/scope-normalize.test.ts, test/cli-help-discoverability.test.ts, test/brainstorm-timeout.test.ts; extended test/facts-absorb-log.test.ts, test/import-file.test.ts, test/e2e/engine-parity.test.ts, test/e2e/serve-http-ingest-webhook.test.ts. Report at docs/v0.38-smoke-test-report.md. Follow-ups in TODOS.md: SQL-shape rewrite of listPrefixSampledPages for PgBouncer, magic-byte allowlist for binary detection, --source-kind override flag, ingest_capture handler migration, provenance-history table, facts:absorb root-cause trace.

  • src/commands/check-resolvable.ts — Standalone CLI wrapper over checkResolvable(). Exports parseFlags, resolveSkillsDir, DEFERRED, runCheckResolvable. Exit rule: 1 on any issue (warnings OR errors), stricter than doctor's ok flag. Stable JSON envelope {ok, skillsDir, report, autoFix, deferred, error, message} — same shape on success and error. --fix runs autoFixDryViolations BEFORE checkResolvable (same ordering as doctor). scripts/skillify-check.ts subprocess-calls gbrain check-resolvable --json (cached per process) and fails loud on binary-missing. AGENTS.md workspaces resolve natively (see src/core/resolver-filenames.ts). DEFERRED[] is empty. Resolver lookup is the multi-file merge in src/core/check-resolvable.ts — entries collected from every RESOLVER.md/AGENTS.md across the skills dir AND its parent, deduped by skillPath (first occurrence wins). Uses autoDetectSkillsDirReadOnly so cd ~ && gbrain check-resolvable finds bundled skills via the install-path fallback; --fix carries the same install-path safety gate (refuses to write when detected.source === 'install_path').

  • src/commands/claw-test.ts + src/core/claw-test/ — gbrain claw-test [--scenario <name>] [--live --agent <name>]. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets GBRAIN_HOME=<tempdir> for hermeticity and captures gbrain's --progress-json events from each child's stderr to verify expected phases ran (import.files, extract.links_fs, doctor.db_checks). Scripted phases: setup → install_brain (gbrain init --pglite) → import (--no-embed) → query → extract → verify (gbrain doctor --json; top-level status is healthy|warnings|unhealthy) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via seed-pglite.ts, NO init — the migration is the scenario under test), prepends a per-run gbrain PATH shim so the BRIEF's bare gbrain runs this checkout, hands BRIEF.md to the agent runner, then verifies a scenario-declared success ORACLE (oracle: {query, min_results, files_exist} in scenario.json; upgrade uses a non-mutating schema-version probe via readPgliteSchemaVersion — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Four runners ship (src/core/claw-test/runners/{openclaw,hermes,grok,opencode}.ts; shared detectBinary/filterAllowlistEnv live in agent-runner.ts): openclaw invokes openclaw agent --local --agent <name> --message <brief>; hermes invokes hermes -z <brief> ($HERMES_BIN > which hermes; HERMES_HOME passthrough is the env-allowlist delta; shared BASE_ENV_ALLOWLIST + validateBinPathEnv live in agent-runner.ts); grok (xAI Grok Build, observed shapes in docs/mcp/GROK-CLI-PIN.md) invokes grok -p <brief> --output-format plain ($GROK_BIN > which grok; delta GROK_HOME + XAI_API_KEY; writes a version preamble into the transcript and warns loudly when the operator's ~/.claude.json registers gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes in docs/mcp/OPENCODE-CLI-PIN.md) invokes opencode run <brief> --format default ($OPENCODE_BIN > which opencode; delta = the EXPLICIT multi-provider keys XAI/Google/Gemini/OpenRouter — BASE carries only Anthropic+OpenAI — plus XDG dirs, OPENCODE_CONFIG(_DIR), and OPENCODE_DISABLE_AUTOUPDATE; OPENCODE_CONFIG_CONTENT deliberately absent, it is a config-shadow channel; no --auto — MCP tools fire without it; bare-semver version preamble is the SST-vs-claimant discriminator; warns loudly when the user-global opencode config carries mcp.gbrain). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are test/e2e/install-real-hermes.serial.test.ts, test/e2e/install-real-grok.serial.test.ts, and test/e2e/install-real-opencode.serial.test.ts (keyless tier: registration only; the free-tier nonce SMOKE T4 runs only in the canary, the free tier being capped per IP (#6049); the gating SMOKE is paid T5, a Haiku turn whose model id is checked against opencode models --refresh before spend, asserting a STRUCTURAL gbrain_* tool_use event via parseOpencodeJsonl as T4 does) (grok door is split-gated: keyless compat tier needs only the binary — mcp doctor is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs XAI_API_KEY and asserts a per-run nonce fact, never the committed one). Transcript capture (transcript-capture.ts) uses fs.createWriteStream with 'drain'-event backpressure (so a 256KB burst cannot stall the child). Env knobs (harness escape hatches, all optional): GBRAIN_BIN_OVERRIDE (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), GBRAIN_CLAW_PHASE_TIMEOUT_MS (per-phase child wall clock, default 5 min; each phase child leads its own process group on POSIX, so the timeout's SIGTERM→SIGKILL, a relayed SIGINT (second SIGINT kills), the process-cleanup pass on SIGTERM/SIGHUP and the phase's settle all signal the whole group (#6775)), GBRAIN_CLAW_AGENT_TIMEOUT_MS (live agent turn wall clock, default 10 min).

  • src/commands/code-def.ts + src/commands/code-refs.ts — symbol definition + references lookup. Query content_chunks.symbol_name or chunk_text ILIKE with page_kind='code' filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard searchKeyword DISTINCT ON (slug) collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the code_def/code_refs MCP ops) carries status + ready from src/core/code-graph-readiness.ts so a count:0 result is distinguishable as not_built (no code indexed) vs ready (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve --source <id> (space or inline = spelling) and the ambient source scope through the shared code-scope.ts resolver, matching code-callers/code-callees; --all-sources restores the brain-wide read. code-intel/read-scope.ts applies the same source, live-page, visibility and current-projection policy to result queries and filtered-type diagnostics. Result identity includes source_id. Partial as well as empty results carry readiness; trusted-local operation wrappers retain their documented brain-wide behavior.

  • src/commands/code-scope.ts — shared --source/--all-sources resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. positionalArgs skips value-taking flags AND their values (--source, --limit, --lang — a naive scan looked up the flag's value as the symbol); inline name=value spellings are one token and consume nothing. A bad .gbrain-source/GBRAIN_SOURCE pin is recognized through the shared isResolverUserError predicate (exported by src/core/source-resolver.ts, next to the messages it matches) and exits 2 with a clean invalid_source_pin envelope instead of an uncaught stack. Also exports pushSourcePredicate(params, opts), the source-scope SQL fragment builder code-def/code-refs share.

  • src/commands/config/keyword-timeout-value.ts — config set value check for search.keyword_statement_timeout_ms (#6495): a value outside 1000..60000 or not an integer is refused (invalid_params, exit 2, a config get verify, nothing written) because the Postgres engine reads a stored value outside the range as the default; called from setConfigWithDecideHooks for every search.* key. Pinned by test/keyword-statement-timeout-knob-6495.test.ts.

  • src/commands/config/contextual-mode-hint.ts — contextualModeHint(sourceId?) (#5012 item 6), printed after config set search.contextual_retrieval and sources set-cr-mode: existing pages keep the mode recorded at import, the new mode applies to later imports, and gbrain repair contextual-mode [--source <id>] --apply stamps pages with none.

  • src/commands/config/facts-values.ts — config set value checks for facts.* keys, called from setConfigWithDecideHooks before the write: facts.page_write_notability_filter (#6231) must be a NOTABILITY_FILTERS value (invalid_params with a config get verify, nothing written), and facts.drain_* keeps drain-config.ts's validation. Pinned by test/config-set.test.ts.

Continued in Commands (1/6, continued).