Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(hosted-option): in-agent fresh-brain guard and own-launcher mute hint, full Tailscale friction list, simpler mute read

garrytan7d06356ec6c1
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 4163df16b7..ac57b7aefb 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -16,7 +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/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 when init created the brain (its mute hint names that install's own launcher), 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. Refs split publish (`cli-mcp-expose`) from friction exits (`cli-mcp-expose-friction`). Muted by the owner list or the `stdio` audience (`hostedOptionMuted`, i.e. `mutedNoticeCodes('stdio')`); `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/src/commands/init.ts b/src/commands/init.ts
index 1850a55a34..afddd9a0a7 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1277,7 +1277,7 @@ export async function initPGLite(opts: {
if (opts.jsonOutput) {
setInitJsonResult({ status: 'success', engine: 'pglite', path: dbPath, pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunJson(await firstRunBundle(engine, searchMode, registrationSurface)) });
} else if (process.env.GBRAIN_IN_AGENT_SETUP === '1') {
- printInAgentReady(dbPath);
+ printInAgentReady(dbPath, freshContentDatabase);
} else {
console.log(`\nBrain ready at ${dbPath}`);
console.log(`${stats.page_count} pages. Engine: PGLite (local Postgres).`);
diff --git a/src/core/agent-install/init-state.ts b/src/core/agent-install/init-state.ts
index 2b9d78e623..4e613be1b3 100644
--- a/src/core/agent-install/init-state.ts
+++ b/src/core/agent-install/init-state.ts
@@ -4,6 +4,7 @@ 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';
+import { shellQuote } from '../agent-output.ts';
/** `onInvalid` lets init's `--json` writer report the refusal (agent contract v1 D2). */
export function readInitConfigState(json: boolean, onInvalid?: (message: string) => never) {
@@ -42,8 +43,8 @@ export function inspectRemoteInitState(force: boolean, fail: (reason: string, me
/** The setup subprocess retains real init warnings and the search-mode matrix,
* then points to the native skill instead of another harness's bootstrap. */
-export function printInAgentReady(databasePath: string): void {
+export function printInAgentReady(databasePath: string, createdBrain = false): 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 });
+ if (createdBrain) writeHostedOption('in_agent', hostedOptionMuted(), { tty: false, mute: `${shellQuote([join(root, 'bin', 'gbrain')])} notices mute hosted_option` });
}
diff --git a/src/core/onboard/hosted-option.ts b/src/core/onboard/hosted-option.ts
index 97595c0d60..da412a81c5 100644
--- a/src/core/onboard/hosted-option.ts
+++ b/src/core/onboard/hosted-option.ts
@@ -18,8 +18,9 @@ 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',
+ 'tailscale_missing', 'tailscale_unsupported_platform', 'tailscale_install_failed', 'tailscale_daemon_not_running',
+ 'tailscale_login_pending', 'tailscale_login_manual', 'tailscale_no_dns_name', 'tailscale_https_not_enabled',
+ 'tailscale_funnel_not_enabled', 'service_install_failed',
]);
export function hostedOptionUrl(where: HostedOptionWhere): string {
@@ -29,20 +30,21 @@ export function hostedOptionUrl(where: HostedOptionWhere): string {
/** 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')]);
+ return mutedNoticeCodes('stdio');
} catch {
return new Set();
}
}
-export function hostedOptionNotice(where: HostedOptionWhere, muted: ReadonlySet<string>): Notice | null {
+/** `mute` names the command that mutes it for this install (an in-agent install passes its absolute launcher). */
+export function hostedOptionNotice(where: HostedOptionWhere, muted: ReadonlySet<string>, mute = MUTE): 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}.`,
+ user_message: `Hosted option: gbrain.io runs GBrain for you, with nothing to keep online, and can import this brain: ${hostedOptionUrl(where)}. Mute: ${mute}.`,
};
}
@@ -52,8 +54,8 @@ export function hostedOptionLine(where: HostedOptionWhere): string {
}
/** 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);
+export function writeHostedOption(where: HostedOptionWhere, muted: ReadonlySet<string>, opts: { tty?: boolean; mute?: string } = {}): void {
+ const notice = hostedOptionNotice(where, muted, opts.mute);
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.ts
index f6cec1a0b8..0290d55a0b 100644
--- a/test/hosted-option.test.ts
+++ b/test/hosted-option.test.ts
@@ -63,14 +63,16 @@ describe('hosted_option notice', () => {
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 () => {
+ test('the in-agent ready text names hosted GBrain only for a brain it created, with the install\'s own launcher in the mute hint', async () => {
await inHome(() => {
const log = spyOn(console, 'log').mockImplementation(() => {});
try {
- const shown = captured(() => printInAgentReady('/tmp/agent-root/data/brain.pglite'));
+ const db = '/tmp/agent root/data/brain.pglite';
+ const shown = captured(() => printInAgentReady(db, true));
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');
+ expect(shown.stdout).toContain("'/tmp/agent root/bin/gbrain' notices mute hosted_option");
+ expect(captured(() => printInAgentReady(db, false)).stdout).not.toContain('gbrain.io');
+ expect(captured(() => printInAgentReady(db)).stdout).not.toContain('gbrain.io');
} finally { log.mockRestore(); }
});
});