Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(dream): D2 one --json document on every path (cycle, drain, retriage, reset-key)

garrytanad9b65010d8a
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 9e63053dd2..2885ed19c6 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -7,8 +7,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.
-- `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; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. `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, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE=3` unless `stopped: drained` with `remaining: 0` (a null count is exit 3, never a drained success), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `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). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
+- `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; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. `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, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. 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). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-- `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; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `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, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE=3` unless `stopped: drained` with `remaining: 0` (a null count is exit 3, never a drained success), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `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). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
+- `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; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `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, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. 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). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index cd77bba8f2..7f9012120b 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -486,6 +486,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Cost preview requires yes. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |
+### cycle_failed
+
+<a id="cycle_failed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+
### d_sel_too_small
<a id="d_sel_too_small"></a>
diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.md
index f904fb2433..339b2dff7c 100644
--- a/docs/guides/exit-codes.md
+++ b/docs/guides/exit-codes.md
@@ -31,6 +31,7 @@ they need the user's confirmation (documented legacy; changing it is a v2 item).
| Command | Before | Now | Why |
|---|---|---|---|
| `gbrain embed --stale` time-budget stop | 3 | 11 | 3 means "ask the user first"; a budget stop means "run the resume command" |
+| `gbrain dream --drain` backlog left (window/deadline/lock stop, busy cycle lock) | 3 | 11 | a resumable stop; `--json` carries `resume_command` |
| `gbrain agent run … --follow` timeout | 3 | 124 | a timeout, not a consent stop; the job keeps running |
| `gbrain providers test` transient provider error | 3 | 1 (retryable) | retryable failure |
| `gbrain sources harden` with sources needing attention | 3 | 1 | failure for cron; the report names what to fix |
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
index a169374253..935e986d5a 100644
--- a/src/cli/cli-error.ts
+++ b/src/cli/cli-error.ts
@@ -62,6 +62,16 @@ export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOp
return r.exitCode;
}
+/**
+ * D2: a refusal that keeps its pre-v1 human stderr line verbatim (`human`,
+ * default the message) and, under `--json`, writes the envelope as the
+ * document. Returns the contract exit code.
+ */
+export function writeCliRefusal(e: OperationError, command: string, opts: { json: boolean; human?: string; legacy?: Record<string, unknown> }): number {
+ console.error(opts.human ?? e.message);
+ return writeCliError(e, command, { json: opts.json, stderr: false, ...(opts.legacy ? { legacy: opts.legacy } : {}) });
+}
+
function withoutUndefined(o: object): Record<string, unknown> {
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
}
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index d4a7ee740c..57b977dc6b 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -224,7 +224,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// retriage --help` printed the one-line dream stub instead of the retriage contract (outside-voice
// CX9).
// thin client: v0.31.1 (CDX-2 op coverage matrix): more local-only commands
- { name: 'dream', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/dream.ts') },
+ { name: 'dream', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/dream.ts') },
// System One decide: local CLI only (calibrate, receipts and proposals are trusted-local); help and a
// key-only probe answer without a brain, so the module opens its own engine.
{ name: 'decide', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/decide.ts') },
diff --git a/src/commands/db-repair.ts b/src/commands/db-repair.ts
index 1a64f380f8..b454daf349 100644
--- a/src/commands/db-repair.ts
+++ b/src/commands/db-repair.ts
@@ -76,7 +76,7 @@ import type { Action } from '../core/agent-output.ts';
import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { opError, type OperationError } from '../core/ops/contract.ts';
import type { RegistryCode } from '../core/error-registry.ts';
-import { writeCliError } from '../cli/cli-error.ts';
+import { writeCliError, writeCliRefusal } from '../cli/cli-error.ts';
class UnknownFlagError extends Error {}
@@ -318,8 +318,7 @@ function emit(json: boolean, report: JsonReport, humanLines: string[]): void {
/** A refusal before any probe: the human line on stderr (unchanged), the envelope under --json. Returns `exitCode`. */
function refuse(json: boolean, exitCode: number, human: string, code: RegistryCode, suggestion: string, fix?: Action): number {
- console.error(human);
- if (json) writeCliError(opError(code, human, suggestion, fix ? { fix } : {}), 'db-repair', { json: true, stderr: false });
+ writeCliRefusal(opError(code, human, suggestion, fix ? { fix } : {}), 'db-repair', { json });
return exitCode;
}
diff --git a/src/commands/dream-reset-key.ts b/src/commands/dream-reset-key.ts
index c981f64dc4..4b77e8820b 100644
--- a/src/commands/dream-reset-key.ts
+++ b/src/commands/dream-reset-key.ts
@@ -7,7 +7,9 @@ import {
countDeadDreamSubmissions, dreamBreakerBaseKey, dreamBreakerResetCommand, loadDreamBreakerThreshold,
resetDreamBreakerKey, DREAM_BREAKER_CONFIG_KEY, DREAM_BREAKER_KEY_PREFIXES,
} from '../core/cycle/dream-breaker.ts';
-import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { opError } from '../core/ops/contract.ts';
+import { usageError, writeCliRefusal } from '../cli/cli-error.ts';
const HELP = `Usage: gbrain dream reset-key <base-key>
gbrain dream reset-key --list [--json]
@@ -28,13 +30,13 @@ export async function runDreamResetKey(engine: BrainEngine | null, args: string[
const json = args.includes('--json');
const positional = args.filter(arg => !arg.startsWith('--'));
if (list === (positional.length === 1) || positional.length > 1) {
- console.error(HELP);
- setCliExitVerdict(2);
+ setCliExitVerdict(writeCliRefusal(usageError('gbrain dream reset-key takes exactly one of <base-key> or --list.',
+ 'Example: gbrain dream reset-key --list --json'), 'dream', { json, human: HELP }));
return;
}
if (!engine) {
- console.error('gbrain dream reset-key needs the brain database; the connection failed.');
- setCliExitVerdict(1);
+ setCliExitVerdict(writeCliRefusal(opError('database_error', 'gbrain dream reset-key needs the brain database; the connection failed.',
+ 'Fix the brain connection (`gbrain doctor --json` names the cause), then retry.'), 'dream', { json }));
return;
}
if (list) {
@@ -42,7 +44,7 @@ export async function runDreamResetKey(engine: BrainEngine | null, args: string[
const rows = await countDeadDreamSubmissions(engine);
const tripped = threshold === 0 ? [] : rows.filter(row => row.dead_submissions >= threshold);
if (json) {
- console.log(JSON.stringify({ threshold, enabled: threshold > 0, tripped: tripped.map(row => ({ ...row, reset_command: dreamBreakerResetCommand(row.base_key) })) }, null, 2));
+ await writeJsonDocument(JSON.stringify({ threshold, enabled: threshold > 0, tripped: tripped.map(row => ({ ...row, reset_command: dreamBreakerResetCommand(row.base_key) })) }, null, 2));
return;
}
if (threshold === 0) { console.log(`The paid-loop breaker is disabled (${DREAM_BREAKER_CONFIG_KEY}=0).`); return; }
@@ -53,11 +55,12 @@ export async function runDreamResetKey(engine: BrainEngine | null, args: string[
}
const baseKey = dreamBreakerBaseKey(positional[0]!);
if (!DREAM_BREAKER_KEY_PREFIXES.some(prefix => baseKey.startsWith(prefix))) {
- console.error(`Not a dream breaker key: ${baseKey}. Keys start with ${DREAM_BREAKER_KEY_PREFIXES.join(' or ')}; run gbrain dream reset-key --list.`);
- setCliExitVerdict(2);
+ setCliExitVerdict(writeCliRefusal(usageError(`Not a dream breaker key: ${baseKey}. Keys start with ${DREAM_BREAKER_KEY_PREFIXES.join(' or ')}; run gbrain dream reset-key --list.`,
+ 'Run `gbrain dream reset-key --list --json` for the tripped keys and their reset commands.'), 'dream', { json }));
return;
}
const before = (await countDeadDreamSubmissions(engine)).find(row => row.base_key === baseKey)?.dead_submissions ?? 0;
await resetDreamBreakerKey(engine, baseKey);
console.log(`Reset ${baseKey} (${before} dead submission(s) in the last 24h no longer count). The next dream cycle may submit it again.`);
+ if (json) await writeJsonDocument(JSON.stringify({ status: 'reset', base_key: baseKey, dead_submissions_before: before }));
}
diff --git a/src/commands/dream-retriage.ts b/src/commands/dream-retriage.ts
index 4e4016cfc6..ce651b903e 100644
--- a/src/commands/dream-retriage.ts
+++ b/src/commands/dream-retriage.ts
@@ -54,7 +54,9 @@ import {
import { discoverTranscripts } from '../core/cycle/transcript-discovery.ts';
import { passesTriageGate, rescueConfigOf } from '../core/cycle/triage-rescue.ts';
import { estimateTriageDecideUsd, resolveTriageDecide } from '../core/cycle/triage-decide.ts';
-import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { opError, type OperationError } from '../core/ops/contract.ts';
+import { usageError, writeCliRefusal } from '../cli/cli-error.ts';
import { MinionQueue } from '../core/minions/queue.ts';
import { canonicalLookup } from '../core/model-pricing.ts';
import { SPEND_CONFIRM_USD, UNPRICED_CONFIRM_FILES } from './dream-retriage-constants.ts';
@@ -282,14 +284,18 @@ async function retriageConsent(engine: BrainEngine | null, args: string[], json:
}, { json, env: engineConsentEnv(engine) });
}
+/** D2: the human line (unchanged), the envelope under --json, and the verdict. */
+function refuse(args: readonly string[], e: OperationError): void {
+ setCliExitVerdict(writeCliRefusal(e, 'dream', { json: jsonRequested(args) }));
+}
+
export async function runDreamRetriage(engine: BrainEngine | null, args: string[]): Promise<void> {
let parsed: RetriageArgs;
try {
parsed = parseRetriageArgs(args);
} catch (e) {
if (e instanceof UsageError) {
- console.error(`dream retriage: ${e.message} (see: gbrain dream retriage --help)`);
- setCliExitVerdict(2);
+ refuse(args, usageError(`dream retriage: ${e.message} (see: gbrain dream retriage --help)`, 'Run `gbrain dream retriage --help` for the accepted flags.'));
return;
}
throw e;
@@ -300,15 +306,15 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
return;
}
if (engine === null) {
- console.error('gbrain dream retriage requires a connected brain; run `gbrain init` first');
- setCliExitVerdict(1);
+ refuse(args, opError('database_error', 'gbrain dream retriage requires a connected brain; run `gbrain init` first',
+ 'Fix the brain connection (`gbrain doctor --json` names the cause), or run `gbrain init` first.'));
return;
}
const config = await loadSynthConfig(engine);
if (!config.corpusDir) {
- console.error('dream retriage: dream.synthesize.session_corpus_dir is unset — nothing to retriage');
- setCliExitVerdict(1);
+ refuse(args, opError('config_error', 'dream retriage: dream.synthesize.session_corpus_dir is unset — nothing to retriage',
+ 'Ask the user where their session transcripts live, then: gbrain config set dream.synthesize.session_corpus_dir <dir>'));
return;
}
const threshold = parsed.threshold ?? config.triage.threshold;
@@ -382,10 +388,9 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
// CX3: --max-usd is estimate-based; an unpriced model would silently
// disable the budget the operator explicitly asked for — refuse instead.
if (parsed.maxUsd !== null && perFileUsd === null) {
- console.error(
+ refuse(args, usageError(
`dream retriage: --max-usd requires a priced model; "${triageModel}" has no CANONICAL_PRICING entry`,
- );
- setCliExitVerdict(2);
+ 'Drop --max-usd, or register the model\'s price with `gbrain pricing set` (look up its per-token rate first).'));
return;
}
// The frontier audit spends too (security review): fold its worst case
@@ -399,11 +404,10 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
// audit spend cannot be estimated.
const auditUnpriced = parsed.auditRejects !== null && auditPerFileUsd === null;
if (parsed.maxUsd !== null && auditUnpriced) {
- console.error(
+ refuse(args, usageError(
`dream retriage: --max-usd with --audit-rejects requires a priced synthesis model; ` +
`"${config.model}" has no CANONICAL_PRICING entry`,
- );
- setCliExitVerdict(2);
+ 'Drop --max-usd, or register the model\'s price with `gbrain pricing set` (look up its per-token rate first).'));
return;
}
const auditEstimateUsd = parsed.auditRejects !== null && auditPerFileUsd !== null
@@ -505,11 +509,10 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
// often than it means every file was deleted. Refuse to cancel-unmatched
// in that state — a transient outage must not erase the retry frontier.
if (parsed.cancelUnmatched && transcripts.length === 0 && rows.length > 0) {
- console.error(
+ refuse(args, usageError(
`dream retriage: discovery found 0 transcripts but ${rows.length} queued job(s) exist; ` +
'refusing --cancel-unmatched (corpus may be unreachable). Fix discovery or drop the flag.',
- );
- setCliExitVerdict(2);
+ 'Check that dream.synthesize.session_corpus_dir is reachable, or run without --cancel-unmatched.'));
return;
}
reconcile = {
@@ -782,7 +785,7 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
};
if (parsed.json) {
- console.log(JSON.stringify(summary, null, 2));
+ await writeJsonDocument(JSON.stringify(summary, null, 2));
} else {
const would = parsed.dryRun ? ' (dry-run: no cancels performed)' : '';
console.log(`[retriage] ${summary.discovered} discovered | ${summary.pass} pass @ threshold ${threshold} | ` +
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index bcad65f3e8..4445cbfaa9 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -32,7 +32,10 @@ import {
type CycleReport,
} from '../core/cycle.ts';
import { ALL_SOURCES, isResolverUserError, resolveImplicitDefaultSourceId, resolveSourceId } from '../core/source-resolver.ts';
-import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { jsonGuardActive, jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { BUDGET_STOP_EXIT_CODE } from '../core/exit-codes.ts';
+import { opError, type OperationError } from '../core/ops/contract.ts';
+import { usageError, writeCliError, writeCliRefusal } from '../cli/cli-error.ts';
import { fetchSource } from '../core/sources-load.ts';
import { existsSync } from 'fs';
import { resolve } from 'node:path';
@@ -102,8 +105,17 @@ interface DreamArgs {
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const DEFAULT_DRAIN_WINDOW_SECONDS = 300;
-/** Exit code for "drain ran but the backlog isn't empty — run again". */
-const EXIT_DRAIN_INCOMPLETE = 3;
+/** Exit code for "drain ran but the backlog isn't empty — run again" (A3: a resumable stop, never 3). */
+const EXIT_DRAIN_INCOMPLETE = BUDGET_STOP_EXIT_CODE;
+
+/** D2: the human stderr line (unchanged) plus, under --json, the envelope as the document; then exit. */
+function dreamExit(e: OperationError, json = jsonRequested(process.argv.slice(2))): never {
+ process.exit(writeCliRefusal(e, 'dream', { json }));
+}
+
+function sourceError(e: Error): OperationError {
+ return opError('unknown_source', e.message, 'Run `gbrain sources list` for the registered source ids, then pass one with --source.');
+}
/**
* Collect every occurrence of `--<flag> <value>` in argv. Used to
@@ -131,10 +143,10 @@ function parseArgs(args: string[]): DreamArgs {
// ran phase a alone and exited 0 with a report covering one phase. Each
// value is validated, order is preserved, repeats of the same value
// collapse (same contract as the repeated --source handling below).
+ const json = jsonRequested(args);
const phaseValues = collectFlagValues(args, '--phase');
if (phaseValues === null) {
- console.error('--phase <name>: missing value. Usage: gbrain dream --phase <name>');
- process.exit(2);
+ dreamExit(usageError('--phase <name>: missing value. Usage: gbrain dream --phase <name>', 'Example: gbrain dream --phase lint'), json);
}
// issue #2860 (Codex P3): captured BEFORE --input/--drain get a chance to
// implicitly default `phases` below, so --once's validation can require
@@ -147,8 +159,7 @@ function parseArgs(args: string[]): DreamArgs {
let phases: CyclePhase[] = [];
for (const rawPhase of phaseValues) {
if (!(ALL_PHASES as string[]).includes(rawPhase)) {
- console.error(`Unknown phase "${rawPhase}". Valid: ${ALL_PHASES.join(', ')}`);
- process.exit(1);
+ dreamExit(usageError(`Unknown phase "${rawPhase}". Valid: ${ALL_PHASES.join(', ')}`, 'Example: gbrain dream --phase lint'), json);
}
if (!phases.includes(rawPhase as CyclePhase)) phases.push(rawPhase as CyclePhase);
}
@@ -162,33 +173,28 @@ function parseArgs(args: string[]): DreamArgs {
const dateIdx = args.indexOf('--date');
const date = dateIdx !== -1 ? args[dateIdx + 1] ?? null : null;
if (date && !ISO_DATE_RE.test(date)) {
- console.error(`--date must be YYYY-MM-DD; got "${date}"`);
- process.exit(2);
+ dreamExit(usageError(`--date must be YYYY-MM-DD; got "${date}"`, 'Example: gbrain dream --phase synthesize --date 2026-01-31'), json);
}
const fromIdx = args.indexOf('--from');
const from = fromIdx !== -1 ? args[fromIdx + 1] ?? null : null;
if (from && !ISO_DATE_RE.test(from)) {
- console.error(`--from must be YYYY-MM-DD; got "${from}"`);
- process.exit(2);
+ dreamExit(usageError(`--from must be YYYY-MM-DD; got "${from}"`, 'Example: gbrain dream --phase synthesize --from 2026-01-01 --to 2026-01-31'), json);
}
const toIdx = args.indexOf('--to');
const to = toIdx !== -1 ? args[toIdx + 1] ?? null : null;
if (to && !ISO_DATE_RE.test(to)) {
- console.error(`--to must be YYYY-MM-DD; got "${to}"`);
- process.exit(2);
+ dreamExit(usageError(`--to must be YYYY-MM-DD; got "${to}"`, 'Example: gbrain dream --phase synthesize --from 2026-01-01 --to 2026-01-31'), json);
}
if (from && to && from > to) {
- console.error(`--from (${from}) is after --to (${to}); empty range`);
- process.exit(2);
+ dreamExit(usageError(`--from (${from}) is after --to (${to}); empty range`, 'Pass --from on or before --to.'), json);
}
// --input + --date / --from / --to is incoherent: --input is a single
// file, the date filters scan a directory.
if (inputFile && (date || from || to)) {
- console.error('--input cannot be combined with --date / --from / --to');
- process.exit(2);
+ dreamExit(usageError('--input cannot be combined with --date / --from / --to', 'Use --input <file> alone, or the date filters alone.'), json);
}
// --input implies --phase synthesize.
@@ -205,29 +211,24 @@ function parseArgs(args: string[]): DreamArgs {
const sourceValues = collectFlagValues(args, '--source');
const sourceIdValues = collectFlagValues(args, '--source-id');
if (sourceValues === null) {
- console.error('--source <id>: missing value. Usage: gbrain dream --source <source-id>');
- process.exit(2);
+ dreamExit(usageError('--source <id>: missing value. Usage: gbrain dream --source <source-id>', 'Example: gbrain dream --source default'), json);
}
if (sourceIdValues === null) {
- console.error('--source-id <id>: missing value. Usage: gbrain dream --source-id <source-id>');
- process.exit(2);
+ dreamExit(usageError('--source-id <id>: missing value. Usage: gbrain dream --source-id <source-id>', 'Example: gbrain dream --source-id default'), json);
}
const uniqSource = Array.from(new Set(sourceValues));
const uniqSourceId = Array.from(new Set(sourceIdValues));
if (uniqSource.length > 1) {
- console.error(`specify --source once; got [${uniqSource.map(v => `"${v}"`).join(', ')}]`);
- process.exit(2);
+ dreamExit(usageError(`specify --source once; got [${uniqSource.map(v => `"${v}"`).join(', ')}]`, 'Run one dream per source: gbrain dream --source <id>.'), json);
}
if (uniqSourceId.length > 1) {
- console.error(`specify --source-id once; got [${uniqSourceId.map(v => `"${v}"`).join(', ')}]`);
- process.exit(2);
+ dreamExit(usageError(`specify --source-id once; got [${uniqSourceId.map(v => `"${v}"`).join(', ')}]`, 'Run one dream per source: gbrain dream --source <id>.'), json);
}
if (uniqSource.length === 1 && uniqSourceId.length === 1 && uniqSource[0] !== uniqSourceId[0]) {
- console.error(
+ dreamExit(usageError(
`use --source OR --source-id, not both (different values): ` +
`--source="${uniqSource[0]}" vs --source-id="${uniqSourceId[0]}"`,
- );
- process.exit(2);
+ 'Pass one of --source / --source-id.'), json);
}
const source = uniqSource[0] ?? uniqSourceId[0] ?? null;
@@ -240,16 +241,14 @@ function parseArgs(args: string[]): DreamArgs {
if (windowIdx !== -1) {
const raw = args[windowIdx + 1];
if (raw === undefined || !/^\d+$/.test(raw.trim()) || parseInt(raw, 10) <= 0) {
- console.error(`--window must be a positive integer (seconds); got "${raw}"`);
- process.exit(2);
+ dreamExit(usageError(`--window must be a positive integer (seconds); got "${raw}"`, 'Example: gbrain dream --drain --window 300'), json);
}
windowSeconds = parseInt(raw, 10);
}
if (drain) {
if (phases.length === 0) phases = ['extract_atoms'];
else if (phases.length > 1 || phases[0] !== 'extract_atoms') {
- console.error(`--drain currently supports only --phase extract_atoms (got "${phases.join(', ')}")`);
- process.exit(2);
+ dreamExit(usageError(`--drain currently supports only --phase extract_atoms (got "${phases.join(', ')}")`, 'Example: gbrain dream --drain --phase extract_atoms'), json);
}
}
@@ -272,28 +271,26 @@ function parseArgs(args: string[]): DreamArgs {
const once = args.includes('--once');
const wantsHelp = args.includes('--help') || args.includes('-h');
if (once && !phaseWasExplicit && !wantsHelp) {
- console.error(
+ dreamExit(usageError(
'--once requires an explicit --phase <name> (bypasses that one ' +
'phase\'s dream.<phase>.enabled / cycle.<phase>.enabled gate for ' +
'this run only; never touches config). A phase implied by --input ' +
'or --drain does not count — --once would silently do nothing for ' +
'those. Usage: gbrain dream --phase <name> --once',
- );
- process.exit(2);
+ 'Example: gbrain dream --phase synthesize --once'), json);
}
// #4493 corollary: --once bypasses ONE phase's enabled gate; with several
// named phases there is no single target, and force-enabling them all at
// once is the surprise-spend risk #2860 exists to prevent.
if (once && phases.length > 1 && !wantsHelp) {
- console.error(
+ dreamExit(usageError(
`--once supports a single --phase target; got [${phases.join(', ')}]. ` +
'Run each phase in its own --phase <name> --once invocation.',
- );
- process.exit(2);
+ 'Example: gbrain dream --phase synthesize --once'), json);
}
return {
- json: args.includes('--json'),
+ json,
dryRun: args.includes('--dry-run'),
pull: args.includes('--pull'),
phases,
@@ -336,8 +333,7 @@ async function resolveBrainDir(
): Promise<string | null> {
if (explicit) {
if (!existsSync(explicit)) {
- console.error(`--dir path does not exist: ${explicit}`);
- process.exit(1);
+ dreamExit(opError('not_found', `--dir path does not exist: ${explicit}`, 'Pass an existing brain directory to --dir, or omit it to use the configured source.'));
}
// Resolve to absolute so downstream writeFileSync(join(brainDir, slug))
// can't silently land at cwd when explicit is `.` / `./brain` / etc.
@@ -606,7 +602,7 @@ async function runDrain(
if (opts.dryRun) {
const remaining = await countExtractAtomsBacklog(engine, extractionSourceId);
if (opts.json) {
- console.log(JSON.stringify({ phase: 'extract_atoms', status: 'ok', dry_run: true, extracted: 0, skipped: 0, remaining, batches: 0, stopped: 'window', failure_count: 0, failures: [], omitted_failure_count: 0, last_error: null }, null, 2));
+ await writeJsonDocument(JSON.stringify({ phase: 'extract_atoms', status: 'ok', dry_run: true, extracted: 0, skipped: 0, remaining, batches: 0, stopped: 'window', failure_count: 0, failures: [], omitted_failure_count: 0, last_error: null, resume_command: drainCommand(opts) }, null, 2));
} else {
console.log(`[drain] dry-run: ${remaining ?? '?'} page(s) eligible for atom extraction (no work done)`);
}
@@ -632,7 +628,7 @@ async function runDrain(
} catch (e) {
if (e instanceof LockUnavailableError) {
if (opts.json) {
- console.log(JSON.stringify({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running' }, null, 2));
+ await writeJsonDocument(JSON.stringify({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running', resume_command: drainCommand(opts) }, null, 2));
} else {
console.log('[drain] skipped: another cycle holds the lock (cycle_already_running) — run again shortly');
}
@@ -658,7 +654,8 @@ async function runDrain(
);
}
if (opts.json) {
- console.log(JSON.stringify(result, null, 2));
+ const done = result.stopped === 'drained' && result.remaining === 0;
+ await writeJsonDocument(JSON.stringify(done ? result : { ...result, resume_command: drainCommand(opts) }, null, 2));
} else {
console.log(`[drain] extracted ${result.extracted} atom(s) across ${result.batches} batch(es); ${result.remaining ?? '?'} remaining (stopped: ${result.stopped})`);
}
@@ -666,11 +663,15 @@ async function runDrain(
if (result.stopped === 'drained' && result.remaining === 0) return;
process.stderr.write(
`[drain] stopped: ${result.stopped}; ${result.remaining ?? '?'} page(s) remaining. ` +
- `Rerun: gbrain dream --drain --window ${opts.windowSeconds}${opts.source ? ` --source ${opts.source}` : ''}\n`,
+ `Rerun: ${drainCommand(opts)}\n`,
);
process.exit(EXIT_DRAIN_INCOMPLETE);
}
+function drainCommand(opts: DreamArgs): string {
+ return `gbrain dream --drain --window ${opts.windowSeconds}${opts.source ? ` --source ${opts.source}` : ''}`;
+}
+
export async function runDream(engine: BrainEngine | null, args: string[]): Promise<CycleReport | void> {
// ─── `dream retriage` subverb (#4152) — dispatched BEFORE parseArgs so its
// flag set never collides with the cycle flags. `dream --help` never reaches
@@ -699,11 +700,10 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
const RETRIAGE_ONLY_FLAGS = ['--reconcile-queue', '--cancel-unmatched', '--audit-rejects'];
const stray = args.find(a => RETRIAGE_ONLY_FLAGS.includes(a));
if (stray) {
- console.error(
+ setCliExitVerdict(writeCliRefusal(usageError(
`gbrain dream: ${stray} belongs to the 'retriage' subcommand — ` +
`did you mean: gbrain dream retriage ${args.join(' ')}`,
- );
- setCliExitVerdict(2);
+ `Run it as: gbrain dream retriage ${args.join(' ')}`), 'dream', { json: jsonRequested(args) }));
return;
}
}
@@ -748,10 +748,7 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
try {
implicitDefaultSourceId = await resolveImplicitDefaultSourceId(engine);
} catch (e) {
- if (isResolverUserError(e)) {
- console.error((e as Error).message);
- process.exit(1);
- }
+ if (isResolverUserError(e)) dreamExit(sourceError(e as Error), opts.json);
throw e;
}
// Gated on an EMPTY env, not on !envScoped: an explicit GBRAIN_SOURCE=__all__
@@ -763,21 +760,17 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
}
if (opts.source !== null || envScoped) {
if (engine === null) {
- console.error(
+ dreamExit(opError('database_error',
'gbrain dream --source <id> / GBRAIN_SOURCE=<id> requires a connected brain ' +
'(no engine available); omit the source scope or run `gbrain init` first',
- );
- process.exit(1);
+ 'Fix the brain connection (`gbrain doctor --json` names the cause), or run without a source scope.'), opts.json);
}
try {
// A null explicit falls through to tier 2 (GBRAIN_SOURCE: validate +
// assertSourceExists) — the recall.ts pattern.
resolvedSourceId = await resolveSourceId(engine, opts.source);
} catch (e) {
- if (isResolverUserError(e)) {
- console.error((e as Error).message);
- process.exit(1);
- }
+ if (isResolverUserError(e)) dreamExit(sourceError(e as Error), opts.json);
throw e; // genuine bugs propagate with stack trace
}
// #4700 mirror of the path-derived branch below: an env scope naming the
@@ -794,11 +787,10 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
// doesn't project the archived column, so it cannot be used here.
const src = await fetchSource(engine, resolvedSourceId);
if (src?.archived === true) {
- console.error(
+ dreamExit(opError('unknown_source',
`source ${resolvedSourceId} is archived; restore with ` +
`\`gbrain sources restore ${resolvedSourceId}\` before cycling`,
- );
- process.exit(1);
+ `Ask the user whether to restore it (gbrain sources restore ${resolvedSourceId}), then run dream again.`), opts.json);
}
}
@@ -808,11 +800,10 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
// no checkout, the cycle skips filesystem phases and runs DB-only phases
// (resolve_symbol_edges, embed, orphans, ...) — the postgres support path.
if (brainDir === null && engine === null) {
- console.error(
+ dreamExit(opError('no_brain',
'No brain directory found and no database connection. ' +
'Pass --dir <path> or configure a brain via `gbrain init`.',
- );
- process.exit(1);
+ 'Pass --dir <path>, fix the brain connection, or run `gbrain init --pglite --no-embedding`.'), opts.json);
}
// #1869: a path-scoped run (--dir, or the configured sync.repo_path) whose
@@ -844,8 +835,8 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
// ─── issue #1678: bounded single-hold extract_atoms drain ──────────
if (opts.drain) {
if (engine === null) {
- console.error('gbrain dream --drain requires a connected brain (no engine available)');
- process.exit(1);
+ dreamExit(opError('database_error', 'gbrain dream --drain requires a connected brain (no engine available)',
+ 'Fix the brain connection (`gbrain doctor --json` names the cause), then run the drain again.'), opts.json);
}
return runDrain(engine, opts, resolvedSourceId, brainDir);
}
@@ -873,18 +864,20 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
onceForPhase: opts.once ? opts.phases[0]! : undefined,
});
- if (opts.json) {
- console.log(JSON.stringify(report, null, 2));
- } else {
- printHuman(report);
- }
-
// Exit non-zero when the cycle failed overall (helps cron spot real problems).
// 'partial' is not a failure — it means some phase warned but the cycle ran —
// except when a phase threw and was contained so later phases could run.
- if (report.status === 'failed' || report.phases.some(p => p.details?.contained === true)) {
- process.exit(1);
- }
+ const failed = report.status === 'failed' || report.phases.some(p => p.details?.contained === true);
+ if (!opts.json) printHuman(report);
+ else if (!failed || !jsonGuardActive()) await writeJsonDocument(JSON.stringify(report, null, 2));
+ else {
+ // D2: under the --json guard a failed cycle is one envelope leading with the CycleReport keys.
+ const bad = report.phases.filter(p => p.status === 'fail' || p.details?.contained === true).map(p => p.phase);
+ writeCliError(opError('cycle_failed', `The dream cycle ${report.status === 'failed' ? 'failed' : 'contained a phase that threw'}${bad.length ? ` (${bad.join(', ')})` : ''}.`,
+ `Read phases[].error for the cause, fix it, then rerun the phase: gbrain dream --phase ${bad[0] ?? '<phase>'}`),
+ 'dream', { json: true, stderr: false, legacy: { ...report } });
+ }
+ if (failed) process.exit(1);
return report;
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 56098c3564..f3e659ac57 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -95,6 +95,7 @@ export const CODES = {
consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },
cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },
cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },
+ cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
d_sel_too_small: { class: 'caller', summary: "The selection split has too few tasks for meaningful validation." },
database_error: { class: 'server', summary: "The brain database could not be reached or refused the operation." },
demo_graph_failed: { class: 'server', summary: "The fictional graph did not verify." },
diff --git a/test/cli-contract.serial.test.ts b/test/cli-contract.serial.test.ts
index c3fd34eff9..0dbf10ce97 100644
--- a/test/cli-contract.serial.test.ts
+++ b/test/cli-contract.serial.test.ts
@@ -90,6 +90,7 @@ const JSON_ROWS: Record<string, JsonRow> = {
sync: { ok: ['sync', '--source', 'notes', '--no-pull', '--json'], fail: ['sync', '--source', 'notes', '--json'], failOnBrain: true },
embed: { ok: ['embed', '--stale', '--json'], fail: ['embed', '--all', '--json'], failOnBrain: true },
'db-repair': { ok: ['db-repair', '--json'], fail: ['db-repair', '--json'], failOnBrain: true, okE2E: 'test/e2e/cli-json-commands-postgres.test.ts' },
+ dream: { ok: ['dream', '--json', '--phase', 'lint'], fail: ['dream', '--json', '--phase', 'garbage'] },
'post-upgrade': { ok: ['post-upgrade', '--json', '--no-autopilot-install'], fail: ['post-upgrade', '--bogus', '--json'], okOnEmpty: true },
'apply-migrations': { ok: ['apply-migrations', '--dry-run', '--json'], fail: ['apply-migrations', '--json', '--migration', '9.9.9'], failOnBrain: true },
};
diff --git a/test/dream-drain-failure-summary.serial.test.ts b/test/dream-drain-failure-summary.serial.test.ts
index 5311723ef7..3ff5b9e0fb 100644
--- a/test/dream-drain-failure-summary.serial.test.ts
+++ b/test/dream-drain-failure-summary.serial.test.ts
@@ -162,18 +162,18 @@ describe('dream --drain failure summary (#4730)', () => {
});
describe('dream --drain wiring and exit codes (#1678)', () => {
- test('exits 3 while backlog remains or the final count is unknown', async () => {
+ test('exits 11 (resumable stop; A3 reserves 3 for confirmation_required) while backlog remains or the final count is unknown', async () => {
for (const remaining of [4, null]) {
nextResult = baseResult({ remaining });
- expect((await runDrainCaptured([])).exitCode, String(remaining)).toBe(3);
+ expect((await runDrainCaptured([])).exitCode, String(remaining)).toBe(11);
}
});
- test('a held cycle lock reports cycle_already_running and exits 3', async () => {
+ test('a held cycle lock reports cycle_already_running and exits 11', async () => {
nextResult = new LockUnavailableError('gbrain-cycle');
const r = await runDrainCaptured(['--json']);
- expect(JSON.parse(r.stdout.join('\n'))).toEqual({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running' });
- expect(r.exitCode).toBe(3);
+ expect(JSON.parse(r.stdout.join('\n'))).toEqual({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running', resume_command: 'gbrain dream --drain --window 300' });
+ expect(r.exitCode).toBe(11);
});
test('--window sets the drain budget (default 300 s) and --source reaches the shared helper', async () => {
@@ -196,25 +196,25 @@ describe('dream --drain wiring and exit codes (#1678)', () => {
});
});
-// #5809 / #5832 stop contract: every stop that is not `drained` keeps exit 3,
+// #5809 / #5832 stop contract: every stop that is not `drained` exits 11 (was 3; A3),
// prints the drain JSON, and names the exact rerun command on stderr.
describe('dream --drain stop contract (#5809)', () => {
test.each([
{ stopped: 'window' as const, remaining: 12 },
{ stopped: 'deadline' as const, remaining: 30 },
{ stopped: 'lock_lost' as const, remaining: 8 },
- ])('a $stopped stop prints the JSON, exits 3 and names the rerun command', async ({ stopped, remaining }) => {
+ ])('a $stopped stop prints the JSON, exits 11 and names the rerun command', async ({ stopped, remaining }) => {
nextResult = baseResult({ stopped, remaining, extracted: 4, batches: 2 });
const r = await runDrainCaptured(['--json', '--window', '90']);
- expect(JSON.parse(r.stdout.join('\n'))).toMatchObject({ stopped, remaining, extracted: 4, batches: 2 });
- expect(r.exitCode).toBe(3);
+ expect(JSON.parse(r.stdout.join('\n'))).toMatchObject({ stopped, remaining, extracted: 4, batches: 2, resume_command: 'gbrain dream --drain --window 90' });
+ expect(r.exitCode).toBe(11);
expect(r.stderr).toContain(`[drain] stopped: ${stopped}; ${remaining} page(s) remaining. Rerun: gbrain dream --drain --window 90`);
});
- test('a provider_failure stop with an empty final recount still exits 3 (only drained exits 0)', async () => {
+ test('a provider_failure stop with an empty final recount still exits 11 (only drained exits 0)', async () => {
nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', remaining: 0 });
const r = await runDrainCaptured([]);
- expect(r.exitCode).toBe(3);
+ expect(r.exitCode).toBe(11);
expect(r.stderr).toContain('Rerun: gbrain dream --drain --window 300');
});