Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
54.6 KB
Raw Blame

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.ts reconcilePrivateQueue terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable private_queue_reconciled: reason family; renewPrivateQueueLease is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; reconcileOrphanedPrivateQueues cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; classifyPrivateQueueForRecovery is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in gbrain jobs work after driver/selected-child readiness and ensureSchema, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in beforeSpawn. maybeRunWorkerStartupRecovery(queue, process.env, true) keeps this worker-owned ordering even under GBRAIN_SUPERVISED=1. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). deriveWedgeSignal is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports private_queue: true so 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, plus job-pull.ts and job-progress.ts) — one module per built-in handler body, each a make<Name>Handler(engine) factory (or a MinionHandler const when it needs no engine). Registered in a fixed order by registerBuiltinHandlers in src/commands/jobs.ts, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as withFactsAbsorbHaltCooldown; cycle-phase.ts serves the six phase wrappers. Command cores are imported lazily inside each handler. resolveJobPull and the facts-absorb retry predicates are re-exported from jobs.ts. autopilot-global-maintenance runs one runCycle call per maintenance phase and keeps its pass position in config autopilot.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], key fail:<code>, budget, child:<outcome> or deferred, counted once per pass); after three earlier fail: 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 or gbrain autopilot --retry-global (rules in the module header). Phases run through an ItemRun (site autopilot.global_maintenance). Probe: test/pathological/a10-global-maintenance-stamp.test.ts. The deadline comes from GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS > autopilot.global_maintenance_timeout_ms > the autopilot default (autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs); doctor global_maintenance_timeouts (doctor/checks/global-maintenance-timeouts.ts) warns after three consecutive deaths and names gbrain dream --phase <name> (autopilot-global-maintenance-resume-4578.test.ts). The sync handler runs performSync under job.signal composed with job.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 its git pull (async pullRepo on bounded-child-exec.ts) stop and the job is handed back without burning an attempt. A queued autopilot_freshness sync job re-reads its source when it runs and returns {skipped:true, reason:'sync_disabled'} when the source now has syncEnabled:false; any sync job that performSync refuses sync_not_applicable or sync_anchor_relative completes as a skip (the latter carrying the refusal's suggestion and ask-the-user fix, 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 via sync-job-drain.ts. Progress (job-progress.ts reportJobProgress, best-effort: a failed write never fails the job): autopilot-cycle passes CycleOpts.onPhaseStart and autopilot-global-maintenance writes before each phase's runCycle, both {phase, phase_index, phase_count, started_at}; the sync handler always passes jobDrainProgress's onProgress, which writes a classic sync's phase (resolve_repo, git_pull, full_import, import with banked_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 via resolveAdmissionPolicy (config minions.* > per-name defaults tables, 60s in-process cache per engine, fail-open with a once-per-process stderr warn; env kill-switch GBRAIN_MINIONS_ADMISSION=0 disables all three): PARAM-COALESCING (PARAM_COALESCE_DEFAULT — on for subagent; computeParamHash = sha256 of stable-stringified payload excluding __param_hash itself and the __submitter display label — __owner_client_id is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (WAITING_TTL_DEFAULT_HOURS — 48h for subagent; swept by MinionQueue.handleWaitingTTL through cancelJobs(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 is runWaitingTtlTick — first tick counts affected + stamps TTL_NOTICE_SHOWN_KEY with an ISO timestamp, sweeping starts only after ttlNoticeGraceMs() (1h default, env GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS) elapses; gbrain upgrade prints the same one-shot notice and starts the same clock; legacy 'true' flag values sweep immediately), and NAME-GLOBAL QUOTA (QUOTA_MAX_WAITING_DEFAULT EMPTY by operator decision — activates only via minions.quota_max_waiting.<name>; counts the name across ALL queues so per-run dream-inline-* fanout queues can't dodge it, EXACT under concurrency via a minion_quota:<name> advisory xact lock taken only when a quota is configured; throws typed QueueQuotaExceededError, checked everywhere via isQueueQuotaExceededError — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, submit_agent maps to a structured rate_limited OperationError). TTL_REASON_PREFIX is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; safeConfigSegment gates untrusted job names out of copy-pasteable config hints. Alerting rides getStats (drained_completed/failed/dead/cancelled keyed on finished_at + waiting_now + oldest_waiting_minutes), the jobs stats DIVERGENT-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 doctor checkQueueHealth. Pinned by test/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 for maxWaiting AND maxPending coalesce 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). readRecentCoalesceCounts feeds the jobs stats Backpressure 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 by test/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. reserveGroup meters 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 is GroupBudgetRefusal('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 by client_id, so group spend never appears in client budgets or admin client spend. readGroupSpend is 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 throws ChildWorkerShutdownError with separate executionStopped evidence; group cleanup retains its kill backstop after direct-child exit, and unconfirmed cleanup must not authorize configuration release). onExecutionStopped publishes 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 as LocalConfigurationError and other pre-exec spawn failures as ChildSpawnInfraError (no attempt burned), and bounds child pools via env (GBRAIN_POOL_SIZE default 3, GBRAIN_DIRECT_POOL_SIZE=1). A spend-authorized row (opts.spendAuthorized) is never handed to a child that did not advertise spend-enforcement-v1 at readiness: SpendEnforcementUnavailableError releases it through the lease path for an upgraded worker. Pinned by test/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 both MinionSupervisor (standalone gbrain jobs supervisor daemon) and src/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, NO process.exit, NO health check. WORKER_EXIT_CONFIGURATION and the generation-scoped OwnerProcessingState channel block spawning before generic crash accounting; configurationBlocked also 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 shared processing-state.ts validates 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 injected onEvent: (ChildSupervisorEvent) => void. Exit classifier: code === 0 leaves crashCount UNCHANGED (preserves flap detection across mixed exit sequences); code != 0 follows runDuration > stableRunResetMs ? 1 : ++crashCount. Clean-restart budget: sliding window of code=0 exits; when count exceeds cleanRestartBudget (default 10) inside cleanRestartWindowMs (default 60s), emits health_warn { reason: 'clean_restart_budget_exceeded' } and applies cleanRestartBudgetBackoffMs (default 1s). The exit classifier special-cases WORKER_EXIT_RSS_WATCHDOG — likely_cause='rss_watchdog', and that exit does NOT bump crashCount (routes to its own breaker); a dedicated _watchdogExitTimestamps sliding window trips a loud rss_watchdog_loop health_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). Opts watchdogLoopBudget (3), watchdogLoopWindowMs (600000), watchdogBackoffMs (30000); ChildSupervisorEvent extended. Public read-only accessors childAlive, inBackoff, crashCount; killChild(signal) gates on liveness (exitCode === null && signalCode === null), NOT .killed — .killed flips true once a signal is sent, so a !this._child.killed guard 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 _intentionalRestart so the exit is likelyCause='wedge_restart', leaves crashCount UNTOUCHED (never trips max_crashes; like rss_watchdog), and respawns immediately (backoff ms:0 reason='wedge_restart'). awaitChildExit(timeoutMs) short-circuits when child.exitCode !== null || child.signalCode !== null so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the run() loop does not fire onMaxCrashesExceeded at the soft maxCrashes; it announces health_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 at hardStopMaxCrashes (default maxCrashes × HARD_STOP_CRASH_MULTIPLIER = 10×; 0 disables). Test hooks _backoffFloorMs, _now. supervisor-audit.ts carries rss_watchdog as a non-clean cause + its own CrashSummary.by_cause bucket, and wedge_restart to CLEAN_EXIT_CAUSES (a self-heal, not a crash; denylist preserved so future causes route to legacy). Pinned by test/child-worker-supervisor.test.ts (12 cases). #5062: lastExit records 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 at timeoutMs), 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 typed client_misconfigured. runDbReadinessProbe checks every required lane even after read success; a LocalConfigurationError on 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 by test/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 to wiki/agents/<job-id>/*. Removing submit_agent stops 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 (with src/core/ai/invocation-guard.ts available as gbrain/ai/invocation-guard for 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. runWithJobSpend prices 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 for gbrain 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 as stdio[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 by test/detached-stderr.test.ts.

  • src/core/minions/embed-backfill-admission.ts — Centralized, dependency-light embed-backfill admission contract shared by the public MinionQueue.add boundary, CLI, MCP operations, automatic submitters, sync cost reporting, and doctor remediation. embedBackfillWorkerSurface recognizes only explicit postgres as worker-backed; the declared engine-kind switch is compile-time exhaustive, while untyped/cast unknown runtime values still fail closed as no_worker_surface. assertEmbedBackfillQueueAdmission refuses before any database/config access unless the explicit PGLite inline-worker trust is present, validates payload source IDs through the canonical source-id.ts contract before rendering any remedy, and embedBackfillManualDrainCommand(sourceId) is the single injection-safe exact gbrain embed --stale --source <id> recovery command.

  • src/core/minions/errors.ts — dependency-free UnrecoverableError and JobDeferredError(reason, message, retryInMs), re-exported through types.ts for 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. A JobDeferredError returns the job to delayed for retryInMs through MinionQueue.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 (stale last_global_at plus 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 is gbrain dream retriage) feeds doctor global_maintenance_stalled; the daemon writes it to autopilot-global-maintenance.json each full-cycle tick (recordGlobalMaintenanceStallStatus), and so does a global-maintenance pass that stamps last_global_at (#7854, test/autopilot-status-verdict-7854.test.ts), and autopilot --status reads 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 for subagent, subagent_aggregator, embed-backfill, autopilot-cycle, autopilot-global-maintenance, extract (a brain-wide extract --stale pass); 10 min for chronicle_extract + facts-absorb; 60 min for contextual_reindex_per_chunk. HANDLER_DEFAULT_LOCK_DURATION_MS: 300 s for the long LLM/loop handlers and for sync (its blocking git helpers can each outlast a 30 s lease), 120 s for the single-LLM-call handlers, shell deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). defaultTimeoutMsFor / defaultLockDurationMsFor return the mapped default or null (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 by queue.add, the CLI --lock-duration-ms flag (--dry-run echoes the clamped value), and the MCP submit_job param; the same bound is mirrored in SQL at claim time and by the minion_jobs.lock_duration_ms range 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 backfilled timeout_ms with authoring-time snapshot values — do NOT sync v128 when editing the maps (lock_duration_ms has no backfill: NULL = worker default). DEFAULT_CHAT_PER_TURN_TIMEOUT_MS (30 min) and resolveChatPerTurnTimeoutMs resolve ai.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 by test/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. With expected_source_id it 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 tries default and then every live source (test/contextual-reindex-lease-release.test.ts). Resolves models.contextual_synopsis once and isolates cross-worker leases by the full resolved model id. GBRAIN_CONTEXTUAL_SYNOPSIS_RPM controls the cap; GBRAIN_CONTEXTUAL_HAIKU_RPM is the compatibility alias.

  • src/core/minions/handlers/embed-backfill.ts — embed-backfill job handler (the deferred lane behind sync's cost gate). Cap ladder for embed.backfill_max_usd: a present-but-invalid value (0, negative, garbage) is misconfigured and 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 via isModelPriceable + pricing.overrides; the off tokens (off/unlimited/none) remove the ceiling. Single-flights via the same per-source lock key as CLI embed --stale (embed-backfill-lock.ts). Carries the progress-keyed stall watchdog arm: progress = banked embedded + chunksProcessed; a stall aborts the drain and throws stall_timeout so 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 via GBRAIN_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_URL because plain DATABASE_URL is ambiguous). resolveInheritValue(cfg, name) is the value lookup; uses Object.hasOwn to 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. Pure redactSecretsInText(text, secrets) where secrets is any ordered iterable of [name, value] pairs (both production callers — the shell handler and brain-repo-durability.ts's PAT scrub — pass a Map; an array is accepted so two values can share a pattern name): string-mode replaceAll so 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 passes redact_secrets: true (or --redact-secrets), the handler builds a Map of inherit-name → resolved-value and post-processes both tails before throw/return so persisted result.stdout_tail / result.stderr_tail / error_text carry <REDACTED:name>. Only inherit:-resolved values are scrubbed; caller-supplied env: values pass through. Heuristic — defeats echo "$GBRAIN_DATABASE_URL", not adversarial encode-then-print. Default false.

  • src/core/minions/handlers/shell-validate.ts — validateShellJobParams(data, opts?) shared pre-enqueue validator. Throws UnrecoverableError with 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 with gbrain config set <key> hint. Optional redact_secrets?: boolean for output-side scrubbing. Deliberately does NOT police WHICH secrets the agent passes — single-uid trust model. Test seam: opts.config drives the validator hermetically without mocking. Re-called at shell.ts handler entry for defense-in-depth (catches rows that bypassed the pre-enqueue validator).

  • src/core/minions/handlers/shell.ts — shell job handler. Spawns /bin/sh -c cmd (absolute path, PATH-override-safe) or argv[0] argv[1..] (no shell). Env allowlist PATH, HOME, USER, LANG, TZ, NODE_ENV + caller env: overrides + inherit:-resolved keys. UTF-8-safe stdout/stderr tail via string_decoder.StringDecoder. Abort (either ctx.signal or ctx.shutdownSignal) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (registerBuiltinHandlers) and self-gated: unless GBRAIN_ALLOW_SHELL_JOBS === '1' in the worker env — set by gbrain jobs work --allow-shell-jobs after the cwd-.env preflight, or exported from the operator's shell (a cwd .env cannot set it: env-trust.ts) — a claimed job throws UnrecoverableError naming --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 via loadConfig() and injects the value under the derived env key (database_url → GBRAIN_DATABASE_URL; else uppercased). Names persist in minion_jobs.data (and the shell-audit JSONL); values never do. The canonical validator validateShellJobParams (sibling shell-validate.ts) runs PRE-ENQUEUE in both submit surfaces — gbrain jobs submit shell (jobs.ts:271) AND the submit_job op for name='shell' (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER queue.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 (processGroupAlive in job-isolation.ts, not proc.killed), and after the leader exits anything left in the group is terminated and confirmed gone before the job settles (a backgrounded cmd & no longer outlives its job). On Windows abort signals the tree under the direct child with signalProcessTree (taskkill /T, forced by /F after the grace window; a refused polite close waits for that escalation, and only a failed forced kill falls back to proc.kill); liveness is the direct child's, so a descendant orphaned by its parent's exit is not reaped. Pinned by test/minions-shell-process-tree.test.ts.

  • src/core/minions/handlers/subagent-aggregator.ts — subagent_aggregator handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a child_done inbox message with outcome). Reads inbox via ctx.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 markers oneshot_fallback | oneshot_timeout; oneshot-path events carry mode: 'oneshot' and fallback events a reason — both rendered by gbrain agent logs). Never logs prompts or tool inputs. readSubagentAuditForJob(jobId, {sinceIso}) is the readback for gbrain agent logs.

  • src/core/minions/handlers/subagent-oneshot.ts — oneshot synthesis runner. ONE rate-leased tool-less gateway.chat call (static ONESHOT_SYSTEM JSON 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's timeoutMs so 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 exact oneshot_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 SAME brain_put_page ToolDef the loop uses (fences/side-effects/provenance identical) with deferEmbeds, bracketed by standard ledger rows under invocation-scoped ids oneshot-<inv8>-p<i>; a post-batch autoLinkWrittenPage pass 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 by test/minions/subagent-oneshot.test.ts + the oneshot describes in test/subagent-handler.test.ts and test/e2e/dream-synthesize-pglite.test.ts. ONESHOT_SYSTEM spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as length even when the provider normalized the stop to end/other; below-cap malformed output stays unparseable, and valid JSON at the cap proceeds normally. #6160: the task shapes come from data.oneshot_task_prefixes (the cycle's resolved reflections and originals namespaces, set by cycle/synthesize.ts); jobs queued by older builds derive them from allow-list entries whose path has a personal/reflections/ or originals/ 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::jsonb discipline), plus finalizeWriteAccounting: 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, unless isLegitimateZeroWrite accepts the zero-attempt end_turn finish: the oneshot explicit skip (oneshot_skipped: true on a synth_mode_used: 'oneshot' result) or, when the submitter set allow_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 a oneshot-<inv8>-skip ledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call); scopeToolUseIdPrefix narrows the scan to the oneshot invocation family. Fresh brain_put_page rejects are normalized by src/core/minions/tools/put-page-result.ts before 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 legacy dream_output.raw_source) is refused session_source_changed: <reason> before any model call when its session no longer resolves to source_id or 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; MessagesClient is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via resolveMaxOutputTokens (data.max_tokens → agent.max_output_tokens config → 8192 default); a stop_reason: 'max_tokens' final turn surfaces as SubagentStopReason 'max_tokens' (not a silent end_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 in src/core/minions/subagent-stop-reason.ts (#6448; see Core Minions 2/2): an empty or refused final turn is error/refusal, never end_turn, and any trailing tool-free assistant turn is terminal on replay. Throws RateLeaseUnavailableError (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's acquireTurnPermit) 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 above maxConcurrent. Anthropic 400 prompt is too long responses (status 400 + body matches /prompt is too long|prompt_too_long|context.*length/i) classify as UnrecoverableError so the job goes straight to dead on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that synthesize.ts's chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in stop_reason: 'end_turn', the handler returns { ok: true } immediately instead of issuing another messages.create call (re-prompting past end_turn would get a 400 and dead-letter an already-successful job). Pinned by test/subagent-handler.test.ts. Oneshot dispatch: data.mode === 'oneshot' on a FRESH job (zero persisted messages) routes to runSubagentOneshot (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped synth_mode_used: 'agentic_fallback' + fallback_reason. Write accounting (finalizeWriteAccounting in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); data.require_writes jobs (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 completions isLegitimateZeroWrite accepts (an explicit oneshot skip, or an allow_clean_zero_writes child with a completed tool execution). Optional-write jobs can still complete without writing. resolveMaxOutputTokens takes the model: thinking-by-default models (Claude 5 by name or recipe-declared thinking_by_default such as DeepSeek v4, via the gateway's shared isThinkingModel) default to 32000 when neither per-job nor config caps are set. Gateway-path onToolCallStart has 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; __testing unchanged). Tool-execution rows carry NO job-wide unique on the raw provider tool_use_id (migration v131 drops uniq_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-id ON CONFLICT as 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-v131 gbrain jobs work daemon 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; shares computeIsoWeekName() with shell-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 for gbrain doctor. Exports isCrashExit(event), summarizeCrashes(events), CrashSummary type, and CLEAN_EXIT_CAUSES denylist ('clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'). Single shared point — both gbrain doctor (supervisor check) and gbrain jobs supervisor status import from here so the two surfaces can't drift. isCrashExit classifies a single worker_exited against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future likely_cause from child-worker-supervisor.ts) is a crash; audit lines lacking likely_cause fall back to code !== 0. summarizeCrashes returns {total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits} — the legacy bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by test/supervisor-audit.test.ts (14 cases) and 4 source-grep wiring assertions in test/doctor.test.ts.

  • src/core/minions/idempotency-coalesce.ts — the idempotency-key halves of MinionQueue.add: coalesceOnIdempotencyKey (fast path) and insertOrCoalesce (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 apply coalesceDecision from submission-authority.ts. The released key stays on the old row as data.__released_idempotency_key (documented for operators in docs/guides/plugin-handlers.md), read through COALESCE(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 — shared buildJobContext(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 (writeChildOutcomeFile tmp+rename, decodeChildOutcomeFile with a 32MiB cap that throws UnrecoverableError — oversize results die loudly on attempt 1, decode errors report byte counts never content), encodeHandlerError/reconstructHandlerError preserving UnrecoverableError (a SpendGroupRefusedError keeps its envelope: code, fix, group amounts), RateLeaseUnavailableError (with its retry delay), and allowlisted LocalConfigurationError reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (CHILD_ENV, buildChildArgs), resolveChildCliInvocation (explicit GBRAIN_JOB_CHILD_CLI override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in child-readiness.ts (protocol/features plus version-skew reporting; spend-enforcement-v1 is 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 runs taskkillCommand: %SystemRoot%\System32\taskkill.exe /PID <pid> /T for SIGTERM and /T /F for SIGKILL, by absolute path; a descendant whose parent already exited is outside the tree and survives. signalProcessTree returns signalled | gone (ESRCH, taskkill exit 128) | failed (state unknown); killProcessGroup is its boolean (signalled). Pinned by test/job-isolation-protocol.test.ts (incl. real-process grandchild-death) and test/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-jobs when env.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-child re-asserts the env from that flag. Pinned by test/job-isolation-allow-shell-jobs.test.ts. child-job-runner.ts passes opts.env ?? process.env as the base env, so GBRAIN_ALLOW_SHELL_JOBS === '1' in it appends --allow-shell-jobs (any other value does not); pinned by the pass-through case in test/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 fill longJobSlots(concurrency, reserved) (max(1, concurrency - reserved) at concurrency >= 2, else every slot), else []; MinionWorker's poll loop passes the result as MinionQueue.claim's excludeNames (AND NOT (name = ANY($n)), so ordering stays priority then created_at). DEFAULT_LONG_JOB_NAMES holds only single-flight brain-wide passes with a 30-minute-or-longer budget in handler-timeouts.ts (autopilot-cycle, autopilot-global-maintenance, embed-backfill, connector-sync, extract); per-page fan-out jobs and subagent stay out. resolveLanePolicy(engine) reads minions.short_job_reserved_slots (default 1, 0 disables; invalid or unreadable values fall back with one stderr line) and minions.long_job_names (comma list or JSON array, added to the defaults); gbrain jobs work resolves it at start (covering supervisor and autopilot spawns) and prints describeLanePolicy in the started line. Library workers default to the same policy through MinionWorkerOpts.longJobNames / shortJobReservedSlots. The PGLite jobs work drain runs at concurrency 1, so the reservation never applies there. Pinned by test/minions-lanes.test.ts + test/minions-lane-reservation.test.ts; scripts/bench/minions-lane-load.ts (run by test/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 full cancelJobs closure (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 through cancelJobs in one transaction after re-hashing (preview_changed on 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 by gbrain jobs authorize-legacy --select and gbrain jobs cancel --select (parseLegacyJobSelection refuses with legacy_job_selection_invalid), the filled preview/apply commands (selectCommand), the recovery hint every legacy refusal names (legacyRecoveryHint), the legacy_jobs_active precondition listing up to 10 gbrain 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 behind MinionWorker.launchJob's setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. Exports runLockRenewalTick(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 (audit success_after_failure with via: 'verify'); fenced-false → CERTAIN loss → lock_lost (the only certain signal); verify unreachable → defer + reconnect-once (audit failure with deadline_deferred: true), aborting only past hardEvictMs — 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 (default min(lease/3, 15s)), GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS (default min(lease/6, 30s)), GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS (default 2×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 named RenewalCallTimeoutError (call-timeout | refused | fenced-lost), optional deps.loadSnapshot (try/caught — telemetry must never throw into control flow) and deps.onRenewalSuccess (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected deps.now, which production binds to performance.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 to renewLock (best-effort — the fence is the correctness authority). The tick checks state.cancelled() at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: should_abort carries {cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?} and lock_lost carries {cause: 'fenced-lost', via: 'renewal'|'verify'}; the worker stashes the result as per-launch abortMeta so 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 by test/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.renewLock carries 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 --nice flag. parseNiceValue(raw) whole-string parses + range-validates to POSIX [-20, 19] (rejects "3.5"/"10abc" that parseInt would silently truncate). applyNiceness(nice, setPriority?, getPriority?) calls os.setPriority(0, n) and ALWAYS re-reads os.getPriority(0) afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an RLIMIT_NICE clamp 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 by test/niceness.test.ts.

  • src/core/minions/plugin-loader.ts — GBRAIN_PLUGIN_PATH discovery. Absolute paths only, left-wins collision, gbrain.plugin.json with plugin_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 exporting PROTECTED_JOB_NAMES + isProtectedJobName(). Kept pure so queue core can import without loading handler modules. PROTECTED_JOB_NAMES includes synthesize, patterns, consolidate. These phases internally submit subagent children with allowProtectedSubmit=true and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, doctor --remediate) can submit them; MCP requests are rejected by submit_job's protected-name guard.