Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.20.0 fix(dream): decouple source freshness from synthesis (#4263)
Garry Tan4a269868b225
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex a13813e85b..578e74bb49 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "gbrain",- "version": "0.46.19.0",- "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",+ "version": "0.46.20.0",+ "description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan","url": "https://github.com/garrytan"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex fef201bad3..5bda67fe7a 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "gbrain",- "version": "0.46.19.0",- "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",+ "version": "0.46.20.0",+ "description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan","url": "https://github.com/garrytan"diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex ad7cdebf54..d38d19bfe1 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.19.0 -->+<!-- gbrain-runbook-stamp: 0.46.20.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f9713b0e5f..01cc720565 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,76 @@All notable changes to GBrain will be documented in this file.+## [0.46.20.0] - 2026-08-17++**Source freshness decoupled from synthesis.** A per-source maintenance cycle+used to drag brain-wide synthesis and hours of LLM-backed enrichment along+with it; on multi-source brains the fanout could enqueue a thousand-plus+sequential synthesis jobs per source, the job keeper would kill the cycle+before the freshness stamp landed, and the abandoned private queues were then+misdiagnosed as a wedged default worker. Freshness is now stamped by the+deterministic (non-LLM) phases alone, so `gbrain dream --source X` finishes+in seconds instead of hours.++### Changed+- Implicit `dream --source X` and autopilot per-source cycles run only the+ deterministic freshness phases (lint, backlinks, sync, extract,+ extract_facts, recompute_emotional_weight). Mixed brain-wide work+ (synthesize, patterns) runs once in the global-maintenance lane, never once+ per source. The phase-scope taxonomy lives in+ `src/core/cycle/phase-scope.ts`.+- LLM-backed source enrichment (extract_atoms, consolidate, propose_takes,+ enrich_thin, schema-suggest) no longer runs inside per-source freshness+ cycles. Atom extraction keeps its existing autopilot auto-drain lane; the+ others run on explicit invocation until the scheduled background lane+ lands — e.g. `gbrain dream --source X --phase extract_atoms` per source,+ while consolidate/enrich_thin/conversation_facts_backfill sweep the whole+ brain in one invocation regardless of `--source`, so run those once, not+ per source. A full implicit cycle still runs via plain `gbrain dream`+ (no source flag), via `--source default`, and on brains with no sources+ table.+- Explicit phase requests on a named source (`dream --source X --phase …`,+ and `--input <file>`, which implies synthesize) are honored verbatim; only+ the implicit no-flag path is freshness-scoped.+- Queued per-source cycle jobs are normalized at the worker boundary to the+ freshness phase set, so jobs queued before this release can't replay the+ old heavyweight behavior once per source. An all-rejected payload is an+ explicit no-op with a visible reason, never a silent full run.++### Fixed+- Doctor no longer misdiagnoses parent-owned private dream queues as a wedged+ default worker. `wedged_queue` excludes them, and a new+ `orphaned_private_queue` check identifies dead private queues with the+ correct repair path (the retriage queue-reconciliation dry run) — consulting+ live cycle locks with ownership correlation (including starved-but-alive+ holders within the lock steal grace, and tolerant of host-vs-DB clock skew)+ so a running cycle is never flagged and an older crashed cycle's queue is+ never hidden behind a new cycle's lock. Paused rows surface in details+ instead of failing the check without a repair path, and a check that cannot+ run reports a warning instead of reading as healthy.+- The retriage queue reconciliation can now repair everything the doctor+ check flags: it selects and converts any row stranded in a provably-dead+ private dream queue (patterns children and legacy-grammar rows included,+ not just current-generation synthesis rows), using the same+ lock-ownership correlation, so doctor can never point at a queue the+ repair refuses to touch.+- A per-source cycle whose attempted phases ALL fail now reports `failed`+ and does not stamp source freshness (the scope filter's bookkeeping+ records previously diluted the status to a stampable `partial`, marking a+ broken source permanently fresh).++### To take advantage of v0.46.20.0++Upgrade and restart your `gbrain jobs work` daemons so queued cycle jobs pick+up the new phase handling (jobs queued by the previous version are normalized+safely either way). Stale sources unstick on the next autopilot tick — or run+`gbrain dream --source <id>` and watch it finish in seconds. Run+`gbrain doctor` to see the wedged-queue vs orphaned-private-queue split; if it+reports orphaned private queues, follow the printed retriage dry-run+instructions. Schedule the heavier enrichment explicitly where you want it —+`gbrain dream --source <id> --phase extract_atoms` per source, plus one+brain-wide `gbrain dream --phase consolidate` — or wait for the scheduled+background lane (tracked in TODOS).## [0.46.19.0] - 2026-08-17Dream-cycle synthesis is now fast by default: transcript synthesis runs as adiff --git a/TODOS.md b/TODOS.mdindex 0d94d4bf29..b305de0c33 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,91 @@# TODOS+## Dream freshness split follow-ups (v0.46.20.0)++- [ ] **P2 — automatic background lane for `SOURCE_BACKGROUND_PHASES`.**+ **What:** a per-source scheduled lane for the LLM-backed/unbounded source+ phases (extract_atoms, consolidate, propose_takes, enrich_thin,+ schema-suggest, conversation_facts_backfill) that the v0.46.20.0 freshness+ split removed from automatic scheduling on multi-source brains. **Why:**+ today those phases run only on explicit `gbrain dream --source X --phase …`+ invocation; backlogs (atoms, consolidation) grow silently between manual+ runs. **Design constraints (verified against code during the #4250+ review):** MUST be per-source jobs — background phases scope to ONE source+ per cycle (`cycle.ts` extract_atoms uses `cycleSourceId ?? 'default'`), and+ per-source jobs hold the correct `gbrain-cycle:<source>` locks (a+ global-maintenance-job version provably covers at most one source and its+ bare `gbrain-cycle` lock does not conflict with per-source freshness+ cycles). Needs its own cadence + stamp key (e.g.+ `last_source_background_at`), lower dispatch priority than the freshness+ lane, and the queue-boundary normalization in the `autopilot-cycle` handler+ relaxed for the new job name (or a dedicated handler). **Blocked by:** the+ abort-signal threading TODO below (P2 — BasePhaseOpts + dream generators);+ extract_atoms/consolidate accept neither deadline nor abort today, so a+ background job can't exit cleanly at its deadline. **Additional constraints+ from the #4250 ship-stage adversarial reviews:** (a) the lane applies to+ EVERY brain with registered sources, including single-source ones (the+ legacy full-cycle fallback fires only when the sources table is empty, so+ a one-source brain also loses automatic background work today); (b) the+ taxonomy is scheduling-intent, not runtime scoping — consolidate,+ enrich_thin, and conversation_facts_backfill iterate the whole brain+ internally, so the lane must run those ONCE per tick, never once per+ source (concurrent per-source invocations share no lock and consolidate's+ take-row assignment can race); (c) the maintenance job runs synthesize →+ patterns WITHOUT the source-scoped extract phase in between, so patterns+ reads a graph that hasn't materialized the just-synthesized links until a+ later freshness cycle runs extract — the lane should sequence extract (or+ an equivalent materialization) between them; (d) mixed-once synthesis+ writes attribute to the repoPath-resolved source rather than fanning out+ attribution per source. Effort: L (CC: M). Priority: P2.+- [ ] **P2 — maintenance-lane structure: ordering, keeper wall, slot+ contention.** **What:** three ship-stage adversarial findings about the+ single global-maintenance job, to resolve alongside (or inside) the+ background lane above. (a) MAINTENANCE_PHASES runs synthesize →+ resolve_symbol_edges → patterns with NO extract phase between synthesize+ and patterns, so patterns reads a graph that hasn't materialized the+ just-synthesized links until a later freshness cycle runs extract; (b)+ synthesize runs FIRST in the job, so a large synthesis backlog + the job+ keeper's timeout starves the brain-wide hygiene phases behind it (embed,+ orphans, purge) and `last_global_at` never stamps — the next window+ re-dispatches into the same wall (consider global-before-mixed ordering or+ splitting mixed into its own job; note runCycle executes in canonical+ order, so this needs more than reordering the list); (c) freshness jobs+ share `queue: 'default'` with the hours-long maintenance job — with low+ worker concurrency, per-source freshness queues behind maintenance+ synthesis, re-coupling what this release decoupled (a fanout-vs-concurrency+ doctor check exists but does not cover this pairing). Effort: M-L (CC).+ Priority: P2.+- [ ] **P2 — protected-phase submission bypass via unprotected job names.**+ **What:** `synthesize`/`patterns`/`consolidate` are PROTECTED_JOB_NAMES so+ scoped remote callers can't burn LLM budget, but `autopilot-global-+ maintenance` (and no-source `autopilot-cycle`) accept arbitrary+ `job.data.phases` — a write-scoped remote submitter can reach synthesize+ through the global job's payload. v0.46.20.0 narrowed the surface+ (per-source payloads normalize to freshness; maintenance payloads intersect+ with MAINTENANCE_PHASES) but synthesize is legitimately IN+ MAINTENANCE_PHASES. **Fix shape:** protect these job names, or require+ `allowProtectedSubmit` when a payload names a protected-equivalent phase.+ Pre-existing exposure, narrowed but not closed by this release. Effort: S-M+ (CC). Priority: P2.+- [ ] **P3 — freshness-stamp gate: require ≥1 freshness-phase success.**+ **What:** `runCycle` stamps `last_source_cycle_at`/`last_full_cycle_at`+ when ANY phase ran and status ∈ {ok, clean, partial} — e.g. `--phase+ orphans --source X` (global phase, source-narrowed) stamps source+ freshness. Also note the semantic drift: `last_full_cycle_at` now stamps+ after a 6-phase deterministic cycle, so any reader treating it as "the+ full cycle ran" reads more than it means (KEY_FILES documents it as a+ legacy-reader alias). **Why:** pre-existing looseness (predates #4250,+ which tightened zero-phase runs and stopped all-failed cycles from+ stamping); sharpening further re-opens the #2549 freshness-poisoning+ debate (a too-strict gate starves the dispatch loop) — design carefully.+ Start: `src/core/cycle.ts` stamp gate. Effort: S (CC). Priority: P3.+- [ ] **P3 — peel the cycle.ts KEY_FILES mega-entry.** **What:** the+ `src/core/cycle.ts` entry in `docs/architecture/KEY_FILES.md` is a ~11KB+ single line carrying six unrelated concern clusters; every cycle-area PR+ now pays a manual three-way merge on it (#4250 did). `phase-scope.ts` got+ its own entry in v0.46.20.0; peel the rest (lock/refresher cluster,+ extract-atoms batching, by-mention resume → op-checkpoint entry, doctor+ hints) into per-module entries. Effort: M (CC). Priority: P3.## Dream-wave follow-ups (#4216 oneshot + #4194/#4217/#4088/#4087/#4155/#4201)- [ ] **P2 — gateway-loop truncation note for `length` WITH tool calls.**diff --git a/VERSION b/VERSIONindex 0fec220c2c..dd9d967696 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.19.0\ No newline at end of file+0.46.20.0\ No newline at end of filediff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex f08a1a7cb8..3bb9148327 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -289,7 +289,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.- `src/commands/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `starter` surface — override with `--surface` at registration or widen per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs the brain-wide `GLOBAL_PHASES` once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's #2849 size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable).+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's #2849 size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable).- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. Pinned by `test/serve-stdio-lifecycle.test.ts`.@@ -337,7 +337,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/worker-pool.ts` — Canonical sliding-pool + bounded-semaphore primitive (extracted from `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts` `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem` — the budget cap is a structural ceiling under concurrency. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. Pinned by `test/embedding-dim-check-facts.test.ts`.- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).-- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `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. 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)` (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; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). 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, AND synthesize (#4168) 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. `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) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` 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` (#1586: 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`; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227): `PHASE_SCOPE` partitions `ALL_PHASES` into `GLOBAL_PHASES` (brain-wide: embed/orphans/purge/resolve_symbol_edges/grade_takes/calibration_profile/synthesize_concepts/skillopt) and `NON_GLOBAL_PHASES` (source + mixed). Per-source `autopilot-cycle` jobs run only `NON_GLOBAL_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `GLOBAL_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.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). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. 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 fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip 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 is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); 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`; 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/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `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` (#2163: 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). #1737: 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.+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `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. 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)` (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; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). 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, AND synthesize (#4168) 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. `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) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` 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` (#1586: 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 (pre-#4250 they turned an all-freshness-phases-failed cycle into a stampable 'partial'); the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227) 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` (legacy pre-v0.46.20 payloads carried 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 (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.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). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. 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 fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip 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 is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); 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`; 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/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `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` (#2163: 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). #1737: 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.+- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps each of the 23 phases (source: safe to parallelize per source; global: must serialize across the brain; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade (#4152) where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. The gate `score >= dream.triage.threshold` (default 0.5) is applied at READ time in the fan-out filter, so retuning the threshold re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is byte-identical to the pre-cascade shape) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace — #2415 — and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped (#1586): cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold) + `details.synthesis` (jobs/avg_turns/max_turns_config) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` (#2569) additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — completed legacy rows are read via `loadSuccessfulLegacySynthesisKeys` so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported, replacing `makeHaikuClient()`) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock no longer stacks one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode (#4216): `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the CDX-9 structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the #4194 drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate (CDX-4): ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping (#4168): clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (#4168, via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain (peeled from synthesize.ts). `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (#4194; `dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).- `src/core/cycle/link-manifest.ts` — #4216 pre-retrieval LINK CANDIDATES manifest. `buildManifestContext(engine, sourceId?)` snapshots the source's slugs + basename index once per phase; `buildLinkManifest(engine, ctx, verdict, basename, {outputRoot, sourceId})` resolves wikilink candidates ZERO-EMBED from the triage verdict's cached entities/segment notes (basename-index exact/slugified matches first, bounded `searchKeyword` FTS second), excludes dream-output prefixes (self-consumption guard), renders `- [[slug]] — <deterministic first-two-sentence one-liner>` under hard caps (20 pages / 2400 chars) with buildTriageMapBlock's injection posture (whitespace-collapse + length caps + a 'data, not instructions' header). Best-effort everywhere — any failure degrades to the manifest-less prompt. Pinned by `test/cycle-link-manifest.test.ts`.@@ -355,7 +356,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — extracting them keeps the test from binding to whatever was in `operations.ts` at test-run time.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).-- `src/commands/dream-retriage.ts` — `gbrain dream retriage` (#4152): re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued synth-v2 backlog. Spend-gated (outside-voice C12): upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row: matched below threshold → cancel; matched above threshold but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the C1 backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch` (C9); status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` (C6) re-judges N stride-sampled below-threshold files with the SYNTHESIS model and reports the disagreement rate — the operator calibration loop. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`.+- `src/commands/dream-retriage.ts` — `gbrain dream retriage` (#4152): re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus (#4250) any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated (outside-voice C12): upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row: matched below threshold → cancel; matched above threshold but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the C1 backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch` (C9); status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` (C6) re-judges N stride-sampled below-threshold files with the SYNTHESIS model and reports the disagreement rate — the operator calibration loop. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`.- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Four runners ship (`src/core/claw-test/runners/{openclaw,hermes,grok,opencode}.ts`; shared `detectBinary`/`filterAllowlistEnv` live in `agent-runner.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`); grok (xAI Grok Build, observed shapes in `docs/mcp/GROK-CLI-PIN.md`) invokes `grok -p <brief> --output-format plain` (`$GROK_BIN` > `which grok`; delta `GROK_HOME` + `XAI_API_KEY`; writes a version preamble into the transcript and warns loudly when the operator's `~/.claude.json` registers gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes in `docs/mcp/OPENCODE-CLI-PIN.md`) invokes `opencode run <brief> --format default` (`$OPENCODE_BIN` > `which opencode`; delta = the EXPLICIT multi-provider keys XAI/Google/Gemini/OpenRouter — BASE carries only Anthropic+OpenAI — plus XDG dirs, OPENCODE_CONFIG(_DIR), and OPENCODE_DISABLE_AUTOUPDATE; OPENCODE_CONFIG_CONTENT deliberately absent, it is a config-shadow channel; no `--auto` — MCP tools fire without it; bare-semver version preamble is the SST-vs-claimant discriminator; warns loudly when the user-global opencode config carries mcp.gbrain). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are `test/e2e/install-real-hermes.serial.test.ts`, `test/e2e/install-real-grok.serial.test.ts`, and `test/e2e/install-real-opencode.serial.test.ts` (split-gated a step past grok: opencode's anonymous free tier drives MCP tool calls keyless, so even the nonce SMOKE — with a STRUCTURAL `gbrain_*` tool_use assert via `parseOpencodeJsonl` — runs in the keyless tier; the paid anthropic leg self-validates its pinned model id against the authed `opencode models` list before any spend) (grok door is split-gated: keyless compat tier needs only the binary — `mcp doctor` is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs `XAI_API_KEY` and asserts a per-run nonce fact, never the committed one). Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (256KB-burst child-stall fix). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).- `skills/_friction-protocol.md` — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 5aeb408d5f..cd9514e87e 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.19.0",+ "version": "0.46.20.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 2c48514502..fdba7d8dc5 100644--- a/package.json+++ b/package.json@@ -170,7 +170,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.19.0",+ "version": "0.46.20.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 8d8b8df1f8..057677c978 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.19.0",+ "version": "0.46.20.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex f0bcb6d217..39da0c2189 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.19.0",+ "version": "0.46.20.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 06f32b34ad..f80106ca68 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.19.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.20.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 9e3cfb3b9e..5143dad8c1 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.19.0",+ "version": "0.46.20.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 75f72447ec..e619e2dfa1 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.19.0",+ "version": "0.46.20.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex f155d8726b..ab881cb3ce 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.19.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.20.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex e593bc1643..7f4e84465b 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.19.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.20.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 74b2c3e661..5890c692fd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,9 +11,9 @@ src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely;src/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wavesrc/core/ai/gateway.ts 4364 ratchet watchlist; merged: master waves + dream-wave C1-C3+C7 (thinking predicate, length, providerMetadata, turn permits) + TurnPermit signal formsrc/cli.ts 3482 ratchet watchlist; merged unions: cathedral-5 compile-context wiring + gap-closure thin-client routing + cathedral-6 register guards + sources self-help-src/core/cycle.ts 3030 ratchet+src/core/cycle.ts 3080 ratchet grown v0.46.20.0 phase-boundary split (resolveCyclePhases + normalizeQueuedSourcePhases + deriveStatus exclusion filter)src/commands/serve-http.ts 2978 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight) + chennai no-grant federated scope-src/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wave+src/commands/jobs.ts 2960 ratchet grown v0.46.20.0 queue-boundary phase normalization (per-source + maintenance handlers)src/core/search/hybrid.ts 2500 ratchetsrc/core/engine.ts 2345 ratchetsrc/commands/autopilot.ts 2301 ratchetdiff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex 4c1fcc0b97..0969d3a0e2 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -32,7 +32,7 @@import type { BrainEngine, SourceRow } from '../core/engine.ts';import type { MinionQueue } from '../core/minions/queue.ts';-import { NON_GLOBAL_PHASES, GLOBAL_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';+import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';import { sourceConfigHasRemoteUrl } from '../core/sources-load.ts';import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';@@ -476,11 +476,10 @@ export async function dispatchPerSource(repoPath: opts.repoPath,source_id: src.id,pull: shouldPull,- // #2194 fix #3 (cycle split): per-source cycles run ONLY source-scoped- // (+ mixed) phases. The brain-wide global phases (embed, orphans,- // purge, …) run once in autopilot-global-maintenance, not N times- // concurrently here — the fix for the 4→10GB RSS blowout.- phases: NON_GLOBAL_PHASES,+ // Freshness is stamped by bounded deterministic work only. LLM-backed+ // source enrichment (atoms, takes, thin-page development, etc.) is+ // explicit/background work and cannot hold source freshness hostage.+ phases: SOURCE_FRESHNESS_PHASES,},{queue: 'default',@@ -581,7 +580,7 @@ export function isGlobalMaintenanceStale(lastGlobalAtIso: string | null, now = D/*** #2194 fix #3 / #2227 bug #3 — dispatch the single brain-wide maintenance job- * that runs the `global` cycle phases (embed, orphans, purge, …) ONCE per+ * that runs the `mixed` + `global` cycle phases ONCE per* window, instead of N per-source cycles each running them concurrently (the* RSS blowout). Single-flight is structural: one `idempotency_key` per slot +* `maxPending:1` (an in-flight waiting/live-lock-active run suppresses@@ -611,7 +610,7 @@ export async function dispatchGlobalMaintenance(const job = await queue.add('autopilot-global-maintenance',- { repoPath: opts.repoPath, phases: GLOBAL_PHASES },+ { repoPath: opts.repoPath, phases: MAINTENANCE_PHASES },{queue: 'default',// Structural single-flight: one global job per slot; maxPending:1diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex a630d75c58..eedf896d44 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -77,6 +77,7 @@ export {export {computeQueueHealthCheck,computeWedgedQueueCheck,+ computeOrphanedPrivateQueueCheck,computeAutopilotFanoutConcurrencyCheck,checkBatchRetryHealth,} from './doctor/checks/queue-jobs.ts';@@ -156,6 +157,7 @@ import {import {computeQueueHealthCheck,computeWedgedQueueCheck,+ computeOrphanedPrivateQueueCheck,computeAutopilotFanoutConcurrencyCheck,checkBatchRetryHealth,} from './doctor/checks/queue-jobs.ts';@@ -3696,6 +3698,8 @@ export async function buildChecks(// waiting, zero live-lock active, stale completions) as a health error.progress.heartbeat('wedged_queue');checks.push(await computeWedgedQueueCheck(engine));+ progress.heartbeat('orphaned_private_queue');+ checks.push(await computeOrphanedPrivateQueueCheck(engine));// #2194 fix #5 — autopilot fan-out vs worker concurrency mismatch.progress.heartbeat('autopilot_fanout_concurrency');checks.push(await computeAutopilotFanoutConcurrencyCheck(engine));diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.tsindex e7608a70f7..758537f045 100644--- a/src/commands/doctor/checks/queue-jobs.ts+++ b/src/commands/doctor/checks/queue-jobs.ts@@ -326,6 +326,7 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<ChecEXTRACT(EPOCH FROM (now() - max(updated_at) FILTER (WHERE status = 'completed'))) / 60AS mins_since_completionFROM minion_jobs+ WHERE queue NOT LIKE 'dream-inline-%'GROUP BY queue`,);const wedged: string[] = [];@@ -362,6 +363,160 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec}}+/**+ * Private dream queues are owned by one parent cycle and are intentionally not+ * consumed by the default worker. If that parent disappears, restarting the+ * supervisor cannot help; the queue needs reconciliation instead. Keep this+ * diagnosis separate from wedged_queue so Doctor gives the right repair.+ *+ * Liveness model (#4250, mirrors dream-retriage's CX1 rules so the check and+ * its advertised repair agree):+ * - Live cycle locks are the REAL running-cycle signal (queue age alone+ * false-positives on a live parent between child claims). Bare+ * `gbrain-cycle` is the legacy global lock; `gbrain-cycle:<source>` is+ * per-source.+ * - Lock existence is NOT queue ownership: a queue whose birth (the+ * `dream-inline-<ms>-<uuid8>` name timestamp, else min(created_at) as a+ * conservative fallback) predates the live lock's acquired_at cannot+ * belong to that holder — an older crashed cycle's orphan stays visible+ * even while a new cycle runs.+ * - Waiting-class = waiting|delayed — exactly the statuses retriage's+ * conversion path repairs. `paused` rows are surfaced in details only+ * (flagging them would fail doctor with no advertised fix).+ */+export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Promise<Check> {+ if (engine.kind !== 'postgres') {+ return { name: 'orphaned_private_queue', status: 'ok', message: 'PGLite — no private queues to check' };+ }+ const thresholdMin = _resolveEnvNumber('GBRAIN_ORPHANED_PRIVATE_QUEUE_MINUTES', 60);+ try {+ const { dreamInlineQueueAgeMs } = await import('../../../core/cycle/synthesize.ts');+ const { resolveStealGraceSeconds } = await import('../../../core/db-lock.ts');+ const { LOCK_TTL_MINUTES } = await import('../../../core/cycle.ts');+ const rows = await engine.executeRaw<{+ queue: string;+ source_id: string | null;+ active_healthy: string | number;+ waiting: string | number;+ paused: string | number;+ oldest_waiting_minutes: string | number | null;+ birth_epoch_ms: string | number | null;+ }>(+ `SELECT queue,+ min(data->>'source_id') AS source_id,+ count(*) FILTER (WHERE status = 'active' AND lock_until > now()) AS active_healthy,+ count(*) FILTER (WHERE status IN ('waiting','delayed')) AS waiting,+ count(*) FILTER (WHERE status = 'paused') AS paused,+ EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE status IN ('waiting','delayed')))) / 60+ AS oldest_waiting_minutes,+ EXTRACT(EPOCH FROM min(created_at)) * 1000 AS birth_epoch_ms+ FROM minion_jobs+ WHERE queue LIKE 'dream-inline-%'+ GROUP BY queue`,+ );+ // Live cycle locks with their acquisition time, for ownership correlation.+ // Liveness matches db-lock's own model: an unexpired TTL, OR a lapsed TTL+ // whose holder refreshed within the steal grace (starved-but-alive —+ // exactly the holder the steal path refuses to kill; treating it as dead+ // here would point operators at cancelling a still-draining cycle's queue).+ const stealGraceSecs = resolveStealGraceSeconds(LOCK_TTL_MINUTES);+ const locks = await engine.executeRaw<{ id: string; acquired_epoch_ms: string | number }>(+ `SELECT id, EXTRACT(EPOCH FROM acquired_at) * 1000 AS acquired_epoch_ms+ FROM gbrain_cycle_locks+ WHERE (ttl_expires_at > NOW()+ OR last_refreshed_at > NOW() - make_interval(secs => ${Number(stealGraceSecs)}))+ AND id LIKE 'gbrain-cycle%'`,+ );+ const globalLockAcquiredMs = locks+ .filter(l => l.id === 'gbrain-cycle')+ .map(l => Number(l.acquired_epoch_ms))[0];+ const sourceLockAcquiredMs = new Map<string, number>(+ locks+ .filter(l => l.id.startsWith('gbrain-cycle:'))+ .map(l => [l.id.slice('gbrain-cycle:'.length), Number(l.acquired_epoch_ms)]),+ );+ const nowMs = Date.now();+ const orphaned: string[] = [];+ let waitingTotal = 0;+ let pausedTotal = 0;+ let suppressedByLiveLock = 0;+ for (const r of rows) {+ pausedTotal += Number(r.paused ?? 0);+ const activeHealthy = Number(r.active_healthy ?? 0);+ const waiting = Number(r.waiting ?? 0);+ const age = r.oldest_waiting_minutes === null ? null : Number(r.oldest_waiting_minutes);+ if (activeHealthy !== 0 || waiting === 0 || age === null || age <= thresholdMin) continue;+ // Queue birth: prefer the name-embedded timestamp; fall back to the+ // oldest job row. The fallback can only OVERSTATE birth (rows are+ // created at/after queue creation), which biases toward suppression —+ // the fail-safe direction.+ const nameAgeMs = dreamInlineQueueAgeMs(r.queue, nowMs);+ const birthMs = nameAgeMs !== null+ ? nowMs - nameAgeMs+ : (r.birth_epoch_ms === null ? null : Number(r.birth_epoch_ms));+ // A live lock suppresses the queue only if it could OWN it: the queue+ // was born at/after the lock was acquired. SKEW_TOLERANCE_MS absorbs+ // host-clock (queue-name Date.now) vs DB-clock (acquired_at NOW())+ // drift — the maintenance lane mints its queue seconds after lock+ // acquisition, so seconds of skew must not flip a live cycle's own+ // queue into "born before the lock". Unknown birth = possibly owned+ // (fail-safe suppress).+ const SKEW_TOLERANCE_MS = 60_000;+ const candidateLockAcquisitions = [+ ...(globalLockAcquiredMs !== undefined ? [globalLockAcquiredMs] : []),+ ...(r.source_id !== null && sourceLockAcquiredMs.has(r.source_id)+ ? [sourceLockAcquiredMs.get(r.source_id)!]+ : []),+ ];+ const possiblyOwnedByLiveCycle = candidateLockAcquisitions.some(+ acquiredMs => birthMs === null || !Number.isFinite(acquiredMs) || birthMs >= acquiredMs - SKEW_TOLERANCE_MS,+ );+ if (possiblyOwnedByLiveCycle) {+ suppressedByLiveLock++;+ continue;+ }+ waitingTotal += waiting;+ orphaned.push(`'${r.queue}' (${waiting} waiting, oldest ${Math.round(age)}m)`);+ }+ if (orphaned.length === 0) {+ return {+ name: 'orphaned_private_queue',+ status: 'ok',+ message: suppressedByLiveLock > 0+ ? `No provably-orphaned private queues (${suppressedByLiveLock} possibly owned by a live cycle)`+ : 'No orphaned private queues',+ ...(pausedTotal > 0 || suppressedByLiveLock > 0+ ? { details: { paused_jobs: pausedTotal, suppressed_by_live_lock: suppressedByLiveLock } }+ : {}),+ };+ }+ return {+ name: 'orphaned_private_queue',+ status: 'fail',+ message:+ `Orphaned private dream queue(s): ${orphaned.join('; ')}. ` ++ `A supervisor restart cannot consume these parent-owned queues. ` ++ `Run \`gbrain dream retriage --help\` and use its queue-reconciliation dry run; ` ++ `apply cancellation only after reviewing that preview.`,+ details: {+ orphaned_private_queues: orphaned.length,+ waiting_jobs: waitingTotal,+ paused_jobs: pausedTotal,+ suppressed_by_live_lock: suppressedByLiveLock,+ threshold_minutes: thresholdMin,+ },+ };+ } catch (e) {+ // Warn, never ok: a permanently-broken check must not read as+ // permanently healthy (the fail-open would hide every future orphan).+ return {+ name: 'orphaned_private_queue',+ status: 'warn',+ message: `Check could not run (${e instanceof Error ? e.message : String(e)}) — orphan detection is NOT covered this run`,+ };+ }+}+/*** #2194 fix #5: warn when autopilot's per-tick fan-out exceeds the worker's* effective concurrency. Fanning out more cycles than there are worker slots@@ -508,4 +663,3 @@ export async function checkBatchRetryHealth(_engine: BrainEngine): Promise<Check};}}-diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 8a001e98c5..d6e970e95e 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -22,6 +22,7 @@ import {checkPgliteScratchProbe,computeQueueHealthCheck,computeWedgedQueueCheck,+ computeOrphanedPrivateQueueCheck,computeAutopilotFanoutConcurrencyCheck,checkSubagentHealth,checkBatchRetryHealth,@@ -312,6 +313,7 @@ export async function doctorReportRemote(// issue #1801 — wedged_queue (cross-surface parity with buildChecks).checks.push(await computeWedgedQueueCheck(engine));+ checks.push(await computeOrphanedPrivateQueueCheck(engine));// #2194 fix #5 — warn when autopilot fan-out exceeds worker concurrency.checks.push(await computeAutopilotFanoutConcurrencyCheck(engine));diff --git a/src/commands/dream-retriage.ts b/src/commands/dream-retriage.tsindex 00f9016f9c..674f536d2e 100644--- a/src/commands/dream-retriage.ts+++ b/src/commands/dream-retriage.ts@@ -436,8 +436,14 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[FROM minion_jobsWHERE name = 'subagent'AND status IN ('waiting', 'delayed', 'paused')- AND idempotency_key LIKE 'dream:synth-v2:%'`,+ AND (idempotency_key LIKE 'dream:synth-v2:%' OR queue LIKE 'dream-inline-%')`,);+ // #4250: the queue-LIKE arm pulls in NON-synth children stranded in+ // private per-run queues (patterns mints dream-inline-* queues too).+ // Doctor's orphaned_private_queue check points operators HERE; a repair+ // that can't even select the flagged rows is a dead end. Non-synth rows+ // skip the verdict pipeline and are handled by the dead-inline+ // conversion branch below.// Two lookups: membership in the discovered corpus (matched at all?) vs a// usable scored verdict. A discovered file with no reliable score is// "matched but unscored" — kept, never cancelled on missing data. The@@ -482,19 +488,53 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[// with several slow sequential children can legitimately exceed the 1h// grace. Consult the REAL signal: a live (unexpired) cycle lock means a// cycle is running right now, so no dream-inline queue is provably dead.- const liveLocks = await engine.executeRaw<{ id: string }>(- `SELECT id FROM gbrain_cycle_locks WHERE ttl_expires_at > NOW() AND id LIKE 'gbrain-cycle%'`,+ // Liveness matches db-lock's model: unexpired TTL OR refreshed within the+ // steal grace (a starved-but-alive holder must keep suppressing repair).+ const { resolveStealGraceSeconds } = await import('../core/db-lock.ts');+ const { LOCK_TTL_MINUTES } = await import('../core/cycle.ts');+ const stealGraceSecs = resolveStealGraceSeconds(LOCK_TTL_MINUTES);+ const liveLocks = await engine.executeRaw<{ id: string; acquired_epoch_ms: string | number | null }>(+ `SELECT id, EXTRACT(EPOCH FROM acquired_at) * 1000 AS acquired_epoch_ms+ FROM gbrain_cycle_locks+ WHERE (ttl_expires_at > NOW()+ OR last_refreshed_at > NOW() - make_interval(secs => ${Number(stealGraceSecs)}))+ AND id LIKE 'gbrain-cycle%'`,);// Structured-review round 2 P2: cycle locks are per-source// (`gbrain-cycle:<source>`) — a cycle running for source A must not// suppress conversions for source B indefinitely. Only the legacy bare// `gbrain-cycle` lock is global.+ //+ // #4250 ownership correlation (mirrors doctor's orphaned_private_queue):+ // lock existence is NOT queue ownership. A dream-inline queue whose+ // name-embedded birth PREDATES the live lock's acquired_at cannot belong+ // to that holder — an older crashed cycle's queue stays repairable while+ // a new cycle runs. Unknown birth or unparseable acquired_at stays+ // fail-safe possibly-live.+ const lockAcquiredMs = new Map<string, number>(+ liveLocks.map(l => [l.id, Number(l.acquired_epoch_ms ?? Number.NaN)]),+ );const globalLockLive = liveLocks.some(l => l.id === 'gbrain-cycle');const liveLockSources = new Set(liveLocks.map(l => (l.id.startsWith('gbrain-cycle:') ? l.id.slice('gbrain-cycle:'.length) : null)).filter((s): s is string => s !== null),);+ const nowMsForBirth = Date.now();+ /**+ * A live lock suppresses a queue only if it could OWN it: queue born+ * at/after acquisition (or birth/acquisition unknown — fail-safe). The+ * 60s tolerance absorbs host-clock (queue-name Date.now) vs DB-clock+ * (acquired_at NOW()) skew — the maintenance lane mints its queue+ * seconds after acquiring the lock.+ */+ const OWNERSHIP_SKEW_TOLERANCE_MS = 60_000;+ const lockCouldOwnQueue = (lockId: string, queueAgeMs: number | null): boolean => {+ const acquired = lockAcquiredMs.get(lockId);+ if (acquired === undefined) return false; // lock not live+ if (queueAgeMs === null || !Number.isFinite(acquired)) return true; // fail-safe+ return (nowMsForBirth - queueAgeMs) >= acquired - OWNERSHIP_SKEW_TOLERANCE_MS;+ };if (liveLocks.length > 0) {process.stderr.write(`[retriage] live cycle lock(s) detected (${liveLocks.map(l => l.id).join(', ')}); ` +@@ -526,7 +566,9 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[// possibly-live regardless of age (structured-review P2: slow// sequential children can outlive the grace; round 2: per-source, so a// busy source A never suppresses source B's cleanup indefinitely).- const lockLiveForRow = globalLockLive || liveLockSources.has(row.source_id);+ const lockLiveForRow =+ (globalLockLive && lockCouldOwnQueue('gbrain-cycle', inlineQueueAge))+ || (liveLockSources.has(row.source_id) && lockCouldOwnQueue(`gbrain-cycle:${row.source_id}`, inlineQueueAge));const possiblyLiveQueue = isInlineQueue&& (lockLiveForRow || inlineQueueAge === null || inlineQueueAge <= DREAM_INLINE_LIVE_GRACE_MS);if (possiblyLiveQueue) {@@ -540,7 +582,23 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[}const key = parseSynthV2Key(row.idempotency_key);if (!key) {- reconcile.unmatched++;+ // #4250: a NON-synth child (e.g. patterns) stranded in a provably-dead+ // dream-inline queue has no verdict to consult and will never be+ // claimed — convert it like the C1 branch below so doctor's+ // orphaned_private_queue repair path actually repairs. The+ // possibly-live filter above already kept anything a running cycle+ // could own. Non-inline rows keep the unmatched bookkeeping.+ if (isInlineQueue && (row.status === 'waiting' || row.status === 'delayed')) {+ if (!parsed.dryRun) {+ const outcome = await cancelRow(row.id);+ if (outcome === 'cancelled') reconcile.converted_for_resubmit++;+ else reconcile.already_terminal++;+ } else {+ reconcile.converted_for_resubmit++; // dry-run: would convert+ }+ } else {+ reconcile.unmatched++;+ }continue;}// C9 hardening: the key's encoded source must agree with the payload'sdiff --git a/src/commands/dream.ts b/src/commands/dream.tsindex ced0332a89..123d9d9838 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -393,6 +393,10 @@ Options:completion. When omitted, gbrain derives thesource from --dir / the configured checkoutwhen it matches a source's local_path (#1869).+ A named non-default source runs the deterministic+ freshness phases unless --phase is given+ (explicit phases are honored verbatim);+ --source default still runs the full cycle.--source-id <id> Alias for --source. Matches the v0.37.7.0+naming used by import/extract/graph-query.diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 331149f822..879df3075d 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -2473,12 +2473,32 @@ export async function registerBuiltinHandlers(const effectiveBrainDir: string | null = sourceId ? sourceLocalPath : repoPath;// Allow callers to select phases via job data (e.g. skip embed for- // fast cycles). Validates against ALL_PHASES to prevent injection.- const { ALL_PHASES } = await import('../core/cycle.ts');+ // fast cycles). Validates against ALL_PHASES to prevent injection, then+ // normalizes per-source payloads to the freshness set (queue payloads+ // are machine-authored; see normalizeQueuedSourcePhases in cycle.ts).+ const { ALL_PHASES, normalizeQueuedSourcePhases } = await import('../core/cycle.ts');const validPhases = new Set(ALL_PHASES);const requestedPhases = Array.isArray(job.data.phases)? (job.data.phases as string[]).filter(p => validPhases.has(p as any)): undefined;+ const { phases: effectivePhases, rejected: phasesRejectedByNormalization } =+ normalizeQueuedSourcePhases(requestedPhases as any, sourceId);+ // An explicitly-empty phase list (arrived empty, or emptied by the+ // normalization) is a no-op — NOT an implicit run. The reason string is+ // honest about WHICH of the two happened.+ if (effectivePhases !== undefined && effectivePhases.length === 0) {+ return {+ partial: false,+ status: 'skipped',+ report: {+ reason: phasesRejectedByNormalization.length > 0+ ? 'all_phases_rejected_by_normalization'+ : 'empty_phase_list',+ ...(sourceId ? { source_id: sourceId } : {}),+ phases_rejected_by_normalization: phasesRejectedByNormalization,+ },+ };+ }const pull = resolveJobPull(job.data);@@ -2503,7 +2523,7 @@ export async function registerBuiltinHandlers(signal: job.signal, // propagate abort so cycle bails on timeout/canceldeadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time...(sourceId ? { sourceId } : {}),- ...(requestedPhases && requestedPhases.length > 0 ? { phases: requestedPhases as any } : {}),+ ...(effectivePhases !== undefined ? { phases: effectivePhases as any } : {}),yieldBetweenPhases: async () => {// Yield to the event loop so worker lock-renewal can fire.await new Promise<void>(r => setImmediate(r));@@ -2514,26 +2534,34 @@ export async function registerBuiltinHandlers(partial: report.status === 'partial' || report.status === 'failed',status: report.status,report,+ // Surfaced so operators can see the queue-boundary normalization at+ // work in job results (runCycle never sees rejected phases, so its+ // excludedPhases skip-reporting cannot cover them).+ ...(phasesRejectedByNormalization.length > 0+ ? { phases_rejected_by_normalization: phasesRejectedByNormalization }+ : {}),};});- // #2194 fix #3 / #2227 bug #3 — brain-wide maintenance. Runs the `global`- // cycle phases (embed, orphans, purge, resolve_symbol_edges, grade_takes,- // calibration_profile, synthesize_concepts, skillopt) ONCE per window instead- // of N times concurrently across per-source cycles (the 4→10GB RSS blowout).+ // Brain-wide maintenance. Runs mixed + global phases ONCE per window instead+ // of repeating cross-source transcript/reflection reads in every source.// No source_id → uses the legacy global cycle lock; stamps autopilot.last_global_at// on success so the dispatch gate backs off.worker.register('autopilot-global-maintenance', async (job) => {- const { runCycle, GLOBAL_PHASES, LAST_GLOBAL_AT_KEY, ALL_PHASES } = await import('../core/cycle.ts');+ const { runCycle, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } = await import('../core/cycle.ts');const repoPath: string | null = typeof job.data.repoPath === 'string'? job.data.repoPath: (await engine.getConfig('sync.repo_path')) ?? null;- const validPhases = new Set(ALL_PHASES);+ // #4250: queued maintenance payloads are machine-authored too — intersect+ // with MAINTENANCE_PHASES so a stale (or remote-submitted) payload can't+ // run source-scoped phases through the global lane, symmetric with the+ // per-source normalization in the autopilot-cycle handler.+ const maintenanceSet = new Set<string>(MAINTENANCE_PHASES);const requested = Array.isArray(job.data.phases)- ? (job.data.phases as string[]).filter((p) => validPhases.has(p as never))- : GLOBAL_PHASES;- const phases = (requested.length > 0 ? requested : GLOBAL_PHASES) as typeof GLOBAL_PHASES;+ ? (job.data.phases as string[]).filter((p) => maintenanceSet.has(p))+ : MAINTENANCE_PHASES;+ const phases = (requested.length > 0 ? requested : MAINTENANCE_PHASES) as typeof MAINTENANCE_PHASES;const report = await runCycle(engine, {brainDir: repoPath,diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f11d09897c..b75629e201 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -41,7 +41,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'config': ['--all', '--brain', '--column', '--coverage-override', '--detail', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--pattern', '--pglite', '--reset', '--source', '--surface', '--token-ttl', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],+ 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild-rollup', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'],'dream': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],'edges-backfill': ['--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-federated', '--older-than', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--timeout', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 8f711ba430..79838b3173 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -51,6 +51,9 @@ import { createProgress, type ProgressReporter } from './progress.ts';import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';import { tryAcquireDbLock, reapDeadHolderLocks, LockStolenError, type DbLockHandle } from './db-lock.ts';import { assertValidSourceId } from './source-id.ts';+import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';++export { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';// ─── Types ─────────────────────────────────────────────────────────@@ -84,9 +87,9 @@ export type CyclePhase =// Same pack-gate model.| 'extract_atoms' | 'synthesize_concepts'// v0.41.11.0 — opt-in (default OFF) bulk fact extraction for long-form- // conversation pages. The phase wrapper does its own multi-source- // iteration directly (PHASE_SCOPE='source' here is taxonomy only;- // see comment above PHASE_SCOPE). Wraps the per-source loop in ONE+ // conversation pages. The outer scheduler uses PHASE_SCOPE, while this+ // legacy phase wrapper also performs its own multi-source iteration.+ // Wraps the inner per-source loop in ONE// brain-wide BudgetTracker and passes it through opts.budgetTracker// so the core's auto-wrap doesn't REPLACE it.| 'conversation_facts_backfill'@@ -194,82 +197,92 @@ export const ALL_PHASES: CyclePhase[] = [];/**- * v0.38 (CEO + eng review): phase-scope taxonomy. Each entry in- * `ALL_PHASES` declares whether its work is naturally per-source,- * brain-global, or mixed. Static documentation only — no runtime- * enforcement yet (filed as follow-up TODO in the plan).+ * #2194 fix #3 / #2227 bug #3 — the cycle split.*- * Load-bearing for any future fan-out wave:- * - `source`: safe to parallelize per source. Sync reads/writes the- * one source's rows; extract walks changed slugs.- * - `global`: must serialize across the brain. Embed walks all stale- * chunks; purge sweeps brain-wide; orphans can report a single- * resolved source but still belongs in the serialized global lane;- * grade_takes + calibration aggregate across sources;- * resolve_symbol_edges walks every chunk.- * - `mixed`: per-phase decomposition needed before parallelizing.- * Synthesize reads the brain-global transcripts dir but writes to- * per-source slugs (via subagent allowlist). Patterns reads- * cross-source reflections but writes pattern pages.+ * Per-source autopilot cycles enqueue ONLY the deterministic freshness subset+ * (SOURCE_FRESHNESS_PHASES); the autopilot-cycle handler normalizes queued+ * per-source payloads down to that subset so legacy payloads can't re-run+ * heavier work N-way. Mixed phases read brain-wide inputs and therefore+ * cannot safely fan out by source: synthesize reads the global transcript+ * corpus, and patterns reads cross-source reflections. They join the+ * brain-wide phases in the single maintenance job instead of being repeated+ * into every source. SOURCE_BACKGROUND_PHASES have no automatic lane on+ * multi-source brains yet — they run on explicit invocation+ * (`gbrain dream --source X --phase extract_atoms`) until the background+ * lane lands (see TODOS).*- * Per-source cycle locks (codex r2 fix) let two cycles RUN concurrently,- * but `global` phases inside each cycle will still touch the same rows.- * Genuine per-source autopilot fan-out requires the deferred TODOs.+ * SOURCE_PHASES ∪ MIXED_PHASES ∪ GLOBAL_PHASES == ALL_PHASES, with no overlap.+ * MAINTENANCE_PHASES is MIXED ∪ GLOBAL in original cycle order.*/-export type PhaseScope = 'source' | 'global' | 'mixed';-export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {- lint: 'source',- backlinks: 'source',- sync: 'source',- synthesize: 'mixed',- extract: 'source',- extract_facts: 'source',- resolve_symbol_edges: 'global',- patterns: 'mixed',- recompute_emotional_weight: 'source',- consolidate: 'source',- propose_takes: 'source',- grade_takes: 'global',- calibration_profile: 'global',- // #2653 — drift walks takes brain-wide (same posture as grade_takes) and- // writes one brain-global report page.- drift: 'global',- embed: 'global',- orphans: 'global',- purge: 'global',- 'schema-suggest': 'source',- // v0.41 T9 — extract_atoms is naturally per-source (each source's- // transcript dir gets walked independently). synthesize_concepts is- // global because concept clusters cross sources by nature.- extract_atoms: 'source',- synthesize_concepts: 'global',- // v0.41.11.0 — declared 'source' for taxonomy alignment with- // extract_facts (per-source semantics). PHASE_SCOPE has no runtime- // fanout enforcement today (per the comment above); the phase- // wrapper does its own multi-source loop via listSources().- conversation_facts_backfill: 'source',- // v0.41.39 (#1700) — per-source (wrapper loops listSources, same as above).- enrich_thin: 'source',- // v0.41.20.0 SkillOpt — global (walks the skills/ directory; per-skill- // DB lock inside D14 handles cross-source coordination).- skillopt: 'global',-};+export const SOURCE_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] === 'source');+export const MIXED_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] === 'mixed');+export const GLOBAL_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] === 'global');+export const MAINTENANCE_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] !== 'source');++/** LLM-backed or unbounded source work that cannot hold freshness hostage. */+export const SOURCE_BACKGROUND_PHASES: CyclePhase[] = SOURCE_PHASES.filter(+ (phase) => !SOURCE_FRESHNESS_PHASES.includes(phase),+);/**- * #2194 fix #3 / #2227 bug #3 — the cycle split.+ * Resolve the effective phase list for one cycle invocation.*- * Per-source autopilot cycles run ONLY the source-scoped (and mixed) phases;- * the brain-wide `global` phases (embed, orphans, purge, resolve_symbol_edges,- * grade_takes, calibration_profile, synthesize_concepts, skillopt) run ONCE in- * a separate `autopilot-global-maintenance` job instead of N times concurrently- * across per-source cycles (the 4→10GB RSS blowout). Single-flight is- * structural: one global job, not a skip-and-pretend-fresh hack (codex #1/#2).+ * An IMPLICIT cycle for a named non-default source runs the deterministic+ * freshness phases only. This is the normal `dream --source X` path used by+ * the freshness keeper: it must be able to finish and stamp source freshness+ * without first draining LLM-backed maintenance work.*- * GLOBAL_PHASES ∪ NON_GLOBAL_PHASES == ALL_PHASES, with no overlap — pinned by- * test/autopilot-global-maintenance.test.ts.+ * EXPLICIT phase lists are honored verbatim. `dream --source X --phase+ * synthesize` (and `--input <file>`, which implies synthesize) is a single+ * deliberate operator action, not the N-way fanout duplication this boundary+ * exists to prevent — the caller that looped `dream --source <id>` over every+ * source with no phase flag hits the implicit branch above. Machine callers+ * that enqueue per-source phase lists are normalized at the queue boundary+ * instead (the `autopilot-cycle` handler intersects queued per-source+ * payloads with SOURCE_FRESHNESS_PHASES), so a queued legacy payload cannot+ * re-run mixed or background work once per source while human intent stays+ * authoritative.+ *+ * The canonical `default` cycle remains the one place where a full implicit+ * cycle (including mixed phases) is valid.*/-export const GLOBAL_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] === 'global');-export const NON_GLOBAL_PHASES: CyclePhase[] = ALL_PHASES.filter((p) => PHASE_SCOPE[p] !== 'global');+export function resolveCyclePhases(+ requested: CyclePhase[] | undefined,+ sourceId: string | undefined,+): CyclePhase[] {+ if (!sourceId || sourceId === 'default') return requested ?? ALL_PHASES;+ if (requested === undefined) return SOURCE_FRESHNESS_PHASES;+ return requested;+}++/**+ * Queue-boundary normalization for PER-SOURCE cycle job payloads (#4250).+ *+ * Queued phase lists are machine-authored (autopilot fanout, legacy replays),+ * not operator intent. Pre-v0.46.20 fanout payloads carried the old+ * NON_GLOBAL set — mixed + background work that must not re-run once per+ * source when a legacy job drains after upgrade. Intersecting with+ * SOURCE_FRESHNESS_PHASES is a fixed point for current fanout payloads and a+ * safe downgrade for legacy ones. Operator intent goes through the CLI+ * (`gbrain dream --source X --phase …`), which resolveCyclePhases honors+ * verbatim — this normalization is for the queue handler only.+ *+ * No-source or no-phases payloads pass through untouched. Callers must treat+ * a returned EMPTY phases array as an explicit no-op, never as an implicit+ * run (omitting `phases` from CycleOpts would silently convert an+ * all-rejected payload into a freshness cycle).+ */+export function normalizeQueuedSourcePhases(+ requested: CyclePhase[] | undefined,+ sourceId: string | undefined,+): { phases: CyclePhase[] | undefined; rejected: CyclePhase[] } {+ if (!sourceId || requested === undefined) return { phases: requested, rejected: [] };+ const freshness = new Set<CyclePhase>(SOURCE_FRESHNESS_PHASES);+ return {+ phases: requested.filter((p) => freshness.has(p)),+ rejected: requested.filter((p) => !freshness.has(p)),+ };+}/** Config key holding the ISO timestamp of the last successful global-maintenance run. */export const LAST_GLOBAL_AT_KEY = 'autopilot.last_global_at';@@ -566,7 +579,7 @@ const LEGACY_CYCLE_LOCK_ID = 'gbrain-cycle';// long-running cycle keeps the TTL alive while the shorter window// shrinks crash recovery 6×.const LOCK_TTL_MS = 5 * 60 * 1000; // 5 minutes (was 30)-const LOCK_TTL_MINUTES = 5; // was 30; db-lock.ts takes minutes+export const LOCK_TTL_MINUTES = 5; // was 30; db-lock.ts takes minutes (exported: doctor/retriage liveness grace derives from it)// Lazy: GBRAIN_HOME may be set after module load; resolve at call time.const getLockFilePathDefault = () => gbrainPath('cycle.lock');@@ -1074,7 +1087,7 @@ interface SyncPhaseResult extends PhaseResult {* everything but name, so dream derives the source id up front and passes* it as opts.sourceId — landing the freshness stamp without changing* runCycle's stamp/lock semantics for legacy global callers (the- * autopilot-global-maintenance handler runs GLOBAL_PHASES with a brainDir+ * autopilot-global-maintenance handler runs MAINTENANCE_PHASES with a brainDir* and MUST NOT stamp per-source freshness; see rejected PR #2549).*/export async function resolveSourceForDir(@@ -1761,11 +1774,23 @@ export async function runCycle(opts: CycleOpts,): Promise<CycleReport> {const start = performance.now();- const phases = opts.phases ?? ALL_PHASES;+ const requestedPhases = opts.phases ?? ALL_PHASES;+ const phases = resolveCyclePhases(opts.phases, opts.sourceId);+ const excludedPhases = requestedPhases.filter((phase) => !phases.includes(phase));const dryRun = !!opts.dryRun;const pull = !!opts.pull;const timestamp = new Date().toISOString();- const phaseResults: PhaseResult[] = [];+ const phaseResults: PhaseResult[] = excludedPhases.map((phase) => ({+ phase,+ status: 'skipped',+ duration_ms: 0,+ summary: `excluded from implicit non-default source cycle (${PHASE_SCOPE[phase]} scope)`,+ details: {+ reason: 'excluded_from_implicit_source_cycle',+ source_id: opts.sourceId,+ phase_scope: PHASE_SCOPE[phase],+ },+ }));// Capture as a const so it narrows to `string` inside the `else` branches of// the per-phase `if (brainDir === null)` guards, even within async closures@@ -2872,7 +2897,7 @@ export async function runCycle(// timestamp post-failure is still higher than missing a successful write, so// the stamp itself is unchanged — only the reporting is.let stampWriteFailed: { source_id: string; error: string } | undefined;- if (opts.sourceId && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {+ if (opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {try {const nowIso = new Date().toISOString();// #2194 fix #3 (the cycle split): `last_source_cycle_at` is the NEW gate@@ -2990,7 +3015,21 @@ function extractTotals(phases: PhaseResult[]): CycleReport['totals'] {return t;}-function deriveStatus(phases: PhaseResult[], totals: CycleReport['totals']): CycleStatus {+export function deriveStatus(phases: PhaseResult[], totals: CycleReport['totals']): CycleStatus {+ // #4250: exclusion bookkeeping records (the implicit source-cycle scope+ // filter's synthetic skips) are not attempted phases and must not dilute+ // failure aggregation. Pre-fix, an implicit source cycle whose SIX real+ // freshness phases ALL failed still carried seventeen exclusion skips, so+ // `allFailed` was false, status became 'partial', and the stamp gate+ // (which accepts 'partial') marked a totally-failed source fresh —+ // suppressing its retry forever. Score only attempted phases; fall back to+ // the full list if somehow every record is an exclusion (unreachable via+ // current callers — SOURCE_FRESHNESS_PHASES is never empty).+ // Exported for test-only consumption; downstream code should NOT call it.+ const attempted = phases.filter(+ p => p.details?.reason !== 'excluded_from_implicit_source_cycle',+ );+ if (attempted.length > 0) phases = attempted;if (phases.length === 0) return 'failed';const anyFailed = phases.some(p => p.status === 'fail');const allFailed = phases.every(p => p.status === 'fail');diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex 8a22766abd..4930cb3b8f 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -7,10 +7,10 @@** Architecture (per CEO + eng review + Codex outside voice):*- * - Per-source iteration HERE. PHASE_SCOPE='source' is taxonomy-only- * (cycle.ts:131 documents this); no runtime fanout exists yet. The- * wrapper enumerates `listSources(engine)` and loops over per-source- * core invocations directly.+ * - Per-source iteration HERE. The outer cycle scheduler now uses+ * PHASE_SCOPE for fanout admission, while this legacy wrapper still+ * enumerates `listSources(engine)` and loops over per-source core+ * invocations directly.** - Brain-wide BudgetTracker created ONCE per phase tick and passed* into every per-source invocation via `opts.budgetTracker`. Thediff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsnew file mode 100644index 0000000000..f24904d6d3--- /dev/null+++ b/src/core/cycle/phase-scope.ts@@ -0,0 +1,45 @@+import type { CyclePhase } from '../cycle.ts';++/**+ * Phase-scope taxonomy. `runCycle` enforces it for explicit non-default+ * sources: only source phases run there; mixed and global phases run once in+ * the default/global-maintenance lane.+ *+ * - source: safe to parallelize per source.+ * - global: must serialize across the brain.+ * - mixed: reads brain-wide input while writing pages, so it stays in the+ * default/global-maintenance lane until decomposed.+ */+export type PhaseScope = 'source' | 'global' | 'mixed';++export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {+ lint: 'source',+ backlinks: 'source',+ sync: 'source',+ synthesize: 'mixed',+ extract: 'source',+ extract_facts: 'source',+ resolve_symbol_edges: 'global',+ patterns: 'mixed',+ recompute_emotional_weight: 'source',+ consolidate: 'source',+ propose_takes: 'source',+ grade_takes: 'global',+ calibration_profile: 'global',+ drift: 'global',+ embed: 'global',+ orphans: 'global',+ purge: 'global',+ 'schema-suggest': 'source',+ extract_atoms: 'source',+ synthesize_concepts: 'global',+ conversation_facts_backfill: 'source',+ enrich_thin: 'source',+ skillopt: 'global',+};++/** Bounded deterministic phases that alone define source freshness. */+export const SOURCE_FRESHNESS_PHASES: CyclePhase[] = [+ 'lint', 'backlinks', 'sync', 'extract', 'extract_facts',+ 'recompute_emotional_weight',+];diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 789e9d0fef..c67473e2a2 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -193,6 +193,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['supervisor_singleton','sync_consolidation','wedged_queue',+ 'orphaned_private_queue','worker_oom_loop','ze_embedding_health',]);diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 93f55dc27f..96f8da499a 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.46.19.0 -->+<!-- gbrain-template-stamp: 0.46.20.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/autopilot-cycle-source-checkout.test.ts b/test/autopilot-cycle-source-checkout.test.tsindex 00387eed81..72f2861f3e 100644--- a/test/autopilot-cycle-source-checkout.test.ts+++ b/test/autopilot-cycle-source-checkout.test.ts@@ -61,10 +61,12 @@ describe('autopilot-cycle handler — per-source checkout binding (#2227/#2194)'const handlers = await captureHandlers();const handler = handlers.get('autopilot-cycle')!;- // DB-only phase keeps the test cheap; brain_dir is stamped from opts.brainDir- // regardless of which phases run, so it still proves the binding.+ // Cheap DB phase from the FRESHNESS set (per-source payloads normalize to+ // SOURCE_FRESHNESS_PHASES since #4250); brain_dir is stamped from+ // opts.brainDir regardless of which phases run, so it still proves the+ // binding.const result = await handler({- data: { source_id: 'repo-a', phases: ['resolve_symbol_edges'] },+ data: { source_id: 'repo-a', phases: ['recompute_emotional_weight'] },signal: undefined,});@@ -84,7 +86,7 @@ describe('autopilot-cycle handler — per-source checkout binding (#2227/#2194)'const handlers = await captureHandlers();const handler = handlers.get('autopilot-cycle')!;const result = await handler({- data: { source_id: 'db-only', phases: ['resolve_symbol_edges'] },+ data: { source_id: 'db-only', phases: ['recompute_emotional_weight'] },signal: undefined,});diff --git a/test/autopilot-global-maintenance.test.ts b/test/autopilot-global-maintenance.test.tsindex 322a197ca2..64c427c35c 100644--- a/test/autopilot-global-maintenance.test.ts+++ b/test/autopilot-global-maintenance.test.ts@@ -1,8 +1,8 @@/*** #2194 fix #3 / #2227 bug #3 — the cycle split.*- * Per-source autopilot cycles run ONLY source-scoped (+ mixed) phases; the- * brain-wide `global` phases run ONCE in a separate autopilot-global-maintenance+ * Per-source autopilot cycles run ONLY source-scoped phases; mixed + global+ * phases run ONCE in a separate autopilot-global-maintenance* job. This replaces the rejected skip-and-stamp-fresh design (codex #1/#2): the* split makes single-flight structural (one global job, not N concurrent embeds)* and never marks a source "fresh" for global work it didn't do. These tests pin@@ -19,9 +19,16 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';import { registerBuiltinHandlers } from '../src/commands/jobs.ts';import {ALL_PHASES,+ SOURCE_PHASES,+ SOURCE_FRESHNESS_PHASES,+ SOURCE_BACKGROUND_PHASES,+ MIXED_PHASES,GLOBAL_PHASES,- NON_GLOBAL_PHASES,+ MAINTENANCE_PHASES,PHASE_SCOPE,+ resolveCyclePhases,+ deriveStatus,+ runCycle,LAST_GLOBAL_AT_KEY,} from '../src/core/cycle.ts';import {@@ -32,13 +39,12 @@ import {import type { BrainEngine } from '../src/core/engine.ts';describe('cycle phase partition (#2194 fix #3)', () => {- test('GLOBAL ∪ NON_GLOBAL == ALL_PHASES, no overlap', () => {- const union = new Set([...GLOBAL_PHASES, ...NON_GLOBAL_PHASES]);+ test('SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES, no overlap', () => {+ const union = new Set([...SOURCE_PHASES, ...MIXED_PHASES, ...GLOBAL_PHASES]);expect(union.size).toBe(ALL_PHASES.length);for (const p of ALL_PHASES) expect(union.has(p)).toBe(true);- // No phase in both.- const overlap = GLOBAL_PHASES.filter((p) => NON_GLOBAL_PHASES.includes(p));- expect(overlap).toEqual([]);+ expect(SOURCE_PHASES.filter((p) => MIXED_PHASES.includes(p) || GLOBAL_PHASES.includes(p))).toEqual([]);+ expect(MIXED_PHASES.filter((p) => GLOBAL_PHASES.includes(p))).toEqual([]);});test('every GLOBAL phase is PHASE_SCOPE==="global"; embed is global, lint is not', () => {@@ -46,10 +52,87 @@ describe('cycle phase partition (#2194 fix #3)', () => {expect(GLOBAL_PHASES).toContain('embed');expect(GLOBAL_PHASES).toContain('orphans');expect(GLOBAL_PHASES).toContain('purge');- expect(NON_GLOBAL_PHASES).toContain('lint');- expect(NON_GLOBAL_PHASES).toContain('sync');- expect(NON_GLOBAL_PHASES).not.toContain('embed');+ expect(SOURCE_PHASES).toContain('lint');+ expect(SOURCE_PHASES).toContain('sync');+ expect(SOURCE_PHASES).not.toContain('embed');+ expect(MIXED_PHASES).toEqual(['synthesize', 'patterns']);+ expect(MAINTENANCE_PHASES).toContain('synthesize');+ expect(MAINTENANCE_PHASES).toContain('patterns');+ expect(MAINTENANCE_PHASES).toContain('embed');});++ test('source freshness excludes LLM-backed/background source work', () => {+ expect(new Set([...SOURCE_FRESHNESS_PHASES, ...SOURCE_BACKGROUND_PHASES])).toEqual(new Set(SOURCE_PHASES));+ expect(SOURCE_FRESHNESS_PHASES).toContain('sync');+ expect(SOURCE_FRESHNESS_PHASES).toContain('extract_facts');+ expect(SOURCE_BACKGROUND_PHASES).toContain('extract_atoms');+ expect(SOURCE_BACKGROUND_PHASES).toContain('consolidate');+ expect(SOURCE_BACKGROUND_PHASES).toContain('propose_takes');+ expect(SOURCE_BACKGROUND_PHASES).toContain('enrich_thin');+ expect(SOURCE_FRESHNESS_PHASES).not.toContain('extract_atoms');+ });++ test('implicit source cycles are freshness-only; explicit phase lists are honored verbatim', () => {+ // `dream --source X` with no phase flag is the freshness path and must+ // finish independently of brain-wide maintenance. An EXPLICIT phase list+ // is deliberate operator intent and is honored verbatim (#4250 regression+ // pin: `dream --source X --phase synthesize`, and `--input <file>` which+ // implies synthesize, must actually run — queue payloads are normalized+ // at the autopilot-cycle handler instead, see the handler tests below).+ expect(resolveCyclePhases(undefined, 'repo-a')).toEqual(SOURCE_FRESHNESS_PHASES);+ expect(resolveCyclePhases(['synthesize'], 'repo-a')).toEqual(['synthesize']);+ expect(resolveCyclePhases(['sync', 'synthesize', 'patterns', 'embed'], 'repo-a'))+ .toEqual(['sync', 'synthesize', 'patterns', 'embed']);+ expect(resolveCyclePhases(undefined, 'default')).toEqual(ALL_PHASES);+ expect(resolveCyclePhases(undefined, undefined)).toEqual(ALL_PHASES);+ expect(resolveCyclePhases(['synthesize'], undefined)).toEqual(['synthesize']);+ });++ test('exclusion skip-records never dilute failure status into a stampable partial (#4250 ship-stage P1)', () => {+ // Pre-fix: six failed freshness phases + seventeen synthetic exclusion+ // skips made deriveStatus see "not every entry failed" → 'partial' →+ // the stamp gate marked a totally-failed source fresh forever.+ const fail = (phase: string) => ({ phase, status: 'fail', duration_ms: 0, summary: '', details: {} });+ const exclusion = (phase: string) => ({+ phase, status: 'skipped', duration_ms: 0, summary: '',+ details: { reason: 'excluded_from_implicit_source_cycle' },+ });+ const realSkip = (phase: string) => ({+ phase, status: 'skipped', duration_ms: 0, summary: '', details: { reason: 'no_brain_dir' },+ });+ const zeroTotals = {} as never;+ // All attempted phases failed + exclusion bookkeeping → 'failed', never 'partial'.+ expect(deriveStatus(+ [fail('sync'), fail('lint'), exclusion('synthesize'), exclusion('patterns'), exclusion('embed')] as never,+ zeroTotals,+ )).toBe('failed');+ // A genuinely mixed run (one fail, one real skip) stays 'partial'.+ expect(deriveStatus([fail('sync'), realSkip('lint')] as never, zeroTotals)).toBe('partial');+ });++ test('implicit source cycle reports excluded non-freshness phases instead of silently omitting them', async () => {+ const report = await runCycle(null, {+ brainDir: null,+ sourceId: 'repo-a',+ dryRun: true,+ });+ const byPhase = new Map(report.phases.map((p) => [p.phase, p]));+ // Every non-freshness phase is present as an explicit exclusion record.+ for (const phase of ALL_PHASES) {+ if (SOURCE_FRESHNESS_PHASES.includes(phase)) continue;+ const rec = byPhase.get(phase);+ expect(rec?.status).toBe('skipped');+ expect(rec?.details.reason).toBe('excluded_from_implicit_source_cycle');+ expect(rec?.details.source_id).toBe('repo-a');+ }+ // The freshness phases themselves are attempted (not exclusion records).+ for (const phase of SOURCE_FRESHNESS_PHASES) {+ const rec = byPhase.get(phase);+ expect(rec).toBeTruthy();+ expect(rec?.details?.reason).not.toBe('excluded_from_implicit_source_cycle');+ }+ });+});describe('isGlobalMaintenanceStale', () => {@@ -91,7 +174,7 @@ describe('dispatchGlobalMaintenance — single-flight gate', () => {// across slot rotation (upstream issue #2).expect(added[0].opts.maxPending).toBe(1);expect(added[0].opts.maxWaiting).toBeUndefined();- expect(added[0].data.phases).toEqual(GLOBAL_PHASES);+ expect(added[0].data.phases).toEqual(MAINTENANCE_PHASES);});test('fresh → does NOT dispatch', async () => {@@ -123,8 +206,8 @@ describe('dispatchGlobalMaintenance — single-flight gate', () => {});});-describe('dispatchPerSource — per-source jobs carry NON_GLOBAL phases (no embed)', () => {- test('each per-source job sets phases = NON_GLOBAL_PHASES', async () => {+describe('dispatchPerSource — per-source jobs carry SOURCE phases only', () => {+ test('each per-source job excludes mixed and global phases', async () => {const sources = [{ id: 'repo-a', name: 'a', config: {} }, { id: 'repo-b', name: 'b', config: {} }];const added: any[] = [];const engine = {@@ -137,7 +220,9 @@ describe('dispatchPerSource — per-source jobs carry NON_GLOBAL phases (no embeawait dispatchPerSource(engine, queue, { repoPath: '/tmp', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true, emit: () => {}, log: () => {} });expect(added.length).toBe(2);for (const j of added) {- expect(j.data.phases).toEqual(NON_GLOBAL_PHASES);+ expect(j.data.phases).toEqual(SOURCE_FRESHNESS_PHASES);+ expect(j.data.phases).not.toContain('synthesize');+ expect(j.data.phases).not.toContain('patterns');expect(j.data.phases).not.toContain('embed');}});@@ -156,6 +241,93 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',return handlers;}+ test('autopilot-cycle handler normalizes a legacy per-source payload down to freshness phases', async () => {+ // Pre-v0.46.20 fanout payloads carried NON_GLOBAL_PHASES (mixed ++ // background). A legacy job draining after upgrade must not re-run that+ // work once per source: the handler intersects the queued list with+ // SOURCE_FRESHNESS_PHASES and surfaces what it rejected.+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path) VALUES ($1, $2, NULL)`,+ ['repo-a', 'repo-a'],+ );+ const handlers = await captureHandlers();+ const handler = handlers.get('autopilot-cycle');+ expect(handler).toBeTruthy();++ const legacyPhases = ['sync', 'synthesize', 'extract', 'patterns', 'extract_atoms', 'consolidate'];+ const result = await handler!({+ data: { source_id: 'repo-a', phases: legacyPhases, pull: false },+ signal: undefined,+ });+ expect(result.phases_rejected_by_normalization)+ .toEqual(['synthesize', 'patterns', 'extract_atoms', 'consolidate']);+ // Only the freshness subset reached runCycle.+ expect(result.report.phases.map((p: any) => p.phase)).toEqual(['sync', 'extract']);+ });++ test('an all-rejected queued payload is an explicit no-op, not an implicit freshness run', async () => {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path) VALUES ($1, $2, NULL)`,+ ['repo-b', 'repo-b'],+ );+ const handlers = await captureHandlers();+ const handler = handlers.get('autopilot-cycle');++ const result = await handler!({+ data: { source_id: 'repo-b', phases: ['synthesize', 'patterns'], pull: false },+ signal: undefined,+ });+ expect(result.status).toBe('skipped');+ expect(result.report.reason).toBe('all_phases_rejected_by_normalization');+ expect(result.report.phases_rejected_by_normalization).toEqual(['synthesize', 'patterns']);+ // No cycle ran → no freshness stamp.+ const source = (await engine.listAllSources()).find((row) => row.id === 'repo-b');+ expect(source?.config.last_source_cycle_at).toBeUndefined();+ expect(source?.config.last_full_cycle_at).toBeUndefined();++ // A payload that ARRIVES empty is the same explicit no-op, with an+ // honest reason (nothing was rejected — the list was empty).+ const empty = await handler!({+ data: { source_id: 'repo-b', phases: [], pull: false },+ signal: undefined,+ });+ expect(empty.status).toBe('skipped');+ expect(empty.report.reason).toBe('empty_phase_list');+ expect(empty.report.phases_rejected_by_normalization).toEqual([]);+ });++ test('an explicit empty phase list with a sourceId runs nothing and never stamps freshness', async () => {+ // Direct-caller edge of the PR-added `phases.length > 0` stamp guard:+ // queue callers are already protected by handler normalization, but a+ // direct runCycle caller passing [] must not get a freshness stamp for+ // work that never ran.+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path) VALUES ($1, $2, NULL)`,+ ['repo-empty', 'repo-empty'],+ );+ const report = await runCycle(engine, { brainDir: null, sourceId: 'repo-empty', phases: [] });+ expect(report.phases).toEqual([]);+ const source = (await engine.listAllSources()).find((row) => row.id === 'repo-empty');+ expect(source?.config.last_source_cycle_at).toBeUndefined();+ expect(source?.config.last_full_cycle_at).toBeUndefined();+ });++ test('a maintenance job with NO phases payload defaults to MAINTENANCE_PHASES (mixed included), not GLOBAL_PHASES', async () => {+ // Regression pin for the split's changed default: a legacy queued+ // maintenance job (or a hand-submitted one) with no explicit phases now+ // runs mixed + global — synthesize/patterns must appear in the report.+ const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-global-default-'));+ const handlers = await captureHandlers();+ const handler = handlers.get('autopilot-global-maintenance');+ const result = await handler!({ data: { repoPath }, signal: undefined });+ const ranPhases = result.report.phases.map((p: any) => p.phase);+ for (const p of MAINTENANCE_PHASES) expect(ranPhases).toContain(p);+ expect(ranPhases).toContain('synthesize');+ expect(ranPhases).toContain('patterns');+ expect(ranPhases).not.toContain('sync');+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();+ }, 60_000);+test('runs global phases (no source_id) and stamps autopilot.last_global_at on success', async () => {expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-global-maintenance-'));diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.tsindex 798b7f8334..12b751aa34 100644--- a/test/cycle-abort.test.ts+++ b/test/cycle-abort.test.ts@@ -107,15 +107,15 @@ describe('autopilot-cycle handler contract (v0.20.5)', () => {// The autopilot-cycle handler MUST pass signal to runCycle.// Source-level regression guard.//- // The slice window was bumped to 6000 in v0.39 — the v0.38 wave added- // source_id validation + archive recheck + pull-flag threading at the- // top of the handler, which pushed the runCycle({signal:...}) call past- // the original 2000-char ceiling. The intent of the guard is unchanged:- // "the autopilot-cycle handler passes job.signal to runCycle." The- // window just needs to be wide enough to span any reasonable handler.+ // The slice window was bumped to 6000 in v0.39 (source_id validation ++ // archive recheck + pull threading) and to 8000 in v0.46.20 (#4250+ // queue-boundary phase normalization) — each wave adds handler prologue+ // that pushes the runCycle({signal:...}) call further down. The intent of+ // the guard is unchanged: "the autopilot-cycle handler passes job.signal+ // to runCycle." The window just needs to span any reasonable handler.const handlerStart = jobsSource.indexOf("registerBuiltinJob(worker, engine, 'autopilot-cycle'");expect(handlerStart).toBeGreaterThan(-1);- const handlerBlock = jobsSource.slice(handlerStart, handlerStart + 6000);+ const handlerBlock = jobsSource.slice(handlerStart, handlerStart + 8000);expect(handlerBlock).toContain('signal: job.signal');});diff --git a/test/cycle-enabled-phase-completeness.test.ts b/test/cycle-enabled-phase-completeness.test.tsindex e74bb009f4..618db6ebdb 100644--- a/test/cycle-enabled-phase-completeness.test.ts+++ b/test/cycle-enabled-phase-completeness.test.ts@@ -91,15 +91,14 @@ async function readLastFullCycleAt(sourceId: string): Promise<string | null> {}describe('#2540 (i) — pack omitting optional phases, all enabled phases complete', () => {- test('full ALL_PHASES cycle with no active pack declaring extract_atoms/synthesize_concepts stamps last_full_cycle_at', async () => {+ test('implicit source freshness cycle excludes background phases and stamps last_full_cycle_at', async () => {await withEnv({ GBRAIN_HOME: gbrainHome, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {await seedSource('no-pack');expect(await readLastFullCycleAt('no-pack')).toBeNull();- // No active pack registered → packDeclaresPhase fails open (false)- // for extract_atoms/synthesize_concepts → both report 'skipped',- // not 'warn'/'fail'. Default ALL_PHASES selection (matches a real- // nightly `gbrain dream`/`gbrain dream --dir` run).+ // Named-source defaults now select the bounded freshness phase set.+ // Background and global phases are reported as intentionally excluded,+ // so they cannot hold source freshness hostage.const report = await runCycle(engine, {brainDir,sourceId: 'no-pack',@@ -108,9 +107,9 @@ describe('#2540 (i) — pack omitting optional phases, all enabled phases compleconst extractAtoms = report.phases.find(p => p.phase === 'extract_atoms');const synthConcepts = report.phases.find(p => p.phase === 'synthesize_concepts');expect(extractAtoms?.status).toBe('skipped');- expect(extractAtoms?.details?.reason).toBe('not_in_active_pack');+ expect(extractAtoms?.details?.reason).toBe('excluded_from_implicit_source_cycle');expect(synthConcepts?.status).toBe('skipped');- expect(synthConcepts?.details?.reason).toBe('not_in_active_pack');+ expect(synthConcepts?.details?.reason).toBe('excluded_from_implicit_source_cycle');// The cycle must not be reported 'failed' outright just because two// phases the pack never declared were skipped.diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.tsindex f5561ea954..1ba0c1b47a 100644--- a/test/doctor-wedged-queue.test.ts+++ b/test/doctor-wedged-queue.test.ts@@ -12,8 +12,13 @@import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { doctorSource } from './helpers/doctor-source.ts';+import { withEnv } from './helpers/with-env.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { computeQueueHealthCheck, computeWedgedQueueCheck } from '../src/commands/doctor.ts';+import {+ computeOrphanedPrivateQueueCheck,+ computeQueueHealthCheck,+ computeWedgedQueueCheck,+} from '../src/commands/doctor.ts';import type { BrainEngine } from '../src/core/engine.ts';let base: PGLiteEngine;@@ -124,6 +129,17 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {expect(check.message).not.toContain("'q-healthy'");});+ it('does NOT misclassify parent-owned dream queues as worker wedges', async () => {+ await seed('dream-inline-dead-parent', 'subagent', 'waiting', {+ createdAtSql: "now() - interval '2 hours'",+ });+ await seed('dream-inline-dead-parent', 'subagent', 'completed', {+ updatedAtSql: "now() - interval '2 hours'",+ });+ const check = await computeWedgedQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ });+it('returns ok on PGLite (no multi-process worker surface)', async () => {const check = await computeWedgedQueueCheck(base as unknown as BrainEngine);expect(check.status).toBe('ok');@@ -131,6 +147,163 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {});});+describe('orphaned private dream queues', () => {+ it('flags an old private queue with waiting jobs and no live parent', async () => {+ await seed('dream-inline-dead-parent', 'subagent', 'waiting', {+ createdAtSql: "now() - interval '2 hours'",+ });+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail');+ expect(check.message).toContain('supervisor restart cannot consume');+ expect(check.message).toContain('queue-reconciliation dry run');+ expect(check.details).toMatchObject({ orphaned_private_queues: 1, waiting_jobs: 1 });+ });++ it('does not flag a private queue whose parent still holds a live job lock', async () => {+ await seed('dream-inline-live-parent', 'subagent', 'waiting', {+ createdAtSql: "now() - interval '2 hours'",+ });+ await seed('dream-inline-live-parent', 'subagent', 'active', {+ lockUntilSql: "now() + interval '5 min'",+ });+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ });++ it('allows a startup grace period for a new private queue', async () => {+ await seed('dream-inline-new-parent', 'subagent', 'waiting', {+ createdAtSql: "now() - interval '10 min'",+ });+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ });++ it('returns ok on PGLite', async () => {+ const check = await computeOrphanedPrivateQueueCheck(base as unknown as BrainEngine);+ expect(check.status).toBe('ok');+ });+});++describe('orphaned private dream queues — cycle-lock liveness + ownership correlation (#4250)', () => {+ async function seedWithData(+ queue: string,+ status: string,+ dataJson: Record<string, unknown>,+ extra: { createdAtSql?: string } = {},+ ): Promise<void> {+ await base.executeRaw(+ `INSERT INTO minion_jobs (name, queue, status, data, created_at)+ VALUES ($1, $2, $3, $4::text::jsonb, ${extra.createdAtSql ?? 'now()'})`,+ ['subagent', queue, status, JSON.stringify(dataJson)],+ );+ }++ async function seedLock(id: string, acquiredAtSql: string): Promise<void> {+ await base.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)+ VALUES ($1, 1234, 'test-host', ${acquiredAtSql}, now() + interval '10 min', now())+ ON CONFLICT (id) DO UPDATE SET acquired_at = ${acquiredAtSql}, ttl_expires_at = now() + interval '10 min'`,+ [id],+ );+ }++ function inlineQueueName(bornMsAgo: number): string {+ return `dream-inline-${Date.now() - bornMsAgo}-abcdef01`;+ }++ beforeEach(async () => {+ await base.executeRaw('DELETE FROM gbrain_cycle_locks');+ });++ it('a live per-source lock acquired BEFORE the queue was born suppresses it (possibly owned)', async () => {+ const q = inlineQueueName(2 * 3600_000); // born 2h ago+ await seedWithData(q, 'waiting', { source_id: 'repo-a' }, { createdAtSql: "now() - interval '2 hours'" });+ await seedLock('gbrain-cycle:repo-a', "now() - interval '3 hours'"); // acquired before birth+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ expect((check.details as any)?.suppressed_by_live_lock).toBe(1);+ });++ it('a live lock acquired AFTER the queue was born cannot own it — still flagged', async () => {+ const q = inlineQueueName(2 * 3600_000); // born 2h ago+ await seedWithData(q, 'waiting', { source_id: 'repo-a' }, { createdAtSql: "now() - interval '2 hours'" });+ await seedLock('gbrain-cycle:repo-a', "now() - interval '30 min'"); // new cycle, acquired after birth+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail');+ expect(check.message).toContain(q);+ });++ it("a live lock for a DIFFERENT source does not suppress another source's dead queue", async () => {+ const q = inlineQueueName(2 * 3600_000);+ await seedWithData(q, 'waiting', { source_id: 'repo-a' }, { createdAtSql: "now() - interval '2 hours'" });+ await seedLock('gbrain-cycle:repo-b', "now() - interval '3 hours'");+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail');+ });++ it('the bare global lock suppresses only queues it could own (born at/after acquisition)', async () => {+ const oldQ = inlineQueueName(4 * 3600_000); // predates the lock → flagged+ const newQ = inlineQueueName(90 * 60_000); // born after acquisition, >60m old → suppressed+ await seedWithData(oldQ, 'waiting', {}, { createdAtSql: "now() - interval '4 hours'" });+ await seedWithData(newQ, 'waiting', {}, { createdAtSql: "now() - interval '90 min'" });+ await seedLock('gbrain-cycle', "now() - interval '2 hours'");+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail');+ expect(check.message).toContain(oldQ);+ expect(check.message).not.toContain(newQ);+ expect((check.details as any)?.suppressed_by_live_lock).toBe(1);+ });++ it('delayed rows count toward the waiting-class (retriage repairs waiting|delayed)', async () => {+ await seedWithData('dream-inline-delayed-only', 'delayed', {}, { createdAtSql: "now() - interval '2 hours'" });+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail');+ expect((check.details as any)?.waiting_jobs).toBe(1);+ });++ it('paused rows never fail the check (no advertised repair path) but surface in details', async () => {+ await seedWithData('dream-inline-paused-only', 'paused', {}, { createdAtSql: "now() - interval '2 hours'" });+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ expect((check.details as any)?.paused_jobs).toBe(1);+ });++ it('GBRAIN_ORPHANED_PRIVATE_QUEUE_MINUTES overrides the age threshold', async () => {+ await seedWithData('dream-inline-fresh-orphan', 'waiting', {}, { createdAtSql: "now() - interval '10 min'" });+ await withEnv({ GBRAIN_ORPHANED_PRIVATE_QUEUE_MINUTES: '5' }, async () => {+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('fail'); // 10min > 5min override; default 60 would pass+ });+ });++ it('a TTL-lapsed lock refreshed within the steal grace still counts as live (starved-but-alive holder)', async () => {+ const q = inlineQueueName(2 * 3600_000);+ await seedWithData(q, 'waiting', { source_id: 'repo-slow' }, { createdAtSql: "now() - interval '2 hours'" });+ // TTL lapsed 1 min ago, but the holder refreshed 30s ago and acquired+ // BEFORE the queue was born — db-lock's steal path would not kill this+ // holder, so doctor must not point operators at cancelling its queue.+ await base.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)+ VALUES ('gbrain-cycle:repo-slow', 1234, 'test-host', now() - interval '3 hours', now() - interval '1 min', now() - interval '30 sec')`,+ );+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ expect((check.details as any)?.suppressed_by_live_lock).toBe(1);+ });++ it('clock-skew tolerance: a lock acquired seconds AFTER the queue birth still owns it', async () => {+ // Host Date.now (queue name) vs DB NOW() (acquired_at) can skew by+ // seconds on remote engines; the maintenance lane mints its queue right+ // after acquiring the lock. A 30s gap must suppress, not flag.+ const q = inlineQueueName(2 * 3600_000);+ await seedWithData(q, 'waiting', { source_id: 'repo-skew' }, { createdAtSql: "now() - interval '2 hours'" });+ await seedLock('gbrain-cycle:repo-skew', "now() - interval '2 hours' + interval '30 sec'");+ const check = await computeOrphanedPrivateQueueCheck(pgLike);+ expect(check.status).toBe('ok');+ expect((check.details as any)?.suppressed_by_live_lock).toBe(1);+ });+});+describe('Minions-visibility wave — computeQueueHealthCheck structured details', () => {it('ok path carries {depth, oldest_age_seconds, worker_alive} (messages unchanged)', async () => {const check = await computeQueueHealthCheck(pgLike, { readWorkers: () => [] });diff --git a/test/dream-retriage.test.ts b/test/dream-retriage.test.tsindex e4c39bad10..014ff08016 100644--- a/test/dream-retriage.test.ts+++ b/test/dream-retriage.test.ts@@ -221,16 +221,19 @@ describe('dream retriage — reconcile matrix', () => {expect(await jobStatus(rig, aboveStale)).toBe('cancelled'); // converted_for_resubmitexpect(await jobStatus(rig, unscoredJob)).toBe('waiting');expect(await jobStatus(rig, unmatchedJob)).toBe('waiting');- expect(await jobStatus(rig, legacyJob)).toBe('waiting'); // legacy grammar → unmatched, untouched+ // #4250: a legacy-grammar row stranded in a provably-DEAD inline queue+ // is exactly the never-claimable orphan class doctor now flags — it+ // converts for resubmit instead of being invisibly stranded (pre-fix it+ // wasn't even selected). Legacy rows in live/non-inline queues stay out+ // of scope (the SELECT's queue arm only adds dream-inline rows).+ expect(await jobStatus(rig, legacyJob)).toBe('cancelled');expect(await jobStatus(rig, completedJob)).toBe('completed'); // terminal rows never selectedexpect(summary.queue.cancelled).toBe(1);- expect(summary.queue.converted_for_resubmit).toBe(1);+ expect(summary.queue.converted_for_resubmit).toBe(2); // aboveStale + legacy dead-queue rowexpect(summary.queue.kept_unscored).toBe(1);- // deleted-file only: the legacy dream:synth: key is excluded at the SQL- // LIKE 'dream:synth-v2:%' filter — it never even becomes a candidate.- expect(summary.queue.unmatched).toBe(1);- expect(summary.queue.candidates).toBe(4); // completed row is status-excluded as well+ expect(summary.queue.unmatched).toBe(1); // deleted-file synth-v2 key with no corpus match+ expect(summary.queue.candidates).toBe(5); // completed row is status-excludedexpect(process.exitCode ?? 0).toBe(0);} finally {await rig.cleanup();@@ -474,16 +477,18 @@ describe('dream retriage — reconcile matrix', () => {}}, 30_000);- test('SR-P2: a live cycle lock marks even OLD inline queues possibly-live (no conversions)', async () => {+ test('SR-P2/#4250: a live lock that could OWN the queue (acquired before its birth) keeps it possibly-live', async () => {const rig = await setupRig();try {const above = writeTranscript(rig.corpusDir, '2026-08-28-locked.txt');await seedScore(rig, above.filePath, above.hash, 0.9);- const job = await seedJob(rig, { key: synthKey('default', basename(above.filePath), above.hash16) });- // Simulate a running cycle: an unexpired cycle-lock row.+ // Queue born 2h ago (past the liveness grace); the running cycle's lock+ // was acquired BEFORE that, so it could own the queue — never convert.+ const queue = `dream-inline-${Date.now() - 2 * 3600_000}-deadbee1`;+ const job = await seedJob(rig, { key: synthKey('default', basename(above.filePath), above.hash16), queue });await rig.engine.executeRaw(- `INSERT INTO gbrain_cycle_locks (id, holder_pid, ttl_expires_at)- VALUES ('gbrain-cycle:default', 12345, NOW() + interval '10 minutes')`,+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, acquired_at, ttl_expires_at)+ VALUES ('gbrain-cycle:default', 12345, NOW() - interval '3 hours', NOW() + interval '10 minutes')`,);const { out } = await captureStdout(() => withoutAnthropicKey(() =>runDreamRetriage(rig.engine, ['--reconcile-queue', '--json'])));@@ -496,6 +501,49 @@ describe('dream retriage — reconcile matrix', () => {}}, 30_000);+ test('#4250: a live lock acquired AFTER the queue was born cannot own it — the old orphan converts', async () => {+ // The doctor↔retriage alignment fix: doctor flags a pre-lock orphan, so+ // retriage must be able to repair it even while a NEW cycle runs.+ const rig = await setupRig();+ try {+ const above = writeTranscript(rig.corpusDir, '2026-08-28-prelock.txt');+ await seedScore(rig, above.filePath, above.hash, 0.9);+ const queue = `dream-inline-${Date.now() - 2 * 3600_000}-deadbee2`;+ const job = await seedJob(rig, { key: synthKey('default', basename(above.filePath), above.hash16), queue });+ await rig.engine.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, acquired_at, ttl_expires_at)+ VALUES ('gbrain-cycle:default', 12345, NOW() - interval '30 minutes', NOW() + interval '10 minutes')`,+ );+ const { out } = await captureStdout(() => withoutAnthropicKey(() =>+ runDreamRetriage(rig.engine, ['--reconcile-queue', '--json'])));+ const summary = JSON.parse(out) as { queue: { kept_live_queue: number; converted_for_resubmit: number } };+ expect(await jobStatus(rig, job)).toBe('cancelled');+ expect(summary.queue.converted_for_resubmit).toBe(1);+ expect(summary.queue.kept_live_queue).toBe(0);+ } finally {+ await rig.cleanup();+ }+ }, 30_000);++ test('#4250: a NON-synth child (patterns-style key) in a provably-dead inline queue converts for resubmit', async () => {+ // Doctor's orphaned_private_queue check flags patterns queues too; the+ // advertised retriage repair must select and convert them, not report+ // unmatched.+ const rig = await setupRig();+ try {+ const queue = `dream-inline-${Date.now() - 2 * 3600_000}-deadbee3`;+ const job = await seedJob(rig, { key: 'patterns:child:not-a-synth-key', queue });+ const { out } = await captureStdout(() => withoutAnthropicKey(() =>+ runDreamRetriage(rig.engine, ['--reconcile-queue', '--json'])));+ const summary = JSON.parse(out) as { queue: { converted_for_resubmit: number; unmatched: number } };+ expect(await jobStatus(rig, job)).toBe('cancelled');+ expect(summary.queue.converted_for_resubmit).toBe(1);+ expect(summary.queue.unmatched).toBe(0);+ } finally {+ await rig.cleanup();+ }+ }, 30_000);+test('SR-P2: dry-run counts would-cancel unmatched rows instead of understating the preview', async () => {const rig = await setupRig();try {diff --git a/test/handlers.test.ts b/test/handlers.test.tsindex 7a4ec3d4f0..b926c9f821 100644--- a/test/handlers.test.ts+++ b/test/handlers.test.ts@@ -248,21 +248,20 @@ describe('autopilot-cycle handler — phase passthrough', () => {}}, 30_000);- test('empty phases array falls back to all phases (same as no phases)', async () => {+ test('empty phases array is an explicit no-op, never an implicit full run (#4250)', async () => {const handler = (worker as any).handlers.get('autopilot-cycle');- // Empty array should fall through to ALL_PHASES (same as omitting phases)+ // Pre-#4250 an explicitly-empty list silently fell through to ALL_PHASES —+ // the "silently convert an empty payload into a full run" footgun. It is+ // now an honest skip.const result = await handler({data: { repoPath: '/definitely-does-not-exist-for-phase-test', phases: [] },signal: { aborted: false } as any,job: { id: 12, name: 'autopilot-cycle' } as any,});- const report = (result as any).report;- // With all phases, filesystem phases fail on missing dir- const phaseNames = report.phases.map((p: any) => p.phase);- expect(phaseNames).toContain('lint');- expect(phaseNames).toContain('backlinks');- expect(phaseNames).toContain('sync');+ expect(result.status).toBe('skipped');+ expect(result.report.reason).toBe('empty_phase_list');+ expect(result.report.phases_rejected_by_normalization).toEqual([]);}, 30_000);test('non-array phases value is ignored (falls back to all)', async () => {