Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Minions (1/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/— Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs;queue.tsreconcilePrivateQueueterminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readableprivate_queue_reconciled:reason family;renewPrivateQueueLeaseis MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease;reconcileOrphanedPrivateQueuescancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage;classifyPrivateQueueForRecoveryis PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs ingbrain jobs workafter driver/selected-child readiness andensureSchema, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues inbeforeSpawn.maybeRunWorkerStartupRecovery(queue, process.env, true)keeps this worker-owned ordering even underGBRAIN_SUPERVISED=1. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child).deriveWedgeSignalis queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reportsprivate_queue: trueso jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.src/core/minions/handlers/sync.ts(and the other built-in job handler modules:embed,lint,lint-fix,extract,extract-conversation-facts,chronicle-extract,loops-extract,enrich,integrity,integrity-auto,sync-retry-failed,import,backlinks,facts-absorb,autopilot-cycle,autopilot-global-maintenance,reindex,repair-jsonb,orphans,purge,cycle-phase,extract-atoms-drain,extract-ner,extract-takes-from-pages,extract-timeline-from-meetings,embed-catch-up,unify-types, plusjob-pull.tsandjob-progress.ts) — one module per built-in handler body, each amake<Name>Handler(engine)factory (or aMinionHandlerconst when it needs no engine). Registered in a fixed order byregisterBuiltinHandlersinsrc/commands/jobs.ts, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such aswithFactsAbsorbHaltCooldown;cycle-phase.tsserves the six phase wrappers. Command cores are imported lazily inside each handler.resolveJobPulland the facts-absorb retry predicates are re-exported fromjobs.ts.autopilot-global-maintenanceruns onerunCyclecall per maintenance phase and keeps its pass position in configautopilot.global_maintenance.progress: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. GBRA-130 A-10: each blocking phase keeps a streak in that row (failures[phase], keyfail:<code>,budget,child:<outcome>ordeferred, counted once per pass); after three earlierfail:passes the pass stamps past it (pass_completed_with_failing_phase),fail:/child:streaks back off from their third pass, and the streak resets on a version change, a new key orgbrain autopilot --retry-global(rules in the module header). Phases run through anItemRun(siteautopilot.global_maintenance). Probe:test/pathological/a10-global-maintenance-stamp.test.ts. The deadline comes fromGBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS>autopilot.global_maintenance_timeout_ms> the autopilot default (autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs); doctorglobal_maintenance_timeouts(doctor/checks/global-maintenance-timeouts.ts) warns after three consecutive deaths and namesgbrain dream --phase <name>(autopilot-global-maintenance-resume-4578.test.ts). Thesynchandler runs performSync underjob.signalcomposed withjob.shutdownSignal: under a signal owner (jobs work, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and itsgit pull(asyncpullRepoonbounded-child-exec.ts) stop and the job is handed back without burning an attempt. A queuedautopilot_freshnesssync job re-reads its source when it runs and returns{skipped:true, reason:'sync_disabled'}when the source now hassyncEnabled:false; any sync job thatperformSyncrefusessync_not_applicableorsync_anchor_relativecompletes as a skip (the latter carrying the refusal'ssuggestionand ask-the-userfix, no stored path), so it never uses up its attempts; explicit sync jobs still run and a failed lookup falls through to syncing (sync-handler-sync-enabled.test.ts). #6706: managed jobs drain viasync-job-drain.ts. Progress (job-progress.tsreportJobProgress, best-effort: a failed write never fails the job):autopilot-cyclepassesCycleOpts.onPhaseStartandautopilot-global-maintenancewrites before each phase'srunCycle, both{phase, phase_index, phase_count, started_at}; thesynchandler always passesjobDrainProgress'sonProgress, which writes a classic sync's phase (resolve_repo,git_pull,full_import,importwithbanked_files) on each change and at most every 10 s within one, beside the managed drain snapshot (test/minion-job-progress-7241.test.ts).src/core/minions/admission.ts— submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name viaresolveAdmissionPolicy(configminions.*> per-name defaults tables, 60s in-process cache per engine, fail-open with a once-per-process stderr warn; env kill-switchGBRAIN_MINIONS_ADMISSION=0disables all three): PARAM-COALESCING (PARAM_COALESCE_DEFAULT— on forsubagent;computeParamHash= sha256 of stable-stringified payload excluding__param_hashitself and the__submitterdisplay label —__owner_client_idis deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (WAITING_TTL_DEFAULT_HOURS— 48h forsubagent; swept byMinionQueue.handleWaitingTTLthroughcancelJobs(ids, {reason, rootStatuses:['waiting']})so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act isrunWaitingTtlTick— first tick counts affected + stampsTTL_NOTICE_SHOWN_KEYwith an ISO timestamp, sweeping starts only afterttlNoticeGraceMs()(1h default, envGBRAIN_MINIONS_TTL_NOTICE_GRACE_MS) elapses;gbrain upgradeprints the same one-shot notice and starts the same clock; legacy'true'flag values sweep immediately), and NAME-GLOBAL QUOTA (QUOTA_MAX_WAITING_DEFAULTEMPTY by operator decision — activates only viaminions.quota_max_waiting.<name>; counts the name across ALL queues so per-rundream-inline-*fanout queues can't dodge it, EXACT under concurrency via aminion_quota:<name>advisory xact lock taken only when a quota is configured; throws typedQueueQuotaExceededError, checked everywhere viaisQueueQuotaExceededError— dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree,submit_agentmaps to a structuredrate_limitedOperationError).TTL_REASON_PREFIXis the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns;safeConfigSegmentgates untrusted job names out of copy-pasteable config hints. Alerting ridesgetStats(drained_completed/failed/dead/cancelledkeyed on finished_at +waiting_now+oldest_waiting_minutes), thejobs statsDIVERGENT-QUEUE / waiting-TTL screams (GBRAIN_QUEUE_DIVERGENCE_RATIO=2,GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) +--json, and doctorcheckQueueHealth. Pinned bytest/minions-admission.test.ts+test/jobs-stats-divergence.serial.test.ts.src/core/minions/attachments.ts— Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).src/core/minions/backpressure-audit.ts— sibling of shell-audit.ts formaxWaitingANDmaxPendingcoalesce events. JSONL at~/.gbrain/audit/backpressure-YYYY-Www.jsonl. One line per coalesce with(queue, name, waiting_count/max_waiting OR pending_count/max_pending, returned_job_id, ts).readRecentCoalesceCountsfeeds thejobs statsBackpressure line (reads current + previous ISO-week files so a 24h window survives week boundaries, filtered per queue). Makes the backpressure guards' coalesces visible instead of silent drops. Pinned bytest/backpressure-audit-read.test.ts.src/core/minions/budget-meter.ts— atomic reserve/settle accounting. Per-client advisory lock plus client row lock protects current cap and outstanding holds. NULL cap means unlimited; a caller's existing finite ceiling still applies. Pending and expired unresolved holds count across UTC dates; TTL marks overdue rather than releasing liability. Unknown-bound holds prevent subsequent finite admission until reconciled. Settlement is idempotent and writes reservation state plus spend log in one transaction.reserveGroupmeters a command group's shared budget (budget_key = 'group:<group_id>', no client row) over its lifetime instead of the UTC day: settled spend plus overdue holds at the cap isGroupBudgetRefusal('exhausted'), live sibling holds that leave no room are'pressure', and an admitted attempt reserves its maximum bounded by the remaining headroom (its actual cost is charged at settle). Each reservation names exactly one budget owner (CHECK); client reads stay keyed byclient_id, so group spend never appears in client budgets or admin client spend.readGroupSpendis the read-only total. Tests cover races, changed caps, unknown usage, late settlement, group pressure/exhaustion and both engines (test/minions/budget-meter.test.ts,test/e2e/budget-meter-group.test.ts).src/core/minions/child-job-runner.ts— parent-side runner:runJobInChild(opts)spawns the child (detached + tini when available, stdio inherit for handler logs, per-job lifecycle log lines), maps per-job abort → group SIGTERM now + group SIGKILL at +25s (CHILD_KILL_GRACE_MS, inside the 30s force-evict backstop), gives worker-shutdown children the drain window to finish AND report (a non-reporting shutdown kill throwsChildWorkerShutdownErrorwith separateexecutionStoppedevidence; group cleanup retains its kill backstop after direct-child exit, and unconfirmed cleanup must not authorize configuration release).onExecutionStoppedpublishes confirmed no-execution failures or supported Linux owned-group/observed-descendant stop evidence once, including normal exits; a handler outcome alone is not that proof. After direct-child exit, termination settles as soon as supported Linux cleanup proof confirms the owned groups gone (bounded backoff poll); without proof the group is SIGKILLed immediately and the stop stays unconfirmed; surviving members still receive the grace SIGKILL. The runner classifies missing/non-executable child paths asLocalConfigurationErrorand other pre-exec spawn failures asChildSpawnInfraError(no attempt burned), and bounds child pools via env (GBRAIN_POOL_SIZEdefault 3,GBRAIN_DIRECT_POOL_SIZE=1). A spend-authorized row (opts.spendAuthorized) is never handed to a child that did not advertisespend-enforcement-v1at readiness:SpendEnforcementUnavailableErrorreleases it through the lease path for an upgraded worker. Pinned bytest/child-job-runner.test.ts(real children) +test/worker-job-isolation.test.ts(full parent path on PGLite).src/core/minions/child-worker-supervisor.ts— shared spawn-and-respawn core reused by bothMinionSupervisor(standalonegbrain jobs supervisordaemon) andsrc/commands/autopilot.ts(autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure spawn-loop class: NO PID file, NO signal handlers, NOprocess.exit, NO health check.WORKER_EXIT_CONFIGURATIONand the generation-scopedOwnerProcessingStatechannel block spawning before generic crash accounting;configurationBlockedalso prevents intentional watchdog/wedge restarts. The owner remains alive with additive readiness diagnostics until explicit restart after repair. Startup stages and retry deadlines remain visible, and missing readiness is bounded by the startup timeout and forced-stop backstop before ordinary crash-budget handling. The sharedprocessing-state.tsvalidates bounded/redacted identities, correlates worker updates to the active runtime token, and does not turn a missing status file into readiness. Lifecycle events fire via injectedonEvent: (ChildSupervisorEvent) => void. Exit classifier:code === 0leavescrashCountUNCHANGED (preserves flap detection across mixed exit sequences);code != 0followsrunDuration > stableRunResetMs ? 1 : ++crashCount. Clean-restart budget: sliding window of code=0 exits; when count exceedscleanRestartBudget(default 10) insidecleanRestartWindowMs(default 60s), emitshealth_warn { reason: 'clean_restart_budget_exceeded' }and appliescleanRestartBudgetBackoffMs(default 1s). The exit classifier special-casesWORKER_EXIT_RSS_WATCHDOG—likely_cause='rss_watchdog', and that exit does NOT bumpcrashCount(routes to its own breaker); a dedicated_watchdogExitTimestampssliding window trips a loudrss_watchdog_loophealth_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). OptswatchdogLoopBudget(3),watchdogLoopWindowMs(600000),watchdogBackoffMs(30000);ChildSupervisorEventextended. Public read-only accessorschildAlive,inBackoff,crashCount;killChild(signal)gates on liveness (exitCode === null && signalCode === null), NOT.killed—.killedflips true once a signal is sent, so a!this._child.killedguard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op.restartCurrentChild(graceMs)(wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags_intentionalRestartso the exit islikelyCause='wedge_restart', leavescrashCountUNTOUCHED (never tripsmax_crashes; likerss_watchdog), and respawns immediately (backoff ms:0 reason='wedge_restart').awaitChildExit(timeoutMs)short-circuits whenchild.exitCode !== null || child.signalCode !== nullso fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: therun()loop does not fireonMaxCrashesExceededat the softmaxCrashes; it announceshealth_warn { reason: 'crash_budget_degraded' }once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only athardStopMaxCrashes(defaultmaxCrashes × HARD_STOP_CRASH_MULTIPLIER= 10×;0disables). Test hooks_backoffFloorMs,_now.supervisor-audit.tscarriesrss_watchdogas a non-clean cause + its ownCrashSummary.by_causebucket, andwedge_restarttoCLEAN_EXIT_CAUSES(a self-heal, not a crash; denylist preserved so future causes route tolegacy). Pinned bytest/child-worker-supervisor.test.ts(12 cases). #5062:lastExitrecords how the most recent child exited, including on the shutdown path, so the composer can tell a clean drain from a forced stop.src/core/minions/db-probe.ts— hermetic DB-liveness probe with pool-starvation disambiguation:runDbProbe(deps)probes the read pool (signal-cancelled attimeoutMs), on failure probes the DIRECT lane (DIRECT_PROBE_TIMEOUT_MS, only when dual-pool is genuinely active) and returns a verdict —pool_starved("server IS reachable; fault is in the transaction-pooler path — client pool exhaustion or a pooler-layer fault", deliberately an honest disjunction),server_unreachable,unknown, or typedclient_misconfigured.runDbReadinessProbechecks every required lane even after read success; aLocalConfigurationErroron either lane wins over outage classification. Ordinary abort/network/timeout errors stay transient. Gauge counts render as a labeled tracked SUBSET; no waiter/available arithmetic. Pinned bytest/db-probe.test.ts.src/core/minions/delegated-admission.ts+delegated-tools.ts— queue admission locks the client row through validation, idempotency/coalescing, counting all nonterminal owned jobs across queues, and insertion. Returning an identical existing job adds no slot. Every delegated tool execution, including replay and one-shot writes, rechecks the current intersection and rebuilds the operation context with its current source/path bounds and authenticated read-source ceiling, including explicit per-call source overrides. Remote-owned writes cannot overwrite private existing pages (including dedup redirects), append their timeline, or run trusted-workspace auto-link/timeline hooks. One-shot remote-owned writes keep links as literal text without probing hidden target existence or counts; trusted local behavior is preserved. Trusted owner fields are separate from user parameters. Replay cannot replace identity or original bounds; valid owned replays and terminal-job retries consume a slot under the same client lock. Legacy terminal jobs missing a stored ceiling require fresh authenticated submission.src/core/minions/delegated-policy.ts— immutable submitted grant ceiling intersected with the current OAuth grant. Tools, explicit operation authority, source-only reads, write prefixes, concurrency and finite budget may narrow but never widen during execution; changed source/brain, revoked clients, archived sources or unusable intersections fail closed. Explicit job namespaces resolve towiki/agents/<job-id>/*. Removingsubmit_agentstops the next execution boundary; explicit operation allowlists also constrain delegated tools, while legacy null operation lists preserve separately bound agent-only tools. Surface controls transport discovery. Empty tools never mean all tools. Legacy running jobs adopt the ceiling frozen in their persisted payload by grant rescope; host/current brain aliases mean the serving brain.src/core/minions/delegated-spend.ts+src/core/ai/invocation-guard.ts+guarded-generation.ts— async-local admission (withsrc/core/ai/invocation-guard.tsavailable asgbrain/ai/invocation-guardfor a companion capped evaluator) around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require a known price (pricing.overrides, loaded once per run, then the tables; rerank: override or embedding-table rate) and an input ceiling plus output maximum before IO (embed/rerank output defaults to 0); unknown pricing/bounds refuse.runWithJobSpendprices the same way (#6546). Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock. The delegated guard nests inside an outer guard (a job's spend-group guard), so both must admit an attempt.src/core/minions/detached-stderr.ts— durable stderr sink + spawn helper forgbrain jobs supervisor start --detach.openDetachedStderrSink()opens an append-mode log in the audit dir (${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-stderr.log, next to the JSONL lifecycle audit), falling back to the null device, then'ignore'; never throws (a sink failure must not block the supervisor start). The detached supervisor gets the fd asstdio[2]and its worker inherits it, so ONE durable descriptor covers both processes — not a per-call EPIPE swallow. Prevents the SIGPIPE failure of inheriting the INVOKER's stderr: a short-lived automation runner closing its capture pipe after the start payload would make the worker exit 141 on its next stderr write (and could take the supervisor down writing its own crash event), leaving active jobs and DB locks stale while producers keep enqueueing. Pinned bytest/detached-stderr.test.ts.src/core/minions/embed-backfill-admission.ts— Centralized, dependency-light embed-backfill admission contract shared by the publicMinionQueue.addboundary, CLI, MCP operations, automatic submitters, sync cost reporting, and doctor remediation.embedBackfillWorkerSurfacerecognizes only explicitpostgresas worker-backed; the declared engine-kind switch is compile-time exhaustive, while untyped/cast unknown runtime values still fail closed asno_worker_surface.assertEmbedBackfillQueueAdmissionrefuses before any database/config access unless the explicit PGLite inline-worker trust is present, validates payload source IDs through the canonicalsource-id.tscontract before rendering any remedy, andembedBackfillManualDrainCommand(sourceId)is the single injection-safe exactgbrain embed --stale --source <id>recovery command.src/core/minions/errors.ts— dependency-freeUnrecoverableErrorandJobDeferredError(reason, message, retryInMs), re-exported throughtypes.tsfor compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction. AJobDeferredErrorreturns the job todelayedforretryInMsthroughMinionQueue.deferJob(no attempt counted, no stacktrace entry); the worker, the facts drain and the isolation codec (errorKind: 'deferred') all route it (test/facts-absorb-keyless-deferral.test.ts).src/core/minions/global-maintenance-stall.ts— brain-wide maintenance stall verdict (GBRA-130 C-6):assessGlobalMaintenanceStall(stalelast_global_atplus failed jobs or a phase streak, or passes stamping past a failing phase or a triage deferral that stopped shrinking, #7307; a deferral streak's fix isgbrain dream retriage) feeds doctorglobal_maintenance_stalled; the daemon writes it toautopilot-global-maintenance.jsoneach full-cycle tick (recordGlobalMaintenanceStallStatus), and so does a global-maintenance pass that stampslast_global_at(#7854,test/autopilot-status-verdict-7854.test.ts), andautopilot --statusreads it without the database (readGlobalMaintenanceVerdict).src/core/minions/handler-timeouts.ts— per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other).HANDLER_DEFAULT_TIMEOUT_MS: 30 min forsubagent,subagent_aggregator,embed-backfill,autopilot-cycle,autopilot-global-maintenance,extract(a brain-wideextract --stalepass); 10 min forchronicle_extract+facts-absorb; 60 min forcontextual_reindex_per_chunk.HANDLER_DEFAULT_LOCK_DURATION_MS: 300 s for the long LLM/loop handlers and forsync(its blocking git helpers can each outlast a 30 s lease), 120 s for the single-LLM-call handlers,shelldeliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway).defaultTimeoutMsFor/defaultLockDurationMsForreturn the mapped default ornull(short handlers keep the tight null-default wall-clock / the 30 s worker lease).clampLockDurationMs+LOCK_DURATION_MS_MIN/MAX([5s, 1h]) is the ONE clamp shared byqueue.add, the CLI--lock-duration-msflag (--dry-runechoes the clamped value), and the MCPsubmit_jobparam; the same bound is mirrored in SQL at claim time and by theminion_jobs.lock_duration_msrange CHECK, so every layer agrees. Layers (explicit value always wins):MinionQueue.add()stamps at submit;MinionQueue.claim()COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilledtimeout_mswith authoring-time snapshot values — do NOT sync v128 when editing the maps (lock_duration_mshas no backfill: NULL = worker default).DEFAULT_CHAT_PER_TURN_TIMEOUT_MS(30 min) andresolveChatPerTurnTimeoutMsresolveai.chat.per_turn_timeout_ms, the per-turn chat timeout the subagent handler hands every gateway-loop turn (ToolLoopOpts.turnTimeoutMs→ChatOpts.timeoutMs, replacing the 300 s gateway backstop) and the oneshot sub-budget ceiling; the job's own signal still ends a turn at the job deadline (#4921). Pinned bytest/minions.test.ts+test/migrations-v128.test.ts+test/migrations-v130.test.ts+test/minions/subagent-turn-timeout.test.ts.src/core/minions/handlers/contextual-reindex-per-chunk.ts— per-page contextual re-embed handler. Withexpected_source_idit resolves the page in that source only and fails the job as stale when the page is missing there, never falling back to a same-slug page in another source; without it, it triesdefaultand then every live source (test/contextual-reindex-lease-release.test.ts). Resolvesmodels.contextual_synopsisonce and isolates cross-worker leases by the full resolved model id.GBRAIN_CONTEXTUAL_SYNOPSIS_RPMcontrols the cap;GBRAIN_CONTEXTUAL_HAIKU_RPMis the compatibility alias.src/core/minions/handlers/embed-backfill.ts—embed-backfilljob handler (the deferred lane behind sync's cost gate). Cap ladder forembed.backfill_max_usd: a present-but-invalid value (0, negative, garbage) ismisconfiguredand FAILS CLOSED to the $10 default, which is never dropped; only the IMPLICIT default cap is lifted (uncapped-with-warning to stderr) when the embedding model is unpriceable viaisModelPriceable+pricing.overrides; the off tokens (off/unlimited/none) remove the ceiling. Single-flights via the same per-source lock key as CLIembed --stale(embed-backfill-lock.ts). Carries the progress-keyed stall watchdog arm: progress = bankedembedded + chunksProcessed; a stall aborts the drain and throwsstall_timeoutso the queue fails the job and the resumable cursor re-runs.src/core/minions/handlers/shell-audit.ts— per-submission JSONL audit trail at~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl(ISO-week rotation; override viaGBRAIN_AUDIT_DIR). Best-effort:mkdirSync(recursive)+appendFileSync; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.src/core/minions/handlers/shell-inherit.ts— three helpers.INHERIT_NAME_RE(/^[a-z][a-z0-9_]*$/) is the snake_case shape guard used by the validator; rejects__proto__, leading-underscore, uppercase, and path-traversal shapes so audit logs stay readable and prototype-pollution lookups can't smuggle through.deriveEnvKey(name)maps config-key → child-env-key (name.toUpperCase()with one override:database_url→GBRAIN_DATABASE_URLbecause plainDATABASE_URLis ambiguous).resolveInheritValue(cfg, name)is the value lookup; usesObject.hasOwnto defeat prototype-pollution lookups, returns undefined for missing / non-string / empty-string values. No closed enum — agent and worker share a uid, so refusing arbitrary config keys defends nothing in that trust model.src/core/minions/handlers/shell-redact.ts— opt-in output-side scrubbing for shell-job stdout/stderr. PureredactSecretsInText(text, secrets)wheresecretsis any ordered iterable of[name, value]pairs (both production callers — the shell handler andbrain-repo-durability.ts's PAT scrub — pass a Map; an array is accepted so two values can share a pattern name): string-modereplaceAllso regex metacharacters in values stay literal, applied in iteration order — when one value is a substring of another the longer one must come first. When the caller passesredact_secrets: true(or--redact-secrets), the handler builds a Map of inherit-name → resolved-value and post-processes both tails before throw/return so persistedresult.stdout_tail/result.stderr_tail/error_textcarry<REDACTED:name>. Onlyinherit:-resolved values are scrubbed; caller-suppliedenv:values pass through. Heuristic — defeatsecho "$GBRAIN_DATABASE_URL", not adversarial encode-then-print. Defaultfalse.src/core/minions/handlers/shell-validate.ts—validateShellJobParams(data, opts?)shared pre-enqueue validator. ThrowsUnrecoverableErrorwith paste-ready operator hints on every failure. Three rules: (1) cmd/argv/cwd/env shape, (2) inherit array shape + snake_case regex per element (prototype-pollution defense), (3) fail-fast on missing config value withgbrain config set <key>hint. Optionalredact_secrets?: booleanfor output-side scrubbing. Deliberately does NOT police WHICH secrets the agent passes — single-uid trust model. Test seam:opts.configdrives the validator hermetically without mocking. Re-called atshell.tshandler entry for defense-in-depth (catches rows that bypassed the pre-enqueue validator).src/core/minions/handlers/shell.ts—shelljob handler. Spawns/bin/sh -c cmd(absolute path, PATH-override-safe) orargv[0] argv[1..](no shell). Env allowlistPATH, HOME, USER, LANG, TZ, NODE_ENV+ callerenv:overrides +inherit:-resolved keys. UTF-8-safe stdout/stderr tail viastring_decoder.StringDecoder. Abort (eitherctx.signalorctx.shutdownSignal) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (registerBuiltinHandlers) and self-gated: unlessGBRAIN_ALLOW_SHELL_JOBS === '1'in the worker env — set bygbrain jobs work --allow-shell-jobsafter the cwd-.envpreflight, or exported from the operator's shell (a cwd.envcannot set it:env-trust.ts) — a claimed job throwsUnrecoverableErrornaming--allow-shell-jobs(dead-letter, no retries).ShellJobParams.inherit?: string[]is a free-form list of snake_case config-key names; the worker resolves each vialoadConfig()and injects the value under the derived env key (database_url→GBRAIN_DATABASE_URL; else uppercased). Names persist inminion_jobs.data(and the shell-audit JSONL); values never do. The canonical validatorvalidateShellJobParams(siblingshell-validate.ts) runs PRE-ENQUEUE in both submit surfaces —gbrain jobs submit shell(jobs.ts:271) AND thesubmit_jobop forname='shell'(operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTERqueue.add()has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker. #5062: on POSIX the job runs in its own process group (detached); abort signals the whole group, escalates SIGTERM→SIGKILL by group liveness (processGroupAliveinjob-isolation.ts, notproc.killed), and after the leader exits anything left in the group is terminated and confirmed gone before the job settles (a backgroundedcmd &no longer outlives its job). On Windows abort signals the tree under the direct child withsignalProcessTree(taskkill/T, forced by/Fafter the grace window; a refused polite close waits for that escalation, and only a failed forced kill falls back toproc.kill); liveness is the direct child's, so a descendant orphaned by its parent's exit is not reaped. Pinned bytest/minions-shell-process-tree.test.ts.src/core/minions/handlers/subagent-aggregator.ts—subagent_aggregatorhandler. Claims AFTER all children resolve (queue guarantees every terminal child posts achild_doneinbox message with outcome). Reads inbox viactx.readInbox(), builds a deterministic mixed-outcome markdown summary. No LLM call.src/core/minions/handlers/subagent-audit.ts— JSONL audit + heartbeat writer at~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl. Events:submission(one per submit) +heartbeat(per turn boundary:llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed, plus the oneshot markersoneshot_fallback | oneshot_timeout; oneshot-path events carrymode: 'oneshot'and fallback events areason— both rendered bygbrain agent logs). Never logs prompts or tool inputs.readSubagentAuditForJob(jobId, {sinceIso})is the readback forgbrain agent logs.src/core/minions/handlers/subagent-oneshot.ts— oneshot synthesis runner. ONE rate-leased tool-lessgateway.chatcall (staticONESHOT_SYSTEMJSON contract rides the prompt-cache prefix; sub-budget min(ai.chat.per_turn_timeout_ms, time left/4) with a job deadline, else 5 min, passed as the call'stimeoutMsso the gateway's 300 s default backstop cannot cut it short →fallback_reason: 'oneshot_timeout'), then all-or-nothing validation BEFORE any write: JSON contract (parseOneshotResponse, ≤12 pages), slug grammar +allowed_slug_prefixes+ reflections/originals task shape + the exactoneshot_slug_suffix(the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (extractWikilinkTargets; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAMEbrain_put_pageToolDef the loop uses (fences/side-effects/provenance identical) withdeferEmbeds, bracketed by standard ledger rows under invocation-scoped idsoneshot-<inv8>-p<i>; a post-batchautoLinkWrittenPagepass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns{kind:'fallback', reason}and the same job falls through to the agentic loop. Pinned bytest/minions/subagent-oneshot.test.ts+ the oneshot describes intest/subagent-handler.test.tsandtest/e2e/dream-synthesize-pglite.test.ts.ONESHOT_SYSTEMspells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back aslengtheven when the provider normalized the stop toend/other; below-cap malformed output staysunparseable, and valid JSON at the cap proceeds normally. #6160: the task shapes come fromdata.oneshot_task_prefixes(the cycle's resolved reflections and originals namespaces, set bycycle/synthesize.ts); jobs queued by older builds derive them from allow-list entries whose path has apersonal/reflections/ororiginals/segment, root-level ones included.src/core/minions/handlers/subagent-persistence.ts— subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all$N::text::jsonbdiscipline), plusfinalizeWriteAccounting: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes, unlessisLegitimateZeroWriteaccepts the zero-attemptend_turnfinish: the oneshot explicit skip (oneshot_skipped: trueon asynth_mode_used: 'oneshot'result) or, when the submitter setallow_clean_zero_writes(the patterns phase), a run with at least one completed tool execution in its ledger — all-attempted-failed, dirty stops, prose-only finishes and runs whose only tools failed still dead-letter (the oneshot runner banks each skip as aoneshot-<inv8>-skipledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call);scopeToolUseIdPrefixnarrows the scan to the oneshot invocation family. Freshbrain_put_pagerejects are normalized bysrc/core/minions/tools/put-page-result.tsbefore ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.src/core/minions/handlers/subagent.ts— LLM-loop handler. A trusted dream synthesis child (corpus_source, or a legacydream_output.raw_source) is refusedsession_source_changed: <reason>before any model call when its session no longer resolves tosource_idor its incarnation (refuseChangedSessionSource, #7850). Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (ctx.signal+ctx.shutdownSignal), Anthropic prompt caching on system + tool defs.makeSubagentHandler({engine, client?, ...})factory;MessagesClientis an injectable interface the real SDK implements structurally. Per-turn output cap resolves viaresolveMaxOutputTokens(data.max_tokens→agent.max_output_tokensconfig → 8192 default); astop_reason: 'max_tokens'final turn surfaces asSubagentStopReason 'max_tokens'(not a silentend_turn), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Every stop-reason mapping (direct, gateway and replay paths) lives insrc/core/minions/subagent-stop-reason.ts(#6448; see Core Minions 2/2): an empty or refused final turn iserror/refusal, neverend_turn, and any trailing tool-free assistant turn is terminal on replay. ThrowsRateLeaseUnavailableError(renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop'sacquireTurnPermit) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running abovemaxConcurrent. Anthropic 400prompt is too longresponses (status 400 + body matches/prompt is too long|prompt_too_long|context.*length/i) classify asUnrecoverableErrorso the job goes straight todeadon first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation thatsynthesize.ts's chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends instop_reason: 'end_turn', the handler returns{ ok: true }immediately instead of issuing anothermessages.createcall (re-prompting pastend_turnwould get a 400 and dead-letter an already-successful job). Pinned bytest/subagent-handler.test.ts. Oneshot dispatch:data.mode === 'oneshot'on a FRESH job (zero persisted messages) routes torunSubagentOneshot(subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stampedsynth_mode_used: 'agentic_fallback'+fallback_reason. Write accounting (finalizeWriteAccountingin subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only);data.require_writesjobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError, except the deliberate zero-write completionsisLegitimateZeroWriteaccepts (an explicit oneshot skip, or anallow_clean_zero_writeschild with a completed tool execution). Optional-write jobs can still complete without writing.resolveMaxOutputTokenstakes the model: thinking-by-default models (Claude 5 by name or recipe-declaredthinking_by_defaultsuch as DeepSeek v4, via the gateway's sharedisThinkingModel) default to 32000 when neither per-job nor config caps are set. Gateway-pathonToolCallStarthas a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a#m<idx>o<ordinal>-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel;__testingunchanged). Tool-execution rows carry NO job-wide unique on the raw providertool_use_id(migration v131 dropsuniq_subagent_tools_use_id: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable(job_id, message_idx, ordinal)unique, and readers/settlement resolve an execution by(message_idx, tool_use_id). Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-idON CONFLICTas the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by(message_idx, tool_use_id)only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131gbrain jobs workdaemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)src/core/minions/handlers/supervisor-audit.ts— supervisor lifecycle JSONL audit at~/.gbrain/audit/supervisor-YYYY-Www.jsonl(ISO-week rotation; sharescomputeIsoWeekName()withshell-audit.ts).writeSupervisorEvent(emission, supervisorPid)appends one line per event (started,worker_spawned,worker_exited,backoff,health_warn,health_error,max_crashes_exceeded,shutting_down,stopped,worker_spawn_failed).readSupervisorEvents({sinceMs})is the readback forgbrain doctor. ExportsisCrashExit(event),summarizeCrashes(events),CrashSummarytype, andCLEAN_EXIT_CAUSESdenylist ('clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'). Single shared point — bothgbrain doctor(supervisor check) andgbrain jobs supervisor statusimport from here so the two surfaces can't drift.isCrashExitclassifies a singleworker_exitedagainst the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any futurelikely_causefromchild-worker-supervisor.ts) is a crash; audit lines lackinglikely_causefall back tocode !== 0.summarizeCrashesreturns{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}— thelegacybucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned bytest/supervisor-audit.test.ts(14 cases) and 4 source-grep wiring assertions intest/doctor.test.ts.src/core/minions/idempotency-coalesce.ts— the idempotency-key halves ofMinionQueue.add:coalesceOnIdempotencyKey(fast path) andinsertOrCoalesce(insert race: re-read the winner, release a dead or cancelled key with a CAS update that rechecks key, status and SQL NULL authority, retry the insert once). Both applycoalesceDecisionfromsubmission-authority.ts. The released key stays on the old row asdata.__released_idempotency_key(documented for operators indocs/guides/plugin-handlers.md), read throughCOALESCE(idempotency_key, data->>'__released_idempotency_key')by the dream paid-loop breaker (cycle/dream-breaker.ts), the synthesize daily cap and doctor's queue checks, so a resubmitted key's deaths still count. Tests:test/minions-legacy-coalesce.test.ts.src/core/minions/job-context.ts— sharedbuildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)(extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.src/core/minions/job-isolation.ts— per-job process-isolation protocol: atomic outcome-file codec (writeChildOutcomeFiletmp+rename,decodeChildOutcomeFilewith a 32MiB cap that throwsUnrecoverableError— oversize results die loudly on attempt 1, decode errors report byte counts never content),encodeHandlerError/reconstructHandlerErrorpreservingUnrecoverableError(aSpendGroupRefusedErrorkeeps its envelope: code, fix, group amounts),RateLeaseUnavailableError(with its retry delay), and allowlistedLocalConfigurationErrorreason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (CHILD_ENV,buildChildArgs),resolveChildCliInvocation(explicitGBRAIN_JOB_CHILD_CLIoverride → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake inchild-readiness.ts(protocol/features plus version-skew reporting;spend-enforcement-v1is advertised but required only for spend-authorized rows; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure).killProcessGroup(pid, sig)— children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. On Windows (no process groups) it runstaskkillCommand:%SystemRoot%\System32\taskkill.exe /PID <pid> /Tfor SIGTERM and/T /Ffor SIGKILL, by absolute path; a descendant whose parent already exited is outside the tree and survives.signalProcessTreereturnssignalled|gone(ESRCH, taskkill exit 128) |failed(state unknown);killProcessGroupis its boolean (signalled). Pinned bytest/job-isolation-protocol.test.ts(incl. real-process grandchild-death) andtest/spawn-windows-hide.test.ts(taskkill argv and outcomes; native tree kill on the windows-latest row).buildChildArgs(jobId, env = process.env)appends--allow-shell-jobswhenenv.GBRAIN_ALLOW_SHELL_JOBS === '1'(child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in;jobs run-childre-asserts the env from that flag. Pinned bytest/job-isolation-allow-shell-jobs.test.ts.child-job-runner.tspassesopts.env ?? process.envas the base env, soGBRAIN_ALLOW_SHELL_JOBS === '1'in it appends--allow-shell-jobs(any other value does not); pinned by the pass-through case intest/child-job-runner.test.ts.src/core/minions/lanes.ts— claim-time long-job lane reservation (#7242).claimExclusions(policy, inFlightNames)(policy is{concurrency, shortJobReservedSlots, longJobNames}, so the worker passes its own opts) returns the long names once in-flight long jobs filllongJobSlots(concurrency, reserved)(max(1, concurrency - reserved)at concurrency >= 2, else every slot), else[];MinionWorker's poll loop passes the result asMinionQueue.claim'sexcludeNames(AND NOT (name = ANY($n)), so ordering stays priority then created_at).DEFAULT_LONG_JOB_NAMESholds only single-flight brain-wide passes with a 30-minute-or-longer budget inhandler-timeouts.ts(autopilot-cycle,autopilot-global-maintenance,embed-backfill,connector-sync,extract); per-page fan-out jobs andsubagentstay out.resolveLanePolicy(engine)readsminions.short_job_reserved_slots(default 1, 0 disables; invalid or unreadable values fall back with one stderr line) andminions.long_job_names(comma list or JSON array, added to the defaults);gbrain jobs workresolves it at start (covering supervisor and autopilot spawns) and printsdescribeLanePolicyin the started line. Library workers default to the same policy throughMinionWorkerOpts.longJobNames/shortJobReservedSlots. The PGLitejobs workdrain runs at concurrency 1, so the reservation never applies there. Pinned bytest/minions-lanes.test.ts+test/minions-lane-reservation.test.ts;scripts/bench/minions-lane-load.ts(run bytest/minions-lane-load.slow.test.ts) measures short-job queue wait under mixed load with and without the reservation.src/core/minions/legacy-cancel.ts—gbrain jobs cancel --select(DX-T2, ENG-O5): selects live rows with SQL NULL or unsupported authority, hashes the fullcancelJobsclosure (selected rows plus parents that return from waiting-children to waiting), refuses a selection that would cascade to a descendant outside it (legacy_job_selection_invalid, E-T4), and applies under a table lock throughcancelJobsin one transaction after re-hashing (preview_changedon drift). Tests:test/jobs-cancel-select.test.ts.src/core/minions/legacy-selection.ts— the--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"grammar shared bygbrain jobs authorize-legacy --selectandgbrain jobs cancel --select(parseLegacyJobSelectionrefuses withlegacy_job_selection_invalid), the filled preview/apply commands (selectCommand), the recovery hint every legacy refusal names (legacyRecoveryHint), thelegacy_jobs_activeprecondition listing up to 10gbrain jobs cancel <id>commands, and the DX-O3(d) summary. Both commands are CLI-only (no operation). Tests:test/jobs-authorize-legacy-select.test.ts.src/core/minions/lock-renewal-tick.ts— Pure function behindMinionWorker.launchJob's setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. ExportsrunLockRenewalTick(deps, state) → Promise<TickResult>+resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs+RenewalCallTimeoutError+LockRenewalTelemetryCtx. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (lease - safetyMargin, cadence-aware:sinceLastSuccess + intervalMs >= deadline), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (auditsuccess_after_failurewithvia: 'verify'); fenced-false → CERTAIN loss →lock_lost(the only certain signal); verify unreachable → defer + reconnect-once (auditfailurewithdeadline_deferred: true), aborting only pasthardEvictMs— a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps):GBRAIN_LOCK_RENEWAL_MAX_FAILURES(default 3, audit-labeling only),GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS(defaultmin(lease/3, 15s)),GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS(defaultmin(lease/6, 30s)),GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS(default2×lease, floored to the soft deadline; setting it TO the deadline approximates abort-at-deadline). Telemetry: tick lateness (now - lastTickFiredAt - intervalMs, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation),overlapSkips(tickInFlight re-entrancy skips only), failure-cause classification via the namedRenewalCallTimeoutError(call-timeout|refused|fenced-lost), optionaldeps.loadSnapshot(try/caught — telemetry must never throw into control flow) anddeps.onRenewalSuccess(worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injecteddeps.now, which production binds toperformance.now()(monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded torenewLock(best-effort — the fence is the correctness authority). The tick checksstate.cancelled()at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union:should_abortcarries{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}andlock_lostcarries{cause: 'fenced-lost', via: 'renewal'|'verify'}; the worker stashes the result as per-launchabortMetaso the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned bytest/worker-lock-renewal.test.ts(hermetic state-machine suite incl. a fake-time starvation replay, the cadence-quantization pin, hard-backstop timelines, relational-clamp cases) +test/e2e/worker-lock-renewal-starvation.test.ts(real-PG foundations).LockRenewalDeps.renewLockcarries an optional per-call{signal}; the timeout race aborts it so the losing UPDATE releases its slot.src/core/minions/niceness.ts— OS scheduling-priority (niceness) primitives for the--niceflag.parseNiceValue(raw)whole-string parses + range-validates to POSIX[-20, 19](rejects"3.5"/"10abc"thatparseIntwould silently truncate).applyNiceness(nice, setPriority?, getPriority?)callsos.setPriority(0, n)and ALWAYS re-readsos.getPriority(0)afterwards — in both the success and the catch paths — so a denied renice (EPERM) or anRLIMIT_NICEclamp records the real effective value (e.g.0), not null; returns{applied, requested, effective, error?}.getEffectiveNiceness(pid, getPriority?)reads an arbitrary pid's niceness (null on dead/unreadable).formatNice(n)→+10/0/-5. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned bytest/niceness.test.ts.src/core/minions/plugin-loader.ts—GBRAIN_PLUGIN_PATHdiscovery. Absolute paths only, left-wins collision,gbrain.plugin.jsonwithplugin_version: "gbrain-plugin-v1", plugins ship DEFS only (no new tools),allowed_tools:validated at load time against the derived registry.src/core/minions/protected-names.ts— side-effect-free constant module exportingPROTECTED_JOB_NAMES+isProtectedJobName(). Kept pure so queue core can import without loading handler modules.PROTECTED_JOB_NAMESincludessynthesize,patterns,consolidate. These phases internally submitsubagentchildren withallowProtectedSubmit=trueand can spend Anthropic credits. Only trusted local callers (CLI, autopilot,doctor --remediate) can submit them; MCP requests are rejected bysubmit_job's protected-name guard.