Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(onboard): hosted_option notice points at gbrain.io where self-hosting costs the most
garrytan97a618a38768
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 3ca4238dfd..4163df16b7 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -16,6 +16,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `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, 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/hosted-option.ts` — the `hosted_option` coaching notice (gbrain.io, hosted GBrain): the one home of its URL, copy and `?ref=` tags. `gbrain setup` appends it when it created the brain, `printInAgentReady` prints it after the in-agent ready text, and `gbrain mcp expose`'s `Session.finish` adds it (JSON `notices`, one human line) on the run that wrote the first receipt and at Tailscale/service friction exits (`EXPOSE_FRICTION_REASONS`), never on the consent-pending document, `--dry-run`, `--status` or `--remove`. Bare `gbrain init` never shows it. Muted by the owner list or the `stdio` audience (`hostedOptionMuted`); `writeHostedOption` prints one plain line on a TTY and the notice block otherwise. No network call. Tests: `test/hosted-option.test.ts`, `test/setup.test.ts`, `test/mcp-expose.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/guides/grok-bot.md b/docs/guides/grok-bot.mdindex 217a8f796f..4e4e131041 100644--- a/docs/guides/grok-bot.md+++ b/docs/guides/grok-bot.md@@ -25,6 +25,7 @@ provider; it does not install memory in Grok Bot.| --- | --- || You have (or can run) GBrain on your own computer — recommended | [Publish it over MCP](remote-mcp.md) with `gbrain mcp expose --funnel` (Funnel, because the Bot runs in the vendor's cloud, not on your tailnet), grant the Bot a client, then install the thin CLI inside the Bot ([hosted harness access](hosted-harness-access.md), adapter `grok-bot`). Memory lives where you can back it up and inspect it. || Already have a hosted GBrain elsewhere (cloud host, team brain) | Same client-side steps: [hosted harness access](hosted-harness-access.md), adapter `grok-bot`; choose the thin CLI for the complete remote command path |+| No always-on machine; want a brain that stays online | Hosted GBrain at [gbrain.io](https://gbrain.io/?ref=grok-bot), then connect the Bot with the connection details gbrain.io gives you || No always-on machine; want memory inside your Bot only | [Local setup](#alternative-install-gbrain-inside-the-bot) below; no model API key needed for the first fact/recall test || Want to keep the connection tailnet-only | Joining the Bot's runtime to your tailnet (userspace `tailscaled` with an ephemeral auth key) is possible in principle; it is advanced, not automated by gbrain, and unverified against a real Bot || Want a native Grok Bot MCP plugin | Native plugin authentication is unverified and release-gated; use the supported thin CLI path until an actual Bot pilot establishes the native connection |diff --git a/docs/guides/muse.md b/docs/guides/muse.mdindex 6c421a6dd3..efb52a694e 100644--- a/docs/guides/muse.md+++ b/docs/guides/muse.md@@ -46,6 +46,7 @@ replacement of the runtime cell.| --- | --- || You have (or can run) GBrain on your own computer, and a confirmed durable user-files directory in Muse — recommended | [Publish it over MCP](remote-mcp.md) with `gbrain mcp expose --funnel` (Funnel, because Muse's runtime is in the vendor's cloud, not on your tailnet), grant Muse a client, then install the thin CLI at the durable root ([hosted harness access](hosted-harness-access.md), adapter `muse`) || Existing hosted brain elsewhere | Same client-side steps: [hosted harness access](hosted-harness-access.md), adapter `muse`, thin CLI |+| No always-on machine; want a brain that stays online | Hosted GBrain at [gbrain.io](https://gbrain.io/?ref=muse), then connect Muse with the connection details gbrain.io gives you || No always-on machine; new brain and a confirmed durable directory | [Local setup](#alternative-install-gbrain-inside-muse) below, adapter `muse` || No confirmed persistent custom-files location | Resolve that platform capability before installing either the thin CLI or durable local memory || Want to keep the connection tailnet-only | Joining Muse's runtime to your tailnet (userspace `tailscaled`, ephemeral auth key) is advanced, not automated by gbrain, and unverified; Sentinel's egress policy applies either way |diff --git a/llms-full.txt b/llms-full.txtindex c0f0fad482..ee91d42cb0 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -597,6 +597,7 @@ provider; it does not install memory in Grok Bot.| --- | --- || You have (or can run) GBrain on your own computer — recommended | [Publish it over MCP](remote-mcp.md) with `gbrain mcp expose --funnel` (Funnel, because the Bot runs in the vendor's cloud, not on your tailnet), grant the Bot a client, then install the thin CLI inside the Bot ([hosted harness access](hosted-harness-access.md), adapter `grok-bot`). Memory lives where you can back it up and inspect it. || Already have a hosted GBrain elsewhere (cloud host, team brain) | Same client-side steps: [hosted harness access](hosted-harness-access.md), adapter `grok-bot`; choose the thin CLI for the complete remote command path |+| No always-on machine; want a brain that stays online | Hosted GBrain at [gbrain.io](https://gbrain.io/?ref=grok-bot), then connect the Bot with the connection details gbrain.io gives you || No always-on machine; want memory inside your Bot only | [Local setup](#alternative-install-gbrain-inside-the-bot) below; no model API key needed for the first fact/recall test || Want to keep the connection tailnet-only | Joining the Bot's runtime to your tailnet (userspace `tailscaled` with an ephemeral auth key) is possible in principle; it is advanced, not automated by gbrain, and unverified against a real Bot || Want a native Grok Bot MCP plugin | Native plugin authentication is unverified and release-gated; use the supported thin CLI path until an actual Bot pilot establishes the native connection |@@ -825,6 +826,7 @@ replacement of the runtime cell.| --- | --- || You have (or can run) GBrain on your own computer, and a confirmed durable user-files directory in Muse — recommended | [Publish it over MCP](remote-mcp.md) with `gbrain mcp expose --funnel` (Funnel, because Muse's runtime is in the vendor's cloud, not on your tailnet), grant Muse a client, then install the thin CLI at the durable root ([hosted harness access](hosted-harness-access.md), adapter `muse`) || Existing hosted brain elsewhere | Same client-side steps: [hosted harness access](hosted-harness-access.md), adapter `muse`, thin CLI |+| No always-on machine; want a brain that stays online | Hosted GBrain at [gbrain.io](https://gbrain.io/?ref=muse), then connect Muse with the connection details gbrain.io gives you || No always-on machine; new brain and a confirmed durable directory | [Local setup](#alternative-install-gbrain-inside-muse) below, adapter `muse` || No confirmed persistent custom-files location | Resolve that platform capability before installing either the thin CLI or durable local memory || Want to keep the connection tailnet-only | Joining Muse's runtime to your tailnet (userspace `tailscaled`, ephemeral auth key) is advanced, not automated by gbrain, and unverified; Sentinel's egress policy applies either way |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4067ab06e8..9aa8995d94 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -45,3 +45,4 @@ src/commands/eval-longmemeval.ts 1532 ratchet new row: crossed the 1500 unlistedsrc/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/core/search/evidence-delivery.ts 1537 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)+src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)diff --git a/src/commands/mcp-expose.ts b/src/commands/mcp-expose.tsindex c0fee29110..f3134369f7 100644--- a/src/commands/mcp-expose.ts+++ b/src/commands/mcp-expose.ts@@ -48,6 +48,8 @@ import {type ExposeReceipt, type ServiceState, type ServiceTarget, type UninstallServiceResult,} from '../core/serve-service.ts';import { shellQuote } from '../core/mcp-registration.ts';+import { cliRenderContext, renderNotice } from '../core/agent-output.ts';+import { EXPOSE_FRICTION_REASONS, hostedOptionLine, hostedOptionMuted, hostedOptionNotice } from '../core/onboard/hosted-option.ts';export const MCP_EXPOSE_HELP = `gbrain mcp expose — publish the MCP server on your Tailscale tailnet and keep it running@@ -130,6 +132,8 @@ export interface McpExposeDeps {plistPath?: string;unitPath?: string;loadConfig?: () => GBrainConfig | null;+ /** The owner's muted notice codes (default: the global and stdio mute lists under GBRAIN_HOME). */+ mutedNotices?: () => ReadonlySet<string>;executionEnv?: ExecutionEnvironment;run?: CommandRunner;which?: (name: string) => string | null;@@ -193,6 +197,7 @@ interface Resolved {sleep: (ms: number) => Promise<void>;executionEnv: ExecutionEnvironment;loadConfig: () => GBrainConfig | null;+ mutedNotices: () => ReadonlySet<string>;gbrainCommand: () => string[];runtimeDir: string;randomHex?: () => string;@@ -232,6 +237,7 @@ function resolveDeps(deps: McpExposeDeps): Resolved {sleep: deps.sleep ?? ((ms: number) => new Promise(resolve => setTimeout(resolve, ms))),executionEnv: deps.executionEnv ?? detectExecutionEnvironment({ env }),loadConfig: deps.loadConfig ?? loadConfig,+ mutedNotices: deps.mutedNotices ?? hostedOptionMuted,gbrainCommand: () => deps.gbrainCommand ?? resolveServeGbrainCommand({ which, fileExists: deps.fileExists }),runtimeDir: deps.runtimeDir ?? dirname(process.execPath || ''),randomHex: deps.randomHex,@@ -302,6 +308,8 @@ export function parseExposeArgs(args: string[]): ExposeOptions {class Session {readonly checks: Check[] = [];readonly nextActions: string[] = [];+ /** Set on the run whose early receipt write created the first receipt: that run shows hosted_option. */+ firstPublish = false;constructor(private readonly d: Resolved, readonly json: boolean) {}/** Prose: stderr under --json, stdout otherwise. */say(line = ''): void { (this.json ? this.d.err : this.d.out)(line); }@@ -311,12 +319,16 @@ class Session {return c;}finish(status: ExposeStatus, code: number, extra: { receipt?: ExposeReceipt | null; reason?: string; message?: string; plan?: string[]; consent?: Record<string, unknown> } = {}): number {+ const where = EXPOSE_FRICTION_REASONS.has(extra.reason ?? '') ? 'mcp_expose_friction'+ : this.firstPublish && (status === 'exposed' || status === 'pending') ? 'mcp_expose' : null;+ const hosted = where ? hostedOptionNotice(where, this.d.mutedNotices()) : null;if (extra.message) this.say(`${status}: ${extra.message}`);+ if (hosted && where && !this.json) this.say(hostedOptionLine(where));if (this.json) {this.d.out(JSON.stringify({status, receipt: extra.receipt ?? null, checks: this.checks, next_actions: this.nextActions,...(extra.reason ? { reason: extra.reason } : {}), ...(extra.message ? { message: extra.message } : {}), ...(extra.plan ? { plan: extra.plan } : {}),- ...(extra.consent ?? {}),+ ...(extra.consent ?? {}), ...(hosted ? { notices: [renderNotice(hosted, cliRenderContext())] } : {}),}));}return code;@@ -955,6 +967,7 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promise// to find. Rewritten below with the settled state (created_at kept).writeExposeReceipt(receiptPath, buildReceipt());receiptWritten = true;+ s.firstPublish = existing === null;// 9. verifyif (opts.noService && !listeningBefore && !keptService) {diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 3ba6e0414e..d0bcc9a60a 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -27,6 +27,7 @@ import { opError, OperationError } from '../core/ops/contract.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 { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../core/onboard/hosted-option.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';@@ -435,11 +436,12 @@ function runBrainInit(initArgv: string[], out: Out, harness: SetupHarnessId): Noprocess.stderr.write(initOut);throw new Error(`\`${initArgv.join(' ')}\` exited ${child.exitCode}; nothing else was written. Fix the init error above, then run setup again.`);}+ const hosted = hostedOptionNotice('setup', hostedOptionMuted());try {const doc = JSON.parse(initOut) as { path?: string; notices?: unknown[] };if (doc.path) say(out, `Brain ready at ${doc.path}`);- return setupFirstRunNotices(doc.notices ?? [], HARNESS_LABEL[harness]);- } catch { process.stderr.write(initOut); return []; }+ return [...setupFirstRunNotices(doc.notices ?? [], HARNESS_LABEL[harness]), ...(hosted ? [hosted] : [])];+ } catch { process.stderr.write(initOut); return hosted ? [hosted] : []; }}async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConfig | null, brainHome: string, out: Out): Promise<number> {@@ -612,6 +614,7 @@ async function finish(out: Out, doc: {: 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');if (state && !doc.remove) say(out, 'Memory: save what the user asks you to remember as a fact with gbrain remember "<fact>", naming its entity and provenance (MCP tool: remember). '+ 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');- writeCliNotices(doc.notices);+ writeCliNotices(doc.notices.filter((n) => n.code !== 'hosted_option'));+ if (doc.notices.some((n) => n.code === 'hosted_option')) writeHostedOption('setup', new Set());return 0;}diff --git a/src/core/agent-install/init-state.ts b/src/core/agent-install/init-state.tsindex 5c29f3cc96..2b9d78e623 100644--- a/src/core/agent-install/init-state.ts+++ b/src/core/agent-install/init-state.ts@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { configPath, gbrainPath, isThinClient, loadConfigFileOnly } from '../config.ts';import { privateWrite, readFileConfigState } from './state.ts';+import { hostedOptionMuted, writeHostedOption } from '../onboard/hosted-option.ts';/** `onInvalid` lets init's `--json` writer report the refusal (agent contract v1 D2). */export function readInitConfigState(json: boolean, onInvalid?: (message: string) => never) {@@ -44,4 +45,5 @@ export function inspectRemoteInitState(force: boolean, fail: (reason: string, meexport function printInAgentReady(databasePath: string): void {const root = dirname(dirname(databasePath));console.log(`\nBrain ready at ${databasePath}\nLocal personal-agent setup will finish at ${join(root, 'bin', 'gbrain')}.\nAttach the generated memory skill in your app, then test a fresh conversation.\nExplicit memory is available; automatic capture and paid maintenance remain separate choices.`);+ writeHostedOption('in_agent', hostedOptionMuted(), { tty: false });}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 758261d4c4..3143f97abd 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -538,6 +538,7 @@ export interface NoticeEntry {/** Notice codes. Mute (`gbrain notices mute`, `mute_notice`) accepts only coaching/info codes. */export const NOTICE_CODES = {atom_drain_budget: { kind: 'info', summary: 'An atom drain (`gbrain dream --drain`) stopped at its per-run spending cap (`cycle.extract_atoms.budget_usd`): the notice names the spend, the cap and the pages left; the fix raises the cap (paid, ask first).' },+ hosted_option: { kind: 'coaching', summary: 'Shown when gbrain setup or an in-agent install creates a brain, and when gbrain mcp expose writes its first receipt or stops at a Tailscale or service step: gbrain.io is hosted GBrain. Mute with `gbrain notices mute hosted_option`.' },backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },diff --git a/src/core/onboard/hosted-option.ts b/src/core/onboard/hosted-option.tsnew file mode 100644index 0000000000..97595c0d60--- /dev/null+++ b/src/core/onboard/hosted-option.ts@@ -0,0 +1,60 @@+/**+ * The hosted-GBrain pointer (`hosted_option`, a coaching notice): one line+ * naming gbrain.io where running GBrain yourself costs the most. Shown when+ * `gbrain setup` or an in-agent install creates a brain, and when+ * `gbrain mcp expose` writes its first receipt or stops at a Tailscale or+ * service step. Never on bare `gbrain init`. No network call; attribution is+ * the `?ref=` query only. Muted by the owner (`gbrain notices mute+ * hosted_option`) or through `mute_notice` on stdio.+ */+import type { Notice } from '../agent-output.ts';+import { writeCliNotices } from '../interop-notices.ts';+import { isInteractive } from '../interaction.ts';+import { mutedNoticeCodes } from '../notice-ledger.ts';++export const HOSTED_URL = 'https://gbrain.io';+const REF = { setup: 'cli-setup', in_agent: 'cli-in-agent', mcp_expose: 'cli-mcp-expose', mcp_expose_friction: 'cli-mcp-expose-friction' } as const;+export type HostedOptionWhere = keyof typeof REF;+const MUTE = 'gbrain notices mute hosted_option';++export const EXPOSE_FRICTION_REASONS: ReadonlySet<string> = new Set([+ 'tailscale_missing', 'tailscale_unsupported_platform', 'tailscale_install_failed', 'tailscale_login_pending',+ 'tailscale_https_not_enabled', 'tailscale_funnel_not_enabled', 'service_install_failed',+]);++export function hostedOptionUrl(where: HostedOptionWhere): string {+ return `${HOSTED_URL}/?ref=${REF[where]}`;+}++/** The owner's mutes: the global list plus the `stdio` audience `mute_notice` writes on the owner's pipe. */+export function hostedOptionMuted(): ReadonlySet<string> {+ try {+ return new Set([...mutedNoticeCodes(), ...mutedNoticeCodes('stdio')]);+ } catch {+ return new Set();+ }+}++export function hostedOptionNotice(where: HostedOptionWhere, muted: ReadonlySet<string>): Notice | null {+ if (muted.has('hosted_option')) return null;+ return {+ code: 'hosted_option',+ kind: 'coaching',+ why: 'gbrain.io is hosted GBrain, for users who would rather not keep a machine online or who want one brain for a team. '+ + 'Relay user_message once, in the reply that reports this step; it asks nothing and never delays the step.',+ user_message: `Hosted option: gbrain.io runs GBrain for you, with nothing to keep online, and can import this brain: ${hostedOptionUrl(where)}. Mute: ${MUTE}.`,+ };+}++/** The terminal form: one plain line with the link and the mute command. */+export function hostedOptionLine(where: HostedOptionWhere): string {+ return `Hosted option: gbrain.io runs GBrain for you, nothing to keep online: ${hostedOptionUrl(where)} (hide: ${MUTE})`;+}++/** One plain line on a terminal; the standard notice block for an agent reading the output. */+export function writeHostedOption(where: HostedOptionWhere, muted: ReadonlySet<string>, opts: { tty?: boolean } = {}): void {+ const notice = hostedOptionNotice(where, muted);+ if (!notice) return;+ if (!(opts.tty ?? isInteractive())) return writeCliNotices([notice]);+ process.stderr.write(`${hostedOptionLine(where)}\n`);+}diff --git a/test/hosted-option.test.ts b/test/hosted-option.test.tsnew file mode 100644index 0000000000..51e7e8ea03--- /dev/null+++ b/test/hosted-option.test.ts@@ -0,0 +1,77 @@+import { describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { MUTEABLE_NOTICE_CODES } from '../src/core/ops/notices.ts';+import { setNoticeMuted } from '../src/core/notice-ledger.ts';+import { inertText } from '../src/core/agent-output.ts';+import { printInAgentReady } from '../src/core/agent-install/init-state.ts';+import { hostedOptionLine, hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../src/core/onboard/hosted-option.ts';++async function inHome<T>(fn: () => T | Promise<T>): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-hosted-'));+ try { return await withEnv({ GBRAIN_HOME: home }, fn); } finally { rmSync(home, { recursive: true, force: true }); }+}++function captured(fn: () => void): { stdout: string; stderr: string } {+ const out = spyOn(process.stdout, 'write').mockImplementation(() => true);+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ fn();+ return { stdout: out.mock.calls.map(c => String(c[0])).join(''), stderr: err.mock.calls.map(c => String(c[0])).join('') };+ } finally { out.mockRestore(); err.mockRestore(); }+}++describe('hosted_option notice', () => {+ test('one coaching notice per surface with its ref tag, a statement, and the mute command', () => {+ for (const [where, ref] of [['setup', 'cli-setup'], ['in_agent', 'cli-in-agent'], ['mcp_expose', 'cli-mcp-expose'], ['mcp_expose_friction', 'cli-mcp-expose-friction']] as const) {+ const n = hostedOptionNotice(where, new Set())!;+ expect(n).toMatchObject({ code: 'hosted_option', kind: 'coaching' });+ expect(n.user_message).toContain(`https://gbrain.io/?ref=${ref}`);+ expect(n.user_message).toContain('gbrain notices mute hosted_option');+ expect(n.user_message).not.toMatch(/\?(\s|$)/);+ expect(inertText(n.user_message!)).toBe(n.user_message!);+ expect(inertText(n.why)).toBe(n.why);+ }+ });++ test('the registry row matches the builder kind, so the code is muteable', () => {+ expect(NOTICE_CODES.hosted_option.kind).toBe(hostedOptionNotice('setup', new Set())!.kind);+ expect(MUTEABLE_NOTICE_CODES).toContain('hosted_option');+ });++ test('muted on the owner list or on the stdio audience means no notice', async () => {+ await inHome(() => {+ expect(hostedOptionNotice('setup', hostedOptionMuted())).not.toBeNull();+ setNoticeMuted('hosted_option', true, 'stdio');+ expect(hostedOptionNotice('setup', hostedOptionMuted())).toBeNull();+ setNoticeMuted('hosted_option', false, 'stdio');+ setNoticeMuted('hosted_option', true);+ expect(hostedOptionNotice('setup', hostedOptionMuted())).toBeNull();+ });+ });++ test('a terminal gets one plain line; an agent gets the standard notice block', () => {+ const tty = captured(() => writeHostedOption('setup', new Set(), { tty: true }));+ expect(tty.stderr).toBe(`${hostedOptionLine('setup')}\n`);+ expect(tty.stdout).toBe('');+ const agent = captured(() => writeHostedOption('setup', new Set(), { tty: false }));+ expect(agent.stdout).toContain('[hosted_option]');+ expect(agent.stdout).toContain('https://gbrain.io/?ref=cli-setup');+ expect(captured(() => writeHostedOption('setup', new Set(['hosted_option']), { tty: true })).stderr).toBe('');+ });++ test('the in-agent ready text ends with the hosted pointer unless muted', async () => {+ await inHome(() => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ const shown = captured(() => printInAgentReady('/tmp/agent-root/data/brain.pglite'));+ expect(shown.stdout).toContain('https://gbrain.io/?ref=cli-in-agent');+ setNoticeMuted('hosted_option', true);+ expect(captured(() => printInAgentReady('/tmp/agent-root/data/brain.pglite')).stdout).not.toContain('gbrain.io');+ } finally { log.mockRestore(); }+ });+ });+});diff --git a/test/mcp-expose.test.ts b/test/mcp-expose.test.tsindex 836fb3aa12..821a88ccb0 100644--- a/test/mcp-expose.test.ts+++ b/test/mcp-expose.test.ts@@ -150,6 +150,7 @@ function fakeTailnet(o: TailnetOpts = {}): Fake {platform: 'linux', env: { HOME: home, USER: 'alice-example', PATH: '/usr/bin' }, home, user: 'alice-example', uid: 1000,serveDir, gbrainEnvFile: join(home, '.gbrain', 'env'), plistPath: join(home, 'LaunchAgents', 'com.gbrain.serve.plist'), unitPath: join(home, '.config', 'systemd', 'user', 'gbrain-serve.service'),loadConfig: () => ({ engine: 'pglite', database_path: join(home, 'brain.pglite') } as never), executionEnv: 'local', run,+ mutedNotices: () => new Set(),which: (n) => (n === 'tailscale' ? TS : n === 'systemctl' ? '/usr/bin/systemctl' : n === 'gbrain' ? '/usr/local/bin/gbrain' : null),fileExists: hermeticExists(home, (p) => p === ts),fetch: async (url) => {@@ -697,6 +698,50 @@ describe('happy path: linux-systemd', () => {});});+describe('hosted_option', () => {+ const hostedOf = (doc: { notices?: { code: string; user_message?: string }[] }) => doc.notices?.find(n => n.code === 'hosted_option');+ test('the run that writes the first receipt carries it; consent-pending, --dry-run, re-publish, --status and --remove do not', async () => {+ const f = fakeTailnet();+ expect(await runMcpExpose(['--dry-run', '--json'], f.deps)).toBe(0);+ expect(hostedOf(jsonDoc(f))).toBeUndefined();+ f.stdout.length = 0;+ expect(await runMcpExpose(['--json'], f.deps)).toBe(2);+ const pending = jsonDoc(f);+ expect(pending.reason).toBe('confirmation_required');+ expect(hostedOf(pending)).toBeUndefined();+ expect(pending.user_message).not.toContain('gbrain.io');+ f.stdout.length = 0;+ expect(await runMcpExpose(['--yes', '--json'], f.deps)).toBe(0);+ const first = jsonDoc(f);+ expect(first.status).toBe('exposed');+ expect(hostedOf(first)).toMatchObject({ kind: 'coaching', contract_version: 1 });+ expect(hostedOf(first)?.user_message).toContain('https://gbrain.io/?ref=cli-mcp-expose');+ for (const args of [['--yes', '--json'], ['--status', '--json'], ['--remove', '--yes', '--json']]) {+ f.stdout.length = 0;+ await runMcpExpose(args, f.deps);+ expect(hostedOf(jsonDoc(f))).toBeUndefined();+ }+ });+ test('friction exits carry it every time; human output prints the one line', async () => {+ const f = fakeTailnet();+ f.deps.which = (n) => (n === 'systemctl' ? '/usr/bin/systemctl' : null);+ f.deps.fileExists = () => false;+ expect(await runMcpExpose(['--yes', '--no-install', '--json'], f.deps)).toBe(1);+ const doc = jsonDoc(f);+ expect(doc.reason).toBe('tailscale_missing');+ expect(hostedOf(doc)?.user_message).toContain('?ref=cli-mcp-expose-friction');+ const login = fakeTailnet({ backendState: 'NeedsLogin', afterUp: 'NeedsLogin' });+ expect(await runMcpExpose(['--yes'], login.deps)).toBe(2);+ expect(login.stdout.join('\n')).toContain('Hosted option: gbrain.io runs GBrain for you, nothing to keep online: https://gbrain.io/?ref=cli-mcp-expose-friction (hide: gbrain notices mute hosted_option)');+ });+ test('a muted owner sees nothing', async () => {+ const f = fakeTailnet();+ f.deps.mutedNotices = () => new Set(['hosted_option']);+ expect(await runMcpExpose(['--yes', '--json'], f.deps)).toBe(0);+ expect(jsonDoc(f).notices).toBeUndefined();+ });+});+describe('happy path: darwin (launchd, app-bundle CLI)', () => {test('login pending → "Open the Tailscale app" guidance, plain `<app> up`, no sudo', async () => {const f = fakeMac({ backendState: 'NeedsLogin', afterUp: 'NeedsLogin' });diff --git a/test/setup.test.ts b/test/setup.test.tsindex e5139b053e..92b9f482ec 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -105,12 +105,25 @@ describe('gbrain setup claude-code: install lifecycle', () => {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.match(/\[AGENT\]/g)).toHaveLength(2);+ const hosted = r.stdout.indexOf('[hosted_option]');+ expect(r.stdout.indexOf('[first_run_decisions]')).toBeGreaterThan(next);+ expect(hosted).toBeGreaterThan(r.stdout.indexOf('[first_run_decisions]'));+ expect(r.stdout.slice(block, hosted)).toContain('in the reply that reports this install');+ expect(r.stdout.slice(block, hosted)).toContain('(id: search_mode)');+ expect(r.stdout.slice(hosted)).toContain('https://gbrain.io/?ref=cli-setup');expect(r.stdout.trimEnd().endsWith('[/AGENT]')).toBe(true);});+ test('hosted_option rides only the run that created the brain', async () => {+ const b = box();+ const first = await setup(b, ['claude-code', '--json']);+ expect(first.doc.notices.map((n: any) => n.code)).toEqual(['first_run_decisions', 'hosted_option']);+ expect(first.doc.notices[1].user_message).toContain('https://gbrain.io/?ref=cli-setup');+ const second = await setup(b, ['claude-code', '--json']);+ expect(second.doc.notices.map((n: any) => n.code)).not.toContain('hosted_option');+ });+test('#6606: after Next, setup names remember as the way to save a fact and what reaches new sessions', async () => {const b = box();const r = await setup(b, ['claude-code']);