Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(setup): relay first-run settings in the install reply instead of init's standalone output

garrytan7ef150d7a2a4
diff --git a/AGENTS.md b/AGENTS.md
index b55b7e8787..b584f77970 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,7 +33,13 @@ start here.
default but printed a 9-cell cost matrix (mode × downstream model)
preceded by `[AGENT]` markers. You MUST relay the matrix to the operator
and confirm their choice before continuing. Cost spread between corners
- is about 200x — silent acceptance is the wrong default. See
+ is about 200x — silent acceptance is the wrong default. After
+ `gbrain setup <harness>` the harness is already wired when the matrix
+ appears in setup's one first-run settings block, so there is nothing left
+ to continue: relay the matrix and the other settings in the reply that
+ reports the install, as the settings in effect and how to change them,
+ and apply the user's choice when they give it. Don't end the install on a
+ question that needs another turn before memory works. See
[`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) Step 3.5 for the
exact ask-the-user protocol. The same banner fires on `gbrain post-upgrade`
for a brain created before v0.32.3, when search modes arrived.
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 3c308e6c38..7e6b5c250e 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -4,7 +4,7 @@ Read this file, then follow the path appropriate to the user’s request. Defaul
> **Choose the installation path first.** Inside **[Grok Bot](docs/guides/grok-bot.md)** or **[Muse](docs/guides/muse.md)**, use their dedicated guide: the recommended shape keeps the brain on the user's own computer, published with `gbrain mcp expose --funnel` ([remote MCP](docs/guides/remote-mcp.md)), and installs the thin CLI inside the agent; `scripts/setup-in-agent.sh` is the in-agent alternative, and its receipt tracks repair and native enablement. To make a brain on this computer reachable from the user's other devices, apps, or cloud agents over MCP, follow the **[remote MCP guide](docs/guides/remote-mcp.md)** (`gbrain mcp expose`; confirm the plan before installing Tailscale or a service; `--funnel` only for cloud agents). For an **[existing hosted brain](docs/guides/hosted-harness-access.md)**, choose the harness's native OAuth/PKCE flow or a private machine handoff. Owner login, client management, permissions, and revocation use the separate [MCP administration](docs/mcp/ADMIN.md) path. This guide covers a local brain for other existing agents.
>
-> **Memory-only path:** install → initialize → relay and confirm the Step 3.5 search-mode choice → connect the harness → verify memory. Skip identity replacement, private-repo bootstrap, automatic capture, cron installation, and paid enrichment unless requested. A keyword-only brain needs no API key. The required search-mode choice still applies; published API cost examples are not prices for the user’s harness subscription.
+> **Memory-only path:** install → initialize → relay and confirm the Step 3.5 search-mode choice → connect the harness → verify memory (with `gbrain setup <harness>`, initialize and connect are one command and the search-mode choice is relayed in the reply that reports the install). Skip identity replacement, private-repo bootstrap, automatic capture, cron installation, and paid enrichment unless requested. A keyword-only brain needs no API key. The required search-mode choice still applies; published API cost examples are not prices for the user’s harness subscription.
>
> Only if the user asks for a **new persistent personal agent** with identity and a private repo, follow `BOOTSTRAP_FOR_AGENTS.md`.
@@ -114,9 +114,14 @@ gbrain setup claude-code --dry-run --json # the resolved target; writes nothin
gbrain setup claude-code --json # brain (if none) + MCP + read-context hooks, verified
```
-It runs `gbrain init --pglite --no-embedding` only when no brain exists, and its
-`--json` document carries init's first-run decision bundle in `notices`: relay
-the search-mode matrix (Step 3.5) and the decisions in one reply. Capture
+It runs `gbrain init --pglite --no-embedding` only when no brain exists and
+prints init's first-run decision bundle once, after the wiring and its smoke
+check (an `[AGENT]` block in human output, `notices` in `--json`), without
+`harness_wiring`, which setup just did. Relay the search-mode matrix (Step 3.5)
+and the other settings in the reply that reports the install, as the settings
+in effect and how to change them; nothing waits on the answer, so don't end
+the install on a question, and apply an answer with its option's command
+whenever the user gives one. Capture
(`--capture`) and providers (`--providers`) stay off unless the user accepts
them. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) means
another owner or a hosted brain holds the target; follow its `fix`.
@@ -234,6 +239,12 @@ and `conservative` when your subagent tier is Haiku-class or neither exists. The
included the cost matrix below preceded by `[AGENT]` markers. You must NOT
silently accept the default. Stop and ask the operator.
+After `gbrain setup <harness>` the harness is already wired when the matrix
+appears, so there is nothing to stop before: show the matrix and the applied
+mode in the reply that reports the install, as a choice the user can make at
+any time, and run `gbrain config set search.mode <mode>` when they pick one.
+Don't hold the install open for the answer.
+
If you already know the operator's choice, record it at install time instead:
`gbrain init --search-mode <conservative|balanced|tokenmax>` stores it as the
operator's (`search.mode_source: operator`) and init asks no `search_mode`
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 2b33b565f3..92a2e41ef6 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -15,7 +15,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `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/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/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.
-- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only. `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.test.ts`.
+- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only, and `setupFirstRunNotices` is `gbrain setup`'s form (from `init --json`: `harness_wiring` dropped, `why`/`user_message` framed as settings in effect that the agent relays in the install reply instead of a reply-to-continue question; Cat 41 wave 2, pinned by `test/init-first-run.test.ts`). `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.test.ts`.
- `src/core/onboard/mcp-onboarding.ts` — onboarding coaching for the owner's stdio pipe. `collectOnboardOpportunities(engine, signal, between?)` is the one home of init's six counts (parallel for `runInitNudge`, sequential with yields for the background refresh; the stale-chunk count uses `countStaleChunks`' predicate, so soft-deleted and `embed_skip` pages are not backlog); a failed count is `null` and never reads as a gap, and `onboardGaps` applies init's thresholds (link < 0.7, timeline < 0.9; an empty brain has none). The per-brain cache (6 h TTL, `GBRAIN_HOME/onboard-counts-<brain>.json`, atomic write, partial runs not persisted) is loaded by `startOnboardingRefresher` and refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchable `gbrain features` recommendations (`pitchableFeatures`, offer state read-only) and the stale-chunk backfill estimate. `mcpOnboardingNotices` is dispatch's one producer on the stdio success path: `first_run_decisions` (writeback + skills via `mcpFirstRunNotices`, from the second successful call, nothing persisted) and one coaching notice per class (`onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`) when `ONBOARD_CALL_AFFINITY` names the call and the class's result predicate holds, plus `features_auto_fix` on `get_backlinks`/`traverse_graph`; fixes are the read-only `get_health` / `gbrain onboard --check` preview, the dismissal line names `mute_notice` only where it is callable. `mutedFirstRunDecisionsNotice` feeds doctor (`memory_writeback`) and `gbrain onboard --check`. HTTP never calls it. Test seams `__warmOnboardingCacheForTests`, `__awaitOnboardingRefreshForTests`, `__resetMcpOnboardingForTests`. Tests: `test/mcp-onboarding.test.ts`, `test/init-nudge.test.ts`, `test/mcp-notice-channels.test.ts`.
- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 36fb720034..9090fc4e4f 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.
-- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding` child, `--providers` drops `--no-embedding`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). Unsupported harness ids (`codex`, `openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
+- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners, and renders `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). Unsupported harness ids (`codex`, `openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.
- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 6b2bb4b8b6..75a41f8843 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -48,6 +48,20 @@ the recorded answers; a flag changes one.
Provider keys in the environment do not change these defaults.
+## First-run settings
+
+When setup creates the brain, it prints init's first-run settings once, after
+the wiring and its check (an `[AGENT]` block at the end of the output, or
+`notices` in `--json`): the search mode init applied, with the cost matrix,
+and automatic saving (`memory.auto_writeback`, off until the user turns it
+on). Setup leaves out init's wiring question and its copy-paste quickstart,
+because it has just done both. Memory works without an answer, so the agent
+relays these settings in the reply that reports the install, as the settings
+in effect and how to change them, and applies a choice whenever the user makes
+one. Automatic saving is separate from the capture decision above; while
+unanswered it comes back in a later session until the user answers or mutes
+it.
+
## States
Setup reports how far the wiring is proven:
diff --git a/llms-full.txt b/llms-full.txt
index e1c87fc115..50c179c096 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1729,7 +1729,13 @@ start here.
default but printed a 9-cell cost matrix (mode × downstream model)
preceded by `[AGENT]` markers. You MUST relay the matrix to the operator
and confirm their choice before continuing. Cost spread between corners
- is about 200x — silent acceptance is the wrong default. See
+ is about 200x — silent acceptance is the wrong default. After
+ `gbrain setup <harness>` the harness is already wired when the matrix
+ appears in setup's one first-run settings block, so there is nothing left
+ to continue: relay the matrix and the other settings in the reply that
+ reports the install, as the settings in effect and how to change them,
+ and apply the user's choice when they give it. Don't end the install on a
+ question that needs another turn before memory works. See
[`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) Step 3.5 for the
exact ask-the-user protocol. The same banner fires on `gbrain post-upgrade`
for a brain created before v0.32.3, when search modes arrived.
@@ -2535,7 +2541,7 @@ Read this file, then follow the path appropriate to the user’s request. Defaul
> **Choose the installation path first.** Inside **[Grok Bot](docs/guides/grok-bot.md)** or **[Muse](docs/guides/muse.md)**, use their dedicated guide: the recommended shape keeps the brain on the user's own computer, published with `gbrain mcp expose --funnel` ([remote MCP](docs/guides/remote-mcp.md)), and installs the thin CLI inside the agent; `scripts/setup-in-agent.sh` is the in-agent alternative, and its receipt tracks repair and native enablement. To make a brain on this computer reachable from the user's other devices, apps, or cloud agents over MCP, follow the **[remote MCP guide](docs/guides/remote-mcp.md)** (`gbrain mcp expose`; confirm the plan before installing Tailscale or a service; `--funnel` only for cloud agents). For an **[existing hosted brain](docs/guides/hosted-harness-access.md)**, choose the harness's native OAuth/PKCE flow or a private machine handoff. Owner login, client management, permissions, and revocation use the separate [MCP administration](docs/mcp/ADMIN.md) path. This guide covers a local brain for other existing agents.
>
-> **Memory-only path:** install → initialize → relay and confirm the Step 3.5 search-mode choice → connect the harness → verify memory. Skip identity replacement, private-repo bootstrap, automatic capture, cron installation, and paid enrichment unless requested. A keyword-only brain needs no API key. The required search-mode choice still applies; published API cost examples are not prices for the user’s harness subscription.
+> **Memory-only path:** install → initialize → relay and confirm the Step 3.5 search-mode choice → connect the harness → verify memory (with `gbrain setup <harness>`, initialize and connect are one command and the search-mode choice is relayed in the reply that reports the install). Skip identity replacement, private-repo bootstrap, automatic capture, cron installation, and paid enrichment unless requested. A keyword-only brain needs no API key. The required search-mode choice still applies; published API cost examples are not prices for the user’s harness subscription.
>
> Only if the user asks for a **new persistent personal agent** with identity and a private repo, follow `BOOTSTRAP_FOR_AGENTS.md`.
@@ -2645,9 +2651,14 @@ gbrain setup claude-code --dry-run --json # the resolved target; writes nothin
gbrain setup claude-code --json # brain (if none) + MCP + read-context hooks, verified
```
-It runs `gbrain init --pglite --no-embedding` only when no brain exists, and its
-`--json` document carries init's first-run decision bundle in `notices`: relay
-the search-mode matrix (Step 3.5) and the decisions in one reply. Capture
+It runs `gbrain init --pglite --no-embedding` only when no brain exists and
+prints init's first-run decision bundle once, after the wiring and its smoke
+check (an `[AGENT]` block in human output, `notices` in `--json`), without
+`harness_wiring`, which setup just did. Relay the search-mode matrix (Step 3.5)
+and the other settings in the reply that reports the install, as the settings
+in effect and how to change them; nothing waits on the answer, so don't end
+the install on a question, and apply an answer with its option's command
+whenever the user gives one. Capture
(`--capture`) and providers (`--providers`) stay off unless the user accepts
them. A coded refusal (`setup_owner_conflict`, `setup_hosted_connection`) means
another owner or a hosted brain holds the target; follow its `fix`.
@@ -2765,6 +2776,12 @@ and `conservative` when your subagent tier is Haiku-class or neither exists. The
included the cost matrix below preceded by `[AGENT]` markers. You must NOT
silently accept the default. Stop and ask the operator.
+After `gbrain setup <harness>` the harness is already wired when the matrix
+appears, so there is nothing to stop before: show the matrix and the applied
+mode in the reply that reports the install, as a choice the user can make at
+any time, and run `gbrain config set search.mode <mode>` when they pick one.
+Don't hold the install open for the answer.
+
If you already know the operator's choice, record it at install time instead:
`gbrain init --search-mode <conservative|balanced|tokenmax>` stores it as the
operator's (`search.mode_source: operator`) and init asks no `search_mode`
diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.ts
index 7a6082837b..30f667eee2 100644
--- a/src/commands/init-first-run.ts
+++ b/src/commands/init-first-run.ts
@@ -113,6 +113,35 @@ export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {
}];
}
+/**
+ * `gbrain setup <harness>`'s form of init's bundle (read from `init --json`).
+ * Setup has already wired the harness, so `harness_wiring` is dropped, and
+ * the rest is framed as settings in effect that the user can change at any
+ * time: the agent relays them in the reply that reports the install instead
+ * of ending it on a question whose answer needs another turn (Cat 41 wave 2).
+ * Open decisions keep returning in later sessions until answered or muted.
+ */
+export function setupFirstRunNotices(initNotices: readonly unknown[], harness: string): Notice[] {
+ const bundle = initNotices.find((n): n is Notice => (n as Notice | null)?.code === 'first_run_decisions');
+ const decisions = (bundle?.decisions ?? []).filter(d => d.id !== 'harness_wiring');
+ if (decisions.length === 0) return [];
+ const searchMode = decisions.find(d => d.id === 'search_mode');
+ const inEffect = [
+ ...(searchMode ? [`search mode ${searchMode.default}`] : []),
+ ...(decisions.some(d => d.id === 'writeback') ? ['agents save only what you ask them to remember, until you turn on automatic saving (gbrain recommends salient: durable facts you state, saved with provenance)'] : []),
+ ];
+ if (inEffect.length === 0) return [];
+ return [{
+ code: 'first_run_decisions',
+ kind: 'ask',
+ why: `Setup is complete: the brain is ready and ${harness} is wired, so memory works now. These first-run settings are in effect as listed; none blocks memory or needs a new session to answer. `
+ + 'Relay them once, in the reply that reports this install, as the current settings and how to change them; do not hold the install open or end it waiting on an answer. '
+ + 'When the user picks an option, run its command. Automatic saving (`writeback`) is separate from setup\'s capture decision (Stop/SessionEnd hooks); while unanswered it comes back in a later session until the user answers or mutes it.',
+ user_message: `gbrain is set up and ${harness} is wired, so memory works now. In effect: ${inEffect.join('; ')}.${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
+ decisions,
+ }];
+}
+
/**
* The deferred-setup line init prints for `--no-embedding`: the same enable
* command readiness gives doctor, embed and MCP (A7 `embeddingEnablement`:
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 7c87b6cee5..109c93d7c3 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -24,7 +24,9 @@
*/
import { realpathSync } from 'node:fs';
import { opError, OperationError } from '../core/ops/contract.ts';
-import { renderCliError, type Action } from '../core/agent-output.ts';
+import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
+import { writeCliNotices } from '../core/interop-notices.ts';
+import { setupFirstRunNotices } from './init-first-run.ts';
import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { configDir, gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';
import { resolveGbrainBin } from '../core/gbrain-bin.ts';
@@ -350,7 +352,7 @@ export async function runSetup(args: string[]): Promise<number> {
}
const brainCreate = !cfg;
- const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), ...(out.json ? ['--json'] : [])];
+ const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), '--json'];
if (flags.dryRun) {
const steps: SetupStep[] = [
{ step: 'receipt', action: found.prior?.status === 'installed' && found.hooksCurrent && (found.mcp.state === 'current' || !!pluginOwner) && !brainCreate ? 'keep' : 'write', detail: found.receiptPath },
@@ -362,7 +364,7 @@ export async function runSetup(args: string[]): Promise<number> {
return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });
}
- let notices: unknown[] = [];
+ let notices: Notice[] = [];
const result = await applyClaudeSetup(plan, consent, {
pluginOwner, brainCreated: brainCreate, abortAfter: process.env.GBRAIN_SETUP_ABORT_AFTER,
beforeMcp: brainCreate ? async () => {
@@ -370,11 +372,15 @@ export async function runSetup(args: string[]): Promise<number> {
const child = Bun.spawnSync(initArgv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env });
const initOut = child.stdout?.toString() ?? '';
process.stderr.write(child.stderr?.toString() ?? '');
- if (!out.json) process.stdout.write(initOut);
- if (child.exitCode !== 0) throw new Error(`\`${initArgv.join(' ')}\` exited ${child.exitCode}; nothing else was written. Fix the init error above, then run setup again.`);
- if (out.json) {
- try { notices = (JSON.parse(initOut) as { notices?: unknown[] }).notices ?? []; } catch { process.stderr.write(initOut); }
+ if (child.exitCode !== 0) {
+ process.stderr.write(initOut);
+ throw new Error(`\`${initArgv.join(' ')}\` exited ${child.exitCode}; nothing else was written. Fix the init error above, then run setup again.`);
}
+ try {
+ const doc = JSON.parse(initOut) as { path?: string; notices?: unknown[] };
+ if (doc.path) say(out, `Brain ready at ${doc.path}`);
+ notices = setupFirstRunNotices(doc.notices ?? [], 'Claude Code');
+ } catch { process.stderr.write(initOut); }
} : undefined,
});
for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);
@@ -428,7 +434,7 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,
async function finish(out: Out, doc: {
dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: SetupStep[]; states: string[];
- verify: { ok: boolean; reason: string; message: string } | null; notices: unknown[]; notes: string[]; preserved?: unknown[];
+ verify: { ok: boolean; reason: string; message: string } | null; notices: Notice[]; notes: string[]; preserved?: unknown[];
}): Promise<number> {
const state = doc.states.at(-1) ?? null;
if (out.json) {
@@ -437,12 +443,13 @@ async function finish(out: Out, doc: {
...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),
steps: doc.steps, preserved: doc.preserved ?? [], states: doc.states, state, verify: doc.verify,
capability: capabilityRows('claude-code')[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,
- notes: doc.notes, notices: doc.notices,
+ notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),
}, null, 2)}\n`, (t) => process.stdout.write(t));
return 0;
}
if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);
if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}). Native push is not claimed until an observed event reaches a fresh session.`);
if (state && !doc.remove) say(out, 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
+ writeCliNotices(doc.notices);
return 0;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 453523df3b..36a9fa3860 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -493,6 +493,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// Low-hanging-fruit wave (GBRA-81 items 2 and 3).
{ since: '0.60.188.0', text: 'Lean `search` and `query` rows (remote callers) now carry `id`, the `fetch` key, only when the connection can call `fetch` at that moment: a `full` surface, a stdio session `request_tools` widened, or an HTTP client whose surface and scopes include it. On `starter` and `verbs` connections, `fetch` was never callable, so the row\'s `slug` and `source_id` identify the page; `fields: "full"` returns every field, `id` included, and the `mcp.result_rows: full` host setting does so for every remote caller. Lean-row `score` now prints 4 significant digits. The local CLI and gbrain\'s thin client keep full rows, unchanged. `fetch` called without an id now says to re-run `search` once `fetch` is callable, or to pass the row\'s slug.' },
{ since: '0.60.188.0', text: 'On stdio MCP and the CLI, the `degraded_recall` notice now shows on every call a transient degradation affects (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, and every other per-call stage); it used to show once per session, so a rerank failure after an earlier embedding timeout returned fused-order results with no notice. A keyless brain whose only degradation is `embed_unavailable` still shows it once per session. HTTP is unchanged: every affected call. `_meta.retrieval.degraded` still records every call\'s stages.' },
+ // Cat 41 wave 2 TTHW (GBRA-60). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.188.0', text: '`gbrain setup claude-code` no longer prints `gbrain init`\'s standalone output when it creates the brain: no search-mode banner, no "Do this next" quickstart (`claude mcp add` and the install-check round trip) and no `harness_wiring` question, since setup has just wired the harness. It prints `Brain ready at <path>`, then the first-run settings once, after `Next:` (an agent block, or `notices` in `--json` without `harness_wiring`): the applied search mode with the cost matrix and automatic saving, framed as settings in effect that the agent relays in the install reply and the user can change at any time, instead of "Reply \'defaults\'". No setting or default changed.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/init-first-run.test.ts b/test/init-first-run.test.ts
index 2692862ec9..afc5d2b078 100644
--- a/test/init-first-run.test.ts
+++ b/test/init-first-run.test.ts
@@ -5,7 +5,8 @@
* offering 'defaults'. Pure: no engine, no filesystem.
*/
import { describe, expect, test } from 'bun:test';
-import { buildInitFirstRunNotices } from '../src/commands/init-first-run.ts';
+import { buildInitFirstRunNotices, setupFirstRunNotices } from '../src/commands/init-first-run.ts';
+import { costMatrixSentence } from '../src/core/search/mode-advice.ts';
const searchMode = { mode: 'balanced' as const, reason: 'Balanced default for a new brain.' };
const scaffold = { missing: ['cold-start', 'book-mirror'], argv: ['gbrain', 'skillpack', 'scaffold', 'cold-start', 'book-mirror'] };
@@ -49,3 +50,43 @@ describe('buildInitFirstRunNotices', () => {
expect(argvs.some(a => a.includes('remember'))).toBe(false);
});
});
+
+describe('setupFirstRunNotices (gbrain setup <harness>)', () => {
+ const wiring = { id: 'harness_wiring', question: 'Which agent app should get gbrain memory?', options: [{ id: 'wire', label: 'wire' }, { id: 'skip', label: 'skip' }], default: 'wire', default_reason: 'detected' };
+ const fromInit = (inputs: Parameters<typeof buildInitFirstRunNotices>[0]) => {
+ const [bundle] = buildInitFirstRunNotices(inputs);
+ return [{ ...bundle, decisions: [...bundle.decisions!, wiring], contract_version: 1 }];
+ };
+
+ test('drops harness_wiring (setup just wired it) and keeps the rest of the bundle', () => {
+ const [n] = setupFirstRunNotices(fromInit({ searchMode, writeback: true, skillsScaffold: scaffold }), 'Claude Code');
+ expect(n).toMatchObject({ code: 'first_run_decisions', kind: 'ask' });
+ expect(n.decisions!.map(d => d.id)).toEqual(['search_mode', 'writeback', 'skills_scaffold']);
+ });
+
+ test('frames the bundle as settings in effect, relayed in the install reply, never a reply-to-continue question', () => {
+ const [n] = setupFirstRunNotices(fromInit({ searchMode, writeback: true }), 'Claude Code');
+ expect(n.user_message).toBe(
+ 'gbrain is set up and Claude Code is wired, so memory works now. In effect: search mode balanced; agents save only what you ask them to remember, '
+ + 'until you turn on automatic saving (gbrain recommends salient: durable facts you state, saved with provenance). '
+ + `${costMatrixSentence()} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
+ );
+ expect(n.user_message).not.toContain("Reply 'defaults'");
+ expect(n.why).toContain('in the reply that reports this install');
+ expect(n.why).toContain('do not hold the install open');
+ });
+
+ test('the search-mode matrix still reaches the user and every option keeps its command', () => {
+ const [n] = setupFirstRunNotices(fromInit({ searchMode }), 'Claude Code');
+ expect(n.user_message).toContain(costMatrixSentence());
+ const mode = n.decisions!.find(d => d.id === 'search_mode')!;
+ expect(mode.options.map(o => o.argv)).toEqual(['conservative', 'balanced', 'tokenmax'].map(m => ['gbrain', 'config', 'set', 'search.mode', m]));
+ expect(n.user_message).not.toContain('automatic saving');
+ });
+
+ test('nothing left to relay → no notice; foreign or missing notices are ignored', () => {
+ expect(setupFirstRunNotices([{ code: 'first_run_decisions', kind: 'ask', why: 'x', decisions: [wiring] }], 'Claude Code')).toEqual([]);
+ expect(setupFirstRunNotices([{ code: 'other', kind: 'info', why: 'x' }, null], 'Claude Code')).toEqual([]);
+ expect(setupFirstRunNotices([], 'Claude Code')).toEqual([]);
+ });
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 2c0ba06280..ec2cdadccc 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -80,6 +80,10 @@ describe('gbrain setup claude-code: install lifecycle', () => {
expect(entry).toEqual({ type: 'stdio', command: b.bin, args: ['serve', '--surface', 'full'], env: { GBRAIN_HOME: b.gbrainHome } });
expect(Object.keys(readJson(settings(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
expect(readJson(receipt(b)).status).toBe('installed');
+ const [bundle] = first.doc.notices;
+ expect(bundle).toMatchObject({ code: 'first_run_decisions', kind: 'ask' });
+ expect(bundle.decisions.map((d: any) => d.id)).not.toContain('harness_wiring');
+ expect(bundle.user_message).not.toContain("Reply 'defaults'");
const before = [readFileSync(claudeJson(b), 'utf8'), readFileSync(settings(b), 'utf8'), readFileSync(receipt(b), 'utf8')];
const second = await setup(b, ['claude-code', '--json']);
@@ -89,6 +93,22 @@ describe('gbrain setup claude-code: install lifecycle', () => {
expect(existsSync(`${settings(b)}.bak`)).toBe(false);
});
+ test('human output ends with one non-blocking settings block after Next, and none of init\'s standalone steps', async () => {
+ const b = box();
+ const r = await setup(b, ['claude-code']);
+ expect(r.exitCode).toBe(0);
+ for (const stale of ['Do this next', 'claude mcp add', "Reply 'defaults'", 'Before continuing', 'gbrain install check', '(id: harness_wiring)']) expect(r.stdout).not.toContain(stale);
+ expect(r.stdout).toContain('Brain ready at ');
+ const next = r.stdout.indexOf('Next: open a new Claude Code session');
+ const block = r.stdout.indexOf('[AGENT]');
+ expect(next).toBeGreaterThan(-1);
+ expect(block).toBeGreaterThan(next);
+ expect(r.stdout.match(/\[AGENT\]/g)).toHaveLength(1);
+ expect(r.stdout.slice(block)).toContain('in the reply that reports this install');
+ expect(r.stdout.slice(block)).toContain('(id: search_mode)');
+ expect(r.stdout.trimEnd().endsWith('[/AGENT]')).toBe(true);
+ });
+
test('--remove deletes exactly the owned entries; foreign hooks, other MCP servers and the brain stay', async () => {
const b = box();
mkdirSync(join(b.home, '.claude'), { recursive: true });