Garry's Opinionated OpenClaw/Hermes Agent Brain
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 completeddream:synth%subagent key intodream_synthesis_completionsin the same statement that deletes the row, so pruning never re-arms paid synthesis.add()takes a 4thtrustedarg (separate fromoptsto prevent spread leakage); protected names inPROTECTED_JOB_NAMESrequire{allowProtectedSubmit: true}and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries{allowPgliteInlineWorker: true}, a narrowly scoped exception used only whengbrain jobs submit embed-backfill --followstarts 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()plumbsmax_stalledthrough with a[1, 100]clamp; omitted values let the schema DEFAULT (5) kick in.handleWallClockTimeouts(lockDurationMs)is Layer 3 kill shot for jobs whereFOR UPDATE SKIP LOCKEDstall 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 onepg_advisory_xact_locknamespace keyed on(name, queue, source):maxWaiting(rate cap, countswaitingonly, NULL-source-as-wildcard scope) andmaxPending(single-flight, countswaiting+ live-lockactiverows wherelock_until > now(), EXACT source scope viaCOALESCE(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-persistedcoalesced: truemetadata on the returned job. Both filter onqueuein addition tonameso cross-queue same-name jobs don't suppress each other.claimandrenewLockissue their UPDATE viaengine.executeRawDirect(notexecuteRaw) 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 toexecuteRaw. The two terminal dead-letter paths (handleWallClockTimeoutswall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH incrementattempts_madeso a long job killed there reads as an honest attempt instead ofattempts 0 / started N; the stall path also bumpsstalled_counter, surfaced bygbrain jobs getasAttempts: M/N (started: X, stalled: S/MaxS). At submit,add()stamps a defaulttimeout_msviadefaultTimeoutMsFor(jobName)(fromhandler-timeouts.ts) when the caller passed none, andclaim()COALESCEs a still-NULLtimeout_msfromHANDLER_DEFAULT_TIMEOUT_MS(raw-object jsonb bind) derivingtimeout_atfrom the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicitopts.timeout_msalways wins. The lock lease follows the identical three-layer shape:add()stampsopts.lock_duration_ms(clamped [5s,1h] via the sharedclampLockDurationMs; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) elsedefaultLockDurationMsFor(jobName);claim()deriveslock_untilfromCOALESCE(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 usesCOALESCE(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 bytest/queue-lock-retry.test.ts(claim never falls back toexecuteRaw),test/postgres-execute-raw-direct.test.ts(routing decision matrix), andtest/minions.test.ts(attempt accounting + default-timeout stamping).MinionQueue.add()gatessubagentjobs on capability, not provider:data.modelis classified viaclassifyCapabilities()(lazy-imported fromsrc/core/ai/capabilities.tsto 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:enforceSubagentCapableruntime fallback +src/commands/doctor/checks/search-eval.tssubagent_capabilitycheck). Pinned bytest/agent-cli.test.ts. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE privatekillJobs(tx, rows, cause, message)tail: it emitschild_done(outcome)to each non-terminal parent's inbox and flips anywaiting-childrenparent whose last open child just died back towaiting— so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST vialockParentsOrdered(ascending-id row locks, matchingfailJob's parent-before-child order) so the reapers andfailJobcan never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): anywaiting-childrenparent with zero non-terminal children flips back towaiting(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 clearsstarted_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 bytest/queue-stall-parent-unblock.test.ts+test/queue-started-at-retry.test.ts.renewLockaccepts 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 asdata.__released_idempotency_key, so the dream paid-loop breaker and daily cap still see the death. The trusted arg'sspendAuthorizationstores a consent-gated producer's record inspend_authorization(never job data); a coalesced live row with no record or alegacy_defaultrecord adopts it by compare-and-set, anauthorizedrow keeps its own.claim()setsspend_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 ofbook-mirror:/enrich:/cli:enrich:keyslegacy_defaultin the same UPDATE.claim(..., { excludeWatchdogSuspects })skips jobs carryingWATCHDOG_SUSPECT_MARK(re-exported fromwatchdog-attribution.ts) for a worker with jobs in flight;releaseWatchdogClaimis the token-fenced uncharged release;handleStalledfirst passes its candidates torequeueCoRunnerStalls. #7240:addpasses job data throughjsonbSafeJson(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;failJobtakes an optionalresult(a refused job'srefusal, #7239). GST-2260:completeJobandfailJobrun their database-only transaction once more when a stale plan aborted it (retryOnStalePlan), so a column another process added tominion_jobsnever fails a job whose handler already ran (test/stale-plan-heal.test.ts).src/core/minions/queue-families.ts—queueFamilyStats(engine, since)behindMinionQueue.getStats().by_queue: one row per queue (waiting_now/active_nownow;total/completed/failed/deadamong rows created in the window, theby_typesemantics), with every per-rundream-inline-*queue folded into onedream-inlinerow whosequeuescounts them.gbrain jobs statsprints a line per row (dream-inline (N queues)) and carriesby_queuein--json;get_job_statsspreads 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 keyanthropic:messages, max viaGBRAIN_ANTHROPIC_MAX_INFLIGHT). Owner-tagged rows withexpires_atauto-prune on acquire;pg_advisory_xact_lockguards check-then-insert; CASCADE on owning job deletion.renewLeaseWithBackoffretries 3x (250/500/1000ms). Canonical home ofRateLeaseUnavailableError(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.tsre-exports it for compatibility) andleaseFullBackoffMs()(the shared 1–3s jittered lease-full requeue backoffworker.tsandinline-drain.tsboth 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 siteretryablewins, 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 itscause; otherUnrecoverableErrors keep their own path). The worker's executeJob catch and the dream inline drain end such a jobdeadafter one attempt withrefusedJobResult(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 errorKindrefusedand is rebuilt asJobRefusedError(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). Formulaclamp(round(0.5 × basisMB), 4096, 16384)wherebasis = min(cgroupLimit, totalmem). LOAD-BEARING NUANCE: plainos.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(literalmax= unlimited) then v1/sys/fs/cgroup/memory/memory.limit_in_bytes. Explicit--max-rss(including0to disable) always wins. Pinned bytest/rss-default.test.ts.src/core/minions/run-child.ts—runChildJobEntry(engine, opts, injectables): thejobs run-childcore. 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 underrunWithJobSpend(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 pollingprocess.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 bytest/run-child-entry.test.ts. #7245: before the handler it compares its build with the worker's (parentBuild, theGBRAIN_JOB_PARENT_BUILDenvrunJobInChildsets fromparentBuildEnvValue) throughjobChildBuildVerdict(child-readiness.ts): a differing version runs, with onejob_build_skew:history entry and one stderr line; a readiness-protocol mismatch or a required feature the child lacks writes the entry and achild_protocol_incompatibleconfiguration 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 bytest/runtime-build-skew-7245.test.ts.src/core/minions/spawn-helpers.ts— puredetectTini()+buildSpawnInvocation()consumed by bothsupervisor.tsandautopilot.ts(one implementation for both spawn sites; tini wrapping is testable withoutmock.module(), rule R2 ofscripts/check-test-isolation.sh).detectTini()callsexecFileSync('which', ['tini'])with explicitenv: process.envso Bun sees runtime PATH mutations.buildSpawnInvocation(tiniPath, cmd, args)returns{cmd, args}withtini -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 bytest/spawn-helpers.test.ts(5) andtest/supervisor-tini.test.ts(4).src/core/minions/spend-authorization.ts+spend-record.ts— submit-time spend authorization on queued paid jobs.spend-record.tsholds the stored shape (version,kindauthorized/legacy_default,group_id,of,cap_usdoruncapped,cap_source,via,command,est_usd,argv,authorized_at), its strict parser andspendBasis(authorized,legacy_default,unrecorded,invalidwith awhy).jobSpendAuthorization(auth, {command, est_usd, of, argv})builds a group from a consentAuthorization;legacyDefaultClaimSetSqlis 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 underwithAIInvocationGuard(nested) so each provider attempt reserves its maximum againstgroup:<id>and settles measured usage. Settled exhaustion (or an unpriced model under a user cap) throwsSpendGroupRefusedError(derived_cap_exhausted/cost_cap_exceeded/no_pricing, group amounts, rerun fix with twice the cap) and records it asresult.spend_refusal; live-hold pressure throwsSpendGroupPressureError(a lease release, at mostMAX_PRESSURE_RENEWALS= 6, counted fromminion_lease_pressure_log); unpriced models under derived/default caps warn and run. Every claimed paid job logs onejob_spend_basisline.spendSubmitSummaryprints the producer's group, kept authorizations (withgbrain jobs cancel --group) and reused rows;groupJobs/jobGroupAmountsbackjobs 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);directStopReasonfor the Messages path (max_tokens→max_tokens,refusal→refusal, a clean stop whose final text is empty →error);gatewayStopReasonfortoolLoop(length→max_tokens,refusal/content_filter→refusal,empty_response/aborted/unrecoverable→error,end→end_turn);replayTerminalStopReasonfor a persisted terminal turn (tokens_out >= cap→max_tokens, empty text →error, elseend_turn). On both replay paths inhandlers/subagent.tsANY 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'sempty_responsestop reason is additive (gateway.tsToolLoopStopReason). Pinned bytest/subagent-stop-reason-6448.test.tsandtest/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 fiveMinionQueue.addcoalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read withLEGACY_AUTHORITY_COLUMNso 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 thelegacy_job_authoritycatalogue error);UNREVIEWED_LIVE_JOBS_WHEREis the claim gate's predicate, shared with doctorlegacy_job_authority. Tests:test/minions-legacy-coalesce.test.ts(PGLite) andtest/e2e/minions-legacy-coalesce-postgres.test.ts, both overtest/helpers/legacy-coalesce-matrix.ts.src/core/minions/authorize-legacy.tsprovides 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 withsaveApprovedSet(preview-approval helper) so--expect <hash> --yesauthorizes exactly that set; every refusal is a catalogue error (legacy_job_selection_invalid,legacy_jobs_active,preview_changed).src/core/minions/source-filesystem.tsprovides 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 sharedexistsSync → readFileSync → parseInt → process.kill(pid,0)PID-file + liveness reader shared byjobs.ts(supervisor status),jobs.ts(stats), anddoctor.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 stopreads it as the recycled-pid fence) and, since PR #6463, the hostname the supervisor puts in its DB lock, whichreadSupervisorPidreturns ashost(absent on an older two-line file). Pinned bytest/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);readSupervisorBuildreads them (null for an older file) andreadSupervisorPidstays unchanged.src/core/minions/supervisor.ts— MinionSupervisor process manager. Spawnsgbrain jobs workas a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internalcliArgsPrefixcarries source-entrypoint arguments while explicit--cli-pathremains 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.OwnerProcessingStatesupplies additive live readiness and redacted runtime identities.consecutiveHealthFailurescounter; on 3 consecutive failures emitshealth_warnwithreason: 'db_connection_degraded'and callsengine.reconnect()to swap in a fresh pool, then resets. Worker exit classifier emitslikely_causeonworker_exitedevents:oom_or_external_kill(SIGKILL),graceful_shutdown(SIGTERM),runtime_error(code 1),clean_exit(code 0),unknown. ConsumesdetectTini()+buildSpawnInvocation()fromsrc/core/minions/spawn-helpers.tsto wrap the worker subtree intini -ssubreaper mode when tini is onPATH(without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposesisTiniDetectedread-only accessor. The spawn-and-respawn loop is the sharedChildWorkerSupervisorcore: MinionSupervisor composes it viarunSuperviseLoop()→new ChildWorkerSupervisor({...})and mapsChildSupervisorEventback throughemit()SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, andprocess.exiton 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 + acrash_budget_degradedhealth_warn) and self-heals when a respawn runs stably; permanentprocess.exit(MAX_CRASHES)fires only at the hard ceilingresolveHardStopMaxCrashes(maxCrashes)(defaultmaxCrashes × 10, envGBRAIN_SUPERVISOR_HARD_STOP_CRASHES,0= never). Separately,gbrain jobs supervisor status+gbrain doctordetect 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-$HOMEdeployment does not read a healthy supervisor as "not running".code=0leavescrashCountuntouched (so a worker alternating real crashes + watchdog drains still tripsmax_crashes);cleanRestartBudget(default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop viahealth_warn { reason: 'clean_restart_budget_exceeded' }+ backoff.shutdown()drains viachildSupervisor.killChild('SIGTERM')+awaitChildExit(35_000). Progress watchdog:healthCheck()restarts an alive-but-wedged child viachildSupervisor.restartCurrentChild(35_000)when a queue has claimable work, 0 live-lock active jobs, and stale completions acrosswedgeRestartChecks(default 3) consecutive checks pastwedgeRestartMinutes(default 15, 0 disables) + astartupGraceMswindow; bounded bywedgeRestartLoopBudget(default 3 /wedgeRestartLoopWindowMs) which switches to a one-shotwedge_restart_loopalert. The wedge query is the exportedqueryWedgeSignals(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 throwawayregisterBuiltinHandlersworker (its newquietopt). Flags--wedge-restart-minutes/--wedge-restart-checks+ envGBRAIN_WEDGE_RESTART_MINUTES/GBRAIN_WEDGE_RESTART_CHECKS. The worker argv is built by the exported purebuildWorkerArgs(opts)(appends--nice Nwhenopts.nice_requestedis 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 thestarted/worker_spawnedaudit emissions. Queue-scoped singleton: the real authority is a DB lock (tryAcquireDbLockfromsrc/core/db-lock.ts) keyed onsupervisorLockId(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-fileagainst the same(database, queue)cannot both run with conflicting--max-rss: the second exitsLOCK_HELD. The pidfile-cleanupprocess.on('exit')listener is installed BEFORE the DB-lock acquisition so theLOCK_HELDearly-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 ownsetInterval(TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exitsLOCK_LOST(code 4) rather than risk a split-brain, while a fenced refresh returningfalse(0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emitshealth_error { reason: 'supervisor_lock_lost' }and exitsLOCK_LOSTimmediately (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. Thestartedaudit recordsmax_rss_mbsogbrain doctor'ssupervisor_singletoncheck can surface the effective cap. ExportssupervisorLockId()and the pureclassifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'(host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned bytest/supervisor.test.ts(16 cases),test/supervisor-tini.test.ts,test/supervisor-wedge.test.ts,test/supervisor-build-worker-args.test.ts, andtest/supervisor-db-lock.test.ts.SupervisorOpts.jobIsolationpasses--job-isolation processto the spawned worker via a CONDITIONALbuildWorkerArgspush (inline argv stays byte-identical).queryWedgeSignals/probeQueueStatethread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion).buildWorkerArgsalso appends--allow-shell-jobswhenopts.allowShellJobs(conditional push like--job-isolation, so existing argv stays byte-identical; pinned bytest/supervisor-build-worker-args.test.ts). Rationale: the worker's startup cwd-.env quarantine dropsGBRAIN_ALLOW_SHELL_JOBSwhenever a .env in the worker's cwd assigns it, so the env copy inrunSuperviseLoopalone could silently disable shell jobs;jobs workparses the flag and re-setsprocess.env.GBRAIN_ALLOW_SHELL_JOBS='1'after preflight (read sites in jobs.ts / handlers/shell.ts unchanged).allowShellJobssets 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 emitsstoppedwithdrained/worker_forced/worker_exit_code/lock_released.gbrain jobs supervisor stop(src/commands/jobs/supervisor.ts) reportsdrainedonly when the pid is gone, the supervisor's ownstoppedrow follows itsshutting_downwithdrained: 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 (readSupervisorRuninsupervisor-audit.ts: from the supervisor pid's laststartedrow, searching back up toSUPERVISOR_RUN_LOOKBACK_WEEKSweekly files, so a run started before the ISO-week boundary keeps its spawns);worker_exitedrows carry the child'spid(null when no process was created) andworker_spawnedrows 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 apidkey pair with spawns by order and addwarnings: ['legacy_exit_pairing']); a run with nostartedrow on record reportsunverified(exit 1,audit_fileslisted), neverdrained. The PID file now holds the pid and, on Linux, its start time on a second line (pidFileContentsinsupervisor-pid.ts, which also stamps audit rows throughprocessStartStamp; every reader takes the first line), andstartedrecordssupervisor_start: when the pid is alive with a different start time, stop reportsstale_pid_file(exit 0,stopped: false) and signals nothing. Process start times come fromprocessStartTimeinsrc/core/pglite-lock.ts(moved fromgraduation-custody.ts, which re-exports it). Pinned bytest/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 nextwait()a no-op (skipped) instead of being lost, andclaimStarted()clears it.idlesays whether a wait is in progress;historykeeps the last 100 waits and how each ended (timer,wakewith its reason,skipped,stop), the decisionstest/pathological/s-sync-queue-wake.test.tsasserts on.src/core/autopilot-heartbeat.ts— #7003: the autopilot daemon's heartbeat sidecarautopilot.heartbeat.jsonbeside the lock (autopilotHeartbeatPath()insrc/core/autopilot-paths.ts), written byautopilot-daemon.tsat the top of every tick (phasecycle) and before every sleep (phasesleep,next_tick_at).daemonStaleAfterSecondsgrades 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.readDaemonStaleAfterreads the lock's mtime and pid and applies it forgbrain 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.gitentry (enclosingGitMetadata,src/core/persistence/root-registry.ts), one boundedgit 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 whichGIT_OPERATION_MARKERSentry (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 idlegbrain jobs workclaim loop when asyncjob turnswaitingin its queue.chooseSyncQueueWake(engine, env)pickslistenonly on a detected direct session (the engine's dual-pool direct route, or a pool whoseprepareis not off, read throughconsumerConnectionRoutein persistence/consumer-lane.ts),pollbehind a transaction pooler or an unknown pooler mode,offon PGLite or withGBRAIN_WORKER_SYNC_WAKE=0.startSyncQueueWakeLISTENs on theminion_jobschannel (the schema'snotify_minion_job_changetrigger) and requires a probe NOTIFY to arrive within 3 s, else it polls; the poll reads oneminion_jobsrow everyGBRAIN_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 inscripts/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 throughreplayWhilePending(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 thanWIRE_WRITE_WAIT_MAX_MSplusWRITE_ADMISSION_HEADROOM_MS(45 s); a job without a deadline replays for theMaintenanceWriteWaitbase (30 s). Only then does the write leave the handler aswrite_pending, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminalfailedreceipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned bytest/subagent-handler.test.ts,test/minions/subagent-pending-write-runners.test.ts,test/minions/subagent-oneshot.test.tsandtest/e2e/subagent-gateway-resume-reconciliation.test.ts.src/core/minions/tools/brain-allowlist.ts— derives the subagent tool registry fromsrc/core/operations.ts(13-name allow-list in the handler-freebrain-tool-allowlist.ts, whichsrc/mcp/surface.tsreads, size pinned bytest/brain-allowlist.test.ts). Attachment toolsfile_listandfile_urlare excluded. Registry construction and execution reject everylocalOnlyoperation;selectAllowedToolsrejects malformed bindings and preserves explicit empty lists as no tools. Includesadd_timeline_entry(the canonical timeline write), fenced server-side by the sameenforceSubagentSlugFencepolicy asput_page. By defaultput_pageschema is namespace-wrapped per subagent (^wiki/agents/<subagentId>/.+). WhenBuildBrainToolsOpts.allowedSlugPrefixesis set, the put_page schema describes the prefix list to the model and the OperationContext is threaded withallowedSlugPrefixes— trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plusdelegatedAuth. 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) threadsOperationContext.deferEmbedsso put_page defers chunk embeddings for the phase-end backfill. Allow-list includesget_recent_salience+find_anomaliesbut deliberately NOTget_recent_transcripts(all subagent calls runctx.remote === trueand the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase callsdiscoverTranscriptsdirectly instead).paramsToInputSchema()consumesparamDefToSchemafromsrc/mcp/tool-defs.ts; required-aggregation at the tool-def level stays here (the shared helper is per-param).execute()runs the samevalidateParamsthe 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.putPageRejectionclassifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed bypersistence/page-input.tsonly after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagentget_pagewithinclude_content: trueis forced tocontent_only: true, so the body arrives once (ascontent) instead of also as parsedcompiled_truth/timeline.BuildBrainToolsOpts.readBudgetBytes(from trustedSubagentHandlerData.read_budget_bytes) routesget_pageresults throughread-budget.ts. #6779: a subagentput_pagerefusedrevision_requirednames the page's current revision (rethrowWithCurrentRevisioninput-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-jobget_pagebyte budget:budgetedPageReadcounts bytes already returned from the job'ssubagent_tool_executionsrows (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, therevision(#6779, so a child can still append or skip), a bounded prefix of the result's renderedcontent/textof at mostREAD_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— renderssubagent_messages+subagent_tool_executionsto markdown. Tool rows splice under their owning assistanttool_useby(message_idx, tool_use_id)— raw provider tool ids may repeat across turns, sotool_use_idalone is not an identity; echoedtool_resultblocks 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_stalledis optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to[1, 100].SubagentHandlerData.require_writesrequires at least one settled successful page write, not merely a clean model finish, except the deliberate zero-write completionsisLegitimateZeroWriteaccepts (an explicit oneshot skip, or anallow_clean_zero_writeschild with a completed tool execution).SubagentHandlerData.corpus_sourcepins 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.TimeoutErrordoes NOT cancel the job;AbortSignalexits without throwing. DefaultpollMs: 1000 on Postgres, 250 on PGLite inline.isTerminalJobStatusis 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 MCPwait_job) and thewait_jobop (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 mostWAIT_JOB_MAX_S= 55 s and returns the get_job row plusterminal). Pinned bytest/minions/job-insight.test.tsandtest/jobs-wait-cli.serial.test.ts.src/core/minions/job-insight.ts— #7241 fields computed on read forjobs get/list --json,get_job,list_jobsandwait_job:submitted_by,blocked_by(queue position and slot holders, waiting children, delay reason, paused, unreviewed authority, heldgbrain-sync:<src>/gbrain-cycle:<src>locks with the holder job from the drain-lease beacon row), lease liveness (heartbeat_age_msfromlock_until - lock_duration_ms, else a lower bound fromupdated_at,heartbeat_basissays which;lock_expires_in_ms;stalled) andspend(token columns pluscost_usdfrom settledmcp_spend_reservationsof the job and its descendants;null/unpricedwhen 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 byMinionQueue.addon the stored data) always drops a caller-supplied__submitterand, for an application-authority submit from a labelled local process, storessubmitterLabel()(autopilot,serve,worker,job:<name>,cli:<command>;librarystores nothing) as job data__submitter. It is a display label only:submission_authorityis untouched,PARAM_HASH_EXCLUDED_KEYS(admission.ts) leaves it out of the param hash, the remote submit paths cannot carry it (prepareRemoteJobrefuses unknown data keys,submit_agentbuilds its own data), anddescribeJobsreads 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_hookis a FILE-plane key only (commands/config.tsFILE_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 absoluteargv[0], spawned withshell: false; the job arrives in GBRAIN_JOB_ID/NAME/QUEUE/STATUS and as fixed-field JSON on stdin (never data or result); killed attimeout_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 workwiresterminalHookNotifierintoMinionWorkerOpts.onJobSettled, which the worker calls fromlaunchJob's settle (outsideexecuteJob); the notifier re-reads the row and fires only for a terminal status. Pinned bytest/minions/terminal-hook.test.ts.__released_idempotency_keyreminder: see theidempotency-coalesce.tsentry 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). ExportsWORKER_EXIT_RSS_WATCHDOG = 12andWORKER_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 acode===0 → clean_exitclassifier would never count it and a respawn loop would stay invisible. A distinct code makes the drainlikely_cause=rss_watchdog. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves thejobs run-childcodes: 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 runninggbrain jobs workself-registersworker-<pid>.jsonundergbrainPath('workers')(brain-isolated viaGBRAIN_HOME; entries tagged withcurrentBrainId()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 shutdownfinallyANDprocess.on('exit')(the unhealthyprocess.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-freeps -o etime=parsed byparseEtimeToMs, 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 throwsWorkerRegistryUnreadableError(errno + path, read withworkerRegistryReadFailure), and every liveness consumer reports unknown instead of zero: doctorqueue_health(worker_alive: null, no start-a-worker fix) andwedged_queue,legacy_job_authority(live_workers: null),jobs supervisor status(workers: null), the submit-timeprobeQueueState(worker_aliveomitted, liveness-unknown warning), themigrate-embeddingswriter census (workers: null) and the readiness worker probe (probe_failed); each carriesworker_registry_unreadable,worker_registry_errnoandworker_registry_path. Pinned bytest/worker-registry.serial.test.ts. #7245: each entry also carriesversion(VERSION in memory) andinstall_root(runtimeInstallRoot(), a local path that no remote output carries); doctorruntime_build_skewreads 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)(thegbrainpackage.json version on disk now) andserveBuild()({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(...)(codeno_worker, kinddegraded). Consumers: CLIjobs submiton PGLite refuses without--followunless--queue-only(src/commands/jobs/submit.ts);gbrain jobs workon PGLite drains viadrainPgliteQueue(src/commands/jobs/work.ts) and exits; MCPsubmit_job/get_job_statsemit the notice (src/core/ops/jobs.ts, PGLite fix wrapped by readinessexclusiveFixbehind a running serve);deriveWedgeSignal(wedge, {workerAlive})returnsno_workerand never calls that case wedged (jobs stats,get_job_stats); doctorqueue_healthcounts PGLite waiting rows (src/commands/doctor/checks/queue-jobs.ts). Pinned bytest/queue-no-worker.test.ts.src/core/minions/worker.ts— MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). Thereadyevent 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 throughMinionQueue.releaseConfigurationJobwithin one bounded shutdown envelope. The active/token-fenced release returnsreleased,no_oporunconfirmed, 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 callfailJobwith reason (timeout/cancel/lock-lost/shutdown);shutdownAbort(instance field) fires on SIGTERM/SIGINT and propagates toctx.shutdownSignal(shell handler listens; non-shell handlers don't). Per-job timeout firesabort.abort(new Error('timeout'))then a 30s grace-then-evict safety net force-evicts the job frominFlightand marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). ThelaunchJoblock-renewal block is a thin sync wrapper around the purerunLockRenewalTickfromsrc/core/minions/lock-renewal-tick.ts(NEVERsetInterval(async () => await renewLock(...))— that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1)cancelledflag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guardtickInFlight(skips counted asoverlapSkipstelemetry) + per-callPromise.racetimeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or thehardEvictMsbackstop — never bare local arithmetic; the per-job lease (job.lock_duration_ms ?? opts.lockDuration) drives the renewal state, and the cadence clamps tomin(lease/2, 60s); (4) explicit.catch()on the storedexecuteJob(...).finally(...)promise closes the second unhandledRejection vector; (5) exportedINFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])so executeJob's catch skipsfailJobfor 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 typedconfigurationErrorlatch; (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 aperf_hooks.monitorEventLoopDelayhistogram (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 stashedabortMeta. CI guardscripts/check-worker-lock-renewal-shape.sh(inbun run verify) asserts the bug pattern stays absent ANDlaunchJobkeeps callingrunLockRenewalTick. Engine-ownership invariant:start()does NOT callengine.disconnect()on shutdown — the CLI handler insrc/commands/jobs.ts case 'work'owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exportedparseRssFromProcStatus(status)(pure parser; field-presence regex soRssAnon: 0 + RssShmem: 512parses correctly) andgetAccurateRss(readStatus?)(reads/proc/self/statusforRssAnon + RssShmem, falls back toprocess.memoryUsage().rsson macOS / restricted containers / kernel <4.5); the defaultgetRssinWorkerOptsisgetAccurateRss.checkMemoryLimittracks 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 viaget rssWatchdogTriggered()) sojobs work's finally canprocess.exit(WORKER_EXIT_RSS_WATCHDOG)after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wrapsclaimin try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry afterUPDATE...RETURNINGcommitted but the socket died would double-claim).LockRenewalDepsis wired withreconnectwhen the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (GBRAIN_SUPERVISED=1): the outer guard isif (this.opts.healthCheckInterval > 0)and only the STALL-detection block is wrapped inif (!isSupervisedChild)— so a supervised worker whose own pool dies self-exitsunhealthy(db_dead)afterdbFailExitAfterprobes (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 thetest/worker-lock-renewal.test.tshermetic suite,test/audit/lock-renewal-audit.test.ts,test/scripts/check-worker-lock-renewal-shape.test.ts,test/worker-shutdown-disconnect.test.ts(assertsdisconnectSpy).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/childTiniPathswaphandler(context)forrunJobInChild(...)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) andChildNotClaimedError(the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates torunDbProbe(db-probe.ts) with a cancellation signal on every probe and emits averdict(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 underrunWithJobSpend; an isolated spend-authorized job passesspendAuthorizedto the child runner's capability gate. #5062:requestShutdown()is the signal entry point (thejobs worksignal 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 (endedByShutdowninworker-shutdown.ts) exceptUnrecoverableError, 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 withdrainForcedset, whichjobs workturns into exitWORKER_EXIT_DRAIN_FORCED(17). The RSS watchdog'sgracefulShutdown(reason)aborts everyinFlightjob and records the reason; a claim whoseUPDATE … RETURNINGcommitted before the shutdown but whose result had not reached the poll loop is not ininFlightyet, solaunchJobaborts 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 intest/worker-shutdown-error-matrix.test.ts, which holds the claim result until the watchdog has fired). EachinFlightentry carriesshared(another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job tosettleWatchdogAbort(back towaitinguncharged, marked to run alone), so only a job that ran alone is chargedaborted: 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 throughidleWaiter(src/core/minions/idle-wait.ts), which the sync-queue wake ends early;claimStarted()runs right before each claim, andstop()andrequestShutdown()end the wait at once. Before recording a handler's return, the worker reads it withjobResultOutcome: a reported failure ends the job throughfailJob(..., 'failed', 0, result)and a partial one completes, each storingjobOutcomeResult. #7966: whileautopilotPaused()(either pause marker), the non-supervised stall watchdog restarts its no-progress clock each tick instead of emittingstalled; the DB liveness probe still runs. Doctor'swedged_queuereports a paused queue aswarn(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:settleWatchdogAbortrequeues each such job token-fenced with no attempt burned (error_textWATCHDOG_DRAIN_RELEASE) and appendsWATCHDOG_SUSPECT_MARKonce to itsstacktrace, 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.unmarkedJobSqlis the claim filter.requeueCoRunnerStallsrequeues, 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 withworker_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 bytest/pathological/a30-watchdog-attribution.test.ts(both engines) andtest/worker-shutdown-error-matrix.test.ts.