Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(autopilot): automatic atom drains get a deadline that covers their window (#6967)
time-attack083c4e7716c9
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 0d8706ca75..e357ddfd11 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.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`.+- `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`.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.- `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`.diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.tsindex 5d28f38fa4..02ff3a88a9 100644--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@ -13,7 +13,7 @@ import { connectorAccountMismatches, connectorAccountMismatchSkipWarning } fromimport { AUTOPILOT_GIT_PULL_KEY, automaticGitPullDisabled, automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';import { isSyncDisabledConfig } from '../core/sync-policy.ts';import { automaticSyncSkip, loadActivationPendingSourceIds, reportAutomaticSyncSkip, skipActivationPendingSync } from '../core/sync-policy.ts';-import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';+import { resolveAutopilotAutoDrainBounds, resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';import {autopilotRemediationIdempotencyKey,autopilotTargetedSteps,@@ -102,8 +102,9 @@ export async function dispatchAutopilotTick(// maintenance' carry a 30-min handler anchor (handler-timeouts.ts)// because a full cycle can outlive short daemon intervals — unlike// the lighter interval-derived `timeoutMs` above (sync/freshness,- // extract-atoms-drain, targeted small-plan steps), which have no- // such anchor and are meant to stay interval-derived. Naming this+ // targeted small-plan steps), which have no such anchor and are meant+ // to stay interval-derived; auto-drains co-stamp their window and+ // deadline (resolveAutopilotAutoDrainBounds). Naming this// separately (rather than reusing the outer `timeoutMs`) avoids// the #2781 bug class: dispatchGlobalMaintenance previously reused// the outer non-full-cycle `timeoutMs` by shorthand, silently@@ -458,7 +459,8 @@ export async function submitAutoDrains(return Number.isFinite(n) && n >= 0 ? n : d;};const threshold = parsePosInt(await engine.getConfig('autopilot.auto_drain.threshold'), 25);- const windowSeconds = parsePosInt(await engine.getConfig('autopilot.auto_drain.window_seconds'), 120);+ const { AI_CHAT_TIMEOUT_MS } = await import('../core/ai/gateway.ts');+ const bounds = resolveAutopilotAutoDrainBounds(timeoutMs, parsePosInt(await engine.getConfig('autopilot.auto_drain.window_seconds'), 120), AI_CHAT_TIMEOUT_MS);const maxUsdPerDay = parseNonNegFloat(await engine.getConfig('autopilot.auto_drain.max_usd_per_day'), 2.0);// Each drain attempt runs under one BudgetTracker capped at ~$0.30// (cycle.extract_atoms.budget_usd); bound the brain-wide daily attempt@@ -537,7 +539,7 @@ export async function submitAutoDrains(}const job = await queue.add('extract-atoms-drain',- { sourceId: src.id, window: windowSeconds, ...(kind === 'checkout' ? { repoPath: src.local_path } : {}) },+ { sourceId: src.id, window: bounds.windowSeconds, ...(kind === 'checkout' ? { repoPath: src.local_path } : {}) },{queue: 'default',idempotency_key: idemKey,@@ -545,7 +547,7 @@ export async function submitAutoDrains(// all-provider-failed batch, so give the queue's// backoff a chance (was 1 — dead-lettered instantly).max_attempts: 3,- timeout_ms: timeoutMs,+ timeout_ms: bounds.timeoutMs,},{ allowProtectedSubmit: true },);diff --git a/src/commands/autopilot-timeout.ts b/src/commands/autopilot-timeout.tsindex c8189a9d3b..b638cdf85c 100644--- a/src/commands/autopilot-timeout.ts+++ b/src/commands/autopilot-timeout.ts@@ -40,3 +40,23 @@ export function resolveAutopilotDispatchTimeoutMs(? Math.max(intervalDerivedTimeoutMs, FULL_CYCLE_TIMEOUT_FLOOR_MS): intervalDerivedTimeoutMs;}++/**+ * Co-stamp an automatic atom drain's window and job deadline. The drain+ * checks its window only between items and hard-stops at the job deadline+ * (#5809, dead-lettering the job and aborting the paid call in flight), so+ * the deadline covers the window plus one final item: two chat calls (a+ * schema-rejecting provider retries once) and a minute to publish. The+ * window is clamped so the deadline stays within the full-cycle anchor; a+ * longer interval-derived deadline still wins. Manual drains are unchanged.+ */+export function resolveAutopilotAutoDrainBounds(+ intervalTimeoutMs: number,+ requestedWindowSeconds: number,+ chatTimeoutMs: number,+): { windowSeconds: number; timeoutMs: number } {+ const completionAllowanceMs = Math.ceil(2 * chatTimeoutMs + 60_000);+ const maxWindowSeconds = Math.max(1, Math.floor((FULL_CYCLE_TIMEOUT_FLOOR_MS - completionAllowanceMs) / 1000));+ const windowSeconds = Math.min(Math.max(1, Math.floor(requestedWindowSeconds)), maxWindowSeconds);+ return { windowSeconds, timeoutMs: Math.max(intervalTimeoutMs, windowSeconds * 1000 + completionAllowanceMs) };+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex fecd2bda5d..bdb5a15964 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -100,8 +100,8 @@ function resolveAiTimeoutMs(envVar: string, fallback: number): number {const n = Number(raw);return Number.isFinite(n) && n > 0 ? n : fallback;}-/** chat / expansion / OCR — generous; only catches true hangs (non-streaming generateText). */-const AI_CHAT_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_CHAT_TIMEOUT_MS', 300_000);+/** chat / expansion / OCR — generous; only catches true hangs (non-streaming generateText). Also sizes the auto-drain job deadline. */+export const AI_CHAT_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_CHAT_TIMEOUT_MS', 300_000);/** embed sub-batch (per SDK call, NOT per whole import). */const AI_EMBED_TIMEOUT_MS = resolveAiTimeoutMs('GBRAIN_AI_EMBED_TIMEOUT_MS', 60_000);/** multimodal per request. */diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3fe21ecd8e..1ba61f5d00 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -910,6 +910,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: '`gbrain dream --drain` no longer exits 11 for every incomplete stop. A stop running again cannot clear now exits 1 with a `Fix:` line instead of a rerun hint: a provider failure on every item caused by auth, billing, an unknown model or a content block (`atom_drain_provider_failure`), and `no_progress` over a counted backlog (`atom_drain_no_progress`). A rate limit, a transient provider failure, the window, budget, batch cap, deadline, lock and an unknown backlog count still exit 11 with the rerun command. `--json` of an incomplete stop now reports `status` `incomplete` or `provider_failure` (never `ok`) with `retryable`, `code` and `reason`, and the help no longer says exit 3. The `extract-atoms-drain` job dead-letters an auth, billing, unknown-model or content-block failure at once instead of retrying it.' },{ since: '0.60.307.0', text: '`gbrain transcripts ingest --format <f>` now refuses a symlink or an unreadable path before parsing, as auto-detection already did, instead of handing the path to the adapter. A refused file is reported per file with its cause and next step (an unreadable path carries its `errno`, for example ENOENT or EACCES); the rest of the run still imports.' },{ since: '0.60.307.0', text: 'A Claude Code session that ended with no conversation (only session bookkeeping and local slash commands such as `/rename`) is now reported by the session-end hook as `empty_session` instead of `parser_drift`, so the next session no longer shows a transcript-ingestion alert for it. A record that carries a message but yields no turn, or a file of only unknown records, still reports `parser_drift`.' },+ { since: '0.60.307.0', text: 'Autopilot\'s automatic atom drain (`extract-atoms-drain` jobs) now gets a job deadline that covers its window plus one final item (two chat timeouts and a minute), instead of the shorter interval-derived deadline that stopped and dead-lettered drains mid-call. `autopilot.auto_drain.window_seconds` is clamped so the deadline stays within 30 minutes (a window of up to 1140 s at the default chat timeout).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/autopilot-auto-drain-dispatch.test.ts b/test/autopilot-auto-drain-dispatch.test.tsindex e73058a363..0fab1825ac 100644--- a/test/autopilot-auto-drain-dispatch.test.ts+++ b/test/autopilot-auto-drain-dispatch.test.ts@@ -15,6 +15,7 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { submitAutoDrains, AUTO_DRAIN_NEXT_KIND_KEY } from '../src/commands/autopilot-dispatch.ts';+import { resolveAutopilotAutoDrainBounds } from '../src/commands/autopilot-timeout.ts';import { withEnv } from './helpers/with-env.ts';let engine: BrainEngine;@@ -68,12 +69,12 @@ async function connectorSource(id: string, type: 'email' | 'meeting' = 'email',}}-async function tick(now = DAY1): Promise<string> {+async function tick(now = DAY1, timeoutMs = 60_000): Promise<string> {let stderr = '';const write = process.stderr.write.bind(process.stderr);process.stderr.write = ((chunk: string | Uint8Array) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;try {- await withEnv({ GBRAIN_HOME: home }, () => submitAutoDrains(engine, queue, { timeoutMs: 60_000, jsonMode: true, now: () => now }));+ await withEnv({ GBRAIN_HOME: home }, () => submitAutoDrains(engine, queue, { timeoutMs, jsonMode: true, now: () => now }));} finally { process.stderr.write = write; }await engine.executeRaw("UPDATE minion_jobs SET created_at=$1::timestamptz WHERE idempotency_key LIKE '%:' || $2",[new Date(now).toISOString(), new Date(now).toISOString().slice(0, 10)]);@@ -171,3 +172,34 @@ test('managed brain: a source whose writer preflight would refuse is skipped witexpect(skip).toMatchObject({ source_id: 'git-unowned' });expect(skip.reason).toContain('requires the configured canonical owner');});++test('automatic drain window and job deadline are bounded together', () => {+ // The drain hard-stops at the job deadline (#5809); its soft window is only checked between+ // batches. The deadline must cover the window plus a final chat call (two on a schema retry).+ expect(resolveAutopilotAutoDrainBounds(600_000, 120, 300_000)).toEqual({ windowSeconds: 120, timeoutMs: 780_000 });+ expect(resolveAutopilotAutoDrainBounds(600_000, 900, 300_000)).toEqual({ windowSeconds: 900, timeoutMs: 1_560_000 });+ expect(resolveAutopilotAutoDrainBounds(600_000, Number.MAX_VALUE, 300_000)).toEqual({ windowSeconds: 1140, timeoutMs: 1_800_000 });+ expect(resolveAutopilotAutoDrainBounds(3_600_000, 900, 300_000)).toEqual({ windowSeconds: 900, timeoutMs: 3_600_000 });+ expect(resolveAutopilotAutoDrainBounds(600_000, 900, 300_000.5)).toEqual({ windowSeconds: 900, timeoutMs: 1_560_001 });+ // A chat timeout that leaves no room under the anchor still gets a deadline covering its one-second window.+ expect(resolveAutopilotAutoDrainBounds(600_000, 900, 869_600)).toEqual({ windowSeconds: 1, timeoutMs: 1_800_200 });+});++for (const row of [+ { setting: null, interval: 600_000, window: 120, timeout: 780_000 },+ { setting: '900', interval: 600_000, window: 900, timeout: 1_560_000 },+ { setting: '86400', interval: 600_000, window: 1140, timeout: 1_800_000 },+ { setting: '900', interval: 3_600_000, window: 900, timeout: 3_600_000 },+]) {+ test(`queued drain covers window ${row.setting ?? 'default'} at a ${row.interval}ms dispatch deadline`, async () => {+ if (row.setting !== null) await engine.setConfig('autopilot.auto_drain.window_seconds', row.setting);+ await gitSource('git-a');+ await tick(DAY1, row.interval);+ const jobs = await engine.executeRaw<{ window: number; timeout_ms: number }>(+ "SELECT (data->>'window')::int AS window, timeout_ms FROM minion_jobs WHERE name='extract-atoms-drain'");+ expect(jobs).toHaveLength(1);+ expect(Number(jobs[0].window)).toBe(row.window);+ expect(Number(jobs[0].timeout_ms)).toBe(row.timeout);+ expect(Number(jobs[0].timeout_ms)).toBeGreaterThan(row.window * 1000);+ });+}diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 0e97007f1e..99e549e65f 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -447,6 +447,7 @@"splitBody"],"./ai/gateway": [+ "AI_CHAT_TIMEOUT_MS","DEFAULT_EMBEDDING_DIMENSIONS","DEFAULT_EMBEDDING_MODEL","DEFAULT_MAX_OUTPUT_TOKENS",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex f20dbe7d58..c445785d38 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1689,6 +1689,13 @@}],"./ai/gateway": [+ {+ "kind": "variable",+ "name": "AI_CHAT_TIMEOUT_MS",+ "signature": [+ "number"+ ]+ },{"kind": "type","name": "ChatBlock",