Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(minions): submitted_by, blocked_by, liveness, spend and progress on job rows; jobs wait + wait_job; finished-since cursor; terminal hook; short-job lane reservation (#7241, #7242)

garrytand392b26fbece
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index a08836f3d7..aa73eba680 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 158 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 159 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -112,6 +112,7 @@ Every non-localOnly operation on the MCP surface: 158 tools across 25 areas. **S
| `send_job_message` | Send a sidechannel message to a running job's inbox (for jobs that read steering messages). | admin | | |
| `submit_agent` | Submit an agent job (agent scope; tools and budget bound to your client). | agent | yes | |
| `submit_job` | Submit a background job. | admin | | |
+| `wait_job` | Wait until a job is completed, failed, dead or cancelled (at most 55 s per call), then return it like get_job plus terminal. | admin | | |
## links
diff --git a/docs/architecture/key-files/core-cycle-primitive.md b/docs/architecture/key-files/core-cycle-primitive.md
index 23dddf222e..7a40ff04dd 100644
--- a/docs/architecture/key-files/core-cycle-primitive.md
+++ b/docs/architecture/key-files/core-cycle-primitive.md
@@ -3,4 +3,4 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` skips with `status: 'skipped'` and `details.reason: 'disabled'` before any scan when `cycle.lint.enabled` is explicitly false (#6369, `cycleLintPhaseEnabled` in `cycle/lint-fix-setting.ts`; `onceForPhase === 'lint'` threads through as `opts.once` and bypasses it for one run; `gbrain lint` never reads it), repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). A lost filesystem-walk or incremental extract write (`ExtractBatchWriteError`, code `extract_write_lost`, `src/core/extract-watermark.ts`) leaves only its pages unstamped and makes the extract phase warn, like a GBRA-130 A-1 stale drain failure; the same cycle's stale drain retries those pages. Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged. The extract_atoms / synthesize_concepts pack gate (#6393) is `src/core/cycle/pack-phase-gate.ts` ([Core Cycle (continued)](core-cycle-continued.md)); `packDeclaresPhase(engine, phase, sourceId?)` delegates to it.
+- `src/core/cycle.ts` — brain maintenance cycle primitive (`ALL_PHASES` is the ordered source of truth; `fence_repair` follows `sync` and runs the `fences` repair kind through `cycle/fence-repair.ts`). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. `runPhaseLint` skips with `status: 'skipped'` and `details.reason: 'disabled'` before any scan when `cycle.lint.enabled` is explicitly false (#6369, `cycleLintPhaseEnabled` in `cycle/lint-fix-setting.ts`; `onceForPhase === 'lint'` threads through as `opts.once` and bypasses it for one run; `gbrain lint` never reads it), repairs with `fix: true` unless DB config `cycle.lint_fix` is explicitly false (report-only; `gbrain lint --fix` unaffected); `cycle.lint_exclude` (#6134, `cycle/lint-fix-setting.ts` `cycleLintExcludes`/`parseCycleLintExclude`) lists basenames the lint phase and the `lint`/`lint-fix` minion handlers skip (`details.excluded`; `config set` refuses a path); managed repairs left pending keep the phase at `warn` and surface as `details.pending` (`test/managed-lint.test.ts`). Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (`src/core/abort-signals.ts`, re-exported; duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; extract_atoms also receives the cycle signal as a real `AbortSignal` and stops at its next item, the others run to their own bounded timeout). A busy DB lock's `cycle_already_running` skip carries `lock_holder` (`id`, `holder_pid`, `holder_host`, `age_ms`). A source-scoped cycle that selects a brain-wide phase (in NEEDS_LOCK and not `source` scope) also tries the shared `gbrain-cycle` lease through `cycle/lock-set.ts`; when another cycle holds it, the source phases run and each brain-wide phase is reported `skipped` with `maintenance_lock_busy` (an all-skipped selection reports `skipped`). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive; `onPhaseStart(phase, index, count)` is awaited inside `timePhase` as each selected phase starts its work (index and count within the resolved selection; a throwing hook is logged, never fatal), which the `autopilot-cycle` handler turns into job progress. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, synthesize AND fence_repair so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain, or a connector source) the 5 filesystem phases (lint/backlinks/sync/synthesize/patterns) skip with `details.reason: 'no_brain_dir'`, extract runs the database-only stale drain (`cycle/connector-extract.ts`), and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). A lost filesystem-walk or incremental extract write (`ExtractBatchWriteError`, code `extract_write_lost`, `src/core/extract-watermark.ts`) leaves only its pages unstamped and makes the extract phase warn, like a GBRA-130 A-1 stale drain failure; the same cycle's stale drain retries those pages. Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; a managed brain (`managedPersistenceEnabled`, false when `persistence_brain` is missing) sees `gbrain sync --all --no-pull --hard-deadline 13m` every 15 minutes on the owner host with `gbrain sources refresh <id>;` chained first for remote-tracking checkouts; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/core/cycle.serial.test.ts` (5-minute DB-lock and file-lock TTL behavior), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run. The `extract_facts` phase runs the S9 conflict sweep as its tail (`ai/decide/sweep.ts` `conflictSweepTail`) only when `decide.slots.conflict.mode` is not off, adding `details.decide_conflict`; with the slot off the phase output is unchanged. The extract_atoms / synthesize_concepts pack gate (#6393) is `src/core/cycle/pack-phase-gate.ts` ([Core Cycle (continued)](core-cycle-continued.md)); `packDeclaresPhase(engine, phase, sourceId?)` delegates to it.
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index 229bed65f4..17090a7c85 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -4,9 +4,9 @@
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`) — 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`; 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`.
+- `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`; 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, 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 only `__param_hash` itself — `__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/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, 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).
@@ -62,12 +62,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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`. Tests: `test/minions-legacy-coalesce.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`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 9f26aa4fc8..49d1d00fec 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -5,6 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`.
+- `src/core/minions/queue-families.ts` — `queueFamilyStats(engine, since)` behind `MinionQueue.getStats().by_queue`: one row per queue (`waiting_now`/`active_now` now; `total`/`completed`/`failed`/`dead` among rows created in the window, the `by_type` semantics), with every per-run `dream-inline-*` queue folded into one `dream-inline` row whose `queues` counts them. `gbrain jobs stats` prints a line per row (`dream-inline (N queues)`) and carries `by_queue` in `--json`; `get_job_stats` spreads it too. `--queue <name>` still scopes the wedge block to one queue. Test: `test/jobs-stats-private-queue.serial.test.ts`.
+
- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).
- `src/core/minions/rss-default.ts` — cgroup-aware auto-sized default for the worker RSS watchdog cap. `resolveDefaultMaxRssMb(opts?)` / `describeDefaultMaxRss(opts?)` (provenance for the startup log) / `readCgroupMemLimitBytes(readFile?)`. Used at every spawn site (`jobs work`, `jobs supervisor`, autopilot, `MinionSupervisor`). Formula `clamp(round(0.5 × basisMB), 4096, 16384)` where `basis = min(cgroupLimit, totalmem)`. LOAD-BEARING NUANCE: plain `os.totalmem()` reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 `/sys/fs/cgroup/memory.max` (literal `max` = unlimited) then v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Explicit `--max-rss` (including `0` to disable) always wins. Pinned by `test/rss-default.test.ts`.
@@ -34,7 +36,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`. `SubagentHandlerData.require_writes` requires at least one settled successful page write, not merely a clean model finish, except the deliberate zero-write completions `isLegitimateZeroWrite` accepts (an explicit oneshot skip, or an `allow_clean_zero_writes` child with a completed tool execution).
-- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.
+- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline. `isTerminalJobStatus` is the one terminal-status test. Consumers: `gbrain jobs wait` (`src/commands/jobs/wait.ts`: exit 0 completed, 1 failed/dead/cancelled, 124 still running at `--timeout`, 2 usage; a thin client loops over MCP `wait_job`) and the `wait_job` op (`ops/jobs.ts`: the get_job owner fence runs before any wait, so a foreign id refuses at once with get_job's exact error; one call holds at most `WAIT_JOB_MAX_S` = 55 s and returns the get_job row plus `terminal`). Pinned by `test/minions/job-insight.test.ts` and `test/jobs-wait-cli.serial.test.ts`.
+- `src/core/minions/job-insight.ts` — #7241 fields computed on read for `jobs get/list --json`, `get_job`, `list_jobs` and `wait_job`: `submitted_by`, `blocked_by` (queue position and slot holders, waiting children, delay reason, paused, unreviewed authority, held `gbrain-sync:<src>` / `gbrain-cycle:<src>` locks with the holder job from the drain-lease beacon row), lease liveness (`heartbeat_age_ms` from `lock_until - lock_duration_ms`, else a lower bound from `updated_at`, `heartbeat_basis` says which; `lock_expires_in_ms`; `stalled`) and `spend` (token columns plus `cost_usd` from settled `mcp_spend_reservations` of the job and its descendants; `null` / `unpriced` when none, never 0). All times use the DB clock. Owner fence: for an agent token without admin a foreign submitter, parent, slot holder or lock holder is its kind only (`{kind:'lock', held:true}`), foreign descendants are left out of cost, and completed foreign children's tokens (completeJob rolls them into the parent) are subtracted, replacing the row's top-level token counts too; a remote caller never sees a lock holder's host or pid. `withSubmitterLabel` (called by `MinionQueue.add` on the stored data) always drops a caller-supplied `__submitter` and, for an application-authority submit from a labelled local process, stores `submitterLabel()` (`autopilot`, `serve`, `worker`, `job:<name>`, `cli:<command>`; `library` stores nothing) as job data `__submitter`. It is a display label only: `submission_authority` is untouched, `PARAM_HASH_EXCLUDED_KEYS` (`admission.ts`) leaves it out of the param hash, the remote submit paths cannot carry it (`prepareRemoteJob` refuses unknown data keys, `submit_agent` builds its own data), and `describeJobs` reads it only for rows whose authority is application. Rows queued before it carry no label.
+- `src/core/minions/terminal-events.ts` — #7242 append-only terminal event cursor (`jobs list --finished-since <iso|cursor> --json`, `list_jobs {finished_since}`): terminal rows ordered by `(finished_at, id)` at microsecond precision, `next_cursor` = `<epoch micros>:<id>`, so pages never repeat or skip; owner-fenced like list_jobs. A retried job that finishes again is a new event; deleted and pruned rows are not.
+- `src/core/minions/terminal-hook.ts` — #7242 terminal hook: `minions.terminal_hook` is a FILE-plane key only (`commands/config.ts` FILE_PLANE_DOTTED_KEYS; a DB-plane row is never read, so MCP, job data and anyone who can only write DB config cannot pick the command). An argv array with an absolute `argv[0]`, spawned with `shell: false`; the job arrives in GBRAIN_JOB_ID/NAME/QUEUE/STATUS and as fixed-field JSON on stdin (never data or result); killed at `timeout_ms` (default 10 s), failures logged once, never retried, never failing the job; at most 4 run at once. Runs as the gbrain process user. `gbrain jobs work` wires `terminalHookNotifier` into `MinionWorkerOpts.onJobSettled`, which the worker calls from `launchJob`'s settle (outside `executeJob`); the notifier re-reads the row and fires only for a terminal status. Pinned by `test/minions/terminal-hook.test.ts`.
+- `__released_idempotency_key` reminder: see the `idempotency-coalesce.ts` entry in core-minions-1.md.
- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12` and `WORKER_EXIT_CONFIGURATION = 16`; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).
diff --git a/docs/designs/minion-schedules.md b/docs/designs/minion-schedules.md
new file mode 100644
index 0000000000..be703e8b11
--- /dev/null
+++ b/docs/designs/minion-schedules.md
@@ -0,0 +1,187 @@
+# Minion schedules (deferred design)
+
+Status: deferred. This is an evaluation for issue #7242, item 3 ("native
+schedules"), written so a later wave can build it without redoing the survey.
+
+## Problem
+
+An agent running long work on a large deployment keeps its own cron entries
+for recurring gbrain work: sync wrappers, embed batches, enrichment fan-outs,
+landing watchers, progress gates. Each entry brings its own overlap control,
+spend control and run history, none of which gbrain can see. About a third of
+those entries exist only to watch or prod gbrain's own jobs.
+
+The ask is a built-in primitive: a cron spec, an overlap policy
+(`skip` | `queue` | `replace`), a `max_usd` per schedule and per run,
+and run history readable over the CLI and MCP.
+
+## What autopilot already schedules
+
+`gbrain autopilot` is already a scheduler, but only for gbrain's own
+maintenance, and its cadence is fixed in code rather than declared per job:
+
+- **Host install.** `gbrain autopilot --install` writes one long-running
+ daemon per brain: a launchd agent with `KeepAlive` on macOS, a systemd user
+ unit on Linux, a start script for ephemeral containers, or a crontab line that
+ runs the wrapper every 5 minutes (`src/commands/autopilot.ts`,
+ `src/commands/autopilot/jobs.ts`). The brain-repo durability job is the one
+ launchd `StartInterval` job (`src/core/brain-repo-durability.ts`).
+- **Tick loop.** The daemon ticks every `--interval` seconds (default 300),
+ stretched by brain score (`adaptiveInterval` in
+ `src/commands/autopilot-daemon.ts`). Each tick (`dispatchAutopilotTick` in
+ `src/commands/autopilot-dispatch.ts`) submits per-source freshness syncs,
+ the extract_atoms auto-drain, then either sleeps, fans out per-source
+ `autopilot-cycle` jobs or submits targeted remediation handlers.
+- **Overlap control.** Every submission carries a slot idempotency key
+ (`autopilot-sync:<source>:<slot>`, `autopilot-cycle:<source>:<slot>`,
+ `autopilot-global:<slot>`), where the slot is the tick time floored to the
+ base interval, plus `maxPending: 1` single-flight or `maxWaiting: 1`. That
+ is the `skip` policy, applied by the queue's admission path.
+- **Floors and backoff.** A full cycle runs at least every 60 minutes
+ (`AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES`), brain-wide maintenance at its own
+ floor (`resolveGlobalFloorMin`), and a failing source backs off
+ exponentially (`autopilot.failure_cooldown_min`, in
+ `src/commands/autopilot-fanout.ts`).
+- **Daily probes.** The nightly quality probe is rate-limited to once per 24
+ hours with its own `max_usd` config key (`src/commands/autopilot-probes.ts`).
+- **Per-job timing.** Jobs already carry `delay`, `quiet_hours` (skip or
+ defer) and `stagger_key` (`src/core/minions/types.ts`).
+- **Spend.** Consent-gated producers store a spend authorization on each row
+ (`src/core/minions/spend-authorization.ts`): one group, one approved total,
+ each provider call reserved against `group:<id>` in the durable meter.
+
+What is missing is a user-declared recurring job: any handler name, a cron
+spec, a policy, a budget that renews per run, and a history of fires that
+includes the fires that did not submit anything.
+
+## Proposed design
+
+### Storage
+
+Two tables, added by one migration.
+
+`minion_schedules`:
+
+| Column | Type | Notes |
+|---|---|---|
+| `id` | `bigserial` | |
+| `name` | `text unique` | Operator-chosen, `[a-z0-9-]`, shown in run history and `submitted_by`. |
+| `job_name` | `text` | Must be a registered handler; protected names follow the trust rules below. |
+| `data` | `jsonb` | Job params, validated by the same path as `jobs submit`. |
+| `queue`, `priority`, `timeout_ms`, `max_attempts` | | Copied onto each job. |
+| `cron` | `text` | Five-field cron spec. |
+| `tz` | `text` | IANA zone; default the host zone at creation. |
+| `overlap` | `text` | `skip` \| `queue` \| `replace`. |
+| `max_usd_per_run` | `numeric null` | Required for paid job names. |
+| `max_usd_per_day` | `numeric null` | Optional ceiling across runs. |
+| `spend_authorization` | `jsonb null` | The consent record taken at creation. |
+| `submission_authority` | `jsonb` | Who created it; every run inherits it. |
+| `enabled` | `boolean` | `schedules pause` / `resume`. |
+| `next_run_at` | `timestamptz` | Indexed, partial on `enabled`. |
+| `last_run_at`, `last_job_id` | | |
+| `created_at`, `updated_at` | | |
+
+`minion_schedule_runs`: `schedule_id`, `fire_at` (the cron slot),
+`job_id` (null when nothing was submitted), `outcome`
+(`submitted` | `skipped_overlap` | `replaced` | `refused_budget` |
+`refused_disabled` | `missed`), `detail jsonb`, `created_at`. Pruned
+by the cycle's `purge` phase after a retention window. Job outcomes stay on
+`minion_jobs`; a run row only links to its job.
+
+### Tick and submit path
+
+1. A ticker claims due rows:
+ `SELECT ... FROM minion_schedules WHERE enabled AND next_run_at <= now() ORDER BY next_run_at FOR UPDATE SKIP LOCKED LIMIT n`,
+ so several workers can tick one brain safely.
+2. For each row it computes the slot (`fire_at`) and advances
+ `next_run_at` to the next cron time after `now()`. Missed slots during
+ downtime coalesce into one fire; the skipped slots are recorded as one
+ `missed` run with a count, never replayed.
+3. It applies the overlap policy against the schedule's live jobs (waiting,
+ delayed or active with a live lock):
+ - `skip`: record `skipped_overlap` with the live job id.
+ - `queue`: submit behind it (`maxWaiting: 1`, so at most one queued run).
+ - `replace`: cancel the live job through `cancelJob` (its terminal
+ path, children and inbox included), then submit.
+4. It submits through `MinionQueue.add` with
+ `idempotency_key: schedule:<id>:<fire_at>`, so a second ticker or a
+ retried tick coalesces instead of double-submitting, and records
+ `submitted` in the same transaction as the `next_run_at` update.
+
+Where the ticker runs: inside `gbrain jobs work` (every worker, gated by the
+row lock) and inside the autopilot tick. PGLite has no resident worker, so a
+PGLite brain ticks from autopilot's inline loop or from an explicit
+`gbrain schedules tick` a host cron can run.
+
+### Spend
+
+`schedules add` for a paid job name runs the same consent gate as
+`jobs submit enrich|subagent --max-usd` and stores the record on the schedule.
+Each fire stamps a fresh spend authorization on its job: group
+`schedule:<id>:<fire_at>`, approved total `max_usd_per_run`. Before it
+submits, the ticker sums the meter's settled and reserved spend for the
+schedule's groups over the trailing 24 hours (`readGroupSpend`) and records
+`refused_budget` when another run would exceed `max_usd_per_day`. A
+schedule never spends without a stored authorization: a paid job name with no
+`max_usd_per_run` is refused at creation.
+
+### Lineage
+
+Each submitted job carries `submitted_by: { kind: 'schedule', name, run_id }`
+(the producer field #7241 asks for), so `jobs get` names the schedule that
+fired it and `jobs list --schedule <name>` filters on it.
+
+## CLI and MCP surface
+
+CLI (trusted local, `remote = false`):
+
+- `gbrain schedules add <name> --job <job-name> --cron '<spec>' [--tz <zone>] [--overlap skip|queue|replace] [--max-usd <n>] [--max-usd-per-day <n>] [--params <json>] [--queue <q>]`
+- `gbrain schedules list [--json]`, `gbrain schedules get <name> [--runs N] [--json]`
+- `gbrain schedules pause|resume|remove <name>`, `gbrain schedules run <name>` (fire now, same policy)
+- `gbrain schedules tick` (for PGLite and host cron)
+
+MCP: `list_schedules` and `get_schedule` (with recent runs) at `admin` scope,
+read-only. Creating, changing or removing a schedule stays on the trusted local
+CLI in the first version. A schedule is standing authority: it submits jobs and
+spends money with nobody present, long after the call that created it. Remote
+`submit_job` already refuses protected names, rewrites remote params to what
+the grant allows and records the remote authority on the row; a remote
+`create_schedule` would need the same rules plus an expiry and a per-grant
+cap on schedules and spend, which is a trust-posture change that needs its own
+review. Shell jobs keep their worker-side `--allow-shell-jobs` gate.
+
+## Why it is deferred
+
+- It needs two tables and a migration, a cron parser (none is a dependency
+ today), and ticker placement that is correct with several workers on
+ Postgres and with no worker on PGLite.
+- The autopilot overlap and budget machinery works through slot keys and
+ single-flight admission; schedules should reuse those paths rather than add a
+ second scheduler with different semantics. Moving autopilot's own cadence onto
+ schedules is a separate, later decision.
+- Unattended spend needs the consent and meter design above reviewed as a
+ trust change, not added as a flag.
+- The parts of #7241 and #7242 that remove most polling today are smaller and
+ land first: `gbrain jobs wait`, the terminal-state hook, job progress and
+ lineage. With those, an external scheduler can at least wait and be notified
+ instead of polling.
+
+## What it needs
+
+- **Migration:** `minion_schedules` and `minion_schedule_runs` with the
+ `next_run_at` partial index, in `src/schema.sql` as well (CONTRIBUTING.md,
+ "Schema migration").
+- **Core:** a `src/core/minions/schedules.ts` module (claim, policy, submit,
+ record), a cron parser with tests for DST transitions and the five fields,
+ the ticker hook in the worker loop and the autopilot tick.
+- **CLI:** the `schedules` command record in `CLI_COMMANDS`, the flag
+ registry, CLI goldens.
+- **MCP:** the two read ops in a domain module under `src/core/ops/`, scope
+ `admin`, with a test that a remote caller cannot create or change a
+ schedule.
+- **Doctor:** a check for a schedule whose runs keep failing, or that keeps
+ skipping because its previous run never finishes.
+- **Tests:** PGLite and Postgres coverage for two tickers racing one due row
+ (one submit), each overlap policy, missed-slot coalescing after downtime,
+ the per-day budget refusal, `replace` cancelling a running job's children,
+ and the purge retention of run history.
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index 3af70992a3..918bc3ed25 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -101,6 +101,26 @@ check warns if what you asked for isn't what's actually running (e.g. a
negative value denied without privilege, or an OS `RLIMIT_NICE` clamp). This
is distinct from the concurrency / inflight cap and composes with it.
+### Keeping a slot for short jobs
+
+A worker running two or more jobs at once keeps one slot free of long jobs, so
+a 50-minute autopilot cycle can't hold every slot while short per-page jobs
+such as `facts-absorb` wait behind it. At `--concurrency N` (N of 2 or more),
+long jobs run in at most `N - minions.short_job_reserved_slots` slots, never
+fewer than one; the other slots take everything else. The long set is
+`autopilot-cycle`, `autopilot-global-maintenance`, `embed-backfill`,
+`connector-sync` and `extract`. A worker at `--concurrency 1` is unaffected.
+
+```bash
+gbrain config set minions.short_job_reserved_slots 2 # default 1; 0 turns it off
+gbrain config set minions.long_job_names sync,book-mirror # added to the built-in set (comma list or JSON array)
+```
+
+The worker reads both keys at start, so restart the supervisor after changing
+them. The `Minion worker started` line shows the result, for example
+`long-job lane: 1 of 2 slots`. Claim order inside each lane is still
+`priority` then submission time.
+
### Per-job process isolation (`--job-isolation process`)
By default all concurrency slots execute inside one worker process. A
@@ -237,6 +257,32 @@ shutdown) is also written to `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-YY
for historical inspection. `gbrain doctor` reads that file and surfaces
a `supervisor` check in its health report.
+### Watching jobs from an agent
+
+Every `jobs get --json`, `jobs list --json`, `get_job` and `list_jobs` row carries fields computed on read:
+
+- `submitted_by`: `{kind: 'local', via}` for a job submitted on the brain host (`via` is `autopilot`, `serve`, `worker`, `job:<name>` for a handler inside a running job, or `cli:<command>`, kept in the job's data as `__submitter`, a display label and never authority; rows queued before this field existed have no `via`), `{kind: 'parent_job', id}` for a child, `{kind: 'mcp_client', id}` for a remote submitter.
+- `blocked_by`: why a job that is not running is not running: `queue` (its `queue_position`, how many are ahead and which active jobs hold the queue's slots), `waiting_children`, `delayed` (with `delay_until` and the reason), `paused`, `unreviewed_authority`, or `lock` when a sync or cycle lock of the job's source is held (`holder_job_id` names the holding job when the drain lease records one). `null` for running and finished jobs.
+- `heartbeat_age_ms`, `lock_expires_in_ms` and `stalled` for an active job: how long since its lease was last renewed, measured on the database clock, and whether the lease has already run out.
+- `spend`: the token counts plus `cost_usd`, the settled, priced spend of the job and its children. `cost_usd` is `null` (`cost_basis: 'unpriced'`) when nothing priced it, never a made-up 0.
+
+An agent token without admin sees another principal only by kind: a foreign submitter, parent, slot holder or lock holder is never named, and another principal's children are left out of its spend.
+
+`gbrain jobs wait <id> [--timeout 10m] [--json]` blocks until the job ends and prints it. It exits 0 when the job completed, 1 when it failed, died or was cancelled, and 124 when the timeout elapsed and the job is still running (the job is not cancelled). MCP agents call `wait_job {id, timeout_s}`, which answers after at most 55 s with `terminal: true|false`; call it again while `terminal` is false.
+
+To learn about every job that finished without polling each one, read the terminal event cursor: `gbrain jobs list --finished-since <ISO time> --json` (MCP: `list_jobs {finished_since}`) returns `{jobs, next_cursor}`, oldest first. Pass `next_cursor` back on the next call. Rows deleted on completion or pruned are not in it.
+
+#### Terminal hook
+
+A worker can run a command each time a job it ran completes, fails, dies or is cancelled. It is off by default and lives only in the local file-plane config (`~/.gbrain/config.json`), never in the database config, MCP or job data:
+
+```bash
+gbrain config set minions.terminal_hook '["/usr/local/bin/notify-job", "--quiet"]'
+# or, with a timeout: '{"argv": ["/usr/local/bin/notify-job"], "timeout_ms": 5000}'
+```
+
+The value is an argv array whose first element is an absolute path; it is spawned without a shell, so nothing from the job is ever interpolated into a command line. The job arrives in `GBRAIN_JOB_ID`, `GBRAIN_JOB_NAME`, `GBRAIN_JOB_QUEUE` and `GBRAIN_JOB_STATUS`, and as one JSON object on stdin (id, name, queue, status, attempts_made, parent_job_id, created_at, started_at, finished_at, error_text; never the job's data or result: run `gbrain jobs get $GBRAIN_JOB_ID --json` for those). The hook runs as the gbrain process user with that process's environment, is killed after `timeout_ms` (default 10 s), and a failure is logged once on the worker's stderr and never retried; it never changes the job. Workers read it at start, so restart the supervisor after setting it. A job that died in another worker's stall sweep or was cancelled while waiting runs no hook; the event cursor above covers every terminal transition.
+
## Deployment: systemd
For long-running Linux VMs with shell access.
diff --git a/docs/guides/plugin-handlers.md b/docs/guides/plugin-handlers.md
index 2ef3ea3888..17b780545d 100644
--- a/docs/guides/plugin-handlers.md
+++ b/docs/guides/plugin-handlers.md
@@ -103,7 +103,13 @@ network library they use.
**Idempotency.** The queue enforces unique `idempotency_key` at the DB
layer, so you don't need to worry about double-submits from a cron that
-fires while the previous invocation is still running.
+fires while the previous invocation is still running. A dead or cancelled
+job does not hold its key: the next submit with that key clears it from the
+old row and records it there as `data.__released_idempotency_key`, which is
+why many rows (subagent rows especially) carry that field. It is bookkeeping,
+not a parameter: the dream paid-loop breaker, the synthesize daily cap and
+doctor's queue checks read it so a resubmitted key's earlier deaths and
+submissions still count.
## Gbrain's migration flow
diff --git a/docs/guides/queue-operations-runbook.md b/docs/guides/queue-operations-runbook.md
index 0ba825ca58..8eb16db552 100644
--- a/docs/guides/queue-operations-runbook.md
+++ b/docs/guides/queue-operations-runbook.md
@@ -103,8 +103,15 @@ gbrain jobs list --status waiting --limit 50
# What's wrong with a specific job?
gbrain jobs get <id>
+
+# Which queues hold the work? One line per queue (`by_queue` in --json);
+# the per-run dream-inline-* queues share one `dream-inline (N queues)` line.
+gbrain jobs stats
```
+`gbrain jobs stats --queue dream-inline-<ms>-<id>` still scopes the wedge and
+ABANDONED PRIVATE QUEUE lines to one per-run queue.
+
## Rescue actions (in order of escalation)
```bash
diff --git a/docs/progress-events.md b/docs/progress-events.md
index 82fb83a86b..d8de3f1a7b 100644
--- a/docs/progress-events.md
+++ b/docs/progress-events.md
@@ -214,7 +214,13 @@ breaking the orchestrator's `JSON.parse`. Its stdio is explicit:
not on stderr. Each Minion handler that runs a bulk core (embed, sync,
extract, import, backlinks) calls `job.updateProgress({done, total,
…})` per iteration. Agents read per-job progress via the
-`get_job_progress` MCP operation or `gbrain jobs get <id>`.
+`get_job_progress` MCP operation or `gbrain jobs get <id>`. A `sync` job
+writes the phase it is in (`resolve_repo`, `git_pull`, `full_import`,
+`import` with `banked_files`, or the managed drain's `managed_sync.*`
+fields), and `autopilot-cycle` / `autopilot-global-maintenance` write
+`{phase, phase_index, phase_count, started_at}` as each cycle phase starts
+(the phase names are `gbrain dream --phase` names). These writes are
+best-effort: a failed progress write never fails the job.
The `jobs work` daemon itself emits coarse one-line-per-job stderr output
for liveness only. Per-page detail lives in the DB.
diff --git a/scripts/bench/minions-lane-load.ts b/scripts/bench/minions-lane-load.ts
new file mode 100644
index 0000000000..680fdf879f
--- /dev/null
+++ b/scripts/bench/minions-lane-load.ts
@@ -0,0 +1,141 @@
+/**
+ * Synthetic job-load fixture for the long-job lane reservation (#7242).
+ *
+ * Measures queue wait (claim time minus submit time, both stamped by the
+ * database: `started_at - created_at`) for short jobs under a mixed load on
+ * an in-memory PGLite brain with one 2-slot worker. The run is scaled down from
+ * the shape that motivated the issue (50-minute maintenance passes starving
+ * per-page jobs): 3 long jobs of 1500 ms and 40 short jobs of 30 ms, submitted
+ * interleaved on a fixed schedule (a long job at 0, 350 and 700 ms; a short job
+ * every 50 ms from 25 ms). It runs once with no reserved slot (before) and once
+ * with one (after) and prints p50 / p95 / max for the short jobs.
+ *
+ * Usage: bun scripts/bench/minions-lane-load.ts [--json]
+ * test/minions-lane-load.slow.test.ts runs the same fixture and asserts the
+ * reservation cuts short-job p95 wait.
+ */
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+
+export interface LaneLoadOptions {
+ longMs: number;
+ shortMs: number;
+ longAtMs: number[];
+ shortCount: number;
+ shortEveryMs: number;
+ shortStartMs: number;
+ concurrency: number;
+}
+
+export const DEFAULT_LANE_LOAD: LaneLoadOptions = {
+ longMs: 1500,
+ shortMs: 30,
+ longAtMs: [0, 300, 600],
+ shortCount: 30,
+ shortEveryMs: 150,
+ shortStartMs: 50,
+ concurrency: 2,
+};
+
+export interface WaitSummary {
+ count: number;
+ p50: number;
+ p95: number;
+ max: number;
+}
+
+export interface LaneLoadResult {
+ reservedSlots: number;
+ short: WaitSummary;
+ long: WaitSummary;
+ wallMs: number;
+}
+
+const LONG = 'lane-fixture-long';
+const SHORT = 'lane-fixture-short';
+
+/** Nearest-rank percentile of an ascending list. */
+export function percentile(sorted: number[], p: number): number {
+ if (sorted.length === 0) return 0;
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))]!;
+}
+
+export function summarize(waits: number[]): WaitSummary {
+ const sorted = [...waits].sort((a, b) => a - b);
+ return { count: sorted.length, p50: percentile(sorted, 50), p95: percentile(sorted, 95), max: sorted.at(-1) ?? 0 };
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, Math.max(0, ms)));
+}
+
+/** One run on a fresh in-memory brain. */
+export async function runLaneLoad(reservedSlots: number, opts: LaneLoadOptions = DEFAULT_LANE_LOAD): Promise<LaneLoadResult> {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ try {
+ const queue = new MinionQueue(engine);
+ const worker = new MinionWorker(engine, {
+ concurrency: opts.concurrency,
+ pollInterval: 20,
+ healthCheckInterval: 0,
+ stalledInterval: 60_000,
+ longJobNames: [LONG],
+ shortJobReservedSlots: reservedSlots,
+ });
+ worker.register(LONG, async () => { await sleep(opts.longMs); });
+ worker.register(SHORT, async () => { await sleep(opts.shortMs); });
+
+ const schedule = [
+ ...opts.longAtMs.map(at => ({ at, name: LONG })),
+ ...Array.from({ length: opts.shortCount }, (_, i) => ({ at: opts.shortStartMs + i * opts.shortEveryMs, name: SHORT })),
+ ].sort((a, b) => a.at - b.at);
+
+ const t0 = performance.now();
+ const running = worker.start();
+ for (const item of schedule) {
+ await sleep(item.at - (performance.now() - t0));
+ await queue.add(item.name, {});
+ }
+ const total = schedule.length;
+ while (true) {
+ const [row] = await engine.executeRaw<{ done: number }>(`SELECT count(*)::int AS done FROM minion_jobs WHERE status = 'completed'`);
+ if (Number(row?.done) >= total) break;
+ await sleep(50);
+ }
+ const wallMs = Math.round(performance.now() - t0);
+ worker.stop();
+ await running;
+
+ const rows = await engine.executeRaw<{ name: string; wait_ms: number }>(
+ `SELECT name, (EXTRACT(EPOCH FROM (started_at - created_at)) * 1000)::float8 AS wait_ms FROM minion_jobs`,
+ );
+ const waits = (name: string) => rows.filter(r => r.name === name).map(r => Math.round(Number(r.wait_ms)));
+ return { reservedSlots, short: summarize(waits(SHORT)), long: summarize(waits(LONG)), wallMs };
+ } finally {
+ await engine.disconnect();
+ }
+}
+
+export async function runBeforeAfter(opts: LaneLoadOptions = DEFAULT_LANE_LOAD): Promise<{ before: LaneLoadResult; after: LaneLoadResult }> {
+ const before = await runLaneLoad(0, opts);
+ const after = await runLaneLoad(1, opts);
+ return { before, after };
+}
+
+function line(label: string, r: LaneLoadResult): string {
+ return `${label} (reserved ${r.reservedSlots}): short wait p50 ${r.short.p50} ms, p95 ${r.short.p95} ms, max ${r.short.max} ms; ` +
+ `long wait max ${r.long.max} ms; wall ${r.wallMs} ms`;
+}
+
+if (import.meta.main) {
+ const { before, after } = await runBeforeAfter();
+ if (process.argv.includes('--json')) {
+ console.log(JSON.stringify({ options: DEFAULT_LANE_LOAD, before, after }, null, 2));
+ } else {
+ console.log(line('before', before));
+ console.log(line('after ', after));
+ }
+}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 0a8ba48c66..1181356f4d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -9,11 +9,11 @@ src/commands/doctor.ts 692 ratchet +2 Wave B decision #10: Check.skipped_segment
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
src/commands/extract-conversation-facts.ts 2044 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left
src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
-src/commands/jobs.ts 667 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts)
+src/commands/jobs.ts 687 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts)
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
src/core/ai/gateway.ts 4530 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)
src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine
-src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due
+src/core/cycle.ts 3337 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
@@ -24,19 +24,19 @@ src/core/pglite-engine.ts 3087 ratchet +5 agent operator gate fixes: repair-fail
src/core/postgres-engine.ts 3114 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2345 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured)
-src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
+src/core/minions/queue.ts 2539 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import
src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
-src/core/minions/worker.ts 1788 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts)
+src/core/minions/worker.ts 1793 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts)
src/commands/sources.ts 2065 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts)
src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1995 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts)
+src/core/config.ts 1997 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +2 #7242 GBrainConfig.minions.terminal_hook (interface field)
src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
@@ -45,5 +45,5 @@ src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
src/core/search/evidence-delivery.ts 1712 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page
-src/commands/config.ts 1520 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured)
+src/commands/config.ts 1522 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 67f046fe4f..a7091a17a4 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -247,6 +247,7 @@ test/jobs-embed-background-parity.serial.test.ts R2 R2: mock.module(../src/core/
test/jobs-embed-stall-wiring.serial.test.ts R2 R2: mock.module(../src/commands/embed.ts) replaces modules for every file in the process
test/jobs-gateway-refresh.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, ANTHROPIC_API_KEY, OPENAI_API_KEY)
test/jobs-list-get-json.serial.test.ts global-state global-state: patches process stdout/stderr/console
+test/jobs-wait-cli.serial.test.ts global-state global-state: patches process stdout/stderr/console and process.exit
test/jobs-stats-backpressure.serial.test.ts global-state global-state: patches process stdout/stderr/console
test/jobs-stats-divergence.serial.test.ts global-state global-state: patches process stdout/stderr/console
test/jobs-stats-private-queue.serial.test.ts global-state global-state: patches process stdout/stderr/console
diff --git a/src/cli/main.ts b/src/cli/main.ts
index cd39ec2996..a896726331 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2513,7 +2513,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
const cfgJobs = loadConfig();
if (isThinClient(cfgJobs)) {
const jobsSub = args[0];
- if (jobsSub === 'list' || jobsSub === 'get') {
+ if (jobsSub === 'list' || jobsSub === 'get' || jobsSub === 'wait') {
const { runJobs } = await import('../commands/jobs.ts');
await runJobs(null, args);
return null;
diff --git a/src/commands/config.ts b/src/commands/config.ts
index c125548fec..1ee7b3bf9e 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -68,6 +68,7 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([
'persistence.write_wait_ms',
// Engine graduation opt-out: the pre-connect migrate router reads it engine-free.
'migrate.graduation', 'doctor.default_budget_ms', // #6803: the CLI doctor reads it pre-connect (commands/doctor/default-budget.ts)
+ 'minions.terminal_hook', // #7242: a command the worker runs; local file plane only, never the shared DB plane (minions/terminal-hook.ts)
]);
/** #5489: every self_upgrade.* reader (cli.ts startup check, autopilot,
@@ -109,7 +110,7 @@ async function unsetFilePlaneKey(key: string): Promise<boolean> {
const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
const cfg = loadConfigFileOnly();
const dot = key.indexOf('.');
- const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence' | 'migrate' | 'doctor';
+ const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence' | 'migrate' | 'doctor' | 'minions';
const leaf = key.slice(dot + 1);
const branch = cfg?.[top] as Record<string, unknown> | undefined;
if (!cfg || !branch || !(leaf in branch)) return false;
@@ -556,6 +557,7 @@ async function setFilePlaneKey(key: string, value: string, tail: string[]): Prom
saveConfig(cfg);
console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
} else if (key === 'persistence.write_wait_ms') { await setFileWriteWait(cfg, value, saveConfig);
+ } else if (key === 'minions.terminal_hook') { (await import('../core/minions/terminal-hook.ts')).setTerminalHookConfig(cfg, value, saveConfig);
} else if (key === 'doctor.default_budget_ms') { (await import('./doctor/default-budget.ts')).setDoctorDefaultBudget(cfg, value, saveConfig);
} else if (key === 'migrate.graduation') {
const on = isConfigTruthy(value);
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 54489dc3b2..f90aacdd73 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -38,6 +38,7 @@ import { makeSyncHandler } from '../core/minions/handlers/sync.ts';
import { makeUnifyTypesHandler } from '../core/minions/handlers/unify-types.ts';
import { runJobsAuthorizeLegacy } from './jobs/authorize-legacy.ts';
import { runJobsSubmit } from './jobs/submit.ts';
+import { runJobsWait } from './jobs/wait.ts';
import { runJobsList } from './jobs/list.ts';
import { runJobsGet } from './jobs/get.ts';
import { runJobsCancel } from './jobs/cancel.ts';
@@ -166,8 +167,10 @@ USAGE
[--redact-secrets] (shell only; scrubs inherit
values from stdout/stderr)
gbrain jobs list [--status S] [--queue Q] [--limit N] [--json]
+ gbrain jobs list --finished-since ISO|CURSOR [--queue Q] [--name N] [--json]
gbrain jobs list --group SPEND_GROUP [--json]
gbrain jobs get <id> [--json]
+ gbrain jobs wait <id> [--timeout 10m] [--json] (exit 0 completed, 1 failed/dead/cancelled, 124 still running)
gbrain jobs cancel <id> | --group SPEND_GROUP
gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]
gbrain jobs retry <id>
@@ -411,6 +414,22 @@ Without --yes it only previews: counts by job name and status, the first 20 ids,
parents that return to waiting, and the preview hash. The apply cancels exactly
the previewed set; a selection that would cascade to a job outside it refuses.
Stop producers and workers and cancel active jobs (gbrain jobs cancel <id>) first.
+`,
+ wait: `gbrain jobs wait — block until a job is completed, failed, dead or cancelled
+
+USAGE
+ gbrain jobs wait <id> [--timeout 10m] [--json]
+
+OPTIONS
+ --timeout DUR Stop waiting after DUR (60, 60s, 10m, 1h; default 24h). The
+ job is never cancelled; it keeps running.
+ --json Print the final row like \`jobs get --json\`.
+
+EXIT CODES
+ 0 completed
+ 1 failed, dead or cancelled (error_text on stderr), or no such job
+ 2 usage error
+ 124 the timeout elapsed and the job is still running
`,
prune: `gbrain jobs prune — delete old terminal jobs
@@ -431,6 +450,7 @@ const JOBS_SUBCOMMANDS: Record<string, (ctx: JobsCommandContext) => Promise<void
submit: runJobsSubmit,
list: runJobsList,
get: runJobsGet,
+ wait: runJobsWait,
cancel: runJobsCancel,
retry: runJobsRetry,
delete: runJobsDelete,
@@ -470,7 +490,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
// routing bug upstream of this function — refuse instead of crashing
// inside MinionQueue.
const localSupervisorStatus = sub === 'supervisor' && args[1] === 'status';
- if (!engineOrNull && sub !== 'list' && sub !== 'get' && !localSupervisorStatus) {
+ if (!engineOrNull && sub !== 'list' && sub !== 'get' && sub !== 'wait' && !localSupervisorStatus) {
console.error(`\`gbrain jobs ${sub ?? ''}\` needs a local engine and cannot run on a thin client.`);
process.exit(1);
}
diff --git a/src/commands/jobs/get.ts b/src/commands/jobs/get.ts
index 68a6d5655a..5ff8bec564 100644
--- a/src/commands/jobs/get.ts
+++ b/src/commands/jobs/get.ts
@@ -5,6 +5,8 @@ import type { MinionJob } from '../../core/minions/types.ts';
import { callRemoteTool, unpackToolResult } from '../../core/mcp-client.ts';
import { spendBasis } from '../../core/minions/spend-record.ts';
import { jobGroupAmounts } from '../../core/minions/spend-authorization.ts';
+import { describeJobs, withInsight, type JobInsight } from '../../core/minions/job-insight.ts';
+import type { BrainEngine } from '../../core/engine.ts';
export async function runJobsGet({ args, queue, engine }: JobsCommandContext): Promise<void> {
const id = parseInt(args[1], 10);
@@ -33,12 +35,42 @@ export async function runJobsGet({ args, queue, engine }: JobsCommandContext): P
job = await queue.getJob(id);
}
if (!job) { console.error(`Job #${id} not found.`); process.exit(1); }
+ await printJob(job, hasFlag(args, '--json'), isThinClient(cfg) ? null : engine);
+}
+
+/** The `jobs get` document (also printed by `jobs wait`): the row, #7241 insight and spend basis. A thin client's row already carries the insight. */
+export async function printJob(job: MinionJob, json: boolean, engine: BrainEngine | null): Promise<void> {
+ const insight = engine ? (await describeJobs(engine, [job])).get(job.id) : undefined;
+ const doc = withInsight(job, insight) as MinionJob & Partial<JobInsight>;
// #3685: same machine-readable contract as `list --json` above.
- if (hasFlag(args, '--json')) {
+ if (json) {
const { basis, why } = spendBasis(job);
- const group = job.spend_authorization && !isThinClient(cfg) ? await jobGroupAmounts(engine, job.spend_authorization) : undefined;
- console.log(JSON.stringify({ ...job, spend_basis: basis, spend_why: why, ...(group ? { spend_group: group } : {}) }, null, 2));
+ const group = job.spend_authorization && engine ? await jobGroupAmounts(engine, job.spend_authorization) : undefined;
+ console.log(JSON.stringify({ ...doc, spend_basis: basis, spend_why: why, ...(group ? { spend_group: group } : {}) }, null, 2));
return;
}
console.log(formatJobDetail(job));
+ for (const line of insightLines(doc)) console.log(line);
+}
+
+function insightLines(doc: Partial<JobInsight>): string[] {
+ const lines: string[] = [];
+ const by = doc.submitted_by;
+ if (by) lines.push(` Submitted by: ${by.kind}${'id' in by && by.id != null ? ` ${by.id}` : ''}${'via' in by && by.via ? ` (${by.via})` : ''}`);
+ for (const b of doc.blocked_by ?? []) {
+ if (b.kind === 'queue') lines.push(` Blocked by: queue ${b.queue}, position ${b.queue_position} (${b.ahead} ahead, ${b.active} running${b.active_jobs.length ? `: ${b.active_jobs.map(j => `#${j.id} ${j.name}`).join(', ')}` : ''})${b.private_queue ? ', private queue' : ''}`);
+ else if (b.kind === 'waiting_children') lines.push(` Blocked by: ${b.pending} unfinished children${b.child_ids.length ? ` (${b.child_ids.map(c => '#' + c).join(', ')})` : ''}`);
+ else if (b.kind === 'delayed') lines.push(` Blocked by: delayed until ${b.delay_until ?? '?'} (${b.reason})`);
+ else if (b.kind === 'lock') lines.push(` Blocked by: lock ${b.lock ?? ''} held${b.holder_job_id != null ? ` by job #${b.holder_job_id}` : b.holder ? ` by a ${b.holder.kind} holder` : ''}`);
+ else if (b.kind === 'unreviewed_authority') lines.push(` Blocked by: unreviewed legacy authority (${b.fix})`);
+ else lines.push(` Blocked by: ${b.kind}`);
+ }
+ if (doc.lock_expires_in_ms != null) {
+ lines.push(` Heartbeat: ${doc.heartbeat_age_ms == null ? '?' : Math.round(doc.heartbeat_age_ms / 1000) + 's ago'}; lock ${doc.stalled ? `expired ${Math.round(-doc.lock_expires_in_ms / 1000)}s ago (STALLED)` : `expires in ${Math.round(doc.lock_expires_in_ms / 1000)}s`}`);
+ }
+ const s = doc.spend;
+ if (s && (s.tokens_input || s.tokens_output || s.cost_usd !== null)) {
+ lines.push(` Spend: ${s.cost_usd === null ? 'unpriced' : '$' + s.cost_usd.toFixed(4)}${s.includes_children ? ' (with children)' : ''}${s.unsettled_reservations ? `, ${s.unsettled_reservations} unsettled` : ''}`);
+ }
+ return lines;
}
diff --git a/src/commands/jobs/list.ts b/src/commands/jobs/list.ts
index 9ddb294812..c400a8bac7 100644
--- a/src/commands/jobs/list.ts
+++ b/src/commands/jobs/list.ts
@@ -3,6 +3,7 @@ import { formatJob, hasFlag, parseFlag, rehydrateJobDates, type JobsCommandConte
import type { MinionJob, MinionJobStatus } from '../../core/minions/types.ts';
import { isThinClient, loadConfig } from '../../core/config.ts';
import { callRemoteTool, unpackToolResult } from '../../core/mcp-client.ts';
+import { describeJobs, insightCell, withInsight, type JobInsight } from '../../core/minions/job-insight.ts';
export async function runJobsList({ args, queue, engine }: JobsCommandContext): Promise<void> {
const groupId = parseFlag(args, '--group');
@@ -10,6 +11,8 @@ export async function runJobsList({ args, queue, engine }: JobsCommandContext):
const status = parseFlag(args, '--status') as MinionJobStatus | undefined;
const queueName = parseFlag(args, '--queue');
const limit = parseInt(parseFlag(args, '--limit') ?? '20', 10);
+ const finishedSince = parseFlag(args, '--finished-since');
+ if (finishedSince !== undefined) return listFinishedSince(engine, finishedSince, { queue: queueName, name: parseFlag(args, '--name'), limit }, hasFlag(args, '--json'));
// v0.32: thin-client routing. The `list_jobs` MCP op is admin-scoped
// but not localOnly, so a thin-client install with admin access can
@@ -27,6 +30,8 @@ export async function runJobsList({ args, queue, engine }: JobsCommandContext):
try { await queue.ensureSchema(); }
catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }
jobs = await queue.getJobs({ status, queue: queueName, limit });
+ const insight = await describeJobs(engine, jobs);
+ jobs = jobs.map(j => withInsight(j, insight.get(j.id)));
}
// #3685: --json emits the machine-readable array the CHANGELOG's
@@ -43,12 +48,39 @@ export async function runJobsList({ args, queue, engine }: JobsCommandContext):
return;
}
- console.log(` ${'ID'.padEnd(6)} ${'Name'.padEnd(14)} ${'Status'.padEnd(20)} ${'Queue'.padEnd(10)} ${'Time'.padEnd(8)} Created`);
- console.log(' ' + '─'.repeat(80));
- for (const job of jobs) console.log(formatJob(job));
+ console.log(` ${'ID'.padEnd(6)} ${'Name'.padEnd(14)} ${'Status'.padEnd(20)} ${'Queue'.padEnd(10)} ${'Time'.padEnd(8)} ${'Created'.padEnd(19)} Wait/Live`);
+ console.log(' ' + '─'.repeat(100));
+ for (const job of jobs) console.log(`${formatJob(job)} ${insightCell(job, job as MinionJob & JobInsight)}`.trimEnd());
console.log(`\n ${jobs.length} jobs shown`);
}
+/**
+ * `jobs list --finished-since <iso|cursor>` (#7242): every job that reached a terminal status after the cursor, oldest
+ * first, as one `{jobs, next_cursor}` document; pass next_cursor back to read the next events.
+ */
+async function listFinishedSince(engine: JobsCommandContext['engine'], since: string, opts: { queue?: string; name?: string; limit: number }, json: boolean): Promise<void> {
+ const cfg = loadConfig();
+ let page: { jobs: MinionJob[]; next_cursor: string };
+ if (isThinClient(cfg)) {
+ const raw = await callRemoteTool(cfg!, 'list_jobs', { finished_since: since, queue: opts.queue, name: opts.name, limit: opts.limit }, { timeoutMs: 30_000 });
+ const doc = unpackToolResult<{ jobs: MinionJob[]; next_cursor: string }>(raw);
+ page = { jobs: doc.jobs.map(j => rehydrateJobDates(j)), next_cursor: doc.next_cursor };
+ } else {
+ const { listFinishedSince: read, TerminalCursorError } = await import('../../core/minions/terminal-events.ts');
+ try { page = await read(engine, since, opts); }
+ catch (e) {
+ if (!(e instanceof TerminalCursorError)) throw e;
+ console.error(`Error: --finished-since: ${e.message}`);
+ process.exit(2);
+ }
+ const insight = await describeJobs(engine, page.jobs);
+ page = { ...page, jobs: page.jobs.map(j => withInsight(j, insight.get(j.id))) };
+ }
+ if (json) { console.log(JSON.stringify(page, null, 2)); return; }
+ for (const job of page.jobs) console.log(`${formatJob(job)} ${job.finished_at instanceof Date ? job.finished_at.toISOString() : ''}`);
+ console.log(`\n ${page.jobs.length} finished jobs. Next: gbrain jobs list --finished-since ${page.next_cursor}`);
+}
+
/** `jobs list --group <id>`: one spend group's record, amounts and member jobs. */
async function listSpendGroup(engine: JobsCommandContext['engine'], groupId: string, json: boolean): Promise<void> {
const { groupJobs, jobGroupAmounts } = await import('../../core/minions/spend-authorization.ts');
diff --git a/src/commands/jobs/stats.ts b/src/commands/jobs/stats.ts
index a5d0959b72..f1d7d9a433 100644
--- a/src/commands/jobs/stats.ts
+++ b/src/commands/jobs/stats.ts
@@ -1,7 +1,7 @@
/** `gbrain jobs stats` (dispatched by runJobs in src/commands/jobs.ts). */
import { hasFlag, parseFlag, type JobsCommandContext } from './shared.ts';
import { formatNice, getEffectiveNiceness } from '../../core/minions/niceness.ts';
-import { deriveWedgeSignal } from '../../core/minions/queue.ts';
+import { DREAM_INLINE_PRIVATE_QUEUE_PREFIX, deriveWedgeSignal } from '../../core/minions/queue.ts';
export async function runJobsStats({ args, engine, queue }: JobsCommandContext): Promise<void> {
try { await queue.ensureSchema(); }
@@ -84,6 +84,11 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):
console.log(' No jobs in the last 24 hours.');
}
console.log(`\n Queue health: ${stats.queue_health.waiting} waiting, ${stats.queue_health.active} active, ${stats.queue_health.stalled} stalled`);
+ // #7241: one line per queue; the per-run dream-inline-* queues share one line (`--queue <name>` scopes the wedge lines to one).
+ for (const q of stats.by_queue) {
+ const label = `${q.queue}-` === DREAM_INLINE_PRIVATE_QUEUE_PREFIX ? `${q.queue} (${q.queues} queue${q.queues === 1 ? '' : 's'})` : sanitizeName(q.queue);
+ console.log(` ${label.padEnd(26)} ${q.waiting_now} waiting, ${q.active_now} active, ${q.total} total, ${q.completed} done, ${q.failed} failed, ${q.dead} dead`);
+ }
// DIVERGENT-queue scream: intake structurally exceeds useful drain and a
// real backlog is sitting there. This is the default-on protection layer
diff --git a/src/commands/jobs/wait.ts b/src/commands/jobs/wait.ts
new file mode 100644
index 0000000000..1f5d7ff1bb
--- /dev/null
+++ b/src/commands/jobs/wait.ts
@@ -0,0 +1,73 @@
+/**
+ * `gbrain jobs wait <id> [--timeout <dur>] [--json]` (#7242): block until the job is completed, failed, dead or
+ * cancelled, then print it like `jobs get`. Exit codes follow the agent operator protocol: 0 completed,
+ * 1 failed, dead or cancelled (the job's outcome, not a wait error), 124 the --timeout elapsed and the job is
+ * still running (it is NOT cancelled; wait again or `gbrain jobs get <id>`), 2 usage. A thin client waits
+ * through the wait_job MCP op in chunks of at most WAIT_JOB_MAX_S.
+ */
+import { hasFlag, parseFlag, rehydrateJobDates, type JobsCommandContext } from './shared.ts';
+import { isThinClient, loadConfig } from '../../core/config.ts';
+import type { MinionJob } from '../../core/minions/types.ts';
+import { callRemoteTool, unpackToolResult } from '../../core/mcp-client.ts';
+import { parseDurationSeconds } from '../../core/sync-concurrency.ts';
+import { isTerminalJobStatus, TimeoutError, waitForCompletion } from '../../core/minions/wait-for-completion.ts';
+import { printJob } from './get.ts';
+
+export const JOBS_WAIT_EXIT = { completed: 0, unsuccessful: 1, usage: 2, timeout: 124 } as const;
+
+export async function runJobsWait({ args, queue, engine }: JobsCommandContext): Promise<void> {
+ const id = Number(args[1]);
+ if (!Number.isSafeInteger(id) || id <= 0) {
+ console.error('Error: job ID required. Usage: gbrain jobs wait <id> [--timeout 10m] [--json]');
+ process.exit(JOBS_WAIT_EXIT.usage);
+ }
+ let timeoutS: number | undefined;
+ try { timeoutS = parseDurationSeconds(parseFlag(args, '--timeout'), '--timeout'); }
+ catch (e) { console.error(`Error: ${(e as Error).message}`); process.exit(JOBS_WAIT_EXIT.usage); }
+ const json = hasFlag(args, '--json');
+ const timeoutMs = (timeoutS ?? 24 * 3600) * 1000;
+ const cfg = loadConfig();
+ const thin = isThinClient(cfg);
+
+ let job: MinionJob | null;
+ let timedOut = false;
+ if (thin) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const remaining = Math.max(0, deadline - Date.now());
+ let doc: (MinionJob & { terminal?: boolean }) | null;
+ try {
+ doc = unpackToolResult<MinionJob & { terminal?: boolean }>(await callRemoteTool(cfg!, 'wait_job', { id, timeout_s: Math.min(55, Math.ceil(remaining / 1000)) }, { timeoutMs: 75_000 }));
+ } catch (e) {
+ if (/not found/i.test(e instanceof Error ? e.message : String(e))) { console.error(`Job #${id} not found.`); process.exit(JOBS_WAIT_EXIT.unsuccessful); }
+ throw e;
+ }
+ job = rehydrateJobDates(doc);
+ if (doc.terminal === true || isTerminalJobStatus(doc.status)) break;
+ if (Date.now() >= deadline) { timedOut = true; break; }
+ }
+ } else {
+ try { await queue.ensureSchema(); }
+ catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(JOBS_WAIT_EXIT.unsuccessful); }
+ try {
+ job = await waitForCompletion(queue, id, { timeoutMs, pollMs: engine.kind === 'pglite' ? 250 : 1000 });
+ } catch (e) {
+ if (!(e instanceof TimeoutError)) {
+ if (/not found|disappeared/.test((e as Error).message)) { console.error(`Job #${id} not found.`); process.exit(JOBS_WAIT_EXIT.unsuccessful); }
+ throw e;
+ }
+ timedOut = true;
+ job = await queue.getJob(id);
+ if (!job) { console.error(`Job #${id} not found.`); process.exit(JOBS_WAIT_EXIT.unsuccessful); }
+ }
+ }
+ await printJob(job!, json, thin ? null : engine);
+ if (timedOut) {
+ console.error(`Job #${id} is still ${job!.status} after ${Math.round(timeoutMs / 1000)}s; it keeps running. Wait again: gbrain jobs wait ${id}, or check it: gbrain jobs get ${id}`);
+ process.exit(JOBS_WAIT_EXIT.timeout);
+ }
+ if (job!.status !== 'completed') {
+ console.error(`Job #${id} ended ${job!.status}${job!.error_text ? `: ${job!.error_text.slice(0, 300)}` : ''}`);
+ process.exit(JOBS_WAIT_EXIT.unsuccessful);
+ }
+}
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index f845230682..088c25d55a 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -11,6 +11,7 @@ import type { MinionQueue } from '../../core/minions/queue.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig } from '../../core/config.ts';
import { startPersistenceConsumer } from '../../core/persistence/service.ts';
+import { describeLanePolicy, resolveLanePolicy } from '../../core/minions/lanes.ts';
export async function maybeRunWorkerStartupRecovery(
queue: MinionQueue,
@@ -190,9 +191,14 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
}
}
+ const { resolveTerminalHook, terminalHookNotifier } = await import('../../core/minions/terminal-hook.ts');
+ const terminalHook = resolveTerminalHook(loadConfig());
+ const lanes = await resolveLanePolicy(engine);
const worker = new MinionWorker(engine, {
queue: queueName, concurrency, maxRssMb, healthCheckInterval,
jobIsolation, childCliInvocation, childTiniPath,
+ longJobNames: lanes.longJobNames, shortJobReservedSlots: lanes.shortJobReservedSlots,
+ ...(terminalHook ? { onJobSettled: terminalHookNotifier(engine, terminalHook).onJobSettled } : {}),
});
try {
await registerBuiltinHandlers(worker, engine);
@@ -229,7 +235,8 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
const isolationNote = jobIsolation === 'process'
? `, isolation: process (child cli: ${childCliInvocation?.cmd}${childTiniPath ? ', tini' : ''})`
: '';
- console.log(`Minion worker started (queue: ${queueName}, concurrency: ${concurrency}${watchdogNote}${healthNote}${niceNote}${isolationNote})`);
+ const hookNote = terminalHook ? `, terminal hook: ${terminalHook.argv[0]}` : '';
+ console.log(`Minion worker started (queue: ${queueName}, concurrency: ${concurrency}, ${describeLanePolicy(concurrency, lanes.shortJobReservedSlots)}${watchdogNote}${healthNote}${niceNote}${isolationNote}${hookNote})`);
console.log(`Registered handlers: ${worker.registeredNames.join(', ')}`);
// Register in the live worker registry (issue #1815) so jobs stats / doctor
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index cda8c94855..60339ed787 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1053,6 +1053,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },
{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },
{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },
+ // Minions usability PR 2 (#7242): the maintainer's Oct 20, 2026 ask to make minions more usable. `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A `gbrain jobs work` worker running two or more jobs at once (the supervisor and autopilot default is 2) now keeps one slot free of long jobs: autopilot-cycle, autopilot-global-maintenance, embed-backfill, connector-sync and extract run in at most concurrency minus one slots, so short jobs such as facts-absorb no longer wait behind them. Long jobs can take longer to start when one is already running. `gbrain config set minions.short_job_reserved_slots 0` restores the old behavior; `minions.long_job_names` adds job names to the long set.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 95d4e6438c..6bc3dc9a8a 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -78,7 +78,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
diff --git a/src/core/config.ts b/src/core/config.ts
index 36747deede..520bb4acc6 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -37,6 +37,8 @@ export interface GBrainConfig {
* `gbrain config set` routes these two dotted keys here, not to the DB. */
push?: { allow_unverified_remote?: boolean };
hooks?: { stop_push_debounce_min?: number | string };
+ /** #7242 terminal hook (minions/terminal-hook.ts): file plane only, read by `gbrain jobs work`. */
+ minions?: { terminal_hook?: string[] | { argv: string[]; timeout_ms?: number } };
/** Ambient-writeback MIRROR of the DB-plane `memory.*` keys — `gbrain
* config set memory.*` dual-writes both planes so the engine-free Stop-hook
* child and the stdio boot resolve see the same truth the serve does. The
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 88df202311..6918443b75 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -524,6 +524,8 @@ export interface CycleOpts {
* + refreshes the cycle-lock-table TTL.
*/
yieldBetweenPhases?: () => Promise<void>;
+ /** #7241: awaited as each selected phase starts its work (index and count within this cycle's selection); errors are logged, never fatal. */
+ onPhaseStart?: (phase: CyclePhase, index: number, count: number) => Promise<void> | void;
/**
* Generic in-phase keepalive (v0.23). Long-running phases (synthesize
* waiting on a fan-out aggregator, patterns rolling up reflections)
@@ -2185,7 +2187,11 @@ async function runCycleUnscoped(
// synthesize_concepts still can't carry one (W6). Steal-free cycles behave
// byte-identically to timePhase.
// Phase containment (#5484): a failing phase returns a `fail` result so later phases run; abort, lease loss and budget exhaustion still stop the job.
- const timePhase = <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => timeContainedPhase({ engine, sourceId: cycleSourceId ?? 'default', signal: cycleSignal }, phase, fn);
+ const timePhase = async <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => {
+ try { await opts.onPhaseStart?.(phase, phases.indexOf(phase), phases.length); }
+ catch (e) { console.warn(`[cycle] onPhaseStart hook error (non-fatal): ${e instanceof Error ? e.message : String(e)}`); }
+ return timeContainedPhase({ engine, sourceId: cycleSourceId ?? 'default', signal: cycleSignal }, phase, fn);
+ };
const racedTimePhase = <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => raceStolen(timePhase(fn, phase));
// #1972: reap dead-holder sync/cycle locks at cycle start — before the sync
diff --git a/src/core/minions/admission.ts b/src/core/minions/admission.ts
index b86099218e..235beddec1 100644
--- a/src/core/minions/admission.ts
+++ b/src/core/minions/admission.ts
@@ -60,12 +60,13 @@ export const WAITING_TTL_DEFAULT_HOURS: Readonly<Record<string, number>> = {
export const QUOTA_MAX_WAITING_DEFAULT: Readonly<Record<string, number>> = {};
/**
- * Keys excluded from the param hash. ONLY the hash's own storage key:
- * `__owner_client_id` is deliberately INCLUDED so coalescing never crosses
- * owner lanes — one OAuth client's submit must not be suppressed by (or
- * handed a job id owned by) another client.
+ * Keys excluded from the param hash: the hash's own storage key and the
+ * `__submitter` display label (`job-insight.ts`), so a re-submit from another
+ * local process still coalesces. `__owner_client_id` is deliberately INCLUDED
+ * so coalescing never crosses owner lanes — one OAuth client's submit must not
+ * be suppressed by (or handed a job id owned by) another client.
*/
-export const PARAM_HASH_EXCLUDED_KEYS: ReadonlySet<string> = new Set(['__param_hash']);
+export const PARAM_HASH_EXCLUDED_KEYS: ReadonlySet<string> = new Set(['__param_hash', '__submitter']);
/**
* error_text prefix stamped by the waiting-TTL sweep. The 24h-cancellation
diff --git a/src/core/minions/handlers/autopilot-cycle.ts b/src/core/minions/handlers/autopilot-cycle.ts
index 9d70185a3e..f49977a4f3 100644
--- a/src/core/minions/handlers/autopilot-cycle.ts
+++ b/src/core/minions/handlers/autopilot-cycle.ts
@@ -4,6 +4,7 @@
import type { BrainEngine } from '../../engine.ts';
import type { MinionHandler } from '../types.ts';
import { resolveJobPull } from './job-pull.ts';
+import { reportJobProgress } from './job-progress.ts';
import { isConnectorSourceKind } from '../../persistence/connector-identity.ts';
import { CONNECTOR_SOURCE_PHASES } from '../../cycle/phase-scope.ts';
@@ -160,6 +161,8 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
// #6803: a connector cycle has no sync phase; its incremental set is the source's pages changed since its last cycle.
...(connectorSource ? { sourceChangedSince: lastSourceCycleAt } : {}),
...(effectivePhases !== undefined ? { phases: effectivePhases as any } : {}),
+ // #7241: the phase in progress, for `gbrain jobs get` / get_job_progress while the cycle runs.
+ onPhaseStart: (phase, index, count) => reportJobProgress(job, { phase, phase_index: index, phase_count: count, started_at: new Date().toISOString() }),
yieldBetweenPhases: async () => {
// Yield to the event loop so worker lock-renewal can fire.
await new Promise<void>(r => setImmediate(r));
diff --git a/src/core/minions/handlers/autopilot-global-maintenance.ts b/src/core/minions/handlers/autopilot-global-maintenance.ts
index d04ba406cb..24d3980a56 100644
--- a/src/core/minions/handlers/autopilot-global-maintenance.ts
+++ b/src/core/minions/handlers/autopilot-global-maintenance.ts
@@ -8,6 +8,7 @@ import { CODES } from '../../error-registry.ts';
import { ItemRun } from '../../item-failure.ts';
import { OperationError } from '../../ops/contract.ts';
import { VERSION } from '../../../version.ts';
+import { reportJobProgress } from './job-progress.ts';
/**
* #4578: one pass over the maintenance phases may span several jobs. The
@@ -243,6 +244,7 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:
progress.running_phase = phase;
progress.running_job = runToken;
await save();
+ await reportJobProgress(job, { phase, phase_index: i, phase_count: phases.length, started_at: new Date().toISOString() });
let report: CycleReport;
try {
report = await runCycle(engine, {
diff --git a/src/core/minions/handlers/job-progress.ts b/src/core/minions/handlers/job-progress.ts
new file mode 100644
index 0000000000..d74716b1b3
--- /dev/null
+++ b/src/core/minions/handlers/job-progress.ts
@@ -0,0 +1,9 @@
+/**
+ * #7241: best-effort `job.updateProgress` for handlers that report their phase. Progress is advisory, so a
+ * failed write (a lost lock token, a dropped connection) never fails the job it describes.
+ */
+import type { MinionJobContext } from '../types.ts';
+
+export async function reportJobProgress(job: Pick<MinionJobContext, 'updateProgress'>, progress: unknown): Promise<void> {
+ try { await job.updateProgress(progress); } catch { /* advisory: the job's own result is the record */ }
+}
diff --git a/src/core/minions/handlers/sync-job-drain.ts b/src/core/minions/handlers/sync-job-drain.ts
index 25c3349d18..ab3faf1d9d 100644
--- a/src/core/minions/handlers/sync-job-drain.ts
+++ b/src/core/minions/handlers/sync-job-drain.ts
@@ -10,6 +10,7 @@
import type { BrainEngine } from '../../engine.ts';
import type { MinionJobContext } from '../types.ts';
import type { SyncOpts, SyncResult } from '../../../commands/sync.ts';
+import { reportJobProgress } from './job-progress.ts';
/** The smallest worker lease the wall-clock sweep can use for a row without `lock_duration_ms` (the worker default). */
const WORKER_LOCK_DEFAULT_MS = 30_000;
@@ -52,18 +53,31 @@ export async function planJobDrain(engine: BrainEngine, job: MinionJobContext, n
return { opts: { drain: true, deadlineAtMs, lanes, ...(params.noBulk === true ? { noBulk: true } : {}) }, row: row ?? null, trusted };
}
-/** Throttled best-effort progress for `jobs get` / MCP polling while the drain commits pages. Never throws into the sync. */
+/**
+ * Throttled best-effort progress for `jobs get` / MCP polling while the drain commits pages. Never throws into the sync.
+ * #7241: the sync's other phases (`resolve_repo`, `git_pull`, `full_import`, `import` with its checkpointed file count) are
+ * written too, on each phase change and at most every PROGRESS_EVERY_MS within one, so a classic sync's progress is not empty.
+ */
export function jobDrainProgress(job: MinionJobContext, estimate: (remaining: number | null, processed: number, elapsedMs: number) => { rate_pages_per_min: number | null; eta_seconds: number | null }):
{ onProgress: NonNullable<SyncOpts['onProgress']>; flush(): Promise<void> } {
const startedAt = Date.now();
let index = 0, processed = 0, total: number | null = null, phase = 'managed_sync.start', lastAdvanceAt: string | null = null, wroteAt = 0;
+ let syncPhase: string | null = null, syncPhaseAt = 0;
const snapshot = () => {
const remaining = total === null ? null : Math.max(0, total - index);
return { phase, index, total, processed, remaining, ...estimate(remaining, processed, Date.now() - startedAt), last_advance_at: lastAdvanceAt };
};
return {
onProgress: event => {
- if (!event.phase.startsWith('managed_sync.')) return;
+ if (!event.phase.startsWith('managed_sync.')) {
+ const now = Date.now();
+ if (event.phase === syncPhase && now - wroteAt < PROGRESS_EVERY_MS) return;
+ if (event.phase !== syncPhase) { syncPhase = event.phase; syncPhaseAt = now; }
+ wroteAt = now;
+ void reportJobProgress(job, { phase: event.phase, ...(typeof event.bankedFiles === 'number' ? { banked_files: event.bankedFiles } : {}),
+ started_at: new Date(syncPhaseAt).toISOString() });
+ return;
+ }
phase = event.phase;
if (typeof event.total === 'number') total = event.total;
if (typeof event.bankedFiles === 'number') index = event.bankedFiles;
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index 10b9eccaa3..d068925e92 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -117,7 +117,7 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
result = await performSync(engine, {
repoPath, sourceId, noPull, noEmbed, noExtract, signal,
...plan.opts,
- ...(plan.opts.drain ? { onProgress: progress.onProgress } : {}),
+ onProgress: progress.onProgress,
// #6712 PR 1: the job drains under the source's drain lease; a busy lease is the skip below.
drainHolder: { kind: 'job', id: String(job.id) },
concurrency: concurrencyOverride,
diff --git a/src/core/minions/job-insight.ts b/src/core/minions/job-insight.ts
new file mode 100644
index 0000000000..43d3cdcf1c
--- /dev/null
+++ b/src/core/minions/job-insight.ts
@@ -0,0 +1,358 @@
+/**
+ * #7241: what a job row does not say by itself, computed on read: who submitted it (`submitted_by`), why a
+ * job that is not running is not running (`blocked_by`), the lease liveness of an active job
+ * (`heartbeat_age_ms`, `lock_expires_in_ms`, `stalled`) and what it spent (`spend`).
+ *
+ * Every time is measured on the database clock. An owner-fenced caller (an agent token without admin,
+ * `ops/jobs.ts` agentOwnerFence) sees another principal only as its kind: a foreign submitter, parent,
+ * queue-slot holder or lock holder is never named, and foreign children are left out of spend.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { parseGlobalFlags } from '../cli-options.ts';
+import { currentSubmissionAuthority } from './submission-authority.ts';
+import { currentChatPhase } from '../ai/chat-usage.ts';
+import type { MinionJob } from './types.ts';
+
+const HOLDER_ROW_QUEUE = 'gbrain-drain-lease';
+const LIST_CAP = 10;
+
+let labelOverride: string | null = null;
+/** Tests only: pin the label `submitterLabel` returns (null restores argv detection). */
+export function setSubmitterLabelForTests(label: string | null): void { labelOverride = label; }
+
+/**
+ * The local submitter of an application job. A handler submitting from inside a running job is
+ * `job:<name>`; otherwise the CLI command that owns the process (`autopilot`, `serve`, `worker` for
+ * `jobs work` / `jobs supervisor`, `cli:<command>`), or `library` outside the CLI.
+ */
+export function submitterLabel(): string {
+ if (labelOverride) return labelOverride;
+ if (currentSubmissionAuthority()) {
+ const phase = currentChatPhase();
+ return phase?.startsWith('job:') ? phase : 'job';
+ }
+ let rest: string[];
+ try { rest = parseGlobalFlags(process.argv.slice(2)).rest; } catch { return 'library'; }
+ const [command, sub] = rest;
+ if (!command || !/^[a-z][a-z0-9-]{0,40}$/.test(command)) return 'library';
+ if (command === 'autopilot' || command === 'serve') return command;
+ if (command === 'jobs' && (sub === 'work' || sub === 'supervisor')) return 'worker';
+ return `cli:${command}`;
+}
+
+/**
+ * Job data as `MinionQueue.add` stores it: a caller-supplied `__submitter` is always dropped, and an
+ * application submit from a labelled local process carries `submitterLabel()` there. A display label only:
+ * never authority, excluded from the param hash, and read back only for application-authority rows.
+ */
+export function withSubmitterLabel(data: Record<string, unknown> | undefined, application: boolean): Record<string, unknown> {
+ const { __submitter: _dropped, ...rest } = data ?? {};
+ const label = application ? submitterLabel() : 'library';
+ return label === 'library' ? rest : { ...rest, __submitter: label };
+}
+
+export type SubmittedBy =
+ | { kind: 'mcp_client'; id?: string; principal_kind?: string }
+ | { kind: 'parent_job'; id?: number }
+ | { kind: 'local'; via?: string }
+ | { kind: 'unreviewed' };
+
+export type DelayReason = 'retry_backoff' | 'deferred' | 'handed_back' | 'scheduled';
+
+export type BlockedBy =
+ | { kind: 'waiting_children'; pending: number; child_ids: number[] }
+ | { kind: 'delayed'; delay_until: string | null; reason: DelayReason; detail?: string }
+ | { kind: 'paused' }
+ | { kind: 'unreviewed_authority'; fix: string }
+ | { kind: 'queue'; queue: string; queue_position: number; ahead: number; active: number; active_jobs: Array<{ id: number; name: string }>; private_queue?: true }
+ | { kind: 'lock'; held: true; lock?: string; holder_job_id?: number; holder?: { kind: string; pid?: number; host?: string; acquired_at: string | null; ttl_expires_at: string | null } };
+
+export interface JobSpend {
+ tokens_input: number;
+ tokens_output: number;
+ tokens_cache_read: number;
+ /** Settled, priced provider spend (mcp_spend_reservations) of the job and its visible descendants; null when none was priced. */
+ cost_usd: number | null;
+ cost_basis: 'settled_reservations' | 'unpriced';
+ includes_children: boolean;
+ /** Reservations still pending, expired or settled without usage: their cost is not in cost_usd. */
+ unsettled_reservations: number;
+ /** Fenced callers: completed children of another principal were subtracted from the token counts. */
+ excludes_foreign_children?: true;
+}
+
+export interface JobInsight {
+ submitted_by: SubmittedBy;
+ blocked_by: BlockedBy[] | null;
+ heartbeat_age_ms: number | null;
+ heartbeat_basis: 'lease' | 'updated_at' | null;
+ lock_expires_in_ms: number | null;
+ stalled: boolean | null;
+ spend: JobSpend;
+}
+
+export interface InsightOpts {
+ /** Owner-fenced caller's client id (agentOwnerFence); null or absent = unfenced. */
+ owner?: string | null;
+ /** Remote caller: lock holder host and pid are never shown. */
+ remote?: boolean;
+}
+
+export const JOB_INSIGHT_FIELDS: readonly string[] = ['submitted_by', 'blocked_by', 'heartbeat_age_ms', 'heartbeat_basis', 'lock_expires_in_ms', 'stalled', 'spend'];
+
+const num = (v: unknown): number => (v == null ? 0 : Number(v));
+const time = (v: unknown): number | null => (v == null ? null : new Date(v as string).getTime());
+const iso = (v: unknown): string | null => (v == null ? null : new Date(v as string).toISOString());
+const record = (v: unknown): Record<string, unknown> | null => {
+ if (typeof v === 'string') { try { v = JSON.parse(v); } catch { return null; } }
+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;
+};
+
+function sourceOf(job: MinionJob): string {
+ const s = job.data?.sourceId ?? job.data?.source_id;
+ return typeof s === 'string' && s.length > 0 ? s : 'default';
+}
+
+/** The DB-row locks a job that is not running takes when it runs: a sync takes gbrain-sync:<src>, a cycle also gbrain-cycle:<src>. */
+function locksFor(job: MinionJob): string[] {
+ const src = sourceOf(job);
+ if (job.name === 'sync') return [`gbrain-sync:${src}`];
+ if (job.name === 'autopilot-cycle') return [`gbrain-cycle:${src}`, `gbrain-sync:${src}`];
+ return [];
+}
+
+function delayReason(job: MinionJob): { reason: DelayReason; detail?: string } {
+ const text = job.error_text ?? '';
+ const detail = text ? { detail: text.slice(0, 200) } : {};
+ if (text.startsWith('deferred')) return { reason: 'deferred', ...detail };
+ if (text.startsWith('worker_shutdown') || text.includes('released')) return { reason: 'handed_back', ...detail };
+ if (job.attempts_made > 0 && text) return { reason: 'retry_backoff', ...detail };
+ return { reason: 'scheduled', ...detail };
+}
+
+type LockRow = { holder_pid: number; holder_host: string | null; acquired_at: unknown; ttl_expires_at: unknown; beacon: Record<string, unknown> | null; holder_owner: string | null };
+type SpendRow = { root: number; self: boolean; settled_cents: number | string | null; priced: number | string; unsettled: number | string };
+
+/** Insight for each job, keyed by id. Read-only. */
+export async function describeJobs(engine: BrainEngine, jobs: MinionJob[], opts: InsightOpts = {}): Promise<Map<number, JobInsight>> {
+ const out = new Map<number, JobInsight>();
+ if (jobs.length === 0) return out;
+ const owner = opts.owner ?? null;
+ const ids = jobs.map(j => j.id);
+ const owns = (o: unknown) => owner === null || o === owner;
+
+ const [clock] = await engine.executeRaw<{ now: string }>('SELECT now() AS now');
+ const now = new Date(clock.now).getTime();
+
+ const meta = new Map((await engine.executeRaw<{ id: number; submitter: string | null; parent_owner: string | null }>(
+ `SELECT j.id, CASE WHEN j.submission_authority->>'kind' = 'application' THEN j.data->>'__submitter' END AS submitter,
+ p.data->>'__owner_client_id' AS parent_owner
+ FROM minion_jobs j LEFT JOIN minion_jobs p ON p.id = j.parent_job_id
+ WHERE j.id = ANY($1::int[])`, [ids])).map(r => [Number(r.id), r]));
+
+ const waiting = jobs.filter(j => j.status === 'waiting');
+ const positions = new Map<number, number>();
+ const holders = new Map<string, Array<{ id: number; name: string; owner: string | null }>>();
+ if (waiting.length > 0) {
+ const ahead = await engine.executeRaw<{ id: number; ahead: number | string }>(
+ `SELECT j.id, (SELECT count(*) FROM minion_jobs w
+ WHERE w.queue = j.queue AND w.status = 'waiting'
+ AND (w.priority, w.created_at, w.id) < (j.priority, j.created_at, j.id)) AS ahead
+ FROM minion_jobs j WHERE j.id = ANY($1::int[])`, [waiting.map(j => j.id)]);
+ for (const r of ahead) positions.set(Number(r.id), num(r.ahead));
+ const active = await engine.executeRaw<{ id: number; name: string; queue: string; owner: string | null }>(
+ `SELECT id, name, queue, data->>'__owner_client_id' AS owner FROM minion_jobs
+ WHERE status = 'active' AND queue = ANY($1::text[]) AND queue <> $2 ORDER BY started_at ASC NULLS LAST, id ASC LIMIT 500`,
+ [[...new Set(waiting.map(j => j.queue))], HOLDER_ROW_QUEUE]);
+ for (const r of active) {
+ const list = holders.get(r.queue) ?? [];
+ list.push({ id: Number(r.id), name: r.name, owner: r.owner });
+ holders.set(r.queue, list);
+ }
+ }
+
+ const children = new Map<number, Array<{ id: number; owner: string | null }>>();
+ const parents = jobs.filter(j => j.status === 'waiting-children');
+ if (parents.length > 0) {
+ const rows = await engine.executeRaw<{ id: number; parent_job_id: number; owner: string | null }>(
+ `SELECT id, parent_job_id, data->>'__owner_client_id' AS owner FROM minion_jobs
+ WHERE parent_job_id = ANY($1::int[]) AND status NOT IN ('completed','failed','dead','cancelled') ORDER BY id ASC`,
+ [parents.map(j => j.id)]);
+ for (const r of rows) {
+ const list = children.get(Number(r.parent_job_id)) ?? [];
+ list.push({ id: Number(r.id), owner: r.owner });
+ children.set(Number(r.parent_job_id), list);
+ }
+ }
+
+ const locks = new Map<string, LockRow>();
+ const lockIds = [...new Set(jobs.filter(j => j.status === 'waiting' || j.status === 'delayed').flatMap(locksFor))];
+ if (lockIds.length > 0) {
+ const rows = await engine.executeRaw<LockRow & { id: string; beacon: unknown }>(
+ `SELECT l.id, l.holder_pid, l.holder_host, l.acquired_at, l.ttl_expires_at, b.data->'drain_lease_beacon' AS beacon,
+ h.data->>'__owner_client_id' AS holder_owner
+ FROM gbrain_cycle_locks l
+ LEFT JOIN minion_jobs b ON b.queue = $2 AND b.lock_token = l.acquisition_token::text
+ LEFT JOIN minion_jobs h ON (b.data->'drain_lease_beacon'->>'kind') = 'job'
+ AND h.id::text = (b.data->'drain_lease_beacon'->>'id')
+ WHERE l.id = ANY($1::text[]) AND l.ttl_expires_at > now()`, [lockIds, HOLDER_ROW_QUEUE]);
+ for (const r of rows) locks.set(r.id, { ...r, beacon: record(r.beacon) });
+ }
+
+ const spendRows = await engine.executeRaw<SpendRow>(
+ `WITH RECURSIVE tree(root, id, owner, depth) AS (
+ SELECT id, id, data->>'__owner_client_id', 0 FROM minion_jobs WHERE id = ANY($1::int[])
+ UNION ALL
+ SELECT t.root, c.id, c.data->>'__owner_client_id', t.depth + 1 FROM minion_jobs c JOIN tree t ON c.parent_job_id = t.id WHERE t.depth < 20
+ )
+ SELECT t.root, (t.id = t.root) AS self,
+ sum(r.actual_cents) FILTER (WHERE r.status = 'settled' AND r.actual_cents IS NOT NULL) AS settled_cents,
+ count(*) FILTER (WHERE r.status = 'settled' AND r.actual_cents IS NOT NULL) AS priced,
+ count(*) FILTER (WHERE r.status <> 'settled' OR r.actual_cents IS NULL) AS unsettled
+ FROM tree t JOIN mcp_spend_reservations r ON r.job_id = t.id
+ WHERE t.id = t.root OR $2::text IS NULL OR t.owner = $2::text
+ GROUP BY 1, 2`, [ids, owner]);
+ const foreignTokens = new Map<number, { i: number; o: number; c: number }>();
+ if (owner !== null) {
+ const rows = await engine.executeRaw<{ parent_job_id: number; i: number | string; o: number | string; c: number | string }>(
+ `SELECT parent_job_id, sum(tokens_input) AS i, sum(tokens_output) AS o, sum(tokens_cache_read) AS c FROM minion_jobs
+ WHERE parent_job_id = ANY($1::int[]) AND status = 'completed' AND data->>'__owner_client_id' IS DISTINCT FROM $2::text
+ GROUP BY 1`, [ids, owner]);
+ for (const r of rows) foreignTokens.set(Number(r.parent_job_id), { i: num(r.i), o: num(r.o), c: num(r.c) });
+ }
+
+ const ctx: BlockCtx = { positions, holders, children, locks, owns, owner, remote: opts.remote === true };
+ for (const job of jobs) {
+ out.set(job.id, {
+ submitted_by: submittedBy(job, meta.get(job.id), owner),
+ blocked_by: blockedBy(job, ctx),
+ ...liveness(job, now),
+ spend: spendOf(job, spendRows.filter(r => Number(r.root) === job.id), foreignTokens.get(job.id)),
+ });
+ }
+ return out;
+}
+
+function submittedBy(job: MinionJob, m: { submitter: string | null; parent_owner: string | null } | undefined, owner: string | null): SubmittedBy {
+ const authority = job.submission_authority;
+ if (authority && authority.kind !== 'application') {
+ const id = authority.principal.id;
+ if (owner !== null && id !== owner) return { kind: 'mcp_client' };
+ return { kind: 'mcp_client', id, principal_kind: authority.principal.kind };
+ }
+ if (job.parent_job_id != null) {
+ if (owner !== null && m?.parent_owner !== owner) return { kind: 'parent_job' };
+ return { kind: 'parent_job', id: job.parent_job_id };
+ }
+ if (!authority) return { kind: 'unreviewed' };
+ if (owner !== null || !m?.submitter) return { kind: 'local' };
+ return { kind: 'local', via: m.submitter };
+}
+
+interface BlockCtx {
+ positions: Map<number, number>;
+ holders: Map<string, Array<{ id: number; name: string; owner: string | null }>>;
+ children: Map<number, Array<{ id: number; owner: string | null }>>;
+ locks: Map<string, LockRow>;
+ owns: (o: unknown) => boolean;
+ owner: string | null;
+ remote: boolean;
+}
+
+function blockedBy(job: MinionJob, c: BlockCtx): BlockedBy[] | null {
+ const reasons: BlockedBy[] = [];
+ if (job.status === 'waiting-children') {
+ const kids = c.children.get(job.id) ?? [];
+ reasons.push({ kind: 'waiting_children', pending: kids.length, child_ids: kids.filter(k => c.owns(k.owner)).slice(0, LIST_CAP).map(k => k.id) });
+ } else if (job.status === 'delayed') {
+ reasons.push({ kind: 'delayed', delay_until: iso(job.delay_until), ...delayReason(job) });
+ } else if (job.status === 'paused') {
+ reasons.push({ kind: 'paused' });
+ } else if (job.status === 'waiting') {
+ if (!job.submission_authority) reasons.push({ kind: 'unreviewed_authority', fix: `gbrain jobs authorize-legacy --ids ${job.id}` });
+ const active = c.holders.get(job.queue) ?? [];
+ const ahead = c.positions.get(job.id) ?? 0;
+ reasons.push({ kind: 'queue', queue: job.queue, queue_position: ahead + 1, ahead, active: active.length,
+ active_jobs: active.filter(h => c.owns(h.owner)).slice(0, LIST_CAP).map(h => ({ id: h.id, name: h.name })),
+ ...(job.queue.startsWith('dream-inline-') ? { private_queue: true as const } : {}) });
+ } else {
+ return null;
+ }
+ if (job.status !== 'waiting' && job.status !== 'delayed') return reasons;
+ for (const id of locksFor(job)) {
+ const lock = c.locks.get(id);
+ if (!lock) continue;
+ const beacon = lock.beacon;
+ const holderJob = beacon?.kind === 'job' && typeof beacon.id === 'string' && /^\d+$/.test(beacon.id) ? Number(beacon.id) : null;
+ if (holderJob === job.id) continue;
+ if (c.owner !== null) {
+ reasons.push(holderJob !== null && lock.holder_owner === c.owner ? { kind: 'lock', held: true, lock: id, holder_job_id: holderJob } : { kind: 'lock', held: true });
+ continue;
+ }
+ reasons.push({ kind: 'lock', held: true, lock: id, ...(holderJob !== null ? { holder_job_id: holderJob } : {}),
+ holder: { kind: typeof beacon?.kind === 'string' ? beacon.kind : 'unknown',
+ ...(c.remote ? {} : { pid: Number(lock.holder_pid), ...(lock.holder_host ? { host: lock.holder_host } : {}) }),
+ acquired_at: iso(lock.acquired_at), ttl_expires_at: iso(lock.ttl_expires_at) } });
+ }
+ return reasons;
+}
+
+function liveness(job: MinionJob, now: number): Pick<JobInsight, 'heartbeat_age_ms' | 'heartbeat_basis' | 'lock_expires_in_ms' | 'stalled'> {
+ const until = time(job.lock_until);
+ if (job.status !== 'active' || until === null) return { heartbeat_age_ms: null, heartbeat_basis: null, lock_expires_in_ms: null, stalled: null };
+ const renewedAt = job.lock_duration_ms != null ? until - job.lock_duration_ms : time(job.updated_at);
+ return {
+ heartbeat_age_ms: renewedAt === null ? null : Math.max(0, now - renewedAt),
+ heartbeat_basis: job.lock_duration_ms != null ? 'lease' : 'updated_at',
+ lock_expires_in_ms: until - now,
+ stalled: until < now,
+ };
+}
+
+function spendOf(job: MinionJob, rows: SpendRow[], foreign: { i: number; o: number; c: number } | undefined): JobSpend {
+ const priced = rows.reduce((n, r) => n + num(r.priced), 0);
+ const cents = rows.reduce((n, r) => n + num(r.settled_cents), 0);
+ return {
+ tokens_input: Math.max(0, job.tokens_input - (foreign?.i ?? 0)),
+ tokens_output: Math.max(0, job.tokens_output - (foreign?.o ?? 0)),
+ tokens_cache_read: Math.max(0, job.tokens_cache_read - (foreign?.c ?? 0)),
+ cost_usd: priced > 0 ? Math.round(cents * 100) / 10_000 : null,
+ cost_basis: priced > 0 ? 'settled_reservations' : 'unpriced',
+ includes_children: rows.some(r => !r.self && num(r.priced) > 0),
+ unsettled_reservations: rows.reduce((n, r) => n + num(r.unsettled), 0),
+ ...(foreign ? { excludes_foreign_children: true as const } : {}),
+ };
+}
+
+/**
+ * The job with its insight merged in. A fenced caller's top-level token counts are replaced by the spend
+ * counts, which leave out another principal's completed children (completeJob rolls child tokens into the parent).
+ */
+export function withInsight<T extends object>(job: T, insight: JobInsight | undefined): T & Partial<JobInsight> {
+ if (!insight) return job;
+ const tokens = insight.spend.excludes_foreign_children
+ ? { tokens_input: insight.spend.tokens_input, tokens_output: insight.spend.tokens_output, tokens_cache_read: insight.spend.tokens_cache_read }
+ : {};
+ return { ...job, ...tokens, ...insight };
+}
+
+/** One compact cell for `jobs list`: why a job waits, or the liveness of a running one. */
+export function insightCell(job: MinionJob, insight: JobInsight | undefined): string {
+ if (!insight) return '';
+ if (job.status === 'active') {
+ if (insight.stalled) return 'STALLED';
+ return insight.heartbeat_age_ms === null ? '' : `hb ${Math.round(insight.heartbeat_age_ms / 1000)}s`;
+ }
+ const reasons = insight.blocked_by ?? [];
+ const first = reasons.find(b => b.kind !== 'lock' && b.kind !== 'unreviewed_authority') ?? reasons[0];
+ if (!first) return '';
+ const lock = reasons.some(b => b.kind === 'lock') ? ' +lock' : '';
+ switch (first.kind) {
+ case 'queue': return `#${first.queue_position} (${first.active} run)${lock}`;
+ case 'waiting_children': return `${first.pending} children`;
+ case 'delayed': return `${first.reason}${lock}`;
+ case 'paused': return 'paused';
+ case 'unreviewed_authority': return 'unreviewed';
+ case 'lock': return 'lock';
+ }
+}
diff --git a/src/core/minions/lanes.ts b/src/core/minions/lanes.ts
new file mode 100644
index 0000000000..f6dd6efcb8
--- /dev/null
+++ b/src/core/minions/lanes.ts
@@ -0,0 +1,118 @@
+/**
+ * Claim-time lane reservation for long jobs (#7242).
+ *
+ * One worker at `--concurrency 2` could hold both slots with brain-wide
+ * passes (an autopilot cycle, global maintenance, an embed backfill) for tens
+ * of minutes while short per-page jobs such as `facts-absorb` waited behind
+ * them for days. With concurrency >= 2, at most `concurrency - reserved`
+ * slots may hold a long job (never fewer than one, so long work still runs);
+ * the rest stay free for everything else. The worker passes the long names as
+ * `excludeNames` to `MinionQueue.claim` once that budget is used.
+ *
+ * DEFAULT_LONG_JOB_NAMES holds only single-flight, brain-wide passes with a
+ * 30-minute budget in handler-timeouts.ts:
+ * - autopilot-cycle, autopilot-global-maintenance: the per-source and
+ * brain-wide maintenance passes that motivated the issue.
+ * - embed-backfill: a brain-wide embedding backfill.
+ * - connector-sync: a full account sync for a chat connector.
+ * - extract: a brain-wide `extract --stale` sweep or remediation pass.
+ * Per-page jobs (facts-absorb, chronicle_extract, contextual_reindex_per_chunk)
+ * are deliberately absent: they arrive in large fan-outs, so limiting them to
+ * one slot would cut their throughput. subagent jobs are absent too: callers
+ * wait on them interactively. Operators add names with
+ * `minions.long_job_names`.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export const DEFAULT_LONG_JOB_NAMES: readonly string[] = [
+ 'autopilot-cycle',
+ 'autopilot-global-maintenance',
+ 'embed-backfill',
+ 'connector-sync',
+ 'extract',
+];
+
+export const DEFAULT_SHORT_JOB_RESERVED_SLOTS = 1;
+export const SHORT_JOB_RESERVED_SLOTS_KEY = 'minions.short_job_reserved_slots';
+export const LONG_JOB_NAMES_KEY = 'minions.long_job_names';
+
+/** Slots that may hold a long job; equals concurrency when the reservation does not apply. */
+export function longJobSlots(concurrency: number, reservedSlots: number): number {
+ if (concurrency < 2 || reservedSlots <= 0) return concurrency;
+ return Math.max(1, concurrency - reservedSlots);
+}
+
+/** The names the next claim must skip: the long names once in-flight long jobs fill their slots, else none. */
+export function claimExclusions(
+ policy: { concurrency: number; shortJobReservedSlots: number; longJobNames: readonly string[] },
+ inFlightNames: Iterable<string>,
+): string[] {
+ const budget = longJobSlots(policy.concurrency, policy.shortJobReservedSlots);
+ if (budget >= policy.concurrency || policy.longJobNames.length === 0) return [];
+ const long = new Set(policy.longJobNames);
+ let running = 0;
+ for (const name of inFlightNames) if (long.has(name)) running++;
+ return running >= budget ? [...long] : [];
+}
+
+/** `minions.long_job_names`: a JSON array or a comma list, added to the defaults. Unparseable entries are dropped. */
+export function parseLongJobNames(raw: string | null | undefined): string[] {
+ const text = raw?.trim() ?? '';
+ if (text === '') return [];
+ let items: unknown[];
+ if (text.startsWith('[')) {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ items = Array.isArray(parsed) ? parsed : [];
+ } catch {
+ items = [];
+ }
+ } else {
+ items = text.split(',');
+ }
+ return items.filter((s): s is string => typeof s === 'string').map(s => s.trim()).filter(s => s !== '');
+}
+
+/** `minions.short_job_reserved_slots`: a non-negative integer; anything else is null (use the default). */
+export function parseReservedSlots(raw: string | null | undefined): number | null {
+ const text = raw?.trim() ?? '';
+ if (!/^\d+$/.test(text)) return null;
+ return Number(text);
+}
+
+export interface LanePolicy {
+ longJobNames: string[];
+ shortJobReservedSlots: number;
+}
+
+/** Reads both keys; a read failure or invalid value falls back to the defaults with one stderr line. */
+export async function resolveLanePolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<LanePolicy> {
+ let reservedRaw: string | null = null;
+ let namesRaw: string | null = null;
+ try {
+ [reservedRaw, namesRaw] = await Promise.all([
+ engine.getConfig(SHORT_JOB_RESERVED_SLOTS_KEY),
+ engine.getConfig(LONG_JOB_NAMES_KEY),
+ ]);
+ } catch (e) {
+ console.error(`[worker] could not read lane config (${e instanceof Error ? e.message : String(e)}); using defaults.`);
+ }
+ let reserved = parseReservedSlots(reservedRaw);
+ if (reserved === null) {
+ if (reservedRaw != null && reservedRaw.trim() !== '') {
+ console.error(`[worker] ${SHORT_JOB_RESERVED_SLOTS_KEY}=${JSON.stringify(reservedRaw)} is not a non-negative integer; using ${DEFAULT_SHORT_JOB_RESERVED_SLOTS}.`);
+ }
+ reserved = DEFAULT_SHORT_JOB_RESERVED_SLOTS;
+ }
+ return {
+ longJobNames: [...new Set([...DEFAULT_LONG_JOB_NAMES, ...parseLongJobNames(namesRaw)])],
+ shortJobReservedSlots: reserved,
+ };
+}
+
+/** The "Minion worker started" fragment. */
+export function describeLanePolicy(concurrency: number, reservedSlots: number): string {
+ const budget = longJobSlots(concurrency, reservedSlots);
+ if (budget >= concurrency) return 'long-job lane: off';
+ return `long-job lane: ${budget} of ${concurrency} slots`;
+}
diff --git a/src/core/minions/queue-families.ts b/src/core/minions/queue-families.ts
new file mode 100644
index 0000000000..4fa92636e2
--- /dev/null
+++ b/src/core/minions/queue-families.ts
@@ -0,0 +1,28 @@
+/**
+ * #7241: the per-queue lines of `gbrain jobs stats` (`MinionQueue.getStats().by_queue`). Dream phases mint a private
+ * `dream-inline-<ms>-<uuid8>` queue per run, so a busy brain has hundreds of them; they fold into one `dream-inline`
+ * row whose `queues` counts them, beside one row per named queue. `--queue <name>` still scopes the wedge lines to one.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { DREAM_INLINE_PRIVATE_QUEUE_PREFIX } from './queue.ts';
+
+/** Waiting/active now; total/completed/failed/dead among the rows created in the window (the `by_type` semantics). */
+export interface QueueFamilyStats { queue: string; queues: number; waiting_now: number; active_now: number; total: number; completed: number; failed: number; dead: number }
+
+export async function queueFamilyStats(engine: BrainEngine, since: Date): Promise<QueueFamilyStats[]> {
+ const rows = await engine.executeRaw<Record<string, string>>(
+ `SELECT CASE WHEN queue LIKE '${DREAM_INLINE_PRIVATE_QUEUE_PREFIX}%' THEN '${DREAM_INLINE_PRIVATE_QUEUE_PREFIX.slice(0, -1)}' ELSE queue END AS queue,
+ count(DISTINCT queue)::text AS queues,
+ count(*) FILTER (WHERE status = 'waiting')::text AS waiting_now,
+ count(*) FILTER (WHERE status = 'active')::text AS active_now,
+ count(*) FILTER (WHERE created_at >= $1)::text AS total,
+ count(*) FILTER (WHERE created_at >= $1 AND status = 'completed')::text AS completed,
+ count(*) FILTER (WHERE created_at >= $1 AND status = 'failed')::text AS failed,
+ count(*) FILTER (WHERE created_at >= $1 AND status = 'dead')::text AS dead
+ FROM minion_jobs WHERE created_at >= $1 OR status IN ('waiting', 'active')
+ GROUP BY 1 ORDER BY 1`,
+ [since.toISOString()],
+ );
+ return rows.map(r => ({ queue: r.queue!, queues: Number(r.queues), waiting_now: Number(r.waiting_now), active_now: Number(r.active_now),
+ total: Number(r.total), completed: Number(r.completed), failed: Number(r.failed), dead: Number(r.dead) }));
+}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 05f871fa16..9945e1f68a 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -18,8 +18,10 @@ import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
import { WATCHDOG_SUSPECT_MARK, releaseWatchdogClaim, requeueCoRunnerStalls, unmarkedJobSql } from './watchdog-attribution.ts';
export { WATCHDOG_SUSPECT_MARK } from './watchdog-attribution.ts';
import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';
+import { withSubmitterLabel } from './job-insight.ts';
import { adoptSpendAuthorization, legacyDefaultClaimSetSql, legacyDefaultClaimParams, type SpendAuthorization } from './spend-authorization.ts';
import { validateAttachment } from './attachments.ts';
+import type { QueueFamilyStats } from './queue-families.ts';
import { isProtectedJobName } from './protected-names.ts';
import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';
import { lockDelegatedSubmission, checkDelegatedCapacity, prepareDelegatedReplay, admitDelegatedRetry } from './delegated-admission.ts';
@@ -619,7 +621,7 @@ export class MinionQueue {
opts?.queue ?? 'default',
childStatus,
opts?.priority ?? 0,
- data ?? {},
+ withSubmitterLabel(data, authority.kind === 'application'),
opts?.max_attempts ?? 3,
opts?.backoff_type ?? 'exponential',
opts?.backoff_delay ?? 1000,
@@ -1285,6 +1287,7 @@ export class MinionQueue {
drained_completed: number; drained_failed: number; drained_dead: number; drained_cancelled: number;
waiting_now: number; oldest_waiting_minutes: number | null }>;
queue_health: { waiting: number; active: number; stalled: number };
+ by_queue: QueueFamilyStats[];
/**
* issue #1801 — QUEUE-SCOPED wedge signature for the `jobs stats` WEDGED
* line. by_status/by_type/queue_health above stay GLOBAL (dashboard
@@ -1412,6 +1415,7 @@ export class MinionQueue {
active: by_status['active'] ?? 0,
stalled,
},
+ by_queue: await (await import('./queue-families.ts')).queueFamilyStats(this.engine, since),
wedge: {
queue: wedgeQueue,
active_healthy: parseInt(wr.active_healthy ?? '0', 10),
@@ -1442,8 +1446,9 @@ export class MinionQueue {
* The map binds as a RAW object (never JSON.stringify into ::jsonb — the
* postgres.js double-encode trap; PGLite hides it, real PG does not).
*/
- /** `excludeWatchdogSuspects`: a worker with jobs in flight never claims a job marked by a shared watchdog drain (watchdog-attribution.ts). */
- async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[], opts: { excludeWatchdogSuspects?: boolean } = {}): Promise<MinionJob | null> {
+ /** `excludeWatchdogSuspects`: a worker with jobs in flight never claims a job marked by a shared watchdog drain (watchdog-attribution.ts).
+ * `excludeNames`: skip these job names (the worker's long-job lane reservation, lanes.ts). */
+ async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[], opts: { excludeWatchdogSuspects?: boolean; excludeNames?: string[] } = {}): Promise<MinionJob | null> {
if (registeredNames.length === 0) return null;
await assertNoUnreviewedJobs(this.engine);
@@ -1462,6 +1467,7 @@ export class MinionQueue {
// submit surfaces clamp already, but a bypass-written row (direct SQL
// repair, foreign tooling) must not grant a ~24-day lease to a worker
// that crashes before its first renewal (or a 1ms one that thrashes).
+ const excludeNames = opts.excludeNames?.length ? opts.excludeNames : null;
const rows = await this.engine.executeRawDirect<Record<string, unknown>>(
`UPDATE minion_jobs SET
status = 'active',
@@ -1481,14 +1487,14 @@ export class MinionQueue {
updated_at = now()
WHERE id = (
SELECT id FROM minion_jobs
- WHERE queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND name = ANY($4)${opts.excludeWatchdogSuspects ? ` AND ${unmarkedJobSql('$9')}` : ''}
+ WHERE queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND name = ANY($4)${opts.excludeWatchdogSuspects ? ` AND ${unmarkedJobSql('$9')}` : ''}${excludeNames ? ` AND NOT (name = ANY($${opts.excludeWatchdogSuspects ? 10 : 9}))` : ''}
ORDER BY priority ASC, created_at ASC
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING *`,
[lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS, HANDLER_DEFAULT_LOCK_DURATION_MS, ...legacyDefaultClaimParams(),
- ...(opts.excludeWatchdogSuspects ? [WATCHDOG_SUSPECT_MARK] : [])]
+ ...(opts.excludeWatchdogSuspects ? [WATCHDOG_SUSPECT_MARK] : []), ...(excludeNames ? [excludeNames] : [])]
);
return rows.length > 0 ? rowToMinionJob(rows[0]) : null;
}
diff --git a/src/core/minions/terminal-events.ts b/src/core/minions/terminal-events.ts
new file mode 100644
index 0000000000..bb20ea43ef
--- /dev/null
+++ b/src/core/minions/terminal-events.ts
@@ -0,0 +1,47 @@
+/**
+ * #7242: an append-only cursor over terminal job events, so an agent polls once for every job that finished
+ * instead of once per job. A job is an event when it reaches completed, failed, dead or cancelled; the cursor
+ * orders on (finished_at, id) at microsecond precision, so a page boundary never repeats or skips a row.
+ * A retried job that finishes again is a new event at its new finished_at. Rows deleted on completion
+ * (remove_on_complete / remove_on_fail) and pruned rows are not events.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { rowToMinionJob, type MinionJob } from './types.ts';
+
+export class TerminalCursorError extends Error {
+ constructor(message: string) { super(message); this.name = 'TerminalCursorError'; }
+}
+
+/** `<finished_at epoch microseconds>:<job id>`, or an ISO time (every event at or after it). */
+export function parseTerminalCursor(raw: string): { micros: string; id: number } {
+ const value = raw.trim();
+ const m = /^(\d{1,19}):(\d{1,12})$/.exec(value);
+ if (m) return { micros: m[1], id: Number(m[2]) };
+ const ms = Date.parse(value);
+ if (!/^\d{4}-\d{2}-\d{2}/.test(value) || Number.isNaN(ms)) throw new TerminalCursorError('finished_since must be an ISO time or a next_cursor value (<micros>:<id>).');
+ return { micros: String(BigInt(ms) * 1000n - 1n), id: Number.MAX_SAFE_INTEGER };
+}
+
+const FINISHED_US = "(EXTRACT(EPOCH FROM finished_at) * 1000000)::bigint";
+
+export async function listFinishedSince(engine: BrainEngine, since: string, opts: { queue?: string; name?: string; limit?: number; ownerClientId?: string } = {}): Promise<{ jobs: MinionJob[]; next_cursor: string }> {
+ const cursor = parseTerminalCursor(since);
+ const params: unknown[] = [cursor.micros, cursor.id];
+ const where = [
+ "status IN ('completed', 'failed', 'dead', 'cancelled')", 'finished_at IS NOT NULL',
+ `finished_at >= to_timestamp($1::bigint / 1000000.0) - interval '1 second'`,
+ `(${FINISHED_US}, id) > ($1::bigint, $2::bigint)`,
+ ];
+ if (opts.queue) { params.push(opts.queue); where.push(`queue = $${params.length}`); }
+ if (opts.name) { params.push(opts.name); where.push(`name = $${params.length}`); }
+ if (opts.ownerClientId) { params.push(opts.ownerClientId); where.push(`data->>'__owner_client_id' = $${params.length}`); }
+ params.push(Math.max(1, Math.min(500, Math.floor(opts.limit ?? 50))));
+ const rows = await engine.executeRaw<Record<string, unknown> & { finished_us: string | number }>(
+ `SELECT *, ${FINISHED_US}::text AS finished_us FROM minion_jobs WHERE ${where.join(' AND ')}
+ ORDER BY finished_at ASC, id ASC LIMIT $${params.length}`, params);
+ const last = rows[rows.length - 1];
+ return {
+ jobs: rows.map(rowToMinionJob),
+ next_cursor: last ? `${last.finished_us}:${Number(last.id)}` : `${cursor.micros}:${cursor.id}`,
+ };
+}
diff --git a/src/core/minions/terminal-hook.ts b/src/core/minions/terminal-hook.ts
new file mode 100644
index 0000000000..a0b963c883
--- /dev/null
+++ b/src/core/minions/terminal-hook.ts
@@ -0,0 +1,124 @@
+/**
+ * #7242: the terminal hook. A command from LOCAL file-plane config (`minions.terminal_hook` in
+ * ~/.gbrain/config.json, set with `gbrain config set minions.terminal_hook '["/abs/path", "arg"]'`) that the
+ * worker runs once each job it ran reaches completed, failed, dead or cancelled. It is off by default and is
+ * never read from the database config plane, MCP or job data, so nobody who can only submit jobs or write DB
+ * config can choose what runs.
+ *
+ * The command is an argv array spawned without a shell; job data is never interpolated into it. The job
+ * arrives in a fixed set of env vars (GBRAIN_JOB_ID, GBRAIN_JOB_NAME, GBRAIN_JOB_QUEUE, GBRAIN_JOB_STATUS)
+ * and as one JSON object on stdin (TERMINAL_HOOK_FIELDS, never data or result). It runs as the gbrain process
+ * user with that process's environment, is killed after timeout_ms (default 10 s), and a failure is logged
+ * once and never retried, never changing the job.
+ */
+import { spawn } from 'node:child_process';
+import { isAbsolute } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { isTerminalJobStatus } from './wait-for-completion.ts';
+import { rowToMinionJob, type MinionJob } from './types.ts';
+
+export const TERMINAL_HOOK_CONFIG_KEY = 'minions.terminal_hook';
+export const TERMINAL_HOOK_DEFAULT_TIMEOUT_MS = 10_000;
+const MAX_TIMEOUT_MS = 300_000;
+const MAX_CONCURRENT = 4;
+const TERMINAL_HOOK_FIELDS = ['id', 'name', 'queue', 'status', 'attempts_made', 'parent_job_id', 'created_at', 'started_at', 'finished_at', 'error_text'] as const;
+
+export interface TerminalHook { argv: string[]; timeout_ms: number }
+export type TerminalHookOutcome = 'ok' | 'exit_nonzero' | 'timeout' | 'spawn_error' | 'skipped_busy';
+
+/** The validated hook from a config value (an argv array, or {argv, timeout_ms}); a string or relative argv[0] is an error. */
+export function parseTerminalHook(raw: unknown): TerminalHook {
+ const value = typeof raw === 'string' ? JSON.parse(raw) as unknown : raw;
+ const record = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
+ const argv = Array.isArray(value) ? value : record?.argv;
+ if (!Array.isArray(argv) || argv.length === 0 || !argv.every(a => typeof a === 'string' && a.length > 0 && !a.includes('\0'))) {
+ throw new Error(`${TERMINAL_HOOK_CONFIG_KEY} must be a JSON array of strings (the command and its arguments, no shell), e.g. ["/usr/local/bin/notify-job"]`);
+ }
+ if (!isAbsolute(argv[0])) throw new Error(`${TERMINAL_HOOK_CONFIG_KEY}: the command must be an absolute path (got a relative one).`);
+ const t = record?.timeout_ms;
+ if (t !== undefined && !(typeof t === 'number' && Number.isInteger(t) && t >= 100 && t <= MAX_TIMEOUT_MS)) {
+ throw new Error(`${TERMINAL_HOOK_CONFIG_KEY}.timeout_ms must be an integer from 100 to ${MAX_TIMEOUT_MS}.`);
+ }
+ return { argv: argv as string[], timeout_ms: (t as number | undefined) ?? TERMINAL_HOOK_DEFAULT_TIMEOUT_MS };
+}
+
+/** The configured hook, or null when none is set. A malformed value logs once and disables the hook. */
+export function resolveTerminalHook(cfg: GBrainConfig | null): TerminalHook | null {
+ const raw = (cfg as { minions?: { terminal_hook?: unknown } } | null)?.minions?.terminal_hook;
+ if (raw == null) return null;
+ try { return parseTerminalHook(raw); }
+ catch (e) { console.warn(`[worker] terminal hook disabled: ${(e as Error).message}`); return null; }
+}
+
+/** `gbrain config set minions.terminal_hook <json>`: validate, then write the file plane only. */
+export function setTerminalHookConfig(cfg: GBrainConfig, value: string, save: (cfg: GBrainConfig) => void): void {
+ let hook: TerminalHook;
+ try { hook = parseTerminalHook(value); }
+ catch (e) { console.error(`[config] ${e instanceof SyntaxError ? `${TERMINAL_HOOK_CONFIG_KEY} is not valid JSON` : (e as Error).message}. Nothing was written.`); process.exit(1); }
+ const stored = hook.timeout_ms === TERMINAL_HOOK_DEFAULT_TIMEOUT_MS ? hook.argv : hook;
+ save({ ...cfg, minions: { ...((cfg as { minions?: object }).minions ?? {}), terminal_hook: stored } } as GBrainConfig);
+ console.log(`Set ${TERMINAL_HOOK_CONFIG_KEY} (file plane: ~/.gbrain/config.json). Workers started after this run it, as the gbrain process user, when a job they ran finishes; restart the worker or supervisor to apply.`);
+}
+
+function hookPayload(job: MinionJob): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const f of TERMINAL_HOOK_FIELDS) {
+ const v = job[f];
+ out[f] = v instanceof Date ? v.toISOString() : f === 'error_text' && typeof v === 'string' ? v.slice(0, 2000) : v ?? null;
+ }
+ return out;
+}
+
+/** Run the hook for one terminal job. Never throws; resolves with how it ended. */
+export function runTerminalHook(hook: TerminalHook, job: MinionJob): Promise<TerminalHookOutcome> {
+ return new Promise(resolve => {
+ let settled = false;
+ let stderr = '';
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const done = (outcome: TerminalHookOutcome, detail?: string) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (outcome !== 'ok') console.warn(`[worker] terminal hook for job ${job.id} (${job.name}, ${job.status}) ${outcome}${detail ? `: ${detail}` : ''}`);
+ resolve(outcome);
+ };
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(hook.argv[0], hook.argv.slice(1), {
+ shell: false,
+ stdio: ['pipe', 'ignore', 'pipe'],
+ env: { ...process.env, GBRAIN_JOB_ID: String(job.id), GBRAIN_JOB_NAME: job.name, GBRAIN_JOB_QUEUE: job.queue, GBRAIN_JOB_STATUS: job.status },
+ });
+ } catch (e) {
+ done('spawn_error', (e as Error).message);
+ return;
+ }
+ timer = setTimeout(() => { child.kill('SIGKILL'); done('timeout', `killed after ${hook.timeout_ms}ms`); }, hook.timeout_ms);
+ child.on('error', e => done('spawn_error', e.message));
+ child.stderr?.on('data', (b: Buffer) => { if (stderr.length < 500) stderr += b.toString('utf8'); });
+ child.on('close', (code, signal) => done(code === 0 ? 'ok' : 'exit_nonzero', `exit ${code ?? signal}${stderr ? `, stderr: ${stderr.trim().slice(0, 300)}` : ''}`));
+ child.stdin?.on('error', () => {});
+ child.stdin?.end(JSON.stringify(hookPayload(job)) + '\n');
+ });
+}
+
+/**
+ * The worker's `onJobSettled` callback: re-read the row and run the hook when it is terminal. A job handed back
+ * (waiting, delayed) is not an event. At most MAX_CONCURRENT hooks run at once; past that one is skipped and logged.
+ */
+export function terminalHookNotifier(engine: BrainEngine, hook: TerminalHook): { onJobSettled: (job: MinionJob) => void; drain: () => Promise<void> } {
+ const running = new Set<Promise<unknown>>();
+ const onJobSettled = (claimed: MinionJob) => {
+ const p = (async () => {
+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM minion_jobs WHERE id = $1', [claimed.id]);
+ const job = row ? rowToMinionJob(row) : null;
+ if (!job || !isTerminalJobStatus(job.status)) return;
+ if (running.size - 1 >= MAX_CONCURRENT) { console.warn(`[worker] terminal hook for job ${job.id} skipped_busy: ${MAX_CONCURRENT} hooks already running`); return; }
+ await runTerminalHook(hook, job);
+ })().catch(e => console.warn(`[worker] terminal hook for job ${claimed.id} failed: ${e instanceof Error ? e.message : String(e)}`));
+ running.add(p);
+ void p.finally(() => running.delete(p));
+ };
+ return { onJobSettled, drain: async () => { await Promise.allSettled([...running]); } };
+}
diff --git a/src/core/minions/types.ts b/src/core/minions/types.ts
index 6fd7509627..c4bd787998 100644
--- a/src/core/minions/types.ts
+++ b/src/core/minions/types.ts
@@ -220,6 +220,8 @@ export interface MinionQueueOpts {
export interface MinionWorkerOpts {
queue?: string;
+ /** #7242: called (never awaited, errors swallowed) after each job this worker ran settles; terminal-hook.ts re-reads the row. */
+ onJobSettled?: (job: MinionJob) => void;
concurrency?: number; // default 1
lockDuration?: number; // ms, default 30000
stalledInterval?: number; // ms, default 30000
@@ -264,6 +266,10 @@ export interface MinionWorkerOpts {
childCliInvocation?: { cmd: string; argsPrefix: string[] } | null;
/** tini path for wrapping job children ('' = absent, direct spawn). */
childTiniPath?: string;
+ /** #7242: job names that count against the long-job lane. Default: lanes.ts DEFAULT_LONG_JOB_NAMES. */
+ longJobNames?: readonly string[];
+ /** #7242: slots kept free of long jobs when concurrency >= 2 (at least one slot still takes long jobs). Default 1; 0 disables. */
+ shortJobReservedSlots?: number;
}
// --- Job Context (passed to handlers) ---
diff --git a/src/core/minions/wait-for-completion.ts b/src/core/minions/wait-for-completion.ts
index 55c8a23f9b..34587258bb 100644
--- a/src/core/minions/wait-for-completion.ts
+++ b/src/core/minions/wait-for-completion.ts
@@ -22,6 +22,9 @@ export class TimeoutError extends Error {
const TERMINAL_STATES: readonly MinionJobStatus[] = ['completed', 'failed', 'dead', 'cancelled'] as const;
const TERMINAL_SET = new Set<MinionJobStatus>(TERMINAL_STATES);
+/** completed, failed, dead or cancelled: the job will not run again unless someone retries it. */
+export function isTerminalJobStatus(status: MinionJobStatus): boolean { return TERMINAL_SET.has(status); }
+
export interface WaitOpts {
/** Abort after this many ms. Default: 24h (long enough for most durable runs). */
timeoutMs?: number;
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 8b0e1108dd..43a44fd252 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -89,6 +89,7 @@ import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';
import { endedByShutdown, releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';
import { isWatchdogSuspect, settleWatchdogAbort } from './watchdog-attribution.ts';
import { IdleWaiter } from './idle-wait.ts';
+import { DEFAULT_LONG_JOB_NAMES, DEFAULT_SHORT_JOB_RESERVED_SLOTS, claimExclusions } from './lanes.ts';
import { readFileSync } from 'fs';
/**
@@ -331,6 +332,9 @@ export class MinionWorker extends EventEmitter {
jobIsolation: opts?.jobIsolation ?? 'inline',
childCliInvocation: opts?.childCliInvocation ?? null,
childTiniPath: opts?.childTiniPath ?? '',
+ longJobNames: opts?.longJobNames ?? DEFAULT_LONG_JOB_NAMES,
+ shortJobReservedSlots: opts?.shortJobReservedSlots ?? DEFAULT_SHORT_JOB_RESERVED_SLOTS,
+ onJobSettled: opts?.onJobSettled ?? (() => {}),
};
// Process isolation contract: 'process' without a resolved child CLI
// invocation would silently execute handlers INLINE while the evict path
@@ -854,7 +858,7 @@ export class MinionWorker extends EventEmitter {
this.opts.lockDuration,
this.opts.queue,
this.registeredNames,
- { excludeWatchdogSuspects: this.inFlight.size > 0 },
+ { excludeWatchdogSuspects: this.inFlight.size > 0, excludeNames: claimExclusions(this.opts, [...this.inFlight.values()].map(f => f.job.name)) },
).then(claimed => {
if (claimed) {
this.executions.set(lockToken, { job: claimed, lockToken, stopped: true });
@@ -1458,6 +1462,7 @@ export class MinionWorker extends EventEmitter {
if (!this.configurationError || this.configurationDrainFinished) this.executions.delete(lockToken);
this.jobsCompleted += 1;
this.checkMemoryLimit('post-job');
+ try { this.opts.onJobSettled(job); } catch { /* the terminal hook never affects the job */ }
})
// D7 / codex C5: close the SECOND unhandledRejection vector. If
// executeJob's catch path throws (e.g., failJob's executeRaw
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index 901de8b783..e2e644f5d2 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -80,7 +80,7 @@ const OP_AREAS: Record<string, string> = {
// files (localOnly)
file_list: 'files', file_upload: 'files', file_url: 'files',
// jobs (Minions + agent lane)
- submit_job: 'jobs', get_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
+ submit_job: 'jobs', get_job: 'jobs', wait_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',
resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',
submit_agent: 'jobs', get_agent_job: 'jobs',
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 3d1b0c568a..601ca43789 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -140,6 +140,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"file_url": [load_files, "filesOperations"],
"submit_job": [load_jobs, "jobsOperations"],
"get_job": [load_jobs, "jobsOperations"],
+ "wait_job": [load_jobs, "jobsOperations"],
"list_jobs": [load_jobs, "jobsOperations"],
"cancel_job": [load_jobs, "jobsOperations"],
"retry_job": [load_jobs, "jobsOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 37985096a7..ad67f84ea9 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -3495,6 +3495,29 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"agentCallable": true,
"area": "jobs"
},
+ {
+ "name": "wait_job",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Wait until a job is completed, failed, dead or cancelled (at most 55 s per call), then return it like get_job plus terminal. terminal: false means it is still running: call again. Agent-scoped tokens (no admin) wait only on jobs they own.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ },
+ "timeout_s": {
+ "type": "number",
+ "description": "Seconds to wait (default 30, at most 55)."
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "area": "jobs"
+ },
{
"name": "list_jobs",
"mutating": false,
@@ -3526,6 +3549,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "string"
},
"description": "Return only these job fields (e.g. [\"id\",\"name\",\"status\"]) to save tokens; omit for every field."
+ },
+ "finished_since": {
+ "type": "string",
+ "description": "Terminal-event cursor: an ISO time or the next_cursor of the previous call. Returns {jobs, next_cursor}: jobs that finished after it, oldest first."
}
},
"scope": "admin",
@@ -3740,7 +3767,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"mutating": false,
"idempotent": true,
"outputRedaction": "no_stored_text",
- "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",
+ "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. by_queue has one row per queue (every dream-inline-* queue folded into one dream-inline row). Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",
"params": {
"queue": {
"type": "string",
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index 1e69f8e683..53bf17d17e 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -6,6 +6,13 @@ function publicJob(job: MinionJob) {
return { ...visible, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]' };
}
+/** #7241: public jobs with submitted_by, blocked_by, liveness and spend (job-insight.ts), fenced like the row read. */
+async function insightJobs(ctx: OperationContext, jobs: MinionJob[], owner: string | null) {
+ const { describeJobs, withInsight } = await import('../minions/job-insight.ts');
+ const insight = await describeJobs(ctx.engine, jobs, { owner, remote: ctx.remote !== false });
+ return jobs.map(job => withInsight(publicJob(job), insight.get(job.id)));
+}
+
/** Fields `list_jobs` may project to (F10 token trim): every public job field. */
const LIST_JOB_FIELDS = [
'id', 'name', 'queue', 'status', 'priority', 'data', 'max_attempts', 'attempts_made', 'attempts_started', 'backoff_type',
@@ -15,16 +22,18 @@ const LIST_JOB_FIELDS = [
'private_queue_owner_token', 'private_queue_lease_until', 'quiet_hours', 'stagger_key', 'result', 'progress', 'error_text',
'stacktrace', 'created_at', 'started_at', 'finished_at', 'updated_at', 'coalesced',
] as const satisfies readonly (keyof MinionJob)[];
+/** #7241 computed fields (job-insight.ts JOB_INSIGHT_FIELDS); list_jobs computes them only when projected. */
+const INSIGHT_JOB_FIELDS = ['submitted_by', 'blocked_by', 'heartbeat_age_ms', 'heartbeat_basis', 'lock_expires_in_ms', 'stalled', 'spend'] as const;
/** Parse list_jobs' `fields` (array or comma string); undefined = every field. */
function parseJobFields(raw: unknown): readonly string[] | undefined {
if (raw === undefined || raw === null || raw === '') return undefined;
const list = (Array.isArray(raw) ? raw : String(raw).split(',')).map(f => String(f).trim()).filter(Boolean);
- const valid: ReadonlySet<string> = new Set(LIST_JOB_FIELDS);
+ const valid: ReadonlySet<string> = new Set([...LIST_JOB_FIELDS, ...INSIGHT_JOB_FIELDS]);
const unknown = list.filter(f => !valid.has(f));
if (unknown.length > 0) {
throw opError('invalid_params', `list_jobs: unknown field(s) ${unknown.map(f => JSON.stringify(f.slice(0, 40))).join(', ')}.`,
- `Pass fields from: ${LIST_JOB_FIELDS.join(', ')} (e.g. fields: ["id", "name", "status"]), or omit fields for every field.`);
+ `Pass fields from: ${[...LIST_JOB_FIELDS, ...INSIGHT_JOB_FIELDS].join(', ')} (e.g. fields: ["id", "name", "status"]), or omit fields for every field.`);
}
return list.length ? list : undefined;
}
@@ -618,7 +627,45 @@ const get_job: Operation = {
if (!job) throw jobNotFound(`Job not found: ${p.id}`);
// private_queue_owner_token is a capability credential (lease renewal /
// attach), not job data — never expose it over MCP envelopes.
- return publicJob(job);
+ return (await insightJobs(ctx, [job], owner))[0];
+ },
+};
+
+/** #7242: the longest a single wait_job call holds the request before it answers `terminal: false`. */
+export const WAIT_JOB_MAX_S = 55;
+
+const wait_job: Operation = {
+ name: 'wait_job',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },
+ description: `Wait until a job is completed, failed, dead or cancelled (at most ${WAIT_JOB_MAX_S} s per call), then return it like get_job plus terminal. terminal: false means it is still running: call again. Agent-scoped tokens (no admin) wait only on jobs they own.`,
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ timeout_s: { type: 'number', description: `Seconds to wait (default 30, at most ${WAIT_JOB_MAX_S}).` },
+ },
+ scope: 'admin',
+ agentCallable: true,
+ handler: async (ctx, p) => {
+ const owner = agentOwnerFence(ctx, 'wait_job');
+ if (owner !== null) await assertJobOwned(ctx, p.id as number, owner);
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const { waitForCompletion, TimeoutError, isTerminalJobStatus } = await import('../minions/wait-for-completion.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const first = await queue.getJob(p.id as number);
+ if (!first) throw jobNotFound(`Job not found: ${p.id}`);
+ const requested = typeof p.timeout_s === 'number' && Number.isFinite(p.timeout_s) ? p.timeout_s : 30;
+ const timeoutMs = Math.max(0, Math.min(WAIT_JOB_MAX_S, requested)) * 1000;
+ let job = first;
+ if (!isTerminalJobStatus(job.status) && timeoutMs > 0) {
+ try {
+ job = await waitForCompletion(queue, job.id, { timeoutMs, pollMs: ctx.engine.kind === 'pglite' ? 250 : 1000 });
+ } catch (e) {
+ if (!(e instanceof TimeoutError)) throw e instanceof Error && /disappeared/.test(e.message) ? jobNotFound(`Job not found: ${p.id}`) : e;
+ job = (await queue.getJob(job.id)) ?? job;
+ }
+ }
+ return { ...(await insightJobs(ctx, [job], owner))[0], terminal: isTerminalJobStatus(job.status) };
},
};
@@ -634,12 +681,30 @@ const list_jobs: Operation = {
name: { type: 'string', description: 'Filter by job type' },
limit: { type: 'number', description: 'Max results (default: 50)' },
fields: { type: 'array', items: { type: 'string' }, description: 'Return only these job fields (e.g. ["id","name","status"]) to save tokens; omit for every field.' },
+ finished_since: { type: 'string', description: 'Terminal-event cursor: an ISO time or the next_cursor of the previous call. Returns {jobs, next_cursor}: jobs that finished after it, oldest first.' },
},
scope: 'admin',
agentCallable: true,
handler: async (ctx, p) => {
const fields = parseJobFields(p.fields);
const owner = agentOwnerFence(ctx, 'list_jobs');
+ const project = async (jobs: MinionJob[]) => {
+ const visible = !fields || fields.some(f => (INSIGHT_JOB_FIELDS as readonly string[]).includes(f)) ? await insightJobs(ctx, jobs, owner) : jobs.map(publicJob);
+ return fields ? visible.map(j => Object.fromEntries(fields.map(f => [f, (j as Record<string, unknown>)[f]]))) : visible;
+ };
+ if (p.finished_since !== undefined) {
+ const { listFinishedSince, TerminalCursorError } = await import('../minions/terminal-events.ts');
+ try {
+ const page = await listFinishedSince(ctx.engine, String(p.finished_since), {
+ queue: p.queue as string | undefined, name: p.name as string | undefined, limit: (p.limit as number) || 50,
+ ...(owner !== null ? { ownerClientId: owner } : {}),
+ });
+ return { jobs: await project(page.jobs), next_cursor: page.next_cursor };
+ } catch (e) {
+ if (e instanceof TerminalCursorError) throw invalidParam(ctx, 'list_jobs', 'finished_since', `list_jobs: ${e.message}`, { example: '2026-10-21T00:00:00Z' });
+ throw e;
+ }
+ }
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
const jobs = await queue.getJobs({
@@ -652,8 +717,7 @@ const list_jobs: Operation = {
} as Parameters<typeof queue.getJobs>[0]);
// private_queue_owner_token is a capability credential (lease renewal /
// attach), not job data — never expose it over MCP envelopes.
- const visible = jobs.map(publicJob);
- return fields ? visible.map(j => Object.fromEntries(fields.map(f => [f, (j as Record<string, unknown>)[f]]))) : visible;
+ return project(jobs);
},
};
@@ -879,6 +943,7 @@ const get_job_stats: Operation = {
'private_queue: true means the queue is a parent-owned dream-inline queue: wedged is ' +
'NEVER true for it and a worker restart cannot help — recovery runs automatically at ' +
'worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. ' +
+ 'by_queue has one row per queue (every dream-inline-* queue folded into one dream-inline row). ' +
'Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.',
params: {
queue: { type: 'string', required: false, description: "Queue for the wedge signature (default 'default'). The other blocks stay global/windowed." },
@@ -909,7 +974,7 @@ const get_job_stats: Operation = {
// Ops in EXACTLY the canonical `operations` array order.
export const jobsOperations: Operation[] = [
- submit_job, get_job, list_jobs, cancel_job, retry_job, get_job_progress,
+ submit_job, get_job, wait_job, list_jobs, cancel_job, retry_job, get_job_progress,
pause_job, resume_job, replay_job, send_job_message,
submit_agent, get_agent_job, get_job_stats,
];
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 94efec5f1b..f7d688d53b 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 254763,
- "stdoutSha256": "f6d6005ad68241f8e95fac4a2f61f62b074fd5a0a76206e8e410a02d425692df",
+ "stdoutBytes": 255964,
+ "stdoutSha256": "2ff4733ad376c0ddd2e8cfd7efce710e6d2ff61f82ed9a1a2d7ad12c2499fb2a",
"toolNames": [
"remember",
"entity",
@@ -90,6 +90,7 @@
"file_url",
"submit_job",
"get_job",
+ "wait_job",
"list_jobs",
"cancel_job",
"retry_job",
@@ -4198,6 +4199,35 @@
},
"scope": "admin"
},
+ {
+ "description": "Wait until a job is completed, failed, dead or cancelled (at most 55 s per call), then return it like get_job plus terminal. terminal: false means it is still running: call again. Agent-scoped tokens (no admin) wait only on jobs they own.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "wait_job",
+ "parameters": {
+ "id": "number",
+ "timeout_s": "number?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "id": {
+ "description": "Job ID",
+ "type": "number"
+ },
+ "timeout_s": {
+ "description": "Seconds to wait (default 30, at most 55).",
+ "type": "number"
+ }
+ },
+ "required": [
+ "id"
+ ],
+ "type": "object"
+ },
+ "scope": "admin"
+ },
{
"description": "List background jobs with optional status/queue/name filters; pass fields to project each job to the columns you need. Use when checking queued or failed work. Needs admin scope (agent-scoped tokens see only jobs they own).",
"idempotent": true,
@@ -4206,6 +4236,7 @@
"name": "list_jobs",
"parameters": {
"fields": "array?",
+ "finished_since": "string?",
"limit": "number?",
"name": "string?",
"queue": "string?",
@@ -4221,6 +4252,10 @@
},
"type": "array"
},
+ "finished_since": {
+ "description": "Terminal-event cursor: an ISO time or the next_cursor of the previous call. Returns {jobs, next_cursor}: jobs that finished after it, oldest first.",
+ "type": "string"
+ },
"limit": {
"description": "Max results (default: 50)",
"type": "number"
@@ -4507,7 +4542,7 @@
"scope": "agent"
},
{
- "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",
+ "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. by_queue has one row per queue (every dream-inline-* queue folded into one dream-inline row). Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",
"idempotent": true,
"local_only": false,
"mutating": false,
diff --git a/test/jobs-stats-private-queue.serial.test.ts b/test/jobs-stats-private-queue.serial.test.ts
index e47dd4f546..ca68406896 100644
--- a/test/jobs-stats-private-queue.serial.test.ts
+++ b/test/jobs-stats-private-queue.serial.test.ts
@@ -99,3 +99,44 @@ describe('jobs stats — ABANDONED PRIVATE QUEUE classifier gating', () => {
expect(out).not.toContain('WEDGED QUEUE');
});
});
+
+describe('jobs stats — per-queue lines fold dream-inline-* queues (#7241)', () => {
+ async function seed(): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data)
+ SELECT '{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', s, '{}'::jsonb FROM unnest(ARRAY['waiting','completed','completed']) AS s`,
+ [],
+ );
+ for (const [q, status] of [['dream-inline-1700000000000-aaaa0001', 'completed'], ['dream-inline-1700000000001-aaaa0002', 'completed'],
+ ['dream-inline-1700000000002-aaaa0003', 'dead']] as const) {
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, $2, '{}'::jsonb)`,
+ [q, status],
+ );
+ }
+ }
+
+ test('getStats reports one dream-inline row for every per-run queue, beside the named queues', async () => {
+ await seed();
+ const { MinionQueue } = await import('../src/core/minions/queue.ts');
+ const stats = await new MinionQueue(engine).getStats();
+ expect(stats.by_queue).toEqual([
+ { queue: 'default', queues: 1, waiting_now: 1, active_now: 0, total: 3, completed: 2, failed: 0, dead: 0 },
+ { queue: 'dream-inline', queues: 3, waiting_now: 0, active_now: 0, total: 3, completed: 2, failed: 0, dead: 1 },
+ ]);
+ });
+
+ test('the default output prints a line per queue family; --json carries by_queue; --queue <dream-inline-x> still scopes one queue', async () => {
+ await seed();
+ const out = await captureStats(['stats']);
+ expect(out).toMatch(/dream-inline \(3 queues\)\s+0 waiting, 0 active, 3 total, 2 done, 0 failed, 1 dead/);
+ expect(out).toMatch(/default\s+1 waiting, 0 active, 3 total, 2 done, 0 failed, 0 dead/);
+ const json = JSON.parse(await captureStats(['stats', '--json']));
+ expect(json.by_queue.map((r: { queue: string }) => r.queue)).toEqual(['default', 'dream-inline']);
+ expect(json.queue).toBe('default');
+ const one = JSON.parse(await captureStats(['stats', '--json', '--queue', 'dream-inline-1700000000002-aaaa0003']));
+ expect(one.wedge.queue).toBe('dream-inline-1700000000002-aaaa0003');
+ });
+});
+
diff --git a/test/jobs-wait-cli.serial.test.ts b/test/jobs-wait-cli.serial.test.ts
new file mode 100644
index 0000000000..463d162c74
--- /dev/null
+++ b/test/jobs-wait-cli.serial.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #7242 `gbrain jobs wait` exit codes (0 completed, 1 failed/dead/cancelled, 124 still running, 2 usage) and the
+ * #7241 fields in `jobs get --json` / `jobs list --json` / `jobs list --finished-since`.
+ *
+ * Serial: patches console and process.exit around runJobs and sets GBRAIN_HOME via withEnv
+ * (an empty home forces the local engine path), like jobs-list-get-json.serial.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { withEnv, emptyHome } from './helpers/with-env.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function seed(status: string, extra = ''): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, error_text, finished_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'noop', 'default', $1, '{"__submitter":"cli:test"}'::jsonb, $2,
+ CASE WHEN $1 IN ('completed','failed','dead','cancelled') THEN now() END)
+ RETURNING id`, [status, extra || null]);
+ return Number(rows[0].id);
+}
+
+class Exit extends Error { constructor(readonly code: number) { super(`exit ${code}`); } }
+
+async function run(args: string[]): Promise<{ code: number; out: string; err: string }> {
+ const origLog = console.log, origErr = console.error, origExit = process.exit;
+ let out = '', err = '';
+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };
+ process.exit = ((code?: number) => { throw new Exit(code ?? 0); }) as typeof process.exit;
+ let code = 0;
+ try {
+ await withEnv({ GBRAIN_HOME: emptyHome(), GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined },
+ async () => { await runJobs(engine, args); });
+ } catch (e) {
+ if (!(e instanceof Exit)) throw e;
+ code = e.code;
+ } finally {
+ console.log = origLog; console.error = origErr; process.exit = origExit;
+ }
+ return { code, out, err };
+}
+
+describe('jobs wait', () => {
+ test('a completed job exits 0 and prints the row with the #7241 fields', async () => {
+ const id = await seed('completed');
+ const r = await run(['wait', String(id), '--json']);
+ expect(r.code).toBe(0);
+ const doc = JSON.parse(r.out);
+ expect(doc).toMatchObject({ id, status: 'completed', submitted_by: { kind: 'local', via: 'cli:test' }, blocked_by: null,
+ spend: { cost_usd: null, cost_basis: 'unpriced' } });
+ });
+
+ test('failed, dead and cancelled exit 1 and say how the job ended', async () => {
+ for (const status of ['failed', 'dead', 'cancelled']) {
+ const id = await seed(status, 'boom-example');
+ const r = await run(['wait', String(id)]);
+ expect(r.code).toBe(1);
+ expect(r.err).toContain(`ended ${status}`);
+ }
+ });
+
+ test('the timeout exits 124 (still running, not a failure) and leaves the job alone', async () => {
+ const id = await seed('waiting');
+ const started = Date.now();
+ const r = await run(['wait', String(id), '--timeout', '1s', '--json']);
+ expect(r.code).toBe(124);
+ expect(Date.now() - started).toBeLessThan(5_000);
+ expect(JSON.parse(r.out)).toMatchObject({ id, status: 'waiting' });
+ expect(r.err).toContain('still waiting');
+ expect(r.err).toContain(`gbrain jobs wait ${id}`);
+ const [row] = await engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [id]);
+ expect(row.status).toBe('waiting');
+ });
+
+ test('usage errors exit 2; a missing job exits 1', async () => {
+ expect((await run(['wait'])).code).toBe(2);
+ expect((await run(['wait', '7', '--timeout', 'soon'])).code).toBe(2);
+ const missing = await run(['wait', '999999', '--timeout', '1s']);
+ expect(missing.code).toBe(1);
+ expect(missing.err).toContain('not found');
+ });
+});
+
+describe('jobs get / list carry the #7241 fields', () => {
+ test('get --json and list --json include blocked_by and spend; the table has a wait column', async () => {
+ const a = await seed('waiting');
+ const b = await seed('waiting');
+ const get = JSON.parse((await run(['get', String(b), '--json'])).out);
+ expect(get.blocked_by[0]).toMatchObject({ kind: 'queue', queue_position: 2, ahead: 1 });
+ const list = JSON.parse((await run(['list', '--json'])).out) as Array<Record<string, any>>;
+ expect(list.find(j => j.id === a)!.blocked_by[0]).toMatchObject({ queue_position: 1 });
+ const table = (await run(['list'])).out;
+ expect(table).toContain('Wait/Live');
+ expect(table).toContain('#2 (0 run)');
+ });
+
+ test('list --finished-since pages terminal events with a cursor', async () => {
+ await seed('waiting');
+ const done = await seed('completed');
+ const page = JSON.parse((await run(['list', '--finished-since', '2000-01-01T00:00:00Z', '--json'])).out);
+ expect(page.jobs.map((j: { id: number }) => j.id)).toEqual([done]);
+ expect(page.next_cursor).toMatch(/^\d+:\d+$/);
+ const next = JSON.parse((await run(['list', '--finished-since', page.next_cursor, '--json'])).out);
+ expect(next.jobs).toEqual([]);
+ expect((await run(['list', '--finished-since', 'later'])).code).toBe(2);
+ });
+});
diff --git a/test/minion-job-progress-7241.test.ts b/test/minion-job-progress-7241.test.ts
new file mode 100644
index 0000000000..269cbc4606
--- /dev/null
+++ b/test/minion-job-progress-7241.test.ts
@@ -0,0 +1,96 @@
+/**
+ * #7241: a live `sync`, `autopilot-cycle` or `autopilot-global-maintenance` job writes its phase to
+ * `minion_jobs.progress`, so `gbrain jobs get` shows what it is doing instead of an empty progress column.
+ *
+ * Each case drives the real handler against a real queue row claimed with a lock token (the worker's
+ * token-fenced context from buildJobContext), then reads the column. A progress write that throws never
+ * fails the job.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { buildJobContext } from '../src/core/minions/job-context.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { makeAutopilotCycleHandler } from '../src/core/minions/handlers/autopilot-cycle.ts';
+import { makeAutopilotGlobalMaintenanceHandler } from '../src/core/minions/handlers/autopilot-global-maintenance.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
+import type { CycleReport } from '../src/core/cycle.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-job-progress-'));
+const brain = join(home, 'brain');
+let engine: PGLiteEngine;
+let schemaVersion: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+ mkdirSync(brain, { recursive: true });
+ const repo = await makeGitFixture(brain);
+ writeFileSync(join(brain, 'note.md'), '---\ntitle: Note\ntype: note\n---\n\nA short note.\n');
+ repo.commitAll('add note');
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+});
+
+/** A queue row claimed the way a worker leaves it, with the worker's token-fenced context; every progress write is also recorded. */
+async function claimed(name: string, data: Record<string, unknown>): Promise<{ ctx: MinionJobContext; writes: Array<Record<string, unknown>>; id: number }> {
+ const queue = new MinionQueue(engine);
+ const row = await queue.add(name, data, {}, { allowProtectedSubmit: true });
+ const token = `tok-${row.id}`;
+ await engine.executeRaw(`UPDATE minion_jobs SET status='active', started_at=now(), lock_until=now() + interval '5 minutes', lock_token=$2, claim_generation=claim_generation + 1 WHERE id=$1`, [row.id, token]);
+ const ctx = buildJobContext(engine, queue, (await queue.getJob(row.id))!, token, new AbortController().signal, new AbortController().signal);
+ const writes: Array<Record<string, unknown>> = [];
+ const write = ctx.updateProgress;
+ ctx.updateProgress = async (progress: unknown) => { writes.push(progress as Record<string, unknown>); await write(progress); };
+ return { ctx, writes, id: row.id };
+}
+const storedProgress = async (id: number) =>
+ (await engine.executeRaw<{ progress: Record<string, unknown> | null }>('SELECT progress FROM minion_jobs WHERE id = $1', [id]))[0]!.progress;
+
+describe('#7241 job progress', () => {
+ test('autopilot-cycle writes each phase it enters, with its position in the cycle', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { ctx, writes, id } = await claimed('autopilot-cycle', { phases: ['orphans', 'purge'] });
+ const result = await makeAutopilotCycleHandler(engine)(ctx) as { report: CycleReport };
+ expect(result.report.phases.map(p => p.phase)).toEqual(['orphans', 'purge']);
+ expect(writes.map(w => [w.phase, w.phase_index, w.phase_count])).toEqual([['orphans', 0, 2], ['purge', 1, 2]]);
+ expect(typeof writes[0]!.started_at).toBe('string');
+ expect(await storedProgress(id)).toMatchObject({ phase: 'purge', phase_index: 1, phase_count: 2 });
+ }), 60_000);
+
+ test('autopilot-global-maintenance writes each maintenance phase it starts', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { ctx, writes, id } = await claimed('autopilot-global-maintenance', { phases: ['orphans', 'purge'], repoPath: brain });
+ await makeAutopilotGlobalMaintenanceHandler(engine)(ctx);
+ expect(writes.map(w => [w.phase, w.phase_index, w.phase_count])).toEqual([['orphans', 0, 2], ['purge', 1, 2]]);
+ expect(await storedProgress(id)).toMatchObject({ phase: 'purge', phase_index: 1, phase_count: 2 });
+ }), 60_000);
+
+ test('a classic sync job writes the sync phases it reaches', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brain]);
+ const { ctx, writes, id } = await claimed('sync', { sourceId: 'default', repoPath: brain, pull: false, auto_embed_backfill: false });
+ await makeSyncHandler(engine)(ctx);
+ const phases = writes.map(w => w.phase);
+ expect(phases[0]).toBe('resolve_repo');
+ expect(phases.some(p => p === 'full_import' || p === 'import')).toBe(true);
+ expect((await storedProgress(id))?.phase).toBe(phases.at(-1));
+ }), 60_000);
+
+ test('a progress write that throws never fails the job', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { ctx } = await claimed('autopilot-cycle', { phases: ['orphans'] });
+ ctx.updateProgress = async () => { throw new Error('progress store unavailable'); };
+ const result = await makeAutopilotCycleHandler(engine)(ctx) as { report: CycleReport };
+ expect(result.report.phases.map(p => [p.phase, p.status === 'fail'])).toEqual([['orphans', false]]);
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brain]);
+ const sync = await claimed('sync', { sourceId: 'default', repoPath: brain, pull: false, auto_embed_backfill: false });
+ sync.ctx.updateProgress = async () => { throw new Error('progress store unavailable'); };
+ await expect(makeSyncHandler(engine)(sync.ctx)).resolves.toBeDefined();
+ }), 60_000);
+});
diff --git a/test/minions-lane-load.slow.test.ts b/test/minions-lane-load.slow.test.ts
new file mode 100644
index 0000000000..b1412b642d
--- /dev/null
+++ b/test/minions-lane-load.slow.test.ts
@@ -0,0 +1,30 @@
+/**
+ * Runs the synthetic job-load fixture (scripts/bench/minions-lane-load.ts)
+ * before and after the long-job lane reservation (#7242) and asserts the
+ * reservation cuts short-job queue wait. About 10 s of real time, so it lives
+ * in the slow tier.
+ */
+import { describe, expect, test } from 'bun:test';
+import { DEFAULT_LANE_LOAD, percentile, runBeforeAfter, summarize } from '../scripts/bench/minions-lane-load.ts';
+
+describe('lane-load fixture helpers', () => {
+ test('nearest-rank percentiles', () => {
+ expect(percentile([], 95)).toBe(0);
+ expect(percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 50)).toBe(5);
+ expect(percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 95)).toBe(10);
+ expect(summarize([30, 10, 20])).toEqual({ count: 3, p50: 20, p95: 30, max: 30 });
+ });
+});
+
+describe('short-job queue wait under mixed load (#7242)', () => {
+ test('one reserved slot cuts short-job p95 wait on a 2-slot worker', async () => {
+ const { before, after } = await runBeforeAfter();
+ console.log(`[lane-load] before p50=${before.short.p50} p95=${before.short.p95} max=${before.short.max} ms; after p50=${after.short.p50} p95=${after.short.p95} max=${after.short.max} ms`);
+ expect(before.short.count).toBe(DEFAULT_LANE_LOAD.shortCount);
+ expect(after.short.count).toBe(DEFAULT_LANE_LOAD.shortCount);
+ expect(after.long.count).toBe(DEFAULT_LANE_LOAD.longAtMs.length);
+ // Before: two long jobs hold both slots for most of a long run, so short jobs wait behind them.
+ expect(before.short.p95).toBeGreaterThanOrEqual(DEFAULT_LANE_LOAD.longMs / 2);
+ expect(after.short.p95 * 4).toBeLessThan(before.short.p95);
+ }, 60_000);
+});
diff --git a/test/minions-lane-reservation.test.ts b/test/minions-lane-reservation.test.ts
new file mode 100644
index 0000000000..a98744052d
--- /dev/null
+++ b/test/minions-lane-reservation.test.ts
@@ -0,0 +1,128 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function submitInOrder(names: string[]): Promise<number[]> {
+ const ids: number[] = [];
+ for (const [i, name] of names.entries()) {
+ const job = await queue.add(name, { i });
+ await engine.executeRaw(`UPDATE minion_jobs SET created_at = now() - make_interval(secs => $2) WHERE id = $1`, [job.id, 100 - i]);
+ ids.push(job.id);
+ }
+ return ids;
+}
+
+async function statusOf(id: number): Promise<string | undefined> {
+ return (await queue.getJob(id))?.status;
+}
+
+/** Long handler blocks on a shared gate; short handler returns at once. Claim order is recorded by job id. */
+async function runMixed(opts: { concurrency: number; shortJobReservedSlots: number }) {
+ const [long1, long2, short] = await submitInOrder(['fixture-long', 'fixture-long', 'fixture-short']);
+ let release!: () => void;
+ const gate = new Promise<void>(r => { release = r; });
+ const started: number[] = [];
+ const worker = new MinionWorker(engine, {
+ concurrency: opts.concurrency,
+ pollInterval: 20,
+ healthCheckInterval: 0,
+ stalledInterval: 60_000,
+ longJobNames: ['fixture-long'],
+ shortJobReservedSlots: opts.shortJobReservedSlots,
+ });
+ worker.register('fixture-long', async (job) => { started.push(job.id); await gate; });
+ worker.register('fixture-short', async (job) => { started.push(job.id); });
+ const running = worker.start();
+ return { long1, long2, short, started, release, worker, running };
+}
+
+describe('claim-time lane reservation for long jobs (#7242)', () => {
+ test('a 2-slot worker running one long job claims the short job, not the second long job ahead of it', async () => {
+ const run = await runMixed({ concurrency: 2, shortJobReservedSlots: 1 });
+ try {
+ await waitFor(async () => (await statusOf(run.short)) === 'completed', { timeoutMs: 10_000, label: 'short job completed' });
+ expect(run.started.slice(0, 2)).toEqual([run.long1, run.short]);
+ // Several poll ticks with a free slot: the second long job must stay waiting.
+ await new Promise(r => setTimeout(r, 300));
+ expect(await statusOf(run.long2)).toBe('waiting');
+ expect(await statusOf(run.long1)).toBe('active');
+ } finally {
+ run.release();
+ await waitFor(async () => (await statusOf(run.long2)) === 'completed', { timeoutMs: 10_000, label: 'second long job ran after the first' });
+ run.worker.stop();
+ await run.running;
+ }
+ expect(run.started).toEqual([run.long1, run.short, run.long2]);
+ }, 30_000);
+
+ test('reserved slots 0 keeps the old FIFO claim: the second long job takes the second slot', async () => {
+ const run = await runMixed({ concurrency: 2, shortJobReservedSlots: 0 });
+ try {
+ await waitFor(() => run.started.length >= 2, { timeoutMs: 10_000, label: 'two jobs claimed' });
+ expect(run.started.slice(0, 2)).toEqual([run.long1, run.long2]);
+ expect(await statusOf(run.short)).toBe('waiting');
+ } finally {
+ run.release();
+ await waitFor(async () => (await statusOf(run.short)) === 'completed', { timeoutMs: 10_000, label: 'short job completed' });
+ run.worker.stop();
+ await run.running;
+ }
+ }, 30_000);
+
+ test('concurrency 1 is unaffected: the long job at the head of the queue is claimed', async () => {
+ const run = await runMixed({ concurrency: 1, shortJobReservedSlots: 1 });
+ try {
+ await waitFor(() => run.started.length >= 1, { timeoutMs: 10_000, label: 'first job claimed' });
+ expect(run.started[0]).toBe(run.long1);
+ run.release();
+ await waitFor(() => run.started.length >= 2, { timeoutMs: 10_000, label: 'second job claimed' });
+ expect(run.started[1]).toBe(run.long2);
+ } finally {
+ run.release();
+ await waitFor(async () => (await statusOf(run.short)) === 'completed', { timeoutMs: 10_000, label: 'short job completed' });
+ run.worker.stop();
+ await run.running;
+ }
+ }, 30_000);
+});
+
+describe('MinionQueue.claim excludeNames', () => {
+ test('skips excluded names and claims the next eligible job in priority order', async () => {
+ const [long1, short] = await submitInOrder(['fixture-long', 'fixture-short']);
+ const claimed = await queue.claim('tok-exclude', 30_000, 'default', ['fixture-long', 'fixture-short'], { excludeNames: ['fixture-long'] });
+ expect(claimed?.id).toBe(short);
+ expect(await statusOf(long1)).toBe('waiting');
+ });
+
+ test('returns null when every waiting job is excluded, and an empty list excludes nothing', async () => {
+ const [long1] = await submitInOrder(['fixture-long']);
+ expect(await queue.claim('tok-none', 30_000, 'default', ['fixture-long'], { excludeNames: ['fixture-long'] })).toBeNull();
+ expect((await queue.claim('tok-empty', 30_000, 'default', ['fixture-long'], { excludeNames: [] }))?.id).toBe(long1);
+ });
+
+ test('composes with excludeWatchdogSuspects', async () => {
+ const [, short] = await submitInOrder(['fixture-long', 'fixture-short']);
+ const claimed = await queue.claim('tok-both', 30_000, 'default', ['fixture-long', 'fixture-short'], { excludeWatchdogSuspects: true, excludeNames: ['fixture-long'] });
+ expect(claimed?.id).toBe(short);
+ });
+});
diff --git a/test/minions-lanes.test.ts b/test/minions-lanes.test.ts
new file mode 100644
index 0000000000..6de40678eb
--- /dev/null
+++ b/test/minions-lanes.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ DEFAULT_LONG_JOB_NAMES,
+ DEFAULT_SHORT_JOB_RESERVED_SLOTS,
+ LONG_JOB_NAMES_KEY,
+ SHORT_JOB_RESERVED_SLOTS_KEY,
+ claimExclusions,
+ describeLanePolicy,
+ longJobSlots,
+ parseLongJobNames,
+ parseReservedSlots,
+ resolveLanePolicy,
+} from '../src/core/minions/lanes.ts';
+import { HANDLER_DEFAULT_TIMEOUT_MS } from '../src/core/minions/handler-timeouts.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const LONG = ['long-a', 'long-b'];
+
+describe('longJobSlots', () => {
+ test('reserves slots only at concurrency >= 2 and always leaves one long slot', () => {
+ expect(longJobSlots(1, 1)).toBe(1);
+ expect(longJobSlots(2, 1)).toBe(1);
+ expect(longJobSlots(4, 1)).toBe(3);
+ expect(longJobSlots(4, 2)).toBe(2);
+ expect(longJobSlots(2, 5)).toBe(1);
+ expect(longJobSlots(4, 0)).toBe(4);
+ });
+});
+
+describe('claimExclusions', () => {
+ test('excludes long names once in-flight long jobs fill the long slots', () => {
+ expect(claimExclusions({ concurrency: 2, shortJobReservedSlots: 1, longJobNames: LONG }, [])).toEqual([]);
+ expect(claimExclusions({ concurrency: 2, shortJobReservedSlots: 1, longJobNames: LONG }, ['short'])).toEqual([]);
+ expect(claimExclusions({ concurrency: 2, shortJobReservedSlots: 1, longJobNames: LONG }, ['long-b'])).toEqual(LONG);
+ expect(claimExclusions({ concurrency: 4, shortJobReservedSlots: 1, longJobNames: LONG }, ['long-a', 'long-b'])).toEqual([]);
+ expect(claimExclusions({ concurrency: 4, shortJobReservedSlots: 1, longJobNames: LONG }, ['long-a', 'long-b', 'long-a'])).toEqual(LONG);
+ });
+
+ test('reserved 0, concurrency 1 and an empty long set never exclude', () => {
+ expect(claimExclusions({ concurrency: 2, shortJobReservedSlots: 0, longJobNames: LONG }, ['long-a'])).toEqual([]);
+ expect(claimExclusions({ concurrency: 1, shortJobReservedSlots: 1, longJobNames: LONG }, [])).toEqual([]);
+ expect(claimExclusions({ concurrency: 2, shortJobReservedSlots: 1, longJobNames: [] }, ['long-a'])).toEqual([]);
+ });
+});
+
+describe('config parsing', () => {
+ test('long job names accept a comma list or a JSON array', () => {
+ expect(parseLongJobNames(' sync , book-mirror ,, ')).toEqual(['sync', 'book-mirror']);
+ expect(parseLongJobNames('["sync", "book-mirror", 3, ""]')).toEqual(['sync', 'book-mirror']);
+ expect(parseLongJobNames('[not json')).toEqual([]);
+ expect(parseLongJobNames(null)).toEqual([]);
+ expect(parseLongJobNames(' ')).toEqual([]);
+ });
+
+ test('reserved slots must be a non-negative integer', () => {
+ expect(parseReservedSlots('0')).toBe(0);
+ expect(parseReservedSlots(' 2 ')).toBe(2);
+ expect(parseReservedSlots('-1')).toBeNull();
+ expect(parseReservedSlots('1.5')).toBeNull();
+ expect(parseReservedSlots('one')).toBeNull();
+ expect(parseReservedSlots(null)).toBeNull();
+ });
+});
+
+function fakeEngine(values: Record<string, string | null> | Error): Pick<BrainEngine, 'getConfig'> {
+ return {
+ getConfig: async (key: string) => {
+ if (values instanceof Error) throw values;
+ return values[key] ?? null;
+ },
+ };
+}
+
+describe('resolveLanePolicy', () => {
+ test('defaults: one reserved slot and the built-in long names', async () => {
+ expect(await resolveLanePolicy(fakeEngine({}))).toEqual({
+ longJobNames: [...DEFAULT_LONG_JOB_NAMES],
+ shortJobReservedSlots: DEFAULT_SHORT_JOB_RESERVED_SLOTS,
+ });
+ expect(DEFAULT_SHORT_JOB_RESERVED_SLOTS).toBe(1);
+ });
+
+ test('configured names add to the defaults and 0 disables the reservation', async () => {
+ const policy = await resolveLanePolicy(fakeEngine({
+ [SHORT_JOB_RESERVED_SLOTS_KEY]: '0',
+ [LONG_JOB_NAMES_KEY]: 'sync,autopilot-cycle',
+ }));
+ expect(policy.shortJobReservedSlots).toBe(0);
+ expect(policy.longJobNames).toEqual([...DEFAULT_LONG_JOB_NAMES, 'sync']);
+ });
+
+ test('an invalid reserved value or a failed read falls back to the defaults', async () => {
+ const errors: string[] = [];
+ const original = console.error;
+ console.error = (msg: string) => { errors.push(msg); };
+ try {
+ expect((await resolveLanePolicy(fakeEngine({ [SHORT_JOB_RESERVED_SLOTS_KEY]: 'lots' }))).shortJobReservedSlots).toBe(1);
+ expect(await resolveLanePolicy(fakeEngine(new Error('db down')))).toEqual({
+ longJobNames: [...DEFAULT_LONG_JOB_NAMES],
+ shortJobReservedSlots: 1,
+ });
+ } finally {
+ console.error = original;
+ }
+ expect(errors.some(e => e.includes(SHORT_JOB_RESERVED_SLOTS_KEY))).toBe(true);
+ expect(errors.some(e => e.includes('db down'))).toBe(true);
+ });
+});
+
+describe('defaults', () => {
+ test('every built-in long job has a 30-minute-or-longer handler budget', () => {
+ for (const name of DEFAULT_LONG_JOB_NAMES) {
+ expect(HANDLER_DEFAULT_TIMEOUT_MS[name]).toBeGreaterThanOrEqual(30 * 60 * 1000);
+ }
+ expect(DEFAULT_LONG_JOB_NAMES).toContain('autopilot-cycle');
+ expect(DEFAULT_LONG_JOB_NAMES).toContain('autopilot-global-maintenance');
+ expect(DEFAULT_LONG_JOB_NAMES).not.toContain('facts-absorb');
+ });
+
+ test('a worker built without lane options uses the default policy', () => {
+ const worker = new MinionWorker({ kind: 'pglite' } as unknown as BrainEngine, {});
+ const opts = (worker as unknown as { opts: { longJobNames: readonly string[]; shortJobReservedSlots: number } }).opts;
+ expect(opts.longJobNames).toEqual(DEFAULT_LONG_JOB_NAMES);
+ expect(opts.shortJobReservedSlots).toBe(1);
+ });
+
+ test('the started-line fragment names the long-job budget', () => {
+ expect(describeLanePolicy(2, 1)).toBe('long-job lane: 1 of 2 slots');
+ expect(describeLanePolicy(2, 0)).toBe('long-job lane: off');
+ expect(describeLanePolicy(1, 1)).toBe('long-job lane: off');
+ });
+});
diff --git a/test/minions-submission-authority.test.ts b/test/minions-submission-authority.test.ts
index bb68abd2bc..cf814efa73 100644
--- a/test/minions-submission-authority.test.ts
+++ b/test/minions-submission-authority.test.ts
@@ -182,6 +182,18 @@ describe('generic remote job authority', () => {
await expect(jobsOperations.find(op => op.name === 'retry_job')!.handler(ctx(), { id: local.id })).rejects.toThrow('submitting principal');
}));
+ test('#7241: a remote submit carrying __submitter never shows as a local submitter', () => isolated(async () => {
+ const operation = jobsOperations.find(op => op.name === 'submit_job')!;
+ await expect(operation.handler(ctx(), { name: 'lint', data: { __submitter: 'autopilot' } })).rejects.toThrow('unsupported');
+ const result = await operation.handler(ctx(), { name: 'lint', data: {} }) as Record<string, unknown>;
+ expect((await queue.getJob(result.id as number))?.data.__submitter).toBeUndefined();
+ await engine.executeRaw(`UPDATE minion_jobs SET data = data || '{"__submitter":"autopilot"}'::jsonb WHERE id = $1`, [result.id]);
+ const get = jobsOperations.find(op => op.name === 'get_job')!;
+ const host = { ...ctx(), remote: false, auth: undefined };
+ expect((await get.handler(host, { id: result.id }) as Record<string, unknown>).submitted_by)
+ .toEqual({ kind: 'mcp_client', id: 'client-a', principal_kind: 'oauth_client' });
+ }));
+
test('legacy preview is inert, CAS detects changes, exact IDs retain scheduling and dependencies', () => isolated(async () => {
const parent = await queue.add('maintenance', {});
const child = await queue.add('lint', { dir: root }, { parent_job_id: parent.id, delay: 5000 });
diff --git a/test/minions/job-insight.test.ts b/test/minions/job-insight.test.ts
new file mode 100644
index 0000000000..8434baf416
--- /dev/null
+++ b/test/minions/job-insight.test.ts
@@ -0,0 +1,320 @@
+/**
+ * #7241 / #7242: computed job fields (submitted_by, blocked_by, liveness, spend), the wait_job op and the
+ * terminal-event cursor, on PGLite. The owner fence cases pin the Captain's conditions: a foreign holder,
+ * submitter, parent or child is reported by kind only and never adds to a fenced caller's spend.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';
+import { describeJobs, setSubmitterLabelForTests } from '../../src/core/minions/job-insight.ts';
+import { listFinishedSince, parseTerminalCursor } from '../../src/core/minions/terminal-events.ts';
+import { assertNoUnreviewedJobs } from '../../src/core/minions/submission-authority.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+
+afterAll(async () => {
+ setSubmitterLabelForTests(null);
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ setSubmitterLabelForTests('cli:test');
+ await engine.executeRaw('DELETE FROM mcp_spend_reservations');
+ await engine.executeRaw('DELETE FROM minion_inbox');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');
+});
+
+function ctx(over: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine, config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false, remote: true, sourceId: 'default', ...over,
+ } as OperationContext;
+}
+const agentCtx = (clientId: string) => ctx({ auth: { clientId, scopes: ['agent'] } as OperationContext['auth'] });
+const localCtx = () => ctx({ remote: false });
+
+let seq = 0;
+async function add(name: string, data: Record<string, unknown> = {}, opts: Record<string, unknown> = {}) {
+ return queue.add(name, { n: ++seq, ...data }, { queue: 'default', ...opts }, { allowProtectedSubmit: true });
+}
+async function activate(id: number, lockDurationMs: number | null, untilOffsetMs: number) {
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'active', claim_generation = claim_generation + 1, lock_token = 'w:' || id::text, lock_duration_ms = $2::int,
+ lock_until = now() + ($3::double precision * interval '1 millisecond'), started_at = now(), attempts_started = 1
+ WHERE id = $1`, [id, lockDurationMs, untilOffsetMs]);
+}
+async function reservation(jobId: number, cents: number | null, status = 'settled', client = 'c') {
+ await engine.executeRaw(
+ `INSERT INTO mcp_spend_reservations (reservation_id, client_id, job_id, estimated_cents, actual_cents, model, provider, status, expires_at)
+ VALUES (gen_random_uuid(), $4, $1, 1, $2, 'm', 'p', $3, now() + interval '1 hour')`, [jobId, cents, status, client]);
+}
+async function holdSyncLock(source: string, holderJobId: number) {
+ const token = '00000000-0000-4000-8000-' + String(holderJobId).padStart(12, '0');
+ await engine.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, ttl_expires_at, acquisition_token)
+ VALUES ($1, 4242, 'host-example', now() + interval '10 minutes', $2::uuid)`, [`gbrain-sync:${source}`, token]);
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, submission_authority, data, max_attempts, max_stalled, lock_token, lock_until, started_at)
+ VALUES ('sync', 'gbrain-drain-lease', 'active', '{"version":1,"kind":"application"}'::jsonb, $1::jsonb, 1, 0, $2, now() + interval '10 minutes', now())`,
+ [JSON.stringify({ sourceId: source, drain_lease_beacon: { kind: 'job', id: String(holderJobId), version: 'test' } }), token]);
+}
+
+const get_job = operationsByName['get_job']!;
+const list_jobs = operationsByName['list_jobs']!;
+const wait_job = operationsByName['wait_job']!;
+
+describe('submitted_by', () => {
+ test('a local job names its submitter label; a child names its parent', async () => {
+ const parent = await add('noop');
+ const child = await add('noop', {}, { parent_job_id: parent.id });
+ const insight = await describeJobs(engine, [parent, child]);
+ expect(insight.get(parent.id)!.submitted_by).toEqual({ kind: 'local', via: 'cli:test' });
+ expect(insight.get(child.id)!.submitted_by).toEqual({ kind: 'parent_job', id: parent.id });
+ });
+
+ test('the label is not authority: a differently labelled submit coalesces on the same idempotency key', async () => {
+ const first = await add('noop', {}, { idempotency_key: 'k-label' });
+ setSubmitterLabelForTests('autopilot');
+ const second = await add('noop', {}, { idempotency_key: 'k-label' });
+ expect(second.id).toBe(first.id);
+ expect(first.data.__submitter).toBe('cli:test');
+ expect(first.submission_authority).toEqual({ version: 1, kind: 'application' });
+ await assertNoUnreviewedJobs(engine);
+ });
+
+ test('a re-submit carrying another process\'s label still coalesces on its params', async () => {
+ const first = await queue.add('noop', { target: 'source-a' }, { coalesce_params: true });
+ setSubmitterLabelForTests('autopilot');
+ const second = await queue.add('noop', { ...first.data }, { coalesce_params: true });
+ expect(second.id).toBe(first.id);
+ expect(second.coalesced).toBe(true);
+ });
+
+ test('a caller-supplied __submitter is dropped: the stored label is always the real local process', async () => {
+ const labelled = await add('noop', { __submitter: 'autopilot' });
+ expect(labelled.data.__submitter).toBe('cli:test');
+ setSubmitterLabelForTests(null);
+ const library = await add('noop', { __submitter: 'autopilot' });
+ expect(library.data.__submitter).toBeUndefined();
+ const insight = await describeJobs(engine, [labelled, library]);
+ expect(insight.get(labelled.id)!.submitted_by).toEqual({ kind: 'local', via: 'cli:test' });
+ expect(insight.get(library.id)!.submitted_by).toEqual({ kind: 'local' });
+ });
+});
+
+describe('blocked_by', () => {
+ test('waiting jobs report their queue position and the active jobs holding the queue', async () => {
+ const running = await add('long-runner');
+ await activate(running.id, 30_000, 30_000);
+ const a = await add('short');
+ const b = await add('short');
+ const c = await add('short', {}, { priority: -1 });
+ const insight = await describeJobs(engine, [a, b, c]);
+ const queueOf = (id: number) => insight.get(id)!.blocked_by!.find(r => r.kind === 'queue');
+ expect(queueOf(c.id)).toMatchObject({ kind: 'queue', queue: 'default', queue_position: 1, ahead: 0, active: 1 });
+ expect(queueOf(a.id)).toMatchObject({ queue_position: 2, ahead: 1 });
+ expect(queueOf(b.id)).toMatchObject({ queue_position: 3, ahead: 2, active_jobs: [{ id: running.id, name: 'long-runner' }] });
+ });
+
+ test('waiting-children, delayed and paused jobs say why', async () => {
+ const parent = await add('noop');
+ const kid = await add('noop', {}, { parent_job_id: parent.id });
+ const later = await add('noop', {}, { delay: 60_000 });
+ const [p, l] = await Promise.all([queue.getJob(parent.id), queue.getJob(later.id)]);
+ const insight = await describeJobs(engine, [p!, l!]);
+ expect(insight.get(parent.id)!.blocked_by).toEqual([{ kind: 'waiting_children', pending: 1, child_ids: [kid.id] }]);
+ expect(insight.get(later.id)!.blocked_by![0]).toMatchObject({ kind: 'delayed', reason: 'scheduled' });
+ expect(insight.get(later.id)!.blocked_by![0]).toHaveProperty('delay_until');
+ });
+
+ test('a waiting sync job names the job holding its source lock', async () => {
+ const holder = await add('sync', { sourceId: 'source-a' });
+ await activate(holder.id, 30_000, 30_000);
+ await holdSyncLock('source-a', holder.id);
+ const waiting = await add('sync', { sourceId: 'source-a' });
+ const lock = (await describeJobs(engine, [waiting])).get(waiting.id)!.blocked_by!.find(r => r.kind === 'lock');
+ expect(lock).toMatchObject({ kind: 'lock', held: true, lock: 'gbrain-sync:source-a', holder_job_id: holder.id, holder: { kind: 'job', pid: 4242 } });
+ });
+
+ test('running and finished jobs are not blocked', async () => {
+ const job = await add('noop');
+ await activate(job.id, 30_000, 30_000);
+ expect((await describeJobs(engine, [(await queue.getJob(job.id))!])).get(job.id)!.blocked_by).toBeNull();
+ });
+});
+
+describe('liveness', () => {
+ test('heartbeat age comes from the lease, and an expired lock reads stalled', async () => {
+ const live = await add('noop');
+ const dead = await add('noop');
+ await activate(live.id, 60_000, 50_000);
+ await activate(dead.id, 60_000, -5_000);
+ const rows = await Promise.all([queue.getJob(live.id), queue.getJob(dead.id)]);
+ const insight = await describeJobs(engine, rows.map(r => r!));
+ const l = insight.get(live.id)!, d = insight.get(dead.id)!;
+ expect(l).toMatchObject({ stalled: false, heartbeat_basis: 'lease' });
+ expect(l.heartbeat_age_ms!).toBeGreaterThanOrEqual(9_000);
+ expect(l.heartbeat_age_ms!).toBeLessThan(15_000);
+ expect(l.lock_expires_in_ms!).toBeGreaterThan(40_000);
+ expect(d.stalled).toBe(true);
+ expect(d.lock_expires_in_ms!).toBeLessThan(0);
+ });
+});
+
+describe('spend', () => {
+ test('settled reservations price the job and its children; none means unpriced, not zero', async () => {
+ const parent = await add('noop');
+ const child = await add('noop', {}, { parent_job_id: parent.id });
+ const bare = await add('noop');
+ await reservation(parent.id, 10);
+ await reservation(child.id, 2.5);
+ await reservation(child.id, null, 'pending');
+ const insight = await describeJobs(engine, [parent, bare]);
+ expect(insight.get(parent.id)!.spend).toMatchObject({ cost_usd: 0.125, cost_basis: 'settled_reservations', includes_children: true, unsettled_reservations: 1 });
+ expect(insight.get(bare.id)!.spend).toMatchObject({ cost_usd: null, cost_basis: 'unpriced', unsettled_reservations: 0 });
+ });
+});
+
+describe('owner fence (remote agent callers)', () => {
+ test('a foreign lock holder is reported as held with no job id; an owned holder is named', async () => {
+ const foreignHolder = await add('sync', { sourceId: 'source-a', __owner_client_id: 'agent-b' });
+ await activate(foreignHolder.id, 30_000, 30_000);
+ await holdSyncLock('source-a', foreignHolder.id);
+ const mine = await add('sync', { sourceId: 'source-a', __owner_client_id: 'agent-a' });
+
+ const seen = await get_job.handler(agentCtx('agent-a'), { id: mine.id }) as { blocked_by: Array<Record<string, unknown>> };
+ expect(seen.blocked_by.find(r => r.kind === 'lock')).toEqual({ kind: 'lock', held: true });
+ const queueRow = seen.blocked_by.find(r => r.kind === 'queue')!;
+ expect(queueRow.active).toBe(1);
+ expect(queueRow.active_jobs).toEqual([]);
+
+ const local = await get_job.handler(localCtx(), { id: mine.id }) as { blocked_by: Array<Record<string, unknown>> };
+ expect(local.blocked_by.find(r => r.kind === 'lock')).toMatchObject({ holder_job_id: foreignHolder.id });
+
+ await engine.executeRaw(`UPDATE minion_jobs SET data = data || '{"__owner_client_id":"agent-a"}'::jsonb WHERE id = $1`, [foreignHolder.id]);
+ const owned = await get_job.handler(agentCtx('agent-a'), { id: mine.id }) as { blocked_by: Array<Record<string, unknown>> };
+ expect(owned.blocked_by.find(r => r.kind === 'lock')).toEqual({ kind: 'lock', held: true, lock: 'gbrain-sync:source-a', holder_job_id: foreignHolder.id });
+ });
+
+ test('a foreign parent is redacted to its kind, and foreign children never reach a fenced spend rollup', async () => {
+ const foreignParent = await add('noop', { __owner_client_id: 'agent-b' });
+ const mineUnderForeign = await add('noop', { __owner_client_id: 'agent-a' }, { parent_job_id: foreignParent.id });
+ const seenChild = await get_job.handler(agentCtx('agent-a'), { id: mineUnderForeign.id }) as Record<string, unknown>;
+ expect(seenChild.submitted_by).toEqual({ kind: 'parent_job' });
+
+ const myParent = await add('noop', { __owner_client_id: 'agent-a' });
+ const foreignChild = await add('noop', { __owner_client_id: 'agent-b' }, { parent_job_id: myParent.id });
+ const myChild = await add('noop', { __owner_client_id: 'agent-a' }, { parent_job_id: myParent.id });
+ await reservation(myParent.id, 1);
+ await reservation(foreignChild.id, 40);
+ await reservation(myChild.id, 2);
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now(), tokens_input = 700, tokens_output = 70 WHERE id = $1`, [foreignChild.id]);
+ await engine.executeRaw(`UPDATE minion_jobs SET tokens_input = 1000, tokens_output = 100 WHERE id = $1`, [myParent.id]);
+
+ const fenced = await get_job.handler(agentCtx('agent-a'), { id: myParent.id }) as Record<string, any>;
+ expect(fenced.spend).toMatchObject({ cost_usd: 0.03, tokens_input: 300, tokens_output: 30, excludes_foreign_children: true });
+ expect(fenced.tokens_input).toBe(300);
+ const local = await get_job.handler(localCtx(), { id: myParent.id }) as Record<string, any>;
+ expect(local.spend).toMatchObject({ cost_usd: 0.43, tokens_input: 1000 });
+ expect(local.spend.excludes_foreign_children).toBeUndefined();
+ });
+
+ test('a foreign MCP submitter is never named to a fenced caller', async () => {
+ const job = await add('noop', { __owner_client_id: 'agent-a' });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET submission_authority = $2::jsonb WHERE id = $1`,
+ [job.id, JSON.stringify({ version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: 'agent-b' },
+ grant: { scopes: ['agent'], sourceId: 'default', sourceCreatedAt: new Date().toISOString(), allowedTools: ['get_page'], allowedSlugPrefixes: [] },
+ payloadHash: 'a'.repeat(64) })]);
+ const fenced = await get_job.handler(agentCtx('agent-a'), { id: job.id }) as Record<string, unknown>;
+ expect(fenced.submitted_by).toEqual({ kind: 'mcp_client' });
+ const local = await get_job.handler(localCtx(), { id: job.id }) as Record<string, unknown>;
+ expect(local.submitted_by).toEqual({ kind: 'mcp_client', id: 'agent-b', principal_kind: 'oauth_client' });
+ });
+
+ test('list_jobs carries the same fields and projects them', async () => {
+ const job = await add('noop', { __owner_client_id: 'agent-a' });
+ const rows = await list_jobs.handler(agentCtx('agent-a'), { fields: ['id', 'blocked_by', 'spend'] }) as Array<Record<string, any>>;
+ expect(rows).toHaveLength(1);
+ expect(Object.keys(rows[0]).sort()).toEqual(['blocked_by', 'id', 'spend']);
+ expect(rows[0].id).toBe(job.id);
+ expect(rows[0].blocked_by[0]).toMatchObject({ kind: 'queue', queue_position: 1 });
+ });
+});
+
+describe('wait_job', () => {
+ test('a foreign job id gets exactly the get_job refusal, at once', async () => {
+ const theirs = await add('noop', { __owner_client_id: 'agent-b' });
+ const errOf = async (op: typeof get_job, args: Record<string, unknown>) => {
+ try { await op.handler(agentCtx('agent-a'), args); return null; } catch (e) { return e as Error & Record<string, unknown>; }
+ };
+ const started = Date.now();
+ const waitErr = await errOf(wait_job, { id: theirs.id, timeout_s: 30 });
+ const elapsed = Date.now() - started;
+ const getErr = await errOf(get_job, { id: theirs.id });
+ expect(waitErr).not.toBeNull();
+ expect(elapsed).toBeLessThan(1_000);
+ expect(String(waitErr)).toBe(String(getErr));
+ expect(JSON.stringify(waitErr)).toBe(JSON.stringify(getErr));
+ expect({ code: waitErr!.code, why: waitErr!.why, fix: waitErr!.fix }).toEqual({ code: getErr!.code, why: getErr!.why, fix: getErr!.fix });
+ const missing = await errOf(wait_job, { id: 987_654 });
+ expect(String(missing).replace('987654', 'N')).toBe(String(waitErr).replace(String(theirs.id), 'N'));
+ });
+
+ test('returns terminal: true once the job finishes, and terminal: false at the timeout', async () => {
+ const job = await add('noop', { __owner_client_id: 'agent-a' });
+ const pending = await wait_job.handler(agentCtx('agent-a'), { id: job.id, timeout_s: 1 }) as Record<string, unknown>;
+ expect(pending).toMatchObject({ id: job.id, status: 'waiting', terminal: false });
+ expect(pending.blocked_by).toBeDefined();
+ setTimeout(() => {
+ void engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1`, [job.id]);
+ }, 300);
+ const done = await wait_job.handler(agentCtx('agent-a'), { id: job.id, timeout_s: 10 }) as Record<string, unknown>;
+ expect(done).toMatchObject({ id: job.id, status: 'completed', terminal: true });
+ });
+
+ test('the server caps one call at 55 s and the op is read-only and agent-callable', () => {
+ expect(wait_job).toMatchObject({ scope: 'admin', agentCallable: true, mutating: false });
+ expect(wait_job.description).toContain('55 s');
+ });
+});
+
+describe('terminal event cursor', () => {
+ test('pages every finished job once, oldest first, and respects the owner fence', async () => {
+ const ids: number[] = [];
+ for (let i = 0; i < 5; i++) {
+ const j = await add('noop', i % 2 === 0 ? { __owner_client_id: 'agent-a' } : {});
+ ids.push(j.id);
+ }
+ await add('noop');
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'completed', finished_at = '2026-10-21T00:00:00.000001Z'::timestamptz WHERE id = ANY($1::int[])`, [ids.slice(0, 3)]);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'failed', finished_at = '2026-10-21T00:00:01Z'::timestamptz WHERE id = ANY($1::int[])`, [ids.slice(3)]);
+ const first = await listFinishedSince(engine, '2026-10-20T00:00:00Z', { limit: 2 });
+ expect(first.jobs.map(j => j.id)).toEqual(ids.slice(0, 2));
+ const second = await listFinishedSince(engine, first.next_cursor, { limit: 2 });
+ expect(second.jobs.map(j => j.id)).toEqual(ids.slice(2, 4));
+ const third = await listFinishedSince(engine, second.next_cursor, { limit: 2 });
+ expect(third.jobs.map(j => j.id)).toEqual([ids[4]]);
+ const empty = await listFinishedSince(engine, third.next_cursor, { limit: 2 });
+ expect(empty.jobs).toEqual([]);
+ expect(empty.next_cursor).toBe(third.next_cursor);
+
+ const fenced = await list_jobs.handler(agentCtx('agent-a'), { finished_since: '2026-10-20T00:00:00Z', fields: ['id', 'status'] }) as { jobs: Array<{ id: number }>; next_cursor: string };
+ expect(fenced.jobs.map(j => j.id)).toEqual([ids[0], ids[2], ids[4]]);
+ expect(() => parseTerminalCursor('yesterday')).toThrow(/ISO time/);
+ await expect(list_jobs.handler(agentCtx('agent-a'), { finished_since: 'nope' })).rejects.toThrow(/finished_since/);
+ });
+});
diff --git a/test/minions/terminal-hook.test.ts b/test/minions/terminal-hook.test.ts
new file mode 100644
index 0000000000..f185a54795
--- /dev/null
+++ b/test/minions/terminal-hook.test.ts
@@ -0,0 +1,125 @@
+/**
+ * #7242 terminal hook: an argv from local file-plane config, spawned without a shell, given the job in fixed
+ * env vars and as JSON on stdin, killed at its timeout, its failures logged and never retried, never changing
+ * the job. The worker runs it once per job it ran that reached a terminal status.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, readFileSync, existsSync, readdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+import { UnrecoverableError, type MinionJob } from '../../src/core/minions/types.ts';
+import { parseTerminalHook, resolveTerminalHook, runTerminalHook, terminalHookNotifier } from '../../src/core/minions/terminal-hook.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+function hookScript(body: string): { dir: string; argv: string[] } {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-terminal-hook-'));
+ const script = join(dir, 'hook.sh');
+ writeFileSync(script, `#!/bin/sh\n${body}\n`, { mode: 0o755 });
+ return { dir, argv: ['/bin/sh', script, dir] };
+}
+const RECORD = 'cat > "$1/$GBRAIN_JOB_ID.stdin.json"; printf "%s|%s|%s|%s" "$GBRAIN_JOB_ID" "$GBRAIN_JOB_NAME" "$GBRAIN_JOB_QUEUE" "$GBRAIN_JOB_STATUS" > "$1/$GBRAIN_JOB_ID.env"';
+
+function fakeJob(over: Partial<MinionJob>): MinionJob {
+ return { id: 7, name: 'noop', queue: 'default', status: 'completed', attempts_made: 1, parent_job_id: null,
+ created_at: new Date('2026-10-21T00:00:00Z'), started_at: null, finished_at: new Date('2026-10-21T00:00:01Z'),
+ error_text: null, data: { prompt: 'secret-example' }, result: { value: 'r' }, ...over } as MinionJob;
+}
+
+async function quiet<T>(fn: () => Promise<T>): Promise<{ value: T; warnings: string[] }> {
+ const orig = console.warn;
+ const warnings: string[] = [];
+ console.warn = (...a: unknown[]) => { warnings.push(a.map(String).join(' ')); };
+ try { return { value: await fn(), warnings }; } finally { console.warn = orig; }
+}
+
+describe('config', () => {
+ test('only an argv array with an absolute command is accepted', () => {
+ expect(parseTerminalHook('["/usr/local/bin/notify-job","--quiet"]')).toEqual({ argv: ['/usr/local/bin/notify-job', '--quiet'], timeout_ms: 10_000 });
+ expect(parseTerminalHook({ argv: ['/bin/true'], timeout_ms: 500 })).toEqual({ argv: ['/bin/true'], timeout_ms: 500 });
+ expect(() => parseTerminalHook('"notify-job $GBRAIN_JOB_ID"')).toThrow(/JSON array/);
+ expect(() => parseTerminalHook('notify-job')).toThrow();
+ expect(() => parseTerminalHook(['notify-job'])).toThrow(/absolute path/);
+ expect(() => parseTerminalHook([])).toThrow(/JSON array/);
+ expect(() => parseTerminalHook({ argv: ['/bin/true'], timeout_ms: 0 })).toThrow(/timeout_ms/);
+ });
+
+ test('off by default; read from the file-plane config object only', async () => {
+ expect(resolveTerminalHook(null)).toBeNull();
+ expect(resolveTerminalHook({ engine: 'pglite' } as never)).toBeNull();
+ expect(resolveTerminalHook({ engine: 'pglite', minions: { terminal_hook: ['/bin/true'] } } as never)).toEqual({ argv: ['/bin/true'], timeout_ms: 10_000 });
+ const { value, warnings } = await quiet(async () => resolveTerminalHook({ engine: 'pglite', minions: { terminal_hook: 'sh -c x' } } as never));
+ expect(value).toBeNull();
+ expect(warnings.join('\n')).toContain('terminal hook disabled');
+ });
+});
+
+describe('runTerminalHook', () => {
+ test('passes the job in fixed env vars and on stdin, never through a shell string', async () => {
+ const { dir, argv } = hookScript(RECORD);
+ const name = 'noop$(touch pwned-example)';
+ const outcome = await runTerminalHook({ argv, timeout_ms: 5_000 }, fakeJob({ id: 41, name, status: 'failed', error_text: 'boom-example' }));
+ expect(outcome).toBe('ok');
+ expect(readFileSync(join(dir, '41.env'), 'utf8')).toBe(`41|${name}|default|failed`);
+ const payload = JSON.parse(readFileSync(join(dir, '41.stdin.json'), 'utf8'));
+ expect(Object.keys(payload).sort()).toEqual(['attempts_made', 'created_at', 'error_text', 'finished_at', 'id', 'name', 'parent_job_id', 'queue', 'started_at', 'status']);
+ expect(payload).toMatchObject({ id: 41, status: 'failed', error_text: 'boom-example', finished_at: '2026-10-21T00:00:01.000Z' });
+ expect(JSON.stringify(payload)).not.toContain('secret-example');
+ expect(existsSync(join(dir, 'pwned-example'))).toBe(false);
+ expect(existsSync('pwned-example')).toBe(false);
+ });
+
+ test('a hook past its timeout is killed and logged; a nonzero exit is logged; neither throws', async () => {
+ const slow = hookScript('sleep 5');
+ const started = Date.now();
+ const t = await quiet(() => runTerminalHook({ argv: slow.argv, timeout_ms: 200 }, fakeJob({})));
+ expect(t.value).toBe('timeout');
+ expect(Date.now() - started).toBeLessThan(3_000);
+ expect(t.warnings.join('\n')).toContain('timeout');
+ const failing = hookScript('echo nope-example >&2; exit 3');
+ const f = await quiet(() => runTerminalHook({ argv: failing.argv, timeout_ms: 5_000 }, fakeJob({})));
+ expect(f.value).toBe('exit_nonzero');
+ expect(f.warnings.join('\n')).toContain('exit 3');
+ expect(f.warnings.join('\n')).toContain('nope-example');
+ const missing = await quiet(() => runTerminalHook({ argv: ['/nonexistent/hook-example'], timeout_ms: 5_000 }, fakeJob({})));
+ expect(missing.value).toBe('spawn_error');
+ });
+});
+
+describe('worker wiring', () => {
+ test('the worker runs the hook once per terminal job it ran, and never for a job going back to the queue', async () => {
+ const { dir, argv } = hookScript(RECORD);
+ const queue = new MinionQueue(engine);
+ const ok = await queue.add('hook-ok', { n: 1 });
+ const dead = await queue.add('hook-dead', { n: 2 });
+ const retry = await queue.add('hook-retry', { n: 3 }, { max_attempts: 3, backoff_delay: 60_000, backoff_type: 'fixed' });
+ const notifier = terminalHookNotifier(engine, { argv, timeout_ms: 5_000 });
+ const worker = new MinionWorker(engine, { pollInterval: 50, onJobSettled: notifier.onJobSettled });
+ worker.register('hook-ok', async () => ({ fine: true }));
+ worker.register('hook-dead', async () => { throw new UnrecoverableError('broken-example'); });
+ worker.register('hook-retry', async () => { throw new Error('transient-example'); });
+ const running = worker.start();
+ for (let i = 0; i < 200; i++) {
+ const rows = await Promise.all([ok, dead, retry].map(j => queue.getJob(j.id)));
+ if (rows[0]?.status === 'completed' && rows[1]?.status === 'dead' && rows[2]?.status === 'delayed') break;
+ await new Promise(r => setTimeout(r, 50));
+ }
+ worker.stop();
+ await running;
+ await notifier.drain();
+ expect(readFileSync(join(dir, `${ok.id}.env`, ), 'utf8')).toBe(`${ok.id}|hook-ok|default|completed`);
+ expect(readFileSync(join(dir, `${dead.id}.env`), 'utf8')).toBe(`${dead.id}|hook-dead|default|dead`);
+ expect(existsSync(join(dir, `${retry.id}.env`))).toBe(false);
+ expect(readdirSync(dir).filter(f => f.endsWith('.env')).length).toBe(2);
+ expect((await queue.getJob(ok.id))!.status).toBe('completed');
+ });
+});
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index c6f5c2b0bd..b450e89806 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -189,6 +189,7 @@ const LEDGER: Record<string, string> = {
rate_answer: 'test/feedback-store.test.ts',
// Covered by the C1 lifecycle behavioral suite (moved out of UNCOVERED).
get_job_progress: 'test/jobs-lifecycle-ops.test.ts',
+ wait_job: 'test/minions/job-insight.test.ts',
pause_job: 'test/jobs-lifecycle-ops.test.ts',
resume_job: 'test/jobs-lifecycle-ops.test.ts',
replay_job: 'test/jobs-lifecycle-ops.test.ts',
diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.ts
index 9c25d0093c..aece8b69f9 100644
--- a/test/remote-privacy-sweep.test.ts
+++ b/test/remote-privacy-sweep.test.ts
@@ -416,6 +416,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {
sources_remove: 'error',
submit_job: 'error',
get_job: 'error',
+ wait_job: 'error',
cancel_job: 'error',
retry_job: 'error',
get_job_progress: 'error',
diff --git a/test/request-tools.test.ts b/test/request-tools.test.ts
index 2c396ab43f..70ab56da09 100644
--- a/test/request-tools.test.ts
+++ b/test/request-tools.test.ts
@@ -158,7 +158,7 @@ describe('request_tools catalog (no args)', () => {
// catalog includes them alongside the submit_agent/get_agent_job pair.
expect(names).toEqual([
'cancel_job', 'get_agent_job', 'get_job', 'get_job_progress',
- 'list_jobs', 'request_tools', 'submit_agent',
+ 'list_jobs', 'request_tools', 'submit_agent', 'wait_job',
]);
});
diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.ts
index a5a76eaf1c..d9c47563ba 100644
--- a/test/truthful-catalog.e2e-lite.test.ts
+++ b/test/truthful-catalog.e2e-lite.test.ts
@@ -683,7 +683,7 @@ describe('E5 truthful catalog — OAuth-path cells (serve-http seams over dispat
// row includes them alongside the submit_agent/get_agent_job pair.
expect(sortedArray(listed)).toEqual([
'cancel_job', 'get_agent_job', 'get_job', 'get_job_progress',
- 'list_jobs', 'request_tools', 'submit_agent',
+ 'list_jobs', 'request_tools', 'submit_agent', 'wait_job',
]);
// Probes: garbage args die at validation (proving the scope layer let