Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/gbra151-autopilot-health-once
garrytanb5de7cbd7097
diff --cc docs/architecture/key-files/commands-1.mdindex b17b85d282,56879d7b41..9a6af8e8b5--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@@ -20,10 -20,9 +20,9 @@@ Current behavior and load-bearing invar- `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](../../guides/minions-fix.md). `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 (to at least 1 s) so that deadline fits the full-cycle anchor (1140 s at the default chat timeout), and a longer interval-derived deadline still 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-restart`s 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](commit-notifier.md#autopilot-and-the-jobs-worker).-- Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). 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`), `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.++ 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](commit-notifier.md#autopilot-and-the-jobs-worker).- - `src/commands/autopilot-health.ts` — `readTickHealth` (#7236): one bounded health read per dispatch tick, shared with `adaptiveInterval`; a Postgres timeout logs `health_degraded` and returns null (no score). Tests: `test/autopilot-tick-health-7236.test.ts`.+ - `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](commit-notifier.md#autopilot-and-the-jobs-worker). #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)`.diff --cc src/commands/autopilot-dispatch.tsindex 8b918cd11f,9f4a48009e..4068db97b7--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@@ -27,11 -25,9 +27,12 @@@ import { readTickHealth } from './autopimport { readCheckoutHead } from '../core/checkout-head.ts';import { SYNC_ON_COMMIT_KEY } from '../core/sync-config-keys.ts';import { autopilotPaused } from '../core/autopilot-paths.ts';+ import { cooldownMinForCount, resolveFailureCooldownOpts } from './autopilot-fanout.ts';-/** Returns cycleOk: false only when the dispatch itself threw. */+/**+ * cycleOk is false only when the dispatch itself threw. health is the snapshot the plan routed on (null: the bounded+ * read timed out), for the daemon's adaptive interval (#7236); absent when the tick threw before reading it.+ */export async function dispatchAutopilotTick(engine: BrainEngine,state: AutopilotDaemonState,