Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
56.4 KB
Raw Blame

Key files: Core Minions (2/2)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/core/minions/queue.ts — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). prune() archives each completed dream:synth% subagent key into dream_synthesis_completions in the same statement that deletes the row, so pruning never re-arms paid synthesis. add() takes a 4th trusted arg (separate from opts to prevent spread leakage); protected names in PROTECTED_JOB_NAMES require {allowProtectedSubmit: true} and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries {allowPgliteInlineWorker: true}, a narrowly scoped exception used only when gbrain jobs submit embed-backfill --follow starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, add() invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. add() plumbs max_stalled through with a [1, 100] clamp; omitted values let the schema DEFAULT (5) kick in. handleWallClockTimeouts(lockDurationMs) is Layer 3 kill shot for jobs where FOR UPDATE SKIP LOCKED stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one pg_advisory_xact_lock namespace keyed on (name, queue, source): maxWaiting (rate cap, counts waiting only, NULL-source-as-wildcard scope) and maxPending (single-flight, counts waiting + live-lock active rows where lock_until > now(), EXACT source scope via COALESCE(data->>'sourceId', data->>'source_id') — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted coalesced: true metadata on the returned job. Both filter on queue in addition to name so cross-queue same-name jobs don't suppress each other. claim and renewLock issue their UPDATE via engine.executeRawDirect (not executeRaw) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to executeRaw. The two terminal dead-letter paths (handleWallClockTimeouts wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment attempts_made so a long job killed there reads as an honest attempt instead of attempts 0 / started N; the stall path also bumps stalled_counter, surfaced by gbrain jobs get as Attempts: M/N (started: X, stalled: S/MaxS). At submit, add() stamps a default timeout_ms via defaultTimeoutMsFor(jobName) (from handler-timeouts.ts) when the caller passed none, and claim() COALESCEs a still-NULL timeout_ms from HANDLER_DEFAULT_TIMEOUT_MS (raw-object jsonb bind) deriving timeout_at from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit opts.timeout_ms always wins. The lock lease follows the identical three-layer shape: add() stamps opts.lock_duration_ms (clamped [5s,1h] via the shared clampLockDurationMs; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else defaultLockDurationMsFor(jobName); claim() derives lock_until from COALESCE(lock_duration_ms, map, worker default) and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; handleWallClockTimeouts' null-timeout fallback uses COALESCE(lock_duration_ms, worker default). handleStalled(graceMsOverride?) applies the stall-sweep reclaim grace (GBRAIN_MINION_STALL_RECLAIM_GRACE_MS, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by test/queue-lock-retry.test.ts (claim never falls back to executeRaw), test/postgres-execute-raw-direct.test.ts (routing decision matrix), and test/minions.test.ts (attempt accounting + default-timeout stamping). MinionQueue.add() gates subagent jobs on capability, not provider: data.model is classified via classifyCapabilities() (lazy-imported from src/core/ai/capabilities.ts to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (unusable:no_tools) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: model-config.ts:enforceSubagentCapable runtime fallback + src/commands/doctor/checks/search-eval.ts subagent_capability check). Pinned by test/agent-cli.test.ts. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private killJobs(tx, rows, cause, message) tail: it emits child_done(outcome) to each non-terminal parent's inbox and flips any waiting-children parent whose last open child just died back to waiting — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via lockParentsOrdered (ascending-id row locks, matching failJob's parent-before-child order) so the reapers and failJob can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any waiting-children parent with zero non-terminal children flips back to waiting (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears started_at (failJob's delayed retry branch, the stall requeue, lease release, promoteDelayed, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by test/queue-stall-parent-unblock.test.ts + test/queue-started-at-retry.test.ts. renewLock accepts optional {signal} forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as data.__released_idempotency_key, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's spendAuthorization stores a consent-gated producer's record in spend_authorization (never job data); a coalesced live row with no record or a legacy_default record adopts it by compare-and-set, an authorized row keeps its own. claim() sets spend_claim_token = claim_generation + 1 (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of book-mirror:/enrich:/cli:enrich: keys legacy_default in the same UPDATE. claim(..., { excludeWatchdogSuspects }) skips jobs carrying WATCHDOG_SUSPECT_MARK (re-exported from watchdog-attribution.ts) for a worker with jobs in flight; releaseWatchdogClaim is the token-fenced uncharged release; handleStalled first passes its candidates to requeueCoRunnerStalls. #7240: add passes job data through jsonbSafeJson (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; failJob takes an optional result (a refused job's refusal, #7239). GST-2260: completeJob and failJob run their database-only transaction once more when a stale plan aborted it (retryOnStalePlan), so a column another process added to minion_jobs never fails a job whose handler already ran (test/stale-plan-heal.test.ts).

  • src/core/minions/queue-families.ts — queueFamilyStats(engine, since) behind MinionQueue.getStats().by_queue: one row per queue (waiting_now/active_now now; total/completed/failed/dead among rows created in the window, the by_type semantics), with every per-run dream-inline-* queue folded into one dream-inline row whose queues counts them. gbrain jobs stats prints a line per row (dream-inline (N queues)) and carries by_queue in --json; get_job_stats spreads it too. --queue <name> still scopes the wedge block to one queue. Test: test/jobs-stats-private-queue.serial.test.ts.

  • src/core/minions/rate-leases.ts — lease-based concurrency cap for outbound providers (default key anthropic:messages, max via GBRAIN_ANTHROPIC_MAX_INFLIGHT). Owner-tagged rows with expires_at auto-prune on acquire; pg_advisory_xact_lock guards check-then-insert; CASCADE on owning job deletion. renewLeaseWithBackoff retries 3x (250/500/1000ms). Canonical home of RateLeaseUnavailableError (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; subagent.ts re-exports it for compatibility) and leaseFullBackoffMs() (the shared 1–3s jittered lease-full requeue backoff worker.ts and inline-drain.ts both use, so the two curves cannot silently desync).

  • src/core/minions/refusal.ts — #7239: jobRefusal(err) decides whether a handler error is a deterministic refusal from its error-registry code: a site retryable wins, else a caller/consent/host_only code the registry does not mark retryable, except the concurrency codes (revision_conflict, page_identity_changed, concurrent_write); classes retryable/server/unavailable, unregistered codes and code-less errors are not (a code-less error is looked through to its cause; other UnrecoverableErrors keep their own path). The worker's executeJob catch and the dream inline drain end such a job dead after one attempt with refusedJobResult (job_outcome: 'refused', refusal: {code, reason, message, fix, docs_cmd}); the suggestion prose is never stored (job rows are served remotely). Across the per-job child boundary it travels as errorKind refused and is rebuilt as JobRefusedError (errors.ts). Tests: test/minions-refusal-7239.test.ts.

  • src/core/minions/rss-default.ts — cgroup-aware auto-sized default for the worker RSS watchdog cap. resolveDefaultMaxRssMb(opts?) / describeDefaultMaxRss(opts?) (provenance for the startup log) / readCgroupMemLimitBytes(readFile?). Used at every spawn site (jobs work, jobs supervisor, autopilot, MinionSupervisor). Formula clamp(round(0.5 × basisMB), 4096, 16384) where basis = min(cgroupLimit, totalmem). LOAD-BEARING NUANCE: plain os.totalmem() reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 /sys/fs/cgroup/memory.max (literal max = unlimited) then v1 /sys/fs/cgroup/memory/memory.limit_in_bytes. Explicit --max-rss (including 0 to disable) always wins. Pinned by test/rss-default.test.ts.

  • src/core/minions/run-child.ts — runChildJobEntry(engine, opts, injectables): the jobs run-child core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler under runWithJobSpend (the job's spend authorization), writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling process.kill(parentPid, 0) (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by test/run-child-entry.test.ts. #7245: before the handler it compares its build with the worker's (parentBuild, the GBRAIN_JOB_PARENT_BUILD env runJobInChild sets from parentBuildEnvValue) through jobChildBuildVerdict (child-readiness.ts): a differing version runs, with one job_build_skew: history entry and one stderr line; a readiness-protocol mismatch or a required feature the child lacks writes the entry and a child_protocol_incompatible configuration outcome (exit 16) without running the handler, so the worker blocks for configuration as the startup handshake does. A worker that sends no build (older) gets no comparison. Pinned by test/runtime-build-skew-7245.test.ts.

  • src/core/minions/spawn-helpers.ts — pure detectTini() + buildSpawnInvocation() consumed by both supervisor.ts and autopilot.ts (one implementation for both spawn sites; tini wrapping is testable without mock.module(), rule R2 of scripts/check-test-isolation.sh). detectTini() calls execFileSync('which', ['tini']) with explicit env: process.env so Bun sees runtime PATH mutations. buildSpawnInvocation(tiniPath, cmd, args) returns {cmd, args} with tini -s -- prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by test/spawn-helpers.test.ts (5) and test/supervisor-tini.test.ts (4).

  • src/core/minions/spend-authorization.ts + spend-record.ts — submit-time spend authorization on queued paid jobs. spend-record.ts holds the stored shape (version, kind authorized/legacy_default, group_id, of, cap_usd or uncapped, cap_source, via, command, est_usd, argv, authorized_at), its strict parser and spendBasis (authorized, legacy_default, unrecorded, invalid with a why). jobSpendAuthorization(auth, {command, est_usd, of, argv}) builds a group from a consent Authorization; legacyDefaultClaimSetSql is the claim's fence and legacy stamp. runWithJobSpend(engine, job, ctx, handler) runs at both handler seams (worker, run-child; the dream inline drain only claims private-queue subagents, which never carry an authorization): NULL rows run as before, uncapped records reserve nothing, capped records run under withAIInvocationGuard (nested) so each provider attempt reserves its maximum against group:<id> and settles measured usage. Settled exhaustion (or an unpriced model under a user cap) throws SpendGroupRefusedError (derived_cap_exhausted/cost_cap_exceeded/no_pricing, group amounts, rerun fix with twice the cap) and records it as result.spend_refusal; live-hold pressure throws SpendGroupPressureError (a lease release, at most MAX_PRESSURE_RENEWALS = 6, counted from minion_lease_pressure_log); unpriced models under derived/default caps warn and run. Every claimed paid job logs one job_spend_basis line. spendSubmitSummary prints the producer's group, kept authorizations (with gbrain jobs cancel --group) and reused rows; groupJobs/jobGroupAmounts back jobs list --group/jobs cancel --group/jobs get. Tests: test/minions-spend-authorization.test.ts, test/minions-spend-authorization.serial.test.ts, test/minions-spend-enforcement-child.test.ts.

  • src/core/minions/subagent-stop-reason.ts — the one home of the subagent handler's stop-reason mapping (#6448 items 2/3): isEmptyFinalText (empty or whitespace-only text); directStopReason for the Messages path (max_tokens → max_tokens, refusal → refusal, a clean stop whose final text is empty → error); gatewayStopReason for toolLoop (length → max_tokens, refusal/content_filter → refusal, empty_response/aborted/unrecoverable → error, end → end_turn); replayTerminalStopReason for a persisted terminal turn (tokens_out >= cap → max_tokens, empty text → error, else end_turn). On both replay paths in handlers/subagent.ts ANY trailing assistant turn without tool calls is terminal, text or not, so a thinking-only or empty tail is answered from the transcript instead of being re-sent as an assistant prefill; the gateway's empty_response stop reason is additive (gateway.ts ToolLoopStopReason). Pinned by test/subagent-stop-reason-6448.test.ts and test/subagent-stop-reason-helper.test.ts.

  • src/core/minions/submission-authority.ts — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. coalesceDecision(rawRow, authority) is the one coalesce rule for all five MinionQueue.add coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with LEGACY_AUTHORITY_COLUMN so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the legacy_job_authority catalogue error); UNREVIEWED_LIVE_JOBS_WHERE is the claim gate's predicate, shared with doctor legacy_job_authority. Tests: test/minions-legacy-coalesce.test.ts (PGLite) and test/e2e/minions-legacy-coalesce-postgres.test.ts, both over test/helpers/legacy-coalesce-matrix.ts. src/core/minions/authorize-legacy.ts provides explicit local preview and transactional snapshot comparison for selected historical rows: --ids, or --select <filter> whose preview saves the exact id set under a hash of the filter and the snapshot digest with saveApprovedSet (preview-approval helper) so --expect <hash> --yes authorizes exactly that set; every refusal is a catalogue error (legacy_job_selection_invalid, legacy_jobs_active, preview_changed). src/core/minions/source-filesystem.ts provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: docs/guides/authorization-upgrade.md.

  • src/core/minions/supervisor-pid.ts — readSupervisorPid(pidFile) → {pid, running, host?}: the shared existsSync → readFileSync → parseInt → process.kill(pid,0) PID-file + liveness reader shared by jobs.ts (supervisor status), jobs.ts (stats), and doctor.ts. EPERM from the liveness probe counts as running. pidFileContents(pid, host = hostname()) writes three lines: the pid, the kernel start time (empty when unknown; jobs supervisor stop reads it as the recycled-pid fence) and, since PR #6463, the hostname the supervisor puts in its DB lock, which readSupervisorPid returns as host (absent on an older two-line file). Pinned by test/supervisor-pid.test.ts, test/supervisor-singleton-host-6463.test.ts. #7245: lines 4 and 5 are the supervisor's gbrain VERSION and the package root it loaded from (empty in a compiled binary); readSupervisorBuild reads them (null for an older file) and readSupervisorPid stays unchanged.

  • src/core/minions/supervisor.ts — MinionSupervisor process manager. Spawns gbrain jobs work as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal cliArgsPrefix carries source-entrypoint arguments while explicit --cli-path remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. OwnerProcessingState supplies additive live readiness and redacted runtime identities. consecutiveHealthFailures counter; on 3 consecutive failures emits health_warn with reason: 'db_connection_degraded' and calls engine.reconnect() to swap in a fresh pool, then resets. Worker exit classifier emits likely_cause on worker_exited events: oom_or_external_kill (SIGKILL), graceful_shutdown (SIGTERM), runtime_error (code 1), clean_exit (code 0), unknown. Consumes detectTini() + buildSpawnInvocation() from src/core/minions/spawn-helpers.ts to wrap the worker subtree in tini -s subreaper mode when tini is on PATH (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes isTiniDetected read-only accessor. The spawn-and-respawn loop is the shared ChildWorkerSupervisor core: MinionSupervisor composes it via runSuperviseLoop() → new ChildWorkerSupervisor({...}) and maps ChildSupervisorEvent back through emit() SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and process.exit on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (maxCrashes) does not permanently give up: the core drops into degraded retry (capped backoff + a crash_budget_degraded health_warn) and self-heals when a respawn runs stably; permanent process.exit(MAX_CRASHES) fires only at the hard ceiling resolveHardStopMaxCrashes(maxCrashes) (default maxCrashes × 10, env GBRAIN_SUPERVISOR_HARD_STOP_CRASHES, 0 = never). Separately, gbrain jobs supervisor status + gbrain doctor detect a live supervisor through this queue lock (inspectLock + isLockHolderLive, freshness-keyed so PID reuse can't false-positive) when the $HOME-derived pidfile is absent, so a split-$HOME deployment does not read a healthy supervisor as "not running". code=0 leaves crashCount untouched (so a worker alternating real crashes + watchdog drains still trips max_crashes); cleanRestartBudget (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via health_warn { reason: 'clean_restart_budget_exceeded' } + backoff. shutdown() drains via childSupervisor.killChild('SIGTERM') + awaitChildExit(35_000). Progress watchdog: healthCheck() restarts an alive-but-wedged child via childSupervisor.restartCurrentChild(35_000) when a queue has claimable work, 0 live-lock active jobs, and stale completions across wedgeRestartChecks (default 3) consecutive checks past wedgeRestartMinutes (default 15, 0 disables) + a startupGraceMs window; bounded by wedgeRestartLoopBudget (default 3 / wedgeRestartLoopWindowMs) which switches to a one-shot wedge_restart_loop alert. The wedge query is the exported queryWedgeSignals(engine, queue, handlerNames) — name+queue-scoped, active_healthy = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway registerBuiltinHandlers worker (its new quiet opt). Flags --wedge-restart-minutes / --wedge-restart-checks + env GBRAIN_WEDGE_RESTART_MINUTES / GBRAIN_WEDGE_RESTART_CHECKS. The worker argv is built by the exported pure buildWorkerArgs(opts) (appends --nice N when opts.nice_requested is set, alongside --concurrency/--queue/--max-rss); the niceness apply RESULT (nice_requested/nice_effective/nice_error, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the started/worker_spawned audit emissions. Queue-scoped singleton: the real authority is a DB lock (tryAcquireDbLock from src/core/db-lock.ts) keyed on supervisorLockId(queue) = gbrain-supervisor:<queue> — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different $HOME/--pid-file against the same (database, queue) cannot both run with conflicting --max-rss: the second exits LOCK_HELD. The pidfile-cleanup process.on('exit') listener is installed BEFORE the DB-lock acquisition so the LOCK_HELD early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (supervisor-<brainId>.pid) so different brains under one HOME don't false-block. The lock refreshes on its own setInterval (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits LOCK_LOST (code 4) rather than risk a split-brain, while a fenced refresh returning false (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits health_error { reason: 'supervisor_lock_lost' } and exits LOCK_LOST immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). shutdown() releases the lock so a clean restart re-acquires immediately. The started audit records max_rss_mb so gbrain doctor's supervisor_singleton check can surface the effective cap. Exports supervisorLockId() and the pure classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch' (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by test/supervisor.test.ts (16 cases), test/supervisor-tini.test.ts, test/supervisor-wedge.test.ts, test/supervisor-build-worker-args.test.ts, and test/supervisor-db-lock.test.ts. SupervisorOpts.jobIsolation passes --job-isolation process to the spawned worker via a CONDITIONAL buildWorkerArgs push (inline argv stays byte-identical). queryWedgeSignals/probeQueueState thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). buildWorkerArgs also appends --allow-shell-jobs when opts.allowShellJobs (conditional push like --job-isolation, so existing argv stays byte-identical; pinned by test/supervisor-build-worker-args.test.ts). Rationale: the worker's startup cwd-.env quarantine drops GBRAIN_ALLOW_SHELL_JOBS whenever a .env in the worker's cwd assigns it, so the env copy in runSuperviseLoop alone could silently disable shell jobs; jobs work parses the flag and re-sets process.env.GBRAIN_ALLOW_SHELL_JOBS='1' after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). allowShellJobs sets the env var on the child AND pushes --allow-shell-jobs. #5062: registers as the CLI signal owner; shutdown() is one shared promise (repeated signals join it) that keeps refreshing the queue lock while the worker drains (SIGTERM, 35s, SIGKILL by liveness, 5s confirmation), then releases the lock and emits stopped with drained / worker_forced / worker_exit_code / lock_released. gbrain jobs supervisor stop (src/commands/jobs/supervisor.ts) reports drained only when the pid is gone, the supervisor's own stopped row follows its shutting_down with drained: true, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (no_stopped_event, worker_still_running, lock_unverified, lock_still_held, forced) and exits 1. W9F item 7: the rows it reads are the run's own (readSupervisorRun in supervisor-audit.ts: from the supervisor pid's last started row, searching back up to SUPERVISOR_RUN_LOOKBACK_WEEKS weekly files, so a run started before the ISO-week boundary keeps its spawns); worker_exited rows carry the child's pid (null when no process was created) and worker_spawned rows its kernel start time (pid_start), so the live set is spawns with no later exit whose pid is still alive with the recorded start time (a recycled pid is not a live worker; pre-upgrade exit rows without a pid key pair with spawns by order and add warnings: ['legacy_exit_pairing']); a run with no started row on record reports unverified (exit 1, audit_files listed), never drained. The PID file now holds the pid and, on Linux, its start time on a second line (pidFileContents in supervisor-pid.ts, which also stamps audit rows through processStartStamp; every reader takes the first line), and started records supervisor_start: when the pid is alive with a different start time, stop reports stale_pid_file (exit 0, stopped: false) and signals nothing. Process start times come from processStartTime in src/core/pglite-lock.ts (moved from graduation-custody.ts, which re-exports it). Pinned by test/jobs-supervisor-stop-identity.test.ts.

  • src/core/minions/idle-wait.ts — GBRA-133 2a.4: IdleWaiter, the worker claim loop's idle poll wait. wake(reason) ends a wait in progress; a wake while the loop is claiming makes the next wait() a no-op (skipped) instead of being lost, and claimStarted() clears it. idle says whether a wait is in progress; history keeps the last 100 waits and how each ended (timer, wake with its reason, skipped, stop), the decisions test/pathological/s-sync-queue-wake.test.ts asserts on.

  • src/core/autopilot-heartbeat.ts — #7003: the autopilot daemon's heartbeat sidecar autopilot.heartbeat.json beside the lock (autopilotHeartbeatPath() in src/core/autopilot-paths.ts), written by autopilot-daemon.ts at the top of every tick (phase cycle) and before every sleep (phase sleep, next_tick_at). daemonStaleAfterSeconds grades it against the lock: stale once the lock is older than the next tick plus max(base interval, 120 s), or 6 x the daemon's base interval mid-cycle; null (the caller's flag rule) for a missing sidecar, one from another pid than the lock, or one older than the lock. readDaemonStaleAfter reads the lock's mtime and pid and applies it for gbrain autopilot --status. Tests: test/pathological/s-7003-autopilot-heartbeat.test.ts + its Postgres twin.

  • src/core/checkout-head.ts — GBRA-133 2a.4: readCheckoutHead(root) for the autopilot HEAD probe: the git directory from the checkout's own .git entry (enclosingGitMetadata, src/core/persistence/root-registry.ts), one bounded git rev-parse HEAD HEAD:./ (null for a root the enclosing checkout does not track, such as a connector clone under a dotfiles home; execFileBounded, 5 s, GIT_OPTIONAL_LOCKS=0), and which GIT_OPERATION_MARKERS entry (rebase, merge, cherry-pick, revert) is present. Null when git cannot read HEAD.

  • src/core/minions/sync-queue-wake.ts — GBRA-133 2a.4: wakes an idle gbrain jobs work claim loop when a sync job turns waiting in its queue. chooseSyncQueueWake(engine, env) picks listen only on a detected direct session (the engine's dual-pool direct route, or a pool whose prepare is not off, read through consumerConnectionRoute in persistence/consumer-lane.ts), poll behind a transaction pooler or an unknown pooler mode, off on PGLite or with GBRAIN_WORKER_SYNC_WAKE=0. startSyncQueueWake LISTENs on the minion_jobs channel (the schema's notify_minion_job_change trigger) and requires a probe NOTIFY to arrive within 3 s, else it polls; the poll reads one minion_jobs row every GBRAIN_WORKER_SYNC_WAKE_POLL_MS (default 1 s, 250 ms-5 s) only while the worker is idle. It logs one line naming the mode and never throws; the worker's own poll stays the backstop. Tests: test/pathological/s-sync-queue-wake.test.ts + test/e2e/s-sync-queue-wake-postgres.test.ts (listed in scripts/e2e-backend-matrix.txt, so it also runs through PgBouncer).

  • src/core/minions/tool-write-identity.ts — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. awaitCommittedToolWrite(job, toolName, dispatch) wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through replayWhilePending (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than WIRE_WRITE_WAIT_MAX_MS plus WRITE_ADMISSION_HEADROOM_MS (45 s); a job without a deadline replays for the MaintenanceWriteWait base (30 s). Only then does the write leave the handler as write_pending, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal failed receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by test/subagent-handler.test.ts, test/minions/subagent-pending-write-runners.test.ts, test/minions/subagent-oneshot.test.ts and test/e2e/subagent-gateway-resume-reconciliation.test.ts.

  • src/core/minions/tools/brain-allowlist.ts — derives the subagent tool registry from src/core/operations.ts (13-name allow-list in the handler-free brain-tool-allowlist.ts, which src/mcp/surface.ts reads, size pinned by test/brain-allowlist.test.ts). Attachment tools file_list and file_url are excluded. Registry construction and execution reject every localOnly operation; selectAllowedTools rejects malformed bindings and preserves explicit empty lists as no tools. Includes add_timeline_entry (the canonical timeline write), fenced server-side by the same enforceSubagentSlugFence policy as put_page. By default put_page schema is namespace-wrapped per subagent (^wiki/agents/<subagentId>/.+). When BuildBrainToolsOpts.allowedSlugPrefixes is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with allowedSlugPrefixes — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus delegatedAuth. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. BuildBrainToolsOpts.deferEmbeds (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads OperationContext.deferEmbeds so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes get_recent_salience + find_anomalies but deliberately NOT get_recent_transcripts (all subagent calls run ctx.remote === true and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls discoverTranscripts directly instead). paramsToInputSchema() consumes paramDefToSchema from src/mcp/tool-defs.ts; required-aggregation at the tool-def level stays here (the shared helper is per-param). execute() runs the same validateParams the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with <tool>: Missing required parameter: <name> the model can act on, instead of a handler crash. putPageRejection classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by persistence/page-input.ts only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent get_page with include_content: true is forced to content_only: true, so the body arrives once (as content) instead of also as parsed compiled_truth/timeline. BuildBrainToolsOpts.readBudgetBytes (from trusted SubagentHandlerData.read_budget_bytes) routes get_page results through read-budget.ts. #6779: a subagent put_page refused revision_required names the page's current revision (rethrowWithCurrentRevision in put-page-result.ts); MCP and CLI callers keep the bare refusal. A remote-owned job tool call runs the same requester-scope gate as dispatch (scopedJobAccess), read live per call.

  • src/core/minions/tools/read-budget.ts — #6297 per-job get_page byte budget: budgetedPageRead counts bytes already returned from the job's subagent_tool_executions rows (brain_get_page, complete), so a replayed job keeps its spend, and past the budget returns a summary (truncated: true, code: read_budget_exhausted, slug/title/type, the revision (#6779, so a child can still append or skip), a bounded prefix of the result's rendered content/text of at most READ_BUDGET_EXCERPT_BYTES; sizes are result bytes, never a body read, so segmented pages need no body string) instead of the page.

  • src/core/minions/transcript.ts — renders subagent_messages + subagent_tool_executions to markdown. Tool rows splice under their owning assistant tool_use by (message_idx, tool_use_id) — raw provider tool ids may repeat across turns, so tool_use_id alone is not an identity; echoed tool_result blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.

  • src/core/minions/types.ts — MinionJobInput + MinionJobStatus + handler context types. MinionJobInput.max_stalled is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to [1, 100]. SubagentHandlerData.require_writes requires at least one settled successful page write, not merely a clean model finish, except the deliberate zero-write completions isLegitimateZeroWrite accepts (an explicit oneshot skip, or an allow_clean_zero_writes child with a completed tool execution). SubagentHandlerData.corpus_source pins a synthesis child's session-corpus file, corpus dir and source incarnation (#7850).

  • src/core/minions/wait-for-completion.ts — poll-until-terminal helper for CLI callers. TimeoutError does NOT cancel the job; AbortSignal exits without throwing. Default pollMs: 1000 on Postgres, 250 on PGLite inline. isTerminalJobStatus is the one terminal-status test. Consumers: gbrain jobs wait (src/commands/jobs/wait.ts: exit 0 completed, 1 failed/dead/cancelled, 124 still running at --timeout, 2 usage; a thin client loops over MCP wait_job) and the wait_job op (ops/jobs.ts: the get_job owner fence runs before any wait, so a foreign id refuses at once with get_job's exact error; one call holds at most WAIT_JOB_MAX_S = 55 s and returns the get_job row plus terminal). Pinned by test/minions/job-insight.test.ts and test/jobs-wait-cli.serial.test.ts.

  • src/core/minions/job-insight.ts — #7241 fields computed on read for jobs get/list --json, get_job, list_jobs and wait_job: submitted_by, blocked_by (queue position and slot holders, waiting children, delay reason, paused, unreviewed authority, held gbrain-sync:<src> / gbrain-cycle:<src> locks with the holder job from the drain-lease beacon row), lease liveness (heartbeat_age_ms from lock_until - lock_duration_ms, else a lower bound from updated_at, heartbeat_basis says which; lock_expires_in_ms; stalled) and spend (token columns plus cost_usd from settled mcp_spend_reservations of the job and its descendants; null / unpriced when none, never 0). All times use the DB clock. Owner fence: for an agent token without admin a foreign submitter, parent, slot holder or lock holder is its kind only ({kind:'lock', held:true}), foreign descendants are left out of cost, and completed foreign children's tokens (completeJob rolls them into the parent) are subtracted, replacing the row's top-level token counts too; a remote caller never sees a lock holder's host or pid. withSubmitterLabel (called by MinionQueue.add on the stored data) always drops a caller-supplied __submitter and, for an application-authority submit from a labelled local process, stores submitterLabel() (autopilot, serve, worker, job:<name>, cli:<command>; library stores nothing) as job data __submitter. It is a display label only: submission_authority is untouched, PARAM_HASH_EXCLUDED_KEYS (admission.ts) leaves it out of the param hash, the remote submit paths cannot carry it (prepareRemoteJob refuses unknown data keys, submit_agent builds its own data), and describeJobs reads it only for rows whose authority is application. Rows queued before it carry no label.

  • src/core/minions/terminal-events.ts — #7242 append-only terminal event cursor (jobs list --finished-since <iso|cursor> --json, list_jobs {finished_since}): terminal rows ordered by (finished_at, id) at microsecond precision, next_cursor = <epoch micros>:<id>, so pages never repeat or skip; owner-fenced like list_jobs. A retried job that finishes again is a new event; deleted and pruned rows are not.

  • src/core/minions/terminal-hook.ts — #7242 terminal hook: minions.terminal_hook is a FILE-plane key only (commands/config.ts FILE_PLANE_DOTTED_KEYS; a DB-plane row is never read, so MCP, job data and anyone who can only write DB config cannot pick the command). An argv array with an absolute argv[0], spawned with shell: false; the job arrives in GBRAIN_JOB_ID/NAME/QUEUE/STATUS and as fixed-field JSON on stdin (never data or result); killed at timeout_ms (default 10 s), failures logged once, never retried, never failing the job; at most 4 run at once. Runs as the gbrain process user. gbrain jobs work wires terminalHookNotifier into MinionWorkerOpts.onJobSettled, which the worker calls from launchJob's settle (outside executeJob); the notifier re-reads the row and fires only for a terminal status. Pinned by test/minions/terminal-hook.test.ts.

  • __released_idempotency_key reminder: see the idempotency-coalesce.ts entry in core-minions-1.md.

  • src/core/minions/worker-exit-codes.ts — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports WORKER_EXIT_RSS_WATCHDOG = 12 and WORKER_EXIT_CONFIGURATION = 16; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a code===0 → clean_exit classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain likely_cause=rss_watchdog. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the jobs run-child codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).

  • src/core/minions/worker-registry.ts — live worker registry backing niceness observability. Each running gbrain jobs work self-registers worker-<pid>.json under gbrainPath('workers') (brain-isolated via GBRAIN_HOME; entries tagged with currentBrainId() so multiple DBs under one home don't cross-report). registerWorker(info) is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown finally AND process.on('exit') (the unhealthy process.exit(1) bypasses the awaited finally). readWorkers(getNice?) enumerates the dir, drops confirmed-dead pids (classifyLiveness: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free ps -o etime= parsed by parseEtimeToMs, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Only a missing directory (ENOENT) reads as no workers; any other listing failure throws WorkerRegistryUnreadableError (errno + path, read with workerRegistryReadFailure), and every liveness consumer reports unknown instead of zero: doctor queue_health (worker_alive: null, no start-a-worker fix) and wedged_queue, legacy_job_authority (live_workers: null), jobs supervisor status (workers: null), the submit-time probeQueueState (worker_alive omitted, liveness-unknown warning), the migrate-embeddings writer census (workers: null) and the readiness worker probe (probe_failed); each carries worker_registry_unreadable, worker_registry_errno and worker_registry_path. Pinned by test/worker-registry.serial.test.ts. #7245: each entry also carries version (VERSION in memory) and install_root (runtimeInstallRoot(), a local path that no remote output carries); doctor runtime_build_skew reads both.

  • src/core/runtime-build.ts — #7245: runtimeInstallRoot() (the package root this process loaded from; null without a readable package.json, as in a compiled binary), installedVersion(root) (the gbrain package.json version on disk now) and serveBuild() ({version, installed_version, restart_pending} for /health, disk read cached 10 s, never a path).

  • src/core/minions/no-worker.ts — queue honesty (agent-first operator wave E5). queueWorkerAlive(queue, read?) (a live registered worker serves the queue on this host; undefined when the registry is unreadable), runWaitingJobsFix(engineKind, queue) (PGLite: gbrain jobs work [--queue Q], a foreground drain, requires_exclusive; Postgres: gbrain jobs supervisor start), noWorkerNotice(...) (code no_worker, kind degraded). Consumers: CLI jobs submit on PGLite refuses without --follow unless --queue-only (src/commands/jobs/submit.ts); gbrain jobs work on PGLite drains via drainPgliteQueue (src/commands/jobs/work.ts) and exits; MCP submit_job / get_job_stats emit the notice (src/core/ops/jobs.ts, PGLite fix wrapped by readiness exclusiveFix behind a running serve); deriveWedgeSignal(wedge, {workerAlive}) returns no_worker and never calls that case wedged (jobs stats, get_job_stats); doctor queue_health counts PGLite waiting rows (src/commands/doctor/checks/queue-jobs.ts). Pinned by test/queue-no-worker.test.ts.

  • src/core/minions/worker.ts — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The ready event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through MinionQueue.releaseConfigurationJob within one bounded shutdown envelope. The active/token-fenced release returns released, no_op or unconfirmed, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call failJob with reason (timeout/cancel/lock-lost/shutdown); shutdownAbort (instance field) fires on SIGTERM/SIGINT and propagates to ctx.shutdownSignal (shell handler listens; non-shell handlers don't). Per-job timeout fires abort.abort(new Error('timeout')) then a 30s grace-then-evict safety net force-evicts the job from inFlight and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The launchJob lock-renewal block is a thin sync wrapper around the pure runLockRenewalTick from src/core/minions/lock-renewal-tick.ts (NEVER setInterval(async () => await renewLock(...)) — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) cancelled flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard tickInFlight (skips counted as overlapSkips telemetry) + per-call Promise.race timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the hardEvictMs backstop — never bare local arithmetic; the per-job lease (job.lock_duration_ms ?? opts.lockDuration) drives the renewal state, and the cadence clamps to min(lease/2, 60s); (4) explicit .catch() on the stored executeJob(...).finally(...) promise closes the second unhandledRejection vector; (5) exported INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost']) so executeJob's catch skips failJob for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed configurationError latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a perf_hooks.monitorEventLoopDelay histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed abortMeta. CI guard scripts/check-worker-lock-renewal-shape.sh (in bun run verify) asserts the bug pattern stays absent AND launchJob keeps calling runLockRenewalTick. Engine-ownership invariant: start() does NOT call engine.disconnect() on shutdown — the CLI handler in src/commands/jobs.ts case 'work' owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported parseRssFromProcStatus(status) (pure parser; field-presence regex so RssAnon: 0 + RssShmem: 512 parses correctly) and getAccurateRss(readStatus?) (reads /proc/self/status for RssAnon + RssShmem, falls back to process.memoryUsage().rss on macOS / restricted containers / kernel <4.5); the default getRss in WorkerOpts is getAccurateRss. checkMemoryLimit tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets _rssWatchdogTriggered=true (exposed via get rssWatchdogTriggered()) so jobs work's finally can process.exit(WORKER_EXIT_RSS_WATCHDOG) after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps claim in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after UPDATE...RETURNING committed but the socket died would double-claim). LockRenewalDeps is wired with reconnect when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (GBRAIN_SUPERVISED=1): the outer guard is if (this.opts.healthCheckInterval > 0) and only the STALL-detection block is wrapped in if (!isSupervisedChild) — so a supervised worker whose own pool dies self-exits unhealthy(db_dead) after dbFailExitAfter probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the test/worker-lock-renewal.test.ts hermetic suite, test/audit/lock-renewal-audit.test.ts, test/scripts/check-worker-lock-renewal-shape.test.ts, test/worker-shutdown-disconnect.test.ts (asserts disconnectSpy).not.toHaveBeenCalled()), test/worker-rss.test.ts (11), test/worker-supervised-db-probe.test.ts (3). Per-job process isolation: MinionWorkerOpts.jobIsolation (inline|process) + childCliInvocation/childTiniPath swap handler(context) for runJobInChild(...) in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: ChildSpawnInfraError + ChildWorkerShutdownError (released, no attempt burned) and ChildNotClaimedError (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to runDbProbe (db-probe.ts) with a cancellation signal on every probe and emits a verdict (pool_starved/server_unreachable/unknown/client_misconfigured); typed configuration faults block immediately instead of burning the transient DB failure threshold. getHandler(name) is the read-only registry accessor run-child uses. Inline handlers run under runWithJobSpend; an isolated spend-authorized job passes spendAuthorized to the child runner's capability gate. #5062: requestShutdown() is the signal entry point (the jobs work signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (worker-shutdown.ts: token-fenced, no attempt burned, error_text = 'worker_shutdown: <handler error>'); any handler error during shutdown is presumed shutdown-induced (endedByShutdown in worker-shutdown.ts) except UnrecoverableError, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; test/worker-shutdown-error-matrix.test.ts), and claims still running after the 30s drain are handed back the same way with drainForced set, which jobs work turns into exit WORKER_EXIT_DRAIN_FORCED (17). The RSS watchdog's gracefulShutdown(reason) aborts every inFlight job and records the reason; a claim whose UPDATE … RETURNING committed before the shutdown but whose result had not reached the poll loop is not in inFlight yet, so launchJob aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in test/worker-shutdown-error-matrix.test.ts, which holds the claim result until the watchdog has fired). Each inFlight entry carries shared (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to settleWatchdogAbort (back to waiting uncharged, marked to run alone), so only a job that ran alone is charged aborted: watchdog, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job. GBRA-133 2a.4: the idle poll wait (nothing claimed, nothing in flight) goes through idleWaiter (src/core/minions/idle-wait.ts), which the sync-queue wake ends early; claimStarted() runs right before each claim, and stop() and requestShutdown() end the wait at once. Before recording a handler's return, the worker reads it with jobResultOutcome: a reported failure ends the job through failJob(..., 'failed', 0, result) and a partial one completes, each storing jobOutcomeResult. #7966: while autopilotPaused() (either pause marker), the non-supervised stall watchdog restarts its no-progress clock each tick instead of emitting stalled; the DB liveness probe still runs. Doctor's wedged_queue reports a paused queue as warn (details.paused: operator or cooperative) without restart advice. Tests: autopilot-pause-watchdog-7966.test.ts.

  • src/core/minions/watchdog-attribution.ts — RSS watchdog attribution (GBRA-130 A-30). The watchdog measures the whole worker process, so a drain with several jobs in flight cannot name the job that grew: settleWatchdogAbort requeues each such job token-fenced with no attempt burned (error_text WATCHDOG_DRAIN_RELEASE) and appends WATCHDOG_SUSPECT_MARK once to its stacktrace, the job's durable history; a job that ran alone is marked and its caller charges it. An isolated child whose stop is unconfirmed, or any error during the release, leaves the claim to the stall sweep. unmarkedJobSql is the claim filter. requeueCoRunnerStalls requeues, marked and with no stall counted, the stalled claims of a worker that held other expired claims (lock tokens share the <worker id>: prefix, or a co-runner was already requeued with worker_stalled_with_co_runners: <worker id>); a marked or lone job's stall counts as before, so a kernel OOM kill gets the same attribution. Doctor's watchdog-kill counts (error_text = 'aborted: watchdog' on dead/failed rows) therefore count only jobs charged for a solo trip. Pinned by test/pathological/a30-watchdog-attribution.test.ts (both engines) and test/worker-shutdown-error-matrix.test.ts.