Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): --help --json prints one help document

garrytanf1bca19cecf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c67d52ff7e..142b11d7f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,11 +18,14 @@ identifiers and attribution are available in the pre-removal Git revision
**`gbrain dream --drain` stops as no progress when its batches only skip items the backlog keeps counting.** The drain checked for no progress only after a batch that extracted nothing and skipped nothing. A page the phase skips on every batch while the backlog still counts it kept that check from ever running, so the drain ran all 1,000 batches, held the cycle lock for minutes and ended `max_batches` with exit 11, which tells the caller to rerun a stop a rerun cannot clear. A batch that extracts nothing now always rechecks the backlog: when it did not shrink, the drain stops `no_progress` (`atom_drain_no_progress`, exit 1), and skips that do shrink it keep draining. Reported by @h6y3 (#8445).
+**`gbrain dream --help --json` prints its help as one JSON document.** Under `--json`, stdout carries only a JSON document, and dream printed its help as plain text, which went to stderr. So stdout was empty, the run exited 0 and logged a missing-document event that `gbrain doctor` counts under its agent-contract check. It now prints `{"command": "dream", "help": "<the help text>", "contract_version": 1}`, and `dream retriage --help --json` and `dream reset-key --help --json` do the same. `gbrain dream --help` without `--json` prints exactly the same text as before. Reported by @Kkkkkuro (#8510).
+
### Itemized changes
- `src/core/cycle/unindexed-files.ts`: `details.complete` also requires `errors.length === 0`. Test: `test/unindexed-files.test.ts` (a source whose `.git/HEAD` is unreadable: phase `warn`, one error, `complete: false`).
- `src/core/cycle/source-window.ts`: the listing instant and the last page's `updated_at` are formatted with `to_char(... AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`. Test: `test/sync-disabled-cycle-window.test.ts` (the real queued handler under `German, DMY` advances window by window; `German`, `SQL` and `Postgres` styles under a +05:45 time zone give ISO UTC cursors with microseconds and the same windows), now also run on Postgres by `test/e2e/sync-disabled-cycle-window-postgres.test.ts`.
- `src/core/cycle/extract-atoms-drain.ts`: the no-progress recount runs after every batch with `extracted === 0`, not only when `skipped` is also 0. Test: `test/extract-atoms-drain.test.ts` (a skip-only batch over a flat backlog stops `no_progress` after one batch; skip-only batches that shrink the backlog drain).
+- `src/cli/help/render.ts`: new `printHelpText(command, text, args)`, the `--help --json` document for a handler that prints its own help text; `src/commands/dream.ts`, `dream-retriage.ts` and `dream-reset-key.ts` print their help through it. Test: `test/dream-help-json-8510.test.ts` (the real CLI: one document per help, no `json_document_missing` event, plain `--help` stdout equal to the document text).
## [0.60.620.0] - 2026-11-09
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index bb019e0e4a..426e8a1168 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -12,7 +12,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. A notice's unrendered `Notic... (line truncated to 2000 chars)
- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).
- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output; a `pglite_busy` with reason `legacy_owner_unverified` renders its own ask_user fix, `retryable: false`, exit 3). Test: `test/cli-error-render.test.ts`.
-- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.
+- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`. #8510: `printHelpText(command, text, args)` gives the same `--help --json` contract to a handler that prints its own help text with no curated spec: one `{command, help, contract_version}` document under `--json`, the text unchanged otherwise; dream, `dream retriage` and `dream reset-key` use it (`test/dream-help-json-8510.test.ts`). Other self-help commands that declare `json` still print their help through console.log, which the guard sends to stderr.
- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.
- `src/cli/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no `=` token reaches a handler that would drop it. It also covers the hand-parsed `search modes|stats|tune|diagnose` subcommands, the validation-exempt paths (`jobs submit`, whose consent check reads the `=` spending cap, and `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which strips and applies the global flags, hands `auth local-writer` to its own parser and runs the unknown-flag validator, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys, all as main does). Per registered `--flag=value` token: a switch refuses (`invalid_params`, exit 2: a boolean in the command's own table, curated help or `SYNC_FLAGS` for sync, a `--no-` negation, the command's `COMMAND_SWITCHES`, or a name `knownSwitches()` finds boolean in the handler-free `OPERATION_MANIFEST` or any curated help, so `--yes=n` is never answered with `--yes <value>`); `EQUALS_READERS`, keyed by command or `command sub` (the `sync --status` alias reads as `sync status`, `forget --purge` is its own path, and `repos` reads the `sources` keys through `READER_ALIASES`), keeps the token where the handler on that path reads the `=` form itself, empty values included (that handler owns refusing them); elsewhere an empty or flag-like value refuses; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (`forget --purge --reason=3 34` purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (`extract links --source-id=x` walked every source), so keys name the narrowest path. A short flag never takes `=` (`-y=n` refuses). A bare `--` ends the scan only on `END_OF_OPTIONS` paths (`agent run`, `frontmatter validate`), whose handler stops there; `serve`, `auth`, `frontmatter generate`, `questions` and `agent logs` read flags after it, so past `--` an `=` token that is not a registered flag refuses (the unknown-flag validator stops at `--`). A true/false word or 0/1 on a flag with no table entry (`--apply=false`, `--expect=on`) refuses naming both readings, never `--apply <value>`, and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. On the hand-parsed `search` subcommands, which have no registry row, every `=` token but `--json=true` refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers on every path that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), `call`, `config set`, `eval brainbench` and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`) keep their argv. `scripts/generate-flag-registry.ts` skips this module. Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag, both-direction pins of `EQUALS_READERS` against every `=` reader in `src` and of `OWN_EQUALS_PARSERS` against every `=` option parser, stray-positional, dropped-scope, consent and `--` rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope, the direct `auth.ts` entry, `serve -- --access=` and `frontmatter generate` behind `--help` or `--` included).
- `src/cli/search-row-format.ts` — `formatSearchRow`: the human `gbrain search|query` line per row (`[score] slug -- preview`); a saved-fact row prints `fact:<fact_id> <entity>` and its date header and text on one line, never a page slug (#8411).
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index b2c2321d0c..127dc2e88f 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -17,7 +17,7 @@ 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. Its help names the per-source patterns key `dream:patterns:source:<id>`; doctor `dream_paid_loop` reports that prefix as the key's `key_prefix`.
-- `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). Every stop maps through `drainOutcome` (`src/core/cycle/extract-atoms-drain-outcome.ts`): exit 0 only for `stopped: drained` with `remaining: 0`; exit 11 (`BUDGET_STOP_EXIT_CODE`) for a retryable stop (`atom_drain_incomplete`: window, deadline, lock, batch cap, budget, a null count; `atom_drain_provider_failure` reasons `rate_limit`/`transient`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr and adding `resume_command` under `--json`; exit 1 for a stop a rerun cannot clear (`atom_drain_provider_failure` reasons `auth`/`billing`/`model_not_found`/`content_block`, `atom_drain_no_progress` over a counted backlog), printing the registry suggestion as a `Fix:` line and adding the rendered `fix` instead of `resume_command`. `--json` of any incomplete stop carries `status` (`incomplete` or `provider_failure`, never `ok`), `retryable`, `code` and `reason`; `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). `--help` (and the retriage and reset-key subverb help) prints through `printHelpText`, so `--help --json` is one `{command, help, contract_version}` document (#8510). 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). Every stop maps through `drainOutcome` (`src/core/cycle/extract-atoms-drain-outcome.ts`): exit 0 only for `stopped: drained` with `remaining: 0`; exit 11 (`BUDGET_STOP_EXIT_CODE`) for a retryable stop (`atom_drain_incomplete`: window, deadline, lock, batch cap, budget, a null count; `atom_drain_provider_failure` reasons `rate_limit`/`transient`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr and adding `resume_command` under `--json`; exit 1 for a stop a rerun cannot clear (`atom_drain_provider_failure` reasons `auth`/`billing`/`model_not_found`/`content_block`, `atom_drain_no_progress` over a counted backlog), printing the registry suggestion as a `Fix:` line and adding the rendered `fix` instead of `resume_command`. `--json` of any incomplete stop carries `status` (`incomplete` or `provider_failure`, never `ok`), `retryable`, `code` and `reason`; `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). Every stop maps through `drainOutcome` (`src/core/cycle/extract-atoms-drain-outcome.ts`): exit 0 only for `stopped: drained` with `remaining: 0`; exit 11 (`BUDGET_STOP_EXIT_CODE`) for a retryable stop (`atom_drain_incomplete`: window, deadline, lock, batch cap, budget, a null count; `atom_drain_provider_failure` reasons `rate_limit`/`transient`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr and adding `resume_command` under `--json`; exit 1 for a stop a rerun cannot clear (`atom_drain_provider_failure` reasons `auth`/`billing`/`model_not_found`/`content_block`, `atom_drain_no_progress` over a counted backlog), printing the registry suggestion as a `Fix:` line and adding the rendered `fix` instead of `resume_command`. `--json` of any incomplete stop carries `status` (`incomplete` or `provider_failure`, never `ok`), `retryable`, `code` and `reason`; `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.
diff --git a/src/cli/help/render.ts b/src/cli/help/render.ts
index 6d36ba26c0..04ee3d11a6 100644
--- a/src/cli/help/render.ts
+++ b/src/cli/help/render.ts
@@ -36,6 +36,16 @@ export function renderCuratedHelp(command: string, spec: CliHelpSpec): string {
return `${lines.join('\n')}\n`;
}
+/**
+ * #8510: a command's own help text, for a handler that prints its help without a curated spec. Under `--json` it is one
+ * `{command, help, contract_version}` document (the guard sends console.log to stderr, so fd 1 got nothing); otherwise the
+ * text exactly as before.
+ */
+export async function printHelpText(command: string, text: string, args: readonly string[]): Promise<void> {
+ if (jsonRequested(args)) await writeJsonDocument(JSON.stringify({ command, help: text, contract_version: CONTRACT_VERSION }));
+ else console.log(text);
+}
+
/** Prints the curated help when the command has one; returns false otherwise. */
export async function printCuratedHelp(command: string, args: readonly string[]): Promise<boolean> {
const spec = await loadCuratedHelp(command);
diff --git a/src/commands/dream-reset-key.ts b/src/commands/dream-reset-key.ts
index 44fb4e2c3b..f0ce3f3e0e 100644
--- a/src/commands/dream-reset-key.ts
+++ b/src/commands/dream-reset-key.ts
@@ -10,6 +10,7 @@ import {
import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
import { opError } from '../core/ops/contract.ts';
import { usageError, writeCliRefusal } from '../cli/cli-error.ts';
+import { printHelpText } from '../cli/help/render.ts';
const HELP = `Usage: gbrain dream reset-key <base-key>
gbrain dream reset-key --list [--json]
@@ -28,7 +29,7 @@ run read; a completed run resets it, so only consecutive deaths trip it.
`;
export async function runDreamResetKey(engine: BrainEngine | null, args: string[]): Promise<void> {
- if (args.includes('--help') || args.includes('-h')) { console.log(HELP); return; }
+ if (args.includes('--help') || args.includes('-h')) { await printHelpText('dream reset-key', HELP, args); return; }
const list = args.includes('--list');
const json = args.includes('--json');
const positional = args.filter(arg => !arg.startsWith('--'));
diff --git a/src/commands/dream-retriage.ts b/src/commands/dream-retriage.ts
index 93df76ba0e..689ac913cc 100644
--- a/src/commands/dream-retriage.ts
+++ b/src/commands/dream-retriage.ts
@@ -55,6 +55,7 @@ import { discoverTranscripts, conversationPagesOptedIn, withConversationPages }
import { passesTriageGate, rescueConfigOf } from '../core/cycle/triage-rescue.ts';
import { estimateTriageDecideUsd, resolveTriageDecide } from '../core/cycle/triage-decide.ts';
import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { printHelpText } from '../cli/help/render.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';
@@ -161,8 +162,8 @@ function parseRetriageArgs(args: string[]): RetriageArgs {
return out;
}
-function printRetriageHelp(): void {
- console.log(`gbrain dream retriage — re-score the corpus, reconcile the synth backlog
+function printRetriageHelp(args: string[]): Promise<void> {
+ return printHelpText('dream retriage', `gbrain dream retriage — re-score the corpus, reconcile the synth backlog
USAGE
gbrain dream retriage [flags]
@@ -211,7 +212,7 @@ the same passesTriageGate the synthesize fan-out reads)
legacy dream:synth: (v1) keys never touched
Cancelled rows release their idempotency slot, so lowering the threshold
-later cleanly re-submits the work.`);
+later cleanly re-submits the work.`, args);
}
interface QueueCandidate {
@@ -303,7 +304,7 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[
}
// IRON RULE: --help short-circuits before any engine-bearing work.
if (parsed.help) {
- printRetriageHelp();
+ await printRetriageHelp(args);
return;
}
if (engine === null) {
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index 975b91e71f..fb5eda5a52 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -36,6 +36,7 @@ import { jsonGuardActive, jsonRequested, setCliExitVerdict, writeJsonDocument }
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 { printHelpText } from '../cli/help/render.ts';
import { cliRenderContext, renderAction, shellQuote, type Action } from '../core/agent-output.ts';
import { codeEntry } from '../core/error-catalogue.ts';
import { fetchSource } from '../core/sources-load.ts';
@@ -375,8 +376,8 @@ async function resolveBrainDir(
return null;
}
-function printHelp() {
- console.log(`Usage: gbrain dream [options]
+function printHelp(args: string[]): Promise<void> {
+ return printHelpText('dream', `Usage: gbrain dream [options]
gbrain dream retriage [flags] (see: gbrain dream retriage --help)
gbrain dream reset-key <key> | --list (see: gbrain dream reset-key --help)
@@ -491,7 +492,7 @@ Configure synthesize:
Related:
gbrain autopilot --install # continuous maintenance as a daemon
gbrain autopilot # same maintenance cycle, scheduled
-`);
+`, args);
}
// ─── Human-friendly report printing ────────────────────────────────
@@ -756,7 +757,7 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
// ALWAYS prints help and exits 0, never reaching the engine-null gate
// below. If you reorder this, test/dream.test.ts ("--help --source whatever") fails.
if (opts.help) {
- printHelp();
+ await printHelp(args);
return;
}
diff --git a/test/dream-help-json-8510.test.ts b/test/dream-help-json-8510.test.ts
new file mode 100644
index 0000000000..c67683bb63
--- /dev/null
+++ b/test/dream-help-json-8510.test.ts
@@ -0,0 +1,49 @@
+/**
+ * #8510: `gbrain dream --help --json` runs under the CLI's --json document guard (dream declares
+ * `json: 'document'`), which sends console.log to stderr. The help went out through console.log, so fd 1
+ * carried nothing, the run exited 0 and recorded a json_document_missing agent-contract event that doctor
+ * counts. The real CLI, spawned with an empty GBRAIN_HOME, for the command and both subverbs.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const REPO = fileURLToPath(new URL('..', import.meta.url));
+
+async function runCli(home: string, argv: string[]) {
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', ...argv], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, code };
+}
+
+describe('#8510 dream --help --json', () => {
+ for (const [command, argv, usage] of [
+ ['dream', ['dream'], 'Usage: gbrain dream [options]'],
+ ['dream retriage', ['dream', 'retriage'], 'gbrain dream retriage'],
+ ['dream reset-key', ['dream', 'reset-key'], 'gbrain dream reset-key'],
+ ] as const) {
+ test(`${command} --help --json prints one help document; plain --help keeps its text`, async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-8510-'));
+ try {
+ const json = await runCli(home, [...argv, '--help', '--json']);
+ expect(json.code).toBe(0);
+ expect(json.stdout).not.toBe('');
+ const doc = JSON.parse(json.stdout);
+ expect(doc).toEqual({ command, help: expect.any(String), contract_version: 1 });
+ expect(doc.help).toContain(usage);
+ const events = join(home, '.gbrain', 'agent-contract', 'events.jsonl');
+ expect(existsSync(events) ? readFileSync(events, 'utf8') : '').not.toContain('json_document_missing');
+ const human = await runCli(home, [...argv, '--help']);
+ expect(human.code).toBe(0);
+ expect(human.stdout).toBe(`${doc.help}\n`);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 60_000);
+ }
+});