Files
gbrain/docs/guides/queue-operations-runbook.md
Garry Tan 668b9bac30 v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins

Closes the critical- and high-severity items from six privately reported
advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv,
GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a
single commit so no intermediate revision carries a test-fixture credential
shape through the gitleaks range gate.

Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0
owner-approval flow is pinned end to end against a real `serve --http
--enable-dcr` process and in-process: anonymous /authorize mints no code, a
forged code is rejected at /token, revoked clients are refused at grants.begin,
and OAuthGrants.begin() now caps awaiting-decision requests per client_id.

Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2).
registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via
scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only.
Remote sources_remove is source-fenced like sources_status. doctor's
oauth_client_scope_health flags privileged self-registered clients.

Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains
jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus
bearer and db_url_credentials catch-alls; the transcripts lane opts into the
digit-gated high-entropy rule; getRawData follows the page soft-delete on both
engines; delete_page --purge (local-CLI only) hard-removes a leaked page.

Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts
drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_*
variables when a working-directory .env assigns them (key-presence, since Bun
expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs.

Release artifacts: VERSION/package.json/three plugin manifests bumped to
0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md,
CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin
trees, skills.lock, flag registry and llms bundle regenerated; module-size
ceilings adjusted with per-row reasons; TODOS follow-ups filed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: pre-landing review fixes (v0.50.2.0 security wave)

Review cycle 1 of the ship: 6 specialists + red team + coverage audit.

Security / red team:
- env-trust: parse .env with Bun's line grammar (bare CR terminates a line;
  BOM/U+2028 cannot hide an assignment); protect the loader / git / node /
  proxy / AI-CLI variable families a checkout could plant for the programs
  gbrain spawns; cli-preflight re-execs gbrain once with the sanitized
  environment so git, the agent CLI and workers inherit the clean view;
  cwd == ~/.gbrain no longer quarantines the operator's own .env.
- guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths
  (a package name resolves from the cwd's node_modules).
- secret-scan: bounded db_url_credentials quantifiers + per-pattern
  prechecks (linear on long lines), windowed previews that redact every
  sibling span, single-pass longest-first replacement.
- TODOS: follow-up entries reworded to the functional level.

API contract / maintainability:
- delete_page purge: remote callers get permission_denied; a purged
  response always carries write_through; get_raw_data description states
  the soft-delete follow; includeDeleted narrowed to the getRawData
  signature; client_credentials gate evaluated before the DCR ceiling;
  doctor privileged set derived from the scope registry; sources_remove /
  sources_status share assertSourceInCallerScope; shell-job opt-in reaches
  --job-isolation process children as --allow-shell-jobs; stale help copy.
- transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key
  order made every healthy re-run rewrite unchanged rows).

Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified
pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms
bundle, flag registry, tool catalog, structural suites regenerated;
module-size rows adjusted with reasons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave)

Re-exec redesign (security + red team + adversarial findings):
- cli-preflight re-runs gbrain from an empty temporary directory so the
  sanitized child never reloads the hostile .env: dropped keys are absent,
  never carried as '' (git and the dynamic loader presence-check
  GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident).
- The re-run marker is JSON {cwd, neutral} honoured only when the process
  provably started in that empty directory — a marker planted via a cwd
  .env is ignored (the ppid-keyed marker was forgeable under systemd/docker).
- SIGINT is delivered by the tty once (wrapper no longer forwards it);
  SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime.
- Protected families widened: XDG config roots (git reads
  $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust
  stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the
  GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker.
- cwd dotenv parsed once per start; jobs start uses the same '1' literal.

secret-scan (cycle-2 findings):
- db_url_credentials password class only stops at whitespace, '@' and
  string delimiters again (unescaped / { } < > | ^ ` \ passwords redact);
  BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body
  bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts
  were quadratic); incremental PEM line cursor; redactFindings rebuilds
  the text by span-splice in one pass (was O(unique values x text)).

Contract / docs:
- delete_page purge responses carry a residuals hint (git history, exports,
  compiled context, slug-keyed derived rows); CHANGELOG states a single
  truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under
  Changed with a migration note); SECURITY.md / KEY_FILES / docs guides /
  minion-orchestrator skill describe the new mechanism and the
  --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source
  marker on the hook spawn-shape test; new PEM fixtures fragmented.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave)

- Compiled binaries: every `bun build --compile` invocation passes
  `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh`
  guard (self-tested, in verify CHECKS) keeps it that way.
- cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`,
  OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE
  join the protected set; the neutral hop dir is realpath'd; signal
  handlers are installed before the spawn; non-tty wrappers forward SIGINT
  once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had
  a value.
- secret-scan: PEM header-line cursor is O(text) on newline-free tails;
  bounded bearer echo pass redacts bare re-occurrences of claimed tokens.
- transcripts ingest: raw-metadata probe reads active rows only.
- Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT,
  perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms +
  skills.lock + plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave)

Cross-model adversarial pass (Codex) + Claude verifier findings:
- env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS,
  PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH,
  BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded.
- cli-preflight: config-dir exemption refused when the cwd .env assigns
  GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal
  listeners so its exit is always the child's; SIGINT forwarded only
  without a controlling terminal (/dev/tty probe); a dropped planted HOME
  is restored from the passwd home; script-mode runs warn once when the
  cwd bunfig.toml declares a top-level preload.
- secret-scan: overlapping matches redact the UNION of matched spans;
  echo pass covers bearer + high-entropy values (64 unique, <=512 chars)
  via per-value sweeps over unclaimed gaps only; planRedaction/
  applyRedaction share a session-wide echo dictionary in transcripts
  render.
- sources_remove keys on write authority (assertSourceInCallerWriteScope);
  federated read grants confer no removal right.
- delete_page --purge retries the tombstone's file removal and fails
  closed (storage_error) while the file remains.
- Docs: SECURITY.md quarantine example no longer uses the one key that
  refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS
follow-up refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave)

- cli-preflight: hop marker carries the wrapper pid; a verified re-run arms
  an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the
  wrapper is force-killed, so supervisor restarts never orphan a worker;
  relative path-bearing runtime flags (--preload/-r/--require/--import,
  --config/-c, --env-file, --tsconfig-override) are resolved against the
  original cwd before the hop.
- secret-scan: echo pass is a streaming leftmost-longest merge with O(values)
  retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went
  from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now
  covered wall-to-wall.
- Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: update project documentation for v0.50.3.0

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(ci): green the three failing checks on the v0.50.3.0 wave

- semgrep: six `nosemgrep` suppressions with justifications for the
  path-join/resolve and non-literal-RegExp taint heuristics on operator-
  controlled cwd/flag paths and compile-time pattern sources (no behaviour
  change).
- test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s
  intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the
  pty's SIGINT on itself after the child exits (130) instead of relaying
  the child's 42. The pty command now `exec`s the wrapper so no shell stays
  in the foreground group; documented in a `ptyCommand` helper.
- Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly
  the self-registration ceiling (`read write`) via
  `scopesSupportedForDiscovery`, so a connector that copies
  `scopes_supported` into /register succeeds (master's #5122 pin); without
  DCR the full operator list minus `agent` is unchanged. Sibling e2e
  assertions that expected privileged scopes on the DCR-enabled server
  updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES
  updated; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up
refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 21:40:59 -07:00

13 KiB
Raw Blame History

Queue operations runbook

"My queue looks wedged — what do I run?" The commands below are in the order you probably want them.

First signal: jobs aren't running

gbrain doctor --json | jq '.checks[] | select(.name == "queue_health")'

queue_health flags two patterns:

  • stalled-forever: active job whose started_at is older than 1h.
  • waiting-depth: any per-name queue deeper than 10 (override via GBRAIN_QUEUE_WAITING_THRESHOLD). Signals a missing maxWaiting.

The worker is alive but wedged (dead pool)

The nastiest stall: the worker process is running (passes ps / kill -0 / container health), but its DB connection died (common behind a transaction pooler) and never came back, so it claims no jobs and finishes nothing. Jobs pile up with 0 active. Liveness checks all pass; nothing crashes.

This self-heals — you usually won't have to do anything:

  • The worker exits on its own dead pool. Under a supervisor, the worker's DB-liveness probe runs and self-exits (db_dead) after ~3 minutes; the supervisor respawns it with a fresh pool.
  • The supervisor restarts a worker that stops making progress. If a queue has claimable work, 0 live-lock active jobs, and no completions for 15 minutes across 3 consecutive health checks while the child is alive, the supervisor restarts it (covers stuck handlers too, not just dead pools). These thresholds are built in — there are no CLI flags to tune them. A restart-loop breaker caps wedge restarts at 3 per 30-minute window, then switches to a one-shot wedge_restart_loop alert in the audit log.

The signal is loud; check either:

gbrain jobs stats --queue default          # prints a WEDGED QUEUE line
gbrain doctor --json | jq '.checks[] | select(.name == "wedged_queue")'

wedged_queue is a per-queue health error (0 active_healthy + waiting > 0 + stale completions). Manual fix if you ever need it:

# Restart the supervisor with a fresh pool. `start` alone runs in the
# FOREGROUND (blocks); use --detach to get your shell back.
gbrain jobs supervisor stop && gbrain jobs supervisor start --detach --json

# Re-queue any jobs that were dead-lettered during the wedge.
gbrain jobs retry <id>

The backlog grows structurally (DIVERGENT QUEUE)

A different failure from a wedge: the worker is draining fine, but one job type's intake structurally exceeds its completions, so the waiting pile grows forever. The queue has admission control and the signal is loud:

gbrain jobs stats            # Drained/Waiting columns + a DIVERGENT QUEUE
                             # scream per offending type (also in --json)
gbrain doctor --json | jq '.checks[] | select(.name == "queue_health")'
                             # same findings for cron topologies

The scream fires when a type's 24h intake exceeds GBRAIN_QUEUE_DIVERGENCE_RATIO (default 2) × its 24h completions AND more than GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING (default 50) jobs are waiting. Cancellations — including the waiting-TTL sweep — are deliberately not counted as drain: outflow is not work.

What's already protecting you, and the knobs:

  • Param-coalescing (default on for subagent): identical parentless submits — same owner lane, payload, and execution options — coalesce onto the existing waiting job instead of stacking. Per-name toggle: minions.coalesce_params.<name>.
  • Waiting-TTL (default 48h for subagent): jobs still waiting past the TTL are cancelled with an auditable reason instead of queueing forever. Tune or disable: gbrain config set minions.ttl_waiting_hours.<name> <hours|0>. The first sweep never fires cold — a one-time notice prints with the affected-job count, then a one-hour grace window holds before the first cancellation.
  • Waiting quota (opt-in, off by default): a hard cap on a type's waiting count, name-global across queues, exact under concurrent submitters. New submits past the cap are rejected with a structured, retryable error. Opt in: gbrain config set minions.quota_max_waiting.<name> <n>.
  • Kill-switch: GBRAIN_MINIONS_ADMISSION=0 disables all three at once (incident escape hatch, no DB needed).

Triage commands

# Who's active right now?
gbrain jobs list --status active

# Who's waiting, biggest pile first?
gbrain jobs list --status waiting --limit 50

# What's wrong with a specific job?
gbrain jobs get <id>

Rescue actions (in order of escalation)

# Cancel a single stuck job (inline mode: cooperative — the handler must
# observe its abort signal, and after 30s it is force-evicted from tracking
# but the promise keeps running; with --job-isolation process the child is
# actually SIGTERM→SIGKILLed once cancellation is detected):
gbrain jobs cancel <id>

# Clear a specific job entirely (last resort):
gbrain jobs delete <id>

# Health smoke on the mechanism itself:
gbrain jobs smoke --wedge-rescue

What each subcheck means

  • stalled-forever — A worker claimed a job, started executing, and has held the row for over an hour. The wall-clock sweep evicts jobs past 2× timeout_ms. Long-lane handlers (subagent, autopilot-cycle, embed-backfill, …) always have a budget: it is stamped at submit and COALESCEd from HANDLER_DEFAULT_TIMEOUT_MS at claim for rows with a NULL budget. gbrain jobs get <id> prints the effective budget and which kill path applies. If a short-lane job is still active with no budget, the null-default sweep (2 × lock-duration × max_stalled) evicts it within minutes. Cancel it if you can't wait.
  • duplicate cycles — Byte-identical waiting autopilot-cycle rows for one source (the shape a job stalled in active would otherwise leave behind). The maxPending dispatch guard prevents accumulation. Suppressed dispatches are visible in jobs stats (Backpressure line) and the backpressure audit JSONL.
  • waiting-depth — Submitters are piling up jobs faster than workers drain them. Set --max-waiting N on the submission or on the programmatic queue.add() call. If you want a taller pile, raise the threshold via GBRAIN_QUEUE_WAITING_THRESHOLD=50 gbrain doctor.
  • divergent queue — A type's 24h intake structurally exceeds its 24h completions while a real backlog waits (same thresholds as the jobs stats scream, so the two surfaces agree). The finding names the type and prints the exact minions.quota_max_waiting.<name> command to cap admission. See "The backlog grows structurally" above.
  • waiting-TTL cancellations — The admission sweep cancelled queued work that expired unclaimed in the last 24h. That's operating as designed, but it means the divergence is being shredded, not worked — intake still exceeds drain. Tune with gbrain config set minions.ttl_waiting_hours.<name> <hours|0>.

Lock-renewal: reading an eviction, and the knobs

Lock renewal is verify-before-evict: a thrown or timed-out renewal is never treated as loss. At the deadline the worker runs one fenced re-check against the database — the only CERTAIN loss signal is that fenced miss. Every renewal fault also writes a JSONL audit event (~/.gbrain/audit/lock-renewal-*.jsonl) carrying the fields that answer the first incident question — was the database down, or was the worker starved?

How to read a gave_up / eviction line:

Field Reading
cause call-timeout = our own timer fired (starved loop, slow pool, or slow DB); refused = the driver threw (SQLSTATE in error_code); fenced-lost = certain reclaim, not an infrastructure fault.
lateness_ms How late the renewal tick fired vs its own cadence. Tens of seconds = the WORKER was starved; ~0 with refused = the database was actually unreachable.
load1 / cores Raw loadavg at event time, with core count for normalization.
overlap_skips Ticks skipped because a prior renewal call was still in flight.
deadline_deferred The soft deadline passed but the fenced verify was unreachable — the job was KEPT and retried (the fence is the backstop).
event_loop_delay … (log line) p99/max event-loop delay since the last successful renewal — the direct starvation measurement.

A Job N did not exit within 30s of abort line after an infrastructure abort is NOT an orphan leak: the handler is cooperatively cancelling. The line carries the same cause/lateness/load fields. Caveat: eviction is cooperative — an abort-IGNORING handler keeps running past every bound and can duplicate external side effects until it exits; the worker only frees the slot.

Env knobs (incident escape hatches; all validated, warn-once on bad values; defaults derive from the per-job lease):

Env var Default What it does
GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS min(lease/3, 15s) Per-call budget for each renewal attempt (raced + best-effort cancelled).
GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS min(lease/6, 30s) Headroom before lease expiry; the fenced verify fires when the NEXT tick would land past lease - margin.
GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS 2 × lease Hard local backstop when even the verify is unreachable (total outage). Floored to the soft deadline. Setting it TO the soft deadline removes the verify grace and aborts at the deadline.
GBRAIN_LOCK_RENEWAL_MAX_FAILURES 3 Audit-event labeling only — never gates eviction.
GBRAIN_MINION_STALL_RECLAIM_GRACE_MS 15000 Stall-sweep reclaim grace: a lease that lapsed within this window is not reclaimed (starved-owner head start). 0 disables the grace (bare lock_until < now() predicate). Capped at 600000 (10 min, warn-once + clamp) — an oversized value would otherwise disable stalled-job recovery fleet-wide.

Cross-knob invariants are enforced with warn-once clamps (margin < lease/2, call timeout ≤ renewal cadence, hard evict ≥ soft deadline) — a misconfigured knob can degrade cadence but cannot silently re-break the deadline math.

Per-job lease: gbrain jobs submit --lock-duration-ms N (clamped [5 s, 1 h] — enforced at submit, re-applied to the resolved lease at claim, and backed by a database range constraint; --dry-run echoes the clamped value that will actually be stored); long LLM handlers default to 300 s via HANDLER_DEFAULT_LOCK_DURATION_MS in src/core/minions/handler-timeouts.ts. Renewal cadence is min(lease/2, 60 s). Trade-off: a genuinely dead worker's long-lease job requeues after lease + grace + one sweep interval.

Self-check: is a worker even running?

# If you're running autopilot with --no-worker, check that your external
# worker (systemd / Docker / OpenClaw service-manager) is alive:
gbrain jobs list --status active | head -5

If the list is empty AND your submissions keep piling up, no worker is claiming. Start one:

gbrain jobs work --concurrency 4 --allow-shell-jobs   # drop --allow-shell-jobs if you never submit shell jobs

Reading the DB-probe verdicts (pool starved vs server unreachable)

When the worker's health probe fails repeatedly, the terminal [health] DB probe failed N consecutive times (verdict: ...) line — and the unhealthy payload the supervisor sees — carries a verdict that names the failing LAYER (the intermediate (N/3) lines log only the failure detail). Read it before touching anything: a pool_starved verdict on a server sitting at a fraction of max_connections is a client-side problem, and resizing the database instance does nothing for it.

Verdict What it means What to do
pool_starved The read-pool probe failed but the DIRECT-lane probe succeeded — the database server is reachable; the fault is in the transaction-pooler path (client pool exhaustion or a pooler-layer fault; the probe deliberately does not distinguish the two). Look at client-side load: long-running handler queries holding slots, GBRAIN_POOL_SIZE too small for the workload, or a pooler-layer incident. Do NOT resize the database. The worker exit is correct recovery — it frees every client-held slot.
server_unreachable Both the pooler lane and the direct lane failed. Check connectivity/capacity first: network, DNS, the database itself. Both-lanes-failed is the evidence — credential/config errors or a saturated direct lane can also land here, so glance at the probe detail text before concluding the server is down.
unknown The read probe failed and no direct lane exists to disambiguate (single-pool mode: non-Supabase, kill switch active, or no derivable direct URL). Check the startup log for the single-pool warning; consider GBRAIN_DIRECT_DATABASE_URL so future incidents self-diagnose.

The gbrain-tracked in flight counts in the message are a tracked SUBSET (raw/direct/reserved/transaction seams only) — most template-path queries are untracked, so 0 in flight next to a pool_starved verdict means the saturation lives in that untracked traffic or at the pooler layer itself, not that the pool is idle. The verdict, not the counts, is the authoritative signal.