Garry's Opinionated OpenClaw/Hermes Agent Brain
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.tsandsrc/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-retryrecovers 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--listand--dry-runholds the orchestration lock (src/core/migration-orchestration-lock.ts) from before its first ledger write through its final status: a Postgres TTL lease rowgbrain-apply-migrationsingbrain_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 printsanother 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 beforeprocess.exit. Tests:apply-migrations-safety.serial.test.ts,apply-migrations-orchestration-lock.test.ts,e2e/apply-migrations-orchestration-lock.test.tsande2e/migration-preview-safety.test.ts. D2 (json: 'document'): every--jsonpath is one single-line document (statusunconfigured/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_paramsexit 2,migration_failedwith reasons,migrations_pendingwithschema_pending,database_errorfor--require-db,migrations_runningexit 75,migration_lease_lostexit 1 withlease). #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:assertHeldraisesMigrationLeaseLostError(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 ofmigrations_running; testse2e/migration-lease-lost.test.ts. A4:Migration.effects(v0.11.0:persistent_install, its Phase F autopilot install) is asked throughconsentGatebefore the orchestrator runs (skipped under--no-autopilot-installor on PGLite);--yes,--non-interactive(mapped topersistent_installonly), a preapproval or a TTY yes authorize, otherwise exit 3.applyMigrations()returns{exitCode, failure}for in-process callers (post-upgrade);runApplyMigrations()exits. Child CLIs usecliChildStdio(). Tests:test/cli-json-commands.test.ts. the plan addspending_fresh_install(unrun setup work on a braingbrain initcreated; runs likepending, reported as expected work, never as a failed upgrade);--list --jsonprints one row per migration (fresh_install: trueon init stamps) plusnext.argvwhen work remains and awedged[]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,forwardProgressPastinsrc/core/migration-ledger.ts; a superseded wedge is listed aswedged_supersededin the plan and is history; a v0.53.0 wedge whose latest row recordsapply_migrations_pendingstill owes host work,hostWorkOwedForVersion(other migrations set that flag on ordinary partials and keep the forward-progress rule), is never superseded: it is listed aswedged_host_workwith the read-only--migration <v> --dry-run --jsoninspect 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; testsmigration-host-work-owed.test.ts) never reports up to date: it failsmigrations_pendingreasonwedged(exit 1, fixnext: ask_user, verify--list --json), sopost-upgradeexits non-zero andgbrain upgradeprintsMigrations: wedged; testsapply-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'smigrations/completed.jsonl(phases[].detail, if present) throughwedgedLedgerHint(src/core/migration-ledger.ts); a phase'sargvprints as its next step. v0.11.0 Phase F (src/commands/migrations/v0_11_0-install.ts) installs the autopilot only for the brain'ssync.repo_path; without one it installs nothing, isskippedwith the exact install command (the default source'slocal_path, else<REPO_PATH>), records anautopilot-install-needs-repopending host-work item, and the migration completes; doctor'sminions_migrationline (src/commands/doctor/checks/autopilot-install-pending.ts) carries that argv (persistent_install) until an autopilot is installed for this brain. Phase F records areasoncode on those outcomes (no_repo_path,autopilot_already_installed,install_failed).clearRepoPathWedgewrites aretrymarker (reasonphase_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'ssync.repo_pathis unset, so Phase F would now skip; with it set, or any other wedge, the--force-retryadvice 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-retryrecovers a historical false-complete record. Every run except--listand--dry-runholds the orchestration lock (src/core/migration-orchestration-lock.ts) from before its first ledger write through its final status: a Postgres TTL lease rowgbrain-apply-migrationsingbrain_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 printsanother 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 beforeprocess.exit. Tests:apply-migrations-safety.serial.test.ts,apply-migrations-orchestration-lock.test.ts,e2e/apply-migrations-orchestration-lock.test.tsande2e/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).withRunEngineSessionwraps the locked run;setRunEngineSharingenables sharing for the opt-out read, each migration flaggedsharesRunEngine(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-runor a consent prompt) closes the engine.connectMigrationEnginereturns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always).releaseRunEnginecloses it before agbrainchild that needs the brain (v0.11.0'sjobs smoke). A fresh setup's migration child opens the brain three times instead of eight (counting thejobs smokechild); the ledger it writes is pinned bytest/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.connectAtSchemaVersionconnects the configured brain and readsconfig.version(pre-flight,--force-schema); the post-orchestrator check opens it throughconnectMigrationEngine.checkSchemaAfterOrchestratorsre-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.schemaPendingErrorbuildsmigrations_pendingwith reasonnot_applied(fix reruns with--yes),still_behind(after an authorized run) orschema_unreadable(both fixnext: reportwithgbrain doctor --jsonas verify, never another--yes), each naming the pending schema versions.reportDatabaseUnreachablekeeps an unreachable Postgres non-fatal but prints theGBRAIN_DB_ACCESS <reason>marker. Tests:test/apply-migrations-schema-exit.test.ts(PGLite, unreachable Postgres, post-upgrade, postinstall) andtest/e2e/apply-migrations-schema-exit.test.ts(Postgres).src/commands/agent-logs.ts—gbrain agent logs <job> [--follow] [--since]. Merges JSONL heartbeat audit +subagent_messagesinto a chronological timeline.parseSinceaccepts 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 laneANY($1::text[])) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONEengine.transaction(name-scopedpg_advisory_xact_lock→ duplicate-name pre-check →ensureWorkspaceSourcecreate-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) →registerScopedClientwith ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (probeServeHealth+ the unconditionalSCOPES_MIN_SERVE_VERSIONfloor 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 carryingprobe_note+serve_warningfrom 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'*-workspacescratch sources — a workspace named explicitly in--federated-readis still granted, and the print counts the exclusions) andcoding-agent(write-isolated derived<name>-workspaceDB-only source; requires--federated-read); both default the client to thefullsurface (S0/D4) — pass--surface starter|verbsat registration for a capped harness, or narrow per client viagbrain auth rescope-client. Always writestoken_ttl(default 30 days — the server default is 1 hour and would kill a pasted config).--url|--portrequired (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes onauth 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 bytest/agent-register.test.ts.src/commands/agent.ts—gbrain agent run|logs|registerdispatcher.runsubmitssubagent(or N children + 1 aggregator) under{allowProtectedSubmit: true}; single-entry--fanout-manifestshort-circuits; children geton_child_fail: 'continue'+max_stalled: 3;--followis the default on TTY (streams logs + pollswaitForCompletionin parallel; Ctrl-C detaches, does not cancel).logsdelegates toagent-logs.ts;registerlazy-importsagent-register.ts. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the--terminator (agent run -- --helpsubmits the LITERAL prompt); on a brainless machine (null engine) help still prints while realrun/logsinvocations 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. Callsengine.findAnomalies(opts). Two cohort kinds: tag, type. At most 20page_slugsper cohort (page_slugs_complete: false; local--alllists all;test/anomalies-bounded-7246.test.ts).src/commands/auth.ts— token management.gbrain auth create/list/revoke/testfor legacy bearer tokens (revoke-clientruns an atomicDELETE...RETURNINGonoauth_clients; FKON DELETE CASCADEonoauth_tokens.client_idandoauth_codes.client_idpurges every active token + auth code in one transaction;process.exit(1)on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes inaccess_tokens; OAuth clients inoauth_clients; legacy tokens with no scopes grant grandfather toread+write+adminon the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant.--memberwithout--scopesmintsMEMBER_TOKEN_SCOPES(read,write). Every SQL site routes throughsqlQueryForEngine(engine)fromsrc/core/sql-query.ts(andexecuteRawJsonbfor the takes-holderspermissionsJSONB column) sogbrain authworks against PGLite; the takes-holders write goes throughexecuteRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])which round-trips withjsonb_typeof = 'object'.register-clientaccepts--source <id>(write authority, scalar),--federated-read <S1,S2,...>(read scope, array), and--token-ttl <seconds>(per-client access-token TTL persisted tooauth_clients.token_ttl, boundsTOKEN_TTL_MIN_SECONDS=60 toTOKEN_TTL_MAX_SECONDS=7,776,000/90d) and prints the resolvedWrite source+Federated reads; clients without asource_idbackfill to'default'via migration v60. The registration core is the exportedregisterScopedClient(sql, engine, name, parsed, opts)— exit-free, print-free, injected-handle (engine-bound callers likeagent registerpass the dispatcher's engine; a secondwithConfiguredSqlengine self-deadlocks PGLite's single-writer lock), returns aRegisteredClientdata object and throws on failure; the thin CLI wrapper owns exit/print. Its printerformatRegisterClientOutputis a BYTE-PINNED contract (connect.ts'sdefaultRegisterOAuthClientregex-scrapesClient ID:/Client Secret:from it in production) — pinned bytest/auth-register-client-output-pin.test.ts.preflightOauthClientColumns(sql)probesinformation_schema.columnsfor 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 asRegisteredClient.skippedwith 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);clientOperationsViewreports four distinct operation states (SQL NULL =operations: "all"withincludes_future_operations: trueand a re-pinfixnamingauth rescope --client <id> --operations <list>or--profile;[]= deny-all; an explicit list;unavailablewhen the schema predatesallowed_operations) and marks soft-revoked clients (deleted_at)revokedwith no fix (test/auth-clients-operations.test.ts, both engines);tokenLifetimeClampedClientsreads the migration'sclamp_token_ttl/shorten_access_tokensaudit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (token_lifetime_clampedin--json); theTOKEN_TTL_*bounds are re-exported fromsrc/core/grants/model.ts;--usagejoins op-call counts and coverage viasrc/core/mcp-usage.ts. The baregbrain auth create <name>form (no--takes-holders) mints a token via the exported pureparseAuthCreateArgs(rest). Pinned bytest/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-clientandpermissions set-takes-holdersare aliases routed through it.src/commands/autopilot-retry-global.ts—gbrain autopilot --retry-global [--phase <name>] [--json](GBRA-130 A-10): clearsretry_aton the backed-off phase streaks inautopilot.global_maintenance.progress(one phase, or all), keeping each count, so the next brain-wide pass runs the phase again; names a runningautopilot-global-maintenancejob, whose next progress save can restore the back-off. Test:test/pathological/a10-global-maintenance-stamp.test.ts.src/commands/autopilot-pause.ts— engine-freegbrain autopilot pause [--reason <text>]/resume: writes or removes the operator markerautopilot-operator-paused(autopilotOperatorPauseMarkerPathinsrc/core/autopilot-paths.ts, withautopilotPaused()andautopilotPauseReason()). The daemon loop and job workers honor it like the migration hold;--install(and sogbrain 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-polaritypullvalue fromautomaticSyncPull(src/core/persistence/automatic-sync-policy.ts): a parsedremote_urlon an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. ConsumesdetectTini()fromsrc/core/minions/spawn-helpers.ts, resolved once at startup. Composes aChildWorkerSupervisorinstance for spawn-and-respawn with--max-rss 2048and softmaxCrashes: 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 --jsonadds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; it also addsglobal_maintenance, the daemon's latest stall verdict (readGlobalMaintenanceVerdictinsrc/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.onMaxCrashesExceededroutes through autopilot's ownshutdown('max_crashes')so the autopilot lockfile gets cleaned up.shutdown()drains viachildSupervisor.killChild('SIGTERM')+awaitChildExit(35_000). Pinned bytest/autopilot-fanout-wiring.test.tsandtest/autopilot-supervisor-wiring.test.ts(6 static-shape guards: composes ChildWorkerSupervisor not legacy names,--max-rss 2048in argv,maxCrashes: 5literal, shutdown-via-callback, no workerProc reference). tick body invokesrunNightlyQualityProbewhencfg.autopilot.nightly_quality_probe.enabled === true(default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check —runNightlyQualityProbe's internalshouldRunNightly(reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs vialogErrorand does NOT bumpconsecutiveErrors(probe failure is informational, never crashes the loop). Defaultmax_usdcap = 5. Pinned bytest/autopilot-nightly-probe-wiring.test.ts. per-sourceextract_atomsauto-drain. Postgres-only block after the freshness fan-out: gated onautopilot.auto_drain.enabled(default true) AND!packDeclaresPhase(engine,'extract_atoms')(the silent-backlog condition) AND per-sourcecountExtractAtomsBacklog > threshold(default 25) AND a daily capfloor(max_usd_per_day / ~$0.30). EnumeratesloadAllSources. Submits the PROTECTEDextract-atoms-drainjob ({allowProtectedSubmit:true}) with a UTC-day time-sloted idempotency keyautopilot-extract-atoms-drain:<src.id>:<utcDay>(a static key would block the source after the first job completed).src/core/minions/protected-names.tslistsextract-atoms-drain;src/commands/jobs.tsregisters the handler (thin wrapper overrunExtractAtomsDrainForSource,LockUnavailableError→{deferred:true}; aprovider_failureresult throwsformatDrainProviderFailure(result)— batches/remaining plus the drain's sanitizedlast_error— so the dead-lettered job'serror_textnames the cause, e.g. a missing provider key);src/core/config.tscarries theautopilot.auto_drain.*config keys + theautopilot.key prefix. The queued drain'swindowandtimeout_msare co-stamped byresolveAutopilotAutoDrainBounds(autopilot-timeout.ts): the deadline is at least the window plus twice the gateway'sAI_CHAT_TIMEOUT_MSplus 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, loggedauto_drain_window_clamped) to fit the 30-min anchor (1140 s at the default chat timeout); a longer interval-derived deadline wins. Pinned bytest/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_PATHresolves viagbrainPath('autopilot.lock')so it honorsGBRAIN_HOME(two brains can run autopilot simultaneously without lock-stealing); lock file stores PID;src/core/autopilot-lock.tschecks liveness and the process command before takeover.looksLikeGbrainAutopilotCommandrecognizes quoted or unquotedcli.ts/cli.js/cli.mjspaths, 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 bytest/autopilot-lock.test.ts; they are not native Windows process-probe validation. (2) exportedclassifyReconnectError(err)returns'recoverable' | 'unrecoverable'; unrecoverable causesprocess.exit(0)so launchd backs off instead of loopingconfig.database_url undefined. (3) exported puregenerateLaunchdPlist(wrapperPath, home)setsThrottleInterval=300so launchd respects the exit-0 backoff. Pinned bytest/autopilot-lock-path.test.ts+test/autopilot-reconnect-classifier.test.ts. targeted-submit loop instead of blanketautopilot-cycledispatch. Each tick: cheapengine.getHealth()(single SQL count) +computeRecommendations(), then route by shape —score >= 95 AND no plan AND <60min since last full→ sleep;score >= 95 AND >=60min→ submitautopilot-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 fullautopilot-cycle. Thegbrain-cyclelock ensures targeted submissions and the full cycle can't run concurrently.maxWaiting: 1per submit closes the queue-fan-out vector. daemon env lane:writeWrapperScriptadditively sources<gbrainDir>/env(honorsGBRAIN_HOME) after the shell profiles with aset -awrap so dotenv-styleKEY=valuelines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludesGBRAIN_HOME— the wrapper bakes it AFTER sourcing). Exported purechatBootWarning(chatAvailable, gbrainDir)derives both remediation paths from the passed dir and prints viaconsole.logat daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-modelisAvailable('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---installremediation is true: launchd unloads before load (bare load errors on a loaded agent), systemdtry-restarts afterenable --now, cron/container print a residual-process notice instead of auto-killing. Pinned bytest/autopilot-install.test.ts(16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked,guardAutopilotEnginerefuses 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 bytest/autopilot-transaction-fence.test.ts. #5195: install, status and uninstall act on one brain's job, named byresolveAutopilotJob()insrc/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--statusasneeds_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--statusjob report live insrc/commands/autopilot/jobs.ts.--installwithout--repousessync.repo_path, else the default source'slocal_path(src/commands/autopilot/install-repo.ts), and refuses when neither is set; pinned bytest/autopilot-install-repo-fallback-6755.test.ts. Pinned bytest/autopilot-install-id.test.tsandtest/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 asautopilot_pglite_daemon/autopilot_no_repoerrors whose fix points atgbrain 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.runAutopilotis 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 explicitAutopilotDaemonState; stepsprobeDatabaseOrReconnect,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 throughautopilotTargetedStepsinautopilot-remediation-policy.ts, which drops manual-only steps) andautopilot-probes.ts(nightly quality and conversation-parser probes; the quality probe'sresolveNightlyProbeModelRoutesForDaemonrunsrefreshGatewayForJob's two gateway calls (inlined: importingjobs.tswould grant its flags toautopilotin 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 fromNIGHTLY_PROBE_FIXTURES, the embedded assets, and the quality probe passes its cap source andpricing.overridesasresolveBudgetPolicy). 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) thatautopilot --statusreads; a failed write is logged (global_maintenance_verdict_failedunder--json) and leaves the previous verdict to expire. The auto-drain (dispatchAutoDrain→submitAutoDrains) runs on Postgres only, unlessautopilot.auto_drain.enabledisfalse, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protectedextract-atoms-drainjob 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-attemptcycle.extract_atoms.budget_usdestimate) 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 withstructural_refusal:. Checkout-backed and connector sources alternate for free slots, with the next kind persisted inAUTO_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 nolocal_pathand submit norepoPath. 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 stampsources.config.last_extract_atoms_at(stampExtractAtomsRuninsrc/core/cycle/extract-atoms-stamp.ts, which also builds the doctor warning), and theextract_atoms_backlogdoctor 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):automaticGitPullDisabledincore/persistence/automatic-sync-policy.tsis read first byautomaticSyncPull, so a non-truthy value queues every remote source's sync withpull: falsebefore any persistence read;dispatchFreshnessSyncsprints onegit_pull: offline (git_pull_disabledNDJSON event under--json) per tick while it is off. Pinned bytest/autopilot-git-pull-optout-6451.test.ts. GBRA-133 PR 2a additions: commit-notifier.md. #7239:readSyncRefusalHoldsholds 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 localgbrain 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; seedocs/operations/backup-check.mdandtest/backup-cli.serial.test.ts.backup create|restorefailures render the agent-operator contract (storage_error, fixgbrain doctor --json) with the legacyok/reason/message/retryableJSON keys; a message-less thrown value is described only by its bounded name/code/errno (backupFailureMessage), neverString(object).src/commands/backlinks.ts— Back-link checker and fixer (enforces Iron Law).fix(andfix --dry-run) refuses once, before the scan, when the directory is a managed canonical worktree (isManagedFilesystemPathfromsrc/core/persistence/filesystem-guard.ts, the predicateassertManagedFilesystemWriteuses), instead of skipping every page one by one;checkstill runs (#5341). Repair-inserted references land as UNDATED rows (- Referenced in [Title](../path)) in a dedicated## Referenced bysection 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 beforebodyStart, locates the timeline boundary viafindTimelineSplitIndex(existing timeline sentinels take precedence over bare## Timeline/## Historyheadings), appends to an existing## Referenced bysection or creates one above the timeline, and is CRLF-tolerant;insertTimelineEntryis 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).findBacklinkGapsis a streaming two-pass scan (#6438): pass 1 reads each.mdonce and keeps only its slug, title and candidatepeople//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.findBacklinkGapsAsyncis the same scan yielding to the event loop everyBACKLINKS_YIELD_EVERYfiles so the progress heartbeat and the minion RSS watchdog run mid-scan;runBacklinksCoreuses it and returns the gap list inBacklinksResult.gaps, which the CLI prints instead of walking a second time. Pinned bytest/backlinks-gap-parity.test.ts(golden captured from the single-pass walker),test/backlinks-yield.test.tsandtest/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 viawaitForCompletion, reads each child'sjob.result, assembles two-column markdown CLI-side, writes a single operator-trustput_pagetomedia/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 chapterssection. Pinned bytest/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 viamergeCaptureFrontmatter(uses shared data-onlydata-frontmatter, preserving metadata beyondparseMarkdown);/ingestnull-guard + outer try/catch envelope with!res.headersSentguard; dedup via separate normalize-for-hash (normalizeForHashstrips BOM/CRLF/whitespace/NFKC) + body-after-frontmatter-strip on the DB hash (excludescaptured_at+ingested_atso capture-cli timestamp variations don't invalidate the chunk cache); friendlypages_source_id_fkrewrite viamaybeRewriteSourceFkErroron BOTH local + thin-clientcallRemoteToolcatch blocks;facts:absorb'No database connection' suppression via typedinstanceof GBrainError && e.problemcheck + first-occurrence stack-trace info log (module-scoped_hasLoggedDisconnectedFactsAbsorbflag, test seam_resetFactsAbsorbDisconnectedFlagForTests); CLI help discoverability (captureinCLI_ONLY_SELF_HELP+ pre-engine-bind--helpshort-circuit inhandleCliOnly+ aBRAINsection inprintHelp); binary-file guard viadetectBinaryNullByte(buf)first-8KB NUL scan on--file(Buffer-read, no encoding) and--stdin(readStdinBufferaccumulator); provenance write-through — put_page accepts 3 optional params (source_kind, source_uri, ingested_via;ingested_atserver-stamped) + trust gate (whenctx.remote !== falseIGNORE client params, server stampsmcp:put_page, fail-closed) + COALESCE-preserve UPDATE semantics (omitting params on a later put_page preserves prior values; first-write-wins);/admin/api/register-clientscopes normalization vianormalizeScopesInput(raw: unknown)insrc/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 atrunBrainstormentry (single-point wrap covers every internal SQL site, classifies SQLSTATE 57014 via postgres.js.code/.sqlState/ message fallback intoStructuredAgentErrorcodebrainstorm_timeoutwith a hint covering all 3 PG cancel sub-causes); read-path surfaces all 4 provenance columns viagetPageprojection +rowToPage3-state optional read +Pageinterface; canonical source resolver routes capture throughresolveSourceWithTier(engine, parsed.source, cwd); thin-client--sourcerejection (server-side OAuth client registration owns source scope); thesource_kindtaxonomy is closed (capture-cli | put_page | mcp:put_page | webhook | file-watcher | inbox-folder | cron-scheduler),--sourcemaps 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; extendedtest/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 atdocs/v0.38-smoke-test-report.md. Follow-ups in TODOS.md: SQL-shape rewrite oflistPrefixSampledPagesfor PgBouncer, magic-byte allowlist for binary detection,--source-kindoverride flag, ingest_capture handler migration, provenance-history table, facts:absorb root-cause trace.src/commands/check-resolvable.ts— Standalone CLI wrapper overcheckResolvable(). ExportsparseFlags,resolveSkillsDir,DEFERRED,runCheckResolvable. Exit rule: 1 on any issue (warnings OR errors), stricter than doctor'sokflag. Stable JSON envelope{ok, skillsDir, report, autoFix, deferred, error, message}— same shape on success and error.--fixrunsautoFixDryViolationsBEFOREcheckResolvable(same ordering as doctor).scripts/skillify-check.tssubprocess-callsgbrain check-resolvable --json(cached per process) and fails loud on binary-missing. AGENTS.md workspaces resolve natively (seesrc/core/resolver-filenames.ts).DEFERRED[]is empty. Resolver lookup is the multi-file merge insrc/core/check-resolvable.ts— entries collected from everyRESOLVER.md/AGENTS.mdacross the skills dir AND its parent, deduped byskillPath(first occurrence wins). UsesautoDetectSkillsDirReadOnlysocd ~ && gbrain check-resolvablefinds bundled skills via the install-path fallback;--fixcarries the same install-path safety gate (refuses to write whendetected.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). SetsGBRAIN_HOME=<tempdir>for hermeticity and captures gbrain's--progress-jsonevents 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 ishealthy|warnings|unhealthy) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first viaseed-pglite.ts, NO init — the migration is the scenario under test), prepends a per-rungbrainPATH shim so the BRIEF's baregbrainruns this checkout, handsBRIEF.mdto 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 viareadPgliteSchemaVersion— 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; shareddetectBinary/filterAllowlistEnvlive inagent-runner.ts): openclaw invokesopenclaw agent --local --agent <name> --message <brief>; hermes invokeshermes -z <brief>($HERMES_BIN>which hermes;HERMES_HOMEpassthrough is the env-allowlist delta; sharedBASE_ENV_ALLOWLIST+validateBinPathEnvlive inagent-runner.ts); grok (xAI Grok Build, observed shapes indocs/mcp/GROK-CLI-PIN.md) invokesgrok -p <brief> --output-format plain($GROK_BIN>which grok; deltaGROK_HOME+XAI_API_KEY; writes a version preamble into the transcript and warns loudly when the operator's~/.claude.jsonregisters gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes indocs/mcp/OPENCODE-CLI-PIN.md) invokesopencode 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 aretest/e2e/install-real-hermes.serial.test.ts,test/e2e/install-real-grok.serial.test.ts, andtest/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 againstopencode models --refreshbefore spend, asserting a STRUCTURALgbrain_*tool_use event viaparseOpencodeJsonlas T4 does) (grok door is split-gated: keyless compat tier needs only the binary —mcp doctoris grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needsXAI_API_KEYand asserts a per-run nonce fact, never the committed one). Transcript capture (transcript-capture.ts) usesfs.createWriteStreamwith'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. Querycontent_chunks.symbol_nameor chunk_text ILIKE withpage_kind='code'filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standardsearchKeywordDISTINCT ON (slug)collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + thecode_def/code_refsMCP ops) carriesstatus+readyfromsrc/core/code-graph-readiness.tsso acount:0result is distinguishable asnot_built(no code indexed) vsready(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 sharedcode-scope.tsresolver, matchingcode-callers/code-callees;--all-sourcesrestores the brain-wide read.code-intel/read-scope.tsapplies 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-sourcesresolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift.positionalArgsskips value-taking flags AND their values (--source,--limit,--lang— a naive scan looked up the flag's value as the symbol); inlinename=valuespellings are one token and consume nothing. A bad.gbrain-source/GBRAIN_SOURCEpin is recognized through the sharedisResolverUserErrorpredicate (exported bysrc/core/source-resolver.ts, next to the messages it matches) and exits 2 with a cleaninvalid_source_pinenvelope instead of an uncaught stack. Also exportspushSourcePredicate(params, opts), the source-scope SQL fragment builder code-def/code-refs share.src/commands/config/keyword-timeout-value.ts—config setvalue check forsearch.keyword_statement_timeout_ms(#6495): a value outside 1000..60000 or not an integer is refused (invalid_params, exit 2, aconfig getverify, nothing written) because the Postgres engine reads a stored value outside the range as the default; called fromsetConfigWithDecideHooksfor everysearch.*key. Pinned bytest/keyword-statement-timeout-knob-6495.test.ts.src/commands/config/contextual-mode-hint.ts—contextualModeHint(sourceId?)(#5012 item 6), printed afterconfig set search.contextual_retrievalandsources set-cr-mode: existing pages keep the mode recorded at import, the new mode applies to later imports, andgbrain repair contextual-mode [--source <id>] --applystamps pages with none.src/commands/config/facts-values.ts—config setvalue checks forfacts.*keys, called fromsetConfigWithDecideHooksbefore the write:facts.page_write_notability_filter(#6231) must be aNOTABILITY_FILTERSvalue (invalid_paramswith aconfig getverify, nothing written), andfacts.drain_*keepsdrain-config.ts's validation. Pinned bytest/config-set.test.ts.
Continued in Commands (1/6, continued).