Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(init): one first-run decision bundle with writeback and skills_scaffold; no bare registration or made-up fact
garrytanab1294b0cab7
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 1a72e67bc1..dab1b28414 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -178,7 +178,7 @@ risk: Spends up to the cap on embedding calls; no data is deleted.consent: paidactor: agentnext: ask_user-if_yes: gbrain doctor --remediate --max-usd 0.60 --yes To stop asking for runs under a limit the user picks: gbrain config set consent.preapprove.paid.max_usd_per_run '<usd>'+if_yes: gbrain doctor --remediate --max-usd 0.60 --yes — To stop asking for runs under a limit the user picks: gbrain config set consent.preapprove.paid.max_usd_per_run '<usd>'if_no: Nothing runs; nothing was changed. To look first (read-only): gbrain doctor --remediation-plan --json[SHOW USER]Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?@@ -500,7 +500,7 @@ if_yes: <command to run after the user agrees>if_no: <what happens if they decline>verify: <read-only check>1. <decision question> (id: <decision id>)- - <option id>: <label>+ - <option id>: <label> (run: <command that applies it>)default: <option id> — <why this default>[SHOW USER]<text to relay to the user verbatim>diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 79c5d062cb..548221f732 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -50,10 +50,13 @@ the same registry.```bashgbrain init --pglite # 2-second local brainclaude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs # the memory-verb surface-gbrain remember "I prefer dark mode in every editor" --provenance demo --entity people/me-gbrain recall people/me # …now ask your agent in a NEW session+gbrain remember "gbrain install check" --provenance install-check+gbrain recall --query "gbrain install check" # …now ask your agent in a NEW session```+The marker is a test value, never a fact about the user; ask the agent to+`forget` it once the new session recalled it.+> Memories agents save are readable by every agent connected to this brain;> pass `visibility: "private"` for local-CLI-only facts.diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.tsindex b438e47406..4323cb0daa 100644--- a/src/commands/init-first-run.ts+++ b/src/commands/init-first-run.ts@@ -5,12 +5,14 @@* non-blocking (exit 0); the agent relays the message and applies the chosen* options' argv.*- * Ownership: Lane G5 owns the bundle's content (adding `writeback` and- * `skills_scaffold`, the `user_message` wording, the harness smoke follow-up);- * Lane D ships this seam and the decisions it can build today:- * `search_mode` (the picker's recommendation and cost matrix) and- * `harness_wiring` (the A7 readiness fix). Extend `buildInitFirstRunNotices`- * rather than adding a second notice.+ * Decisions: `search_mode` (the picker's recommendation and cost matrix),+ * `writeback` (recommended `salient`, offered on a personal brain whose+ * operator has not answered), `harness_wiring` (the A7 readiness fix) and the+ * optional `skills_scaffold` (recommended skills missing from the detected+ * agent workspace; default skip). Human output renders the same bundle+ * (`[AGENT]` block without a terminal, `Note` lines on one); it replaces+ * init's separate writeback ask and skills pointer. Extend+ * `buildInitFirstRunNotices` rather than adding a second notice.*/import type { Decision, Notice } from '../core/agent-output.ts';import type { GBrainConfig } from '../core/config.ts';@@ -22,6 +24,10 @@ export interface InitFirstRunInputs {searchMode?: { mode: SearchMode; reason: string };/** The config init saved; harness wiring is read from its config-plane readiness. */config?: GBrainConfig | null;+ /** True when the ambient-writeback ask applies (`writebackAskApplies`). */+ writeback?: boolean;+ /** Recommended skills missing from the agent workspace (`initSkillsScaffold`). */+ skillsScaffold?: { missing: string[]; argv: string[] } | null;}const SEARCH_MODE_COST =@@ -54,14 +60,46 @@ function harnessWiringDecision(config: GBrainConfig): Decision | null {};}+function writebackDecision(): Decision {+ const set = (mode: string) => ['gbrain', 'config', 'set', 'memory.auto_writeback', mode];+ return {+ id: 'writeback',+ question: 'Should agents save important facts the user states (preferences, decisions, commitments) automatically, with provenance? '+ + 'Saved facts are readable by agents connected to this brain; transient facts expire. Off any time with `gbrain config set memory.auto_writeback off`.',+ options: [+ { id: 'salient', label: 'Save durable facts the user states directly (recommended)', argv: set('salient') },+ { id: 'all', label: 'Every direct factual statement (more low-value facts, more extraction spend)', argv: set('all') },+ { id: 'off', label: 'Save only what the user explicitly asks to remember (records the answer)', argv: set('off') },+ ],+ default: 'salient',+ default_reason: 'Recommended for a personal brain: the brain learns what the user tells their agents. It is opt-in, so it applies only when the user accepts the defaults or picks it.',+ };+}++function skillsScaffoldDecision(scaffold: { missing: string[]; argv: string[] }): Decision {+ const preview = scaffold.missing.slice(0, 4).join(', ') + (scaffold.missing.length > 4 ? ', …' : '');+ return {+ id: 'skills_scaffold',+ question: `Install ${scaffold.missing.length} recommended gbrain skill(s) into the agent workspace (${preview})? Optional; \`gbrain advisor\` lists what each does.`,+ options: [+ { id: 'skip', label: 'Skip for now.' },+ { id: 'scaffold', label: 'Scaffold the recommended skills into the workspace.', argv: scaffold.argv },+ ],+ default: 'skip',+ default_reason: 'Optional: the brain works without them; scaffolding writes files into the user\'s workspace.',+ };+}+/** The bundle: empty when there is nothing to decide. */export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {const decisions: Decision[] = [];if (inputs.searchMode) decisions.push(searchModeDecision(inputs.searchMode));+ if (inputs.writeback) decisions.push(writebackDecision());if (inputs.config) {const wiring = harnessWiringDecision(inputs.config);if (wiring) decisions.push(wiring);}+ if (inputs.skillsScaffold?.missing.length) decisions.push(skillsScaffoldDecision(inputs.skillsScaffold));if (decisions.length === 0) return [];const defaults = decisions.map(d => `${d.id}: ${d.default}`).join('; ');return [{diff --git a/src/commands/init.ts b/src/commands/init.tsindex 7028c2f1c7..3cf1f9e677 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -18,7 +18,10 @@ import type { BrainEngine } from '../core/engine.ts';import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResult, writeDeferredInitJsonError } from './init-json.ts';import { buildInitFirstRunNotices } from './init-first-run.ts';-import { renderNotice, cliRenderContext } from '../core/agent-output.ts';+import { renderNotice, cliRenderContext, shellQuote, type Notice } from '../core/agent-output.ts';+import { writeCliNotices } from '../core/interop-notices.ts';+import { configReadiness, harnessWiringEntry } from '../core/readiness.ts';+import { resolveGbrainBin } from '../core/gbrain-bin.ts';import { exitCodeForCode } from '../core/error-catalogue.ts';import { promptLineStderr } from '../core/interaction.ts';import type { SearchMode as SearchModeName } from '../core/search/mode.ts';@@ -1268,7 +1271,7 @@ export async function initPGLite(opts: {const stats = await engine.getStats();if (opts.jsonOutput) {- setInitJsonResult({ status: 'success', engine: 'pglite', path: dbPath, pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunNotices(searchMode) });+ setInitJsonResult({ status: 'success', engine: 'pglite', path: dbPath, pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunJson(await firstRunBundle(engine, searchMode)) });} else if (process.env.GBRAIN_IN_AGENT_SETUP === '1') {printInAgentReady(dbPath);} else {@@ -1285,20 +1288,15 @@ export async function initPGLite(opts: {console.log(' gbrain stats (verify links > 0)');}reportModStatus();- const { printAdvisoryIfRecommended } = await import('../core/skillpack/post-install-advisory.ts');- const { VERSION } = await import('../version.ts');- printAdvisoryIfRecommended({ version: VERSION, context: 'init' });// v0.41.18.0 (A4 + A18 + A20, T14): post-initSchema onboard nudge.- // Fail-open; 3s wallclock cap. Skipped silently in non-TTY contexts.+ // Fail-open; 3s wallclock cap.const { runInitNudge } = await import('../core/onboard/init-nudge.ts');await runInitNudge(engine);- // Ambient-writeback consent ask (WP8): personal brains only, fires- // once ever (sentinel), [AGENT]-relayed on non-TTY, never auto-enables,- // never blocks init.- const { runWritebackNudge } = await import('../core/onboard/writeback-nudge.ts');- await runWritebackNudge(engine, { context: 'init' });+ // G5: the ONE first-run decision bundle (search mode, writeback,+ // harness wiring, skills scaffold); never blocks init.+ writeCliNotices(await firstRunBundle(engine, searchMode));// The single primary action, last-on-screen.printMemoryVerbsQuickstart({ emptyBrain: stats.page_count === 0, onPglite: true });@@ -1310,29 +1308,55 @@ export async function initPGLite(opts: {const INIT_EMBEDDING_HINT = 'Pick an embedding model whose dimensions match (`gbrain init --help`), or pass --no-embedding for a keyless brain.';-/** D2/G5: the first-run decision bundle rendered into init's --json document (`notices`, empty → omitted). */-function firstRunNotices(searchMode: { mode: SearchModeName; reason: string } | undefined): { notices?: unknown[]; contract_version: 1 } {- const notices = buildInitFirstRunNotices({ searchMode, config: loadConfig() }).map(n => renderNotice(n, cliRenderContext()));+/**+ * G5: the ONE first-run decision bundle: search mode, writeback (personal+ * brain, unanswered), harness wiring and the optional skills scaffold. Human+ * output writes it through the CLI notice channel; --json carries it.+ */+async function firstRunBundle(engine: BrainEngine, searchMode: { mode: SearchModeName; reason: string } | undefined): Promise<Notice[]> {+ const { writebackAskApplies } = await import('../core/onboard/writeback-nudge.ts');+ const { initSkillsScaffold } = await import('../core/skillpack/post-install-advisory.ts');+ return buildInitFirstRunNotices({ searchMode, config: loadConfig(), writeback: await writebackAskApplies(engine), skillsScaffold: initSkillsScaffold() });+}++/** D2/G5: the bundle rendered into init's --json document (`notices`, empty → omitted). */+function firstRunJson(bundle: Notice[]): { notices?: unknown[]; contract_version: 1 } {+ const notices = bundle.map(n => renderNotice(n, cliRenderContext()));return { ...(notices.length ? { notices } : {}), contract_version: 1 };}+/**+ * The harness registration line for the quickstart: the readiness+ * `harness_wiring` fix (absolute binary, `--surface verbs`) for the detected+ * harness, else the Claude Code registration built the same way. Null when+ * the gbrain binary has no absolute path (never registered bare).+ */+function harnessRegistrationCommand(): string | null {+ const cfg = loadConfig();+ const detected = cfg ? configReadiness(cfg, { transport: 'cli' }).entries.find(e => e.capability === 'harness_wiring')?.fix : undefined;+ if (detected?.argv) return shellQuote(detected.argv);+ const claude = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: null, gbrainBin: resolveGbrainBin() }).fix;+ return claude?.argv ? shellQuote(claude.argv) : null;+}+/*** MEMORY_VERBS v1 quickstart funnel (E3 + D4B + T1 consent). Printed LAST in* both init epilogues as the ONE primary action. The copy-next block is- * EXACTLY three commands (codex DX 9): wire the harness, write a memory, prove- * the resurrection. The demo uses the facts arm only, so it works with NO- * embedding key [F-B]. Secondary paths (import, migrate) ride a single terse+ * three commands (codex DX 9): wire the harness (the readiness+ * `harness_wiring` fix: absolute binary, `--surface verbs`), save an+ * install-check marker (never a made-up fact about the user), and recall it.+ * The demo uses the facts arm only, so it works with NO embedding key [F-B]. Secondary paths (import, migrate) ride a single terse* "More:" footer so they never compete with the primary action.*/function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boolean } = {}): void {+ const register = harnessRegistrationCommand();console.log('');- console.log('→ Do this next — give your agent memory (copy these three commands):');- console.log(' claude mcp add gbrain -- gbrain serve --surface verbs');- console.log(' gbrain remember "I prefer dark mode in every editor" --provenance demo --entity people/me');- // #3697: recall takes the entity as a positional (there is no --entity flag;- // the old form only worked because recall skips unknown flags silently).- console.log(' gbrain recall people/me');- console.log('Then ask your agent in a NEW session — it remembers.');+ console.log(`→ Do this next — give your agent memory (copy these ${register ? 'three' : 'two'} commands):`);+ if (register) console.log(` ${register}`);+ else console.log(' (register gbrain with your agent app first: install gbrain globally so the registration can use its absolute path, then follow docs/protocol/MEMORY_VERBS_v1.md)');+ console.log(' gbrain remember "gbrain install check" --provenance install-check');+ console.log(' gbrain recall --query "gbrain install check"');+ console.log('Then ask your agent in a NEW session to recall "gbrain install check" — it remembers. Ask it to forget that fact afterwards.');console.log('');console.log('Note: memories agents save are readable by every agent connected to');console.log('this brain; use visibility:"private" for local-only facts.');@@ -1608,7 +1632,7 @@ export async function initPostgresCore(opts: {const stats = await engine.getStats();if (opts.jsonOutput) {- setInitJsonResult({ status: 'success', engine: 'postgres', pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunNotices(searchMode) });+ setInitJsonResult({ status: 'success', engine: 'postgres', pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunJson(await firstRunBundle(engine, searchMode)) });} else {console.log(`\nBrain ready. ${stats.page_count} pages. Engine: Postgres (Supabase).`);if (stats.page_count > 0) {@@ -1619,18 +1643,14 @@ export async function initPostgresCore(opts: {console.log(' gbrain stats (verify links > 0)');}reportModStatus();- const { printAdvisoryIfRecommended } = await import('../core/skillpack/post-install-advisory.ts');- const { VERSION } = await import('../version.ts');- printAdvisoryIfRecommended({ version: VERSION, context: 'init' });// v0.41.18.0 (A4 + A18 + A20, T14): post-initSchema onboard nudge.- // Fail-open; 3s wallclock cap. Skipped silently in non-TTY contexts.+ // Fail-open; 3s wallclock cap.const { runInitNudge } = await import('../core/onboard/init-nudge.ts');await runInitNudge(engine);- // Ambient-writeback consent ask (WP8) — same contract as the PGLite arm.- const { runWritebackNudge } = await import('../core/onboard/writeback-nudge.ts');- await runWritebackNudge(engine, { context: 'init' });+ // G5: the first-run decision bundle — same contract as the PGLite arm.+ writeCliNotices(await firstRunBundle(engine, searchMode));// The single primary action, last-on-screen.printMemoryVerbsQuickstart({ emptyBrain: stats.page_count === 0 });diff --git a/src/core/agent-markers.ts b/src/core/agent-markers.tsindex 34dd83ed8d..3f46773263 100644--- a/src/core/agent-markers.ts+++ b/src/core/agent-markers.ts@@ -8,7 +8,12 @@* marker tokens lose their opening bracket, so a page title or model name* cannot open or close a block. Field names come from the fixed vocabulary.*/-import { inertText, type Decision, type RenderedNotice } from './agent-output.ts';+import { inertText, shellQuote, type Decision, type DecisionOption, type RenderedNotice } from './agent-output.ts';++/** One decision option line body: `<id>: <label>`, plus the command that applies it. */+function optionText(o: DecisionOption): string {+ return `${inertText(o.id, 80)}: ${inertText(o.label, MAX_FIELD)}${o.argv?.length ? ` (run: ${inertText(shellQuote(o.argv), MAX_FIELD)})` : ''}`;+}export const AGENT_FIELDS = ['ask', 'why', 'risk', 'consent', 'actor', 'next', 'if_yes', 'if_no', 'verify'] as const;export type AgentField = (typeof AGENT_FIELDS)[number];@@ -24,7 +29,7 @@ export function agentBlock(fields: Partial<Record<AgentField, string>>, opts: {}(opts.decisions ?? []).forEach((d, i) => {lines.push(`${i + 1}. ${inertText(d.question, MAX_FIELD)} (id: ${inertText(d.id, 80)})`);- for (const o of d.options) lines.push(` - ${inertText(o.id, 80)}: ${inertText(o.label, MAX_FIELD)}`);+ for (const o of d.options) lines.push(` - ${optionText(o)}`);lines.push(` default: ${inertText(d.default, 80)} — ${inertText(d.default_reason, MAX_FIELD)}`);});if (opts.showUser) lines.push('[SHOW USER]', inertText(opts.showUser, MAX_FIELD), '[/SHOW USER]');@@ -46,6 +51,10 @@ export function renderCliNotices(notices: readonly RenderedNotice[], opts: { jsoconst lines = notices.flatMap(n => [`Note [${n.code}]: ${n.why}`,...(n.fix?.command ? [` Fix: ${n.fix.command}`] : []),+ ...(n.decisions ?? []).flatMap(d => [+ ` ${inertText(d.question, MAX_FIELD)} (default: ${inertText(d.default, 80)})`,+ ...d.options.map(o => ` - ${optionText(o)}`),+ ]),]);return { stderr: `${lines.join('\n')}\n` };}diff --git a/src/core/onboard/writeback-nudge.ts b/src/core/onboard/writeback-nudge.tsindex 1962fcde8e..46653d7184 100644--- a/src/core/onboard/writeback-nudge.ts+++ b/src/core/onboard/writeback-nudge.ts@@ -35,18 +35,21 @@ import {DEFAULT_TRANSIENT_TTL,} from '../facts/writeback-config.ts';-export async function runWritebackNudge(- engine: BrainEngine,- opts: { context?: 'init' | 'post-upgrade' } = {},-): Promise<void> {+/**+ * Whether the writeback ask applies to this brain right now: a personal host+ * brain whose operator has not answered yet, with no bypass. The gate behind+ * both this nudge and init's first-run `writeback` decision. Never throws+ * (any failure → false).+ */+export async function writebackAskApplies(engine: BrainEngine): Promise<boolean> {try {- if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return;+ if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return false;const cfg = loadConfig();- if (cfg && isThinClient(cfg)) return;+ if (cfg && isThinClient(cfg)) return false;try {- if (resolveBrainId(undefined) !== HOST_BRAIN_ID) return;+ if (resolveBrainId(undefined) !== HOST_BRAIN_ID) return false;} catch {- return; // mount resolution failed — fail-quiet+ return false; // mount resolution failed — fail-quiet}// Double gate: shown once ever, and never when the operator already@@ -55,10 +58,21 @@ export async function runWritebackNudge(engine.getConfig(AUTO_WRITEBACK_NOTICE_KEY),engine.getConfig(AUTO_WRITEBACK_KEY),]);- if (shown === 'true' || mode) return;+ if (shown === 'true' || mode) return false;const audience = await classifyBrainAudience(engine, cfg);- if (audience.audience !== 'personal') return;+ return audience.audience === 'personal';+ } catch {+ return false;+ }+}++export async function runWritebackNudge(+ engine: BrainEngine,+ opts: { context?: 'init' | 'post-upgrade' } = {},+): Promise<void> {+ try {+ if (!(await writebackAskApplies(engine))) return;const line = console.log;line('');diff --git a/src/core/skillpack/post-install-advisory.ts b/src/core/skillpack/post-install-advisory.tsindex 7a28ad996a..f9cb388318 100644--- a/src/core/skillpack/post-install-advisory.ts+++ b/src/core/skillpack/post-install-advisory.ts@@ -116,67 +116,54 @@ function buildAdvisoryWithoutWorkspace(}/**- * Print the advisory to stderr at the end of init / post-upgrade.- * No-op when buildAdvisory returns null.- *- * `init` prints a COMPACT 3-line pointer: the init success screen already- * competes for one primary action (the memory-verbs funnel), and the full- * 55-line agent-addressed banner buried it. The full banner remains the- * `upgrade` surface (its designed audience) and stays available any time- * via `gbrain advisor`. buildAdvisory itself is unchanged — it is the- * agent-readable document, pinned by tests and shared with `gbrain advisor`.+ * init's optional `skills_scaffold` first-run decision: the recommended+ * skills missing from the detected agent workspace and the scaffold argv+ * that installs them. Null when no workspace is detected (scaffold has no+ * target), when every recommended skill is installed, or on any read error.+ * The full agent-addressed banner stays the `upgrade` surface and `gbrain+ * advisor`.+ */+export function initSkillsScaffold(opts: {+ targetWorkspace?: string | null;+ targetSkillsDir?: string | null;+} = {}): { missing: string[]; argv: string[] } | null {+ try {+ let workspace = opts.targetWorkspace ?? null;+ let skillsDir = opts.targetSkillsDir ?? null;+ if (!skillsDir) {+ const detected = autoDetectSkillsDir();+ if (detected.dir) {+ skillsDir = detected.dir;+ if (!workspace) workspace = resolvePath(skillsDir, '..');+ }+ }+ if (!workspace || !skillsDir) return null;+ const all = currentRecommendedSet();+ const installed = detectInstalledSlugs(skillsDir, workspace);+ const missing = all.filter((s) => !installed.has(s.slug));+ if (missing.length === 0) return null;+ const slugs = missing.map((s) => s.slug);+ return { missing: slugs, argv: ['gbrain', 'skillpack', 'scaffold', ...(missing.length === all.length ? ['--all'] : slugs)] };+ } catch {+ return null;+ }+}++/**+ * Print the full advisory to stderr at the end of `post-upgrade`. No-op when+ * buildAdvisory returns null. Fail-open: an unreadable RESOLVER.md never+ * breaks the command.*/export function printAdvisoryIfRecommended(opts: {version: string;- context: 'init' | 'upgrade';+ context: 'upgrade';targetWorkspace?: string | null;targetSkillsDir?: string | null;}): void {- // Fail-open: this is decoration on the init success screen and runs AFTER- // the brain is created (and, since the memory-verbs quickstart now prints- // last, BEFORE it). An unreadable RESOLVER.md must never throw here and- // starve the primary CTA — same posture as runInitNudge.try {const advisory = buildAdvisory(opts);- if (!advisory) return;- if (opts.context === 'init') {- // Derive the counts for the compact form from the same detection the- // full banner used. Detection is hoisted OUT of the filter (one receipt- // read+parse total, matching buildAdvisory's own pattern).- let workspace = opts.targetWorkspace ?? null;- let skillsDir = opts.targetSkillsDir ?? null;- if (!skillsDir) {- const detected = autoDetectSkillsDir();- if (detected.dir) {- skillsDir = detected.dir;- if (!workspace) workspace = resolvePath(skillsDir, '..');- }- }- const all = currentRecommendedSet();- const installed = workspace && skillsDir ? detectInstalledSlugs(skillsDir, workspace) : null;- const missing = installed ? all.filter((s) => !installed.has(s.slug)) : all;- if (missing.length === 0) return;- const names = missing.map((s) => s.slug);- const preview = names.slice(0, 4).join(', ') + (names.length > 4 ? ', …' : '');- // No workspace detected → scaffold has no target; say so (the full- // banner carries the same caveat via workspaceNotDetected).- const noWorkspace = installed === null;- // Human-voiced (prints on the init success screen where a person may read- // it) — no `[AGENT]` stage-direction leaking to the human. An agent reading- // the same line still knows the command to offer.- process.stderr.write(- `\n${missing.length} recommended skill(s) not installed yet (${preview}).\n` +- // NOTE: no bare `--flag` tokens in this string — the flag-registry- // generator harvests them from source strings and would register a- // phantom flag on every command that imports this module.- (noWorkspace- ? `Open your agent workspace first (scaffold needs a target), then \`${scaffoldCommandFor(missing, all)}\`; full list: gbrain advisor\n`- : `Ask me to run \`${scaffoldCommandFor(missing, all)}\`, or see the full list: gbrain advisor\n`),- );- return;- }- process.stderr.write(advisory);+ if (advisory) process.stderr.write(advisory);} catch {- /* advisory is best-effort decoration — never break init */+ /* advisory is best-effort decoration — never break the command */}}diff --git a/test/init-first-run.test.ts b/test/init-first-run.test.tsnew file mode 100644index 0000000000..2692862ec9--- /dev/null+++ b/test/init-first-run.test.ts@@ -0,0 +1,51 @@+/**+ * init's first-run decision bundle (agent operator wave G5): ONE `kind: ask`+ * notice whose decisions carry search mode, writeback (recommended salient),+ * harness wiring and the optional skills scaffold, with one user_message+ * offering 'defaults'. Pure: no engine, no filesystem.+ */+import { describe, expect, test } from 'bun:test';+import { buildInitFirstRunNotices } from '../src/commands/init-first-run.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'] };++describe('buildInitFirstRunNotices', () => {+ test('one ask notice: search_mode, writeback, skills_scaffold in order, one defaults relay', () => {+ const notices = buildInitFirstRunNotices({ searchMode, writeback: true, skillsScaffold: scaffold });+ expect(notices).toHaveLength(1);+ const [bundle] = notices;+ expect(bundle).toMatchObject({ code: 'first_run_decisions', kind: 'ask' });+ expect(bundle.decisions!.map(d => d.id)).toEqual(['search_mode', 'writeback', 'skills_scaffold']);+ expect(bundle.user_message).toBe(+ "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: balanced; writeback: salient; skills_scaffold: skip), or tell me what to change.",+ );+ });++ test('writeback recommends salient; every option applies through config set', () => {+ const writeback = buildInitFirstRunNotices({ writeback: true })[0].decisions!.find(d => d.id === 'writeback')!;+ expect(writeback.default).toBe('salient');+ expect(writeback.options.map(o => o.id)).toEqual(['salient', 'all', 'off']);+ for (const o of writeback.options) expect(o.argv).toEqual(['gbrain', 'config', 'set', 'memory.auto_writeback', o.id]);+ });++ test('skills_scaffold is optional: default skip, the scaffold option carries the argv', () => {+ const decision = buildInitFirstRunNotices({ skillsScaffold: scaffold })[0].decisions!.find(d => d.id === 'skills_scaffold')!;+ expect(decision.default).toBe('skip');+ expect(decision.options.find(o => o.id === 'scaffold')!.argv).toEqual(scaffold.argv);+ expect(decision.options.find(o => o.id === 'skip')!.argv).toBeUndefined();+ expect(decision.question).toContain('cold-start, book-mirror');+ });++ test('no writeback ask and no missing skills → those decisions are omitted', () => {+ const ids = buildInitFirstRunNotices({ searchMode, writeback: false, skillsScaffold: null })[0].decisions!.map(d => d.id);+ expect(ids).toEqual(['search_mode']);+ expect(buildInitFirstRunNotices({ writeback: false, skillsScaffold: { missing: [], argv: [] } })).toEqual([]);+ });++ test('no decision saves a fact: nothing in the bundle runs remember', () => {+ const [bundle] = buildInitFirstRunNotices({ searchMode, writeback: true, skillsScaffold: scaffold });+ const argvs = bundle.decisions!.flatMap(d => d.options.map(o => o.argv ?? []));+ expect(argvs.some(a => a.includes('remember'))).toBe(false);+ });+});diff --git a/test/init-fresh-pglite.slow.test.ts b/test/init-fresh-pglite.slow.test.tsindex e6d80b0dc1..1fb01fbacc 100644--- a/test/init-fresh-pglite.slow.test.ts+++ b/test/init-fresh-pglite.slow.test.ts@@ -288,6 +288,33 @@ describe('v0.37 T12 — D9 --no-embedding deferred-setup mode', () => {expect(cfg.embedding_model).toBeUndefined();}, 120000);+ test('init human output without a terminal: ONE first-run bundle, no separate writeback ask, no bare registration, no made-up fact', async () => {+ const home = makeTempHome();+ try {+ const r = await runCli(['init', '--pglite', '--no-embedding'], { gbrainHome: home, env: {} });+ expect(r.exitCode).toBe(0);+ const out = r.stdout;+ // Exactly one [AGENT] block carries the bundle, with the writeback decision and one relay.+ const bundle = out.slice(out.indexOf('[first_run_decisions]'));+ expect(out.match(/\[first_run_decisions\]/g)).toHaveLength(1);+ expect(bundle).toContain('(id: writeback)');+ expect(bundle).toContain('(run: gbrain config set memory.auto_writeback salient)');+ expect(bundle).toContain('default: salient');+ expect(out.match(/Reply 'defaults'/g)).toHaveLength(1);+ // The old separate writeback banner/[AGENT] ask and the skills pointer are gone.+ expect(out).not.toContain('Ambient memory writeback is available');+ expect(out + r.stderr).not.toContain('Ask me to run');+ expect(out + r.stderr).not.toContain('recommended skill(s) not installed yet');+ // No bare-binary registration and no fabricated user fact.+ expect(out).not.toContain('claude mcp add gbrain -- gbrain serve');+ expect(out).not.toContain('dark mode');+ expect(out).not.toContain('people/me');+ expect(out).toContain('gbrain remember "gbrain install check" --provenance install-check');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 120000);+test('gbrain import refuses with config-set hint after --no-embedding init', async () => {// Seed a markdown file to import.const repoDir = join(tmpHome, 'sample-repo');diff --git a/test/post-install-advisory.test.ts b/test/post-install-advisory.test.tsindex fd07510d66..b8781b73ae 100644--- a/test/post-install-advisory.test.ts+++ b/test/post-install-advisory.test.ts@@ -26,6 +26,7 @@ import {buildAdvisory,detectInstalledSlugs,printAdvisoryIfRecommended,+ initSkillsScaffold,} from '../src/core/skillpack/post-install-advisory.ts';import { currentRecommendedSet } from '../src/core/advisor/recommended-set.ts';@@ -231,7 +232,7 @@ describe('buildAdvisory — agent-readable framing', () => {});});-describe('printAdvisoryIfRecommended — compact init pointer vs full upgrade banner', () => {+describe('initSkillsScaffold — init\'s optional skills_scaffold decision; upgrade keeps the full banner', () => {function captureStderr(fn: () => void): string {const orig = process.stderr.write;let out = '';@@ -247,40 +248,25 @@ describe('printAdvisoryIfRecommended — compact init pointer vs full upgrade bareturn out;}- it('context init with all skills missing prints the compact human-voiced pointer', () => {+ it('all skills missing → every slug and the --all scaffold argv', () => {const { workspace, skillsDir } = scratchWorkspace([]);- const out = captureStderr(() =>- printAdvisoryIfRecommended({- version: '0.25.1',- context: 'init',- targetWorkspace: workspace,- targetSkillsDir: skillsDir,- }),- );- const names = currentRecommendedSet().map((s) => s.slug);- expect(out).toContain('recommended skill(s) not installed yet');- // Preview truncates at 4 slugs + ellipsis; the 5th slug never appears- // (the scaffold command is --all when everything is missing).- expect(out).toContain(`(${names.slice(0, 4).join(', ')}, …)`);- expect(out).not.toContain(names[4]);- expect(out).toContain('gbrain advisor');- // The compact init pointer is human-voiced — no agent stage directions.- expect(out).not.toContain('ACTION FOR THE AGENT');- expect(out).not.toContain('[AGENT]');+ const scaffold = initSkillsScaffold({ targetWorkspace: workspace, targetSkillsDir: skillsDir })!;+ expect(scaffold.missing).toEqual(currentRecommendedSet().map((s) => s.slug));+ expect(scaffold.argv).toEqual(['gbrain', 'skillpack', 'scaffold', '--all']);+ });++ it('some skills installed → only the missing slugs, named in the argv', () => {+ const all = currentRecommendedSet().map((s) => s.slug);+ const { workspace, skillsDir } = scratchWorkspace(all.slice(1));+ const scaffold = initSkillsScaffold({ targetWorkspace: workspace, targetSkillsDir: skillsDir })!;+ expect(scaffold.missing).toEqual([all[0]]);+ expect(scaffold.argv).toEqual(['gbrain', 'skillpack', 'scaffold', all[0]]);});- it('context init with everything installed prints NOTHING', () => {+ it('everything installed → null (no decision)', () => {const allSlugs = currentRecommendedSet().map((s) => s.slug);const { workspace, skillsDir } = scratchWorkspace(allSlugs);- const out = captureStderr(() =>- printAdvisoryIfRecommended({- version: '0.25.1',- context: 'init',- targetWorkspace: workspace,- targetSkillsDir: skillsDir,- }),- );- expect(out).toBe('');+ expect(initSkillsScaffold({ targetWorkspace: workspace, targetSkillsDir: skillsDir })).toBeNull();});it('context upgrade with missing skills keeps the full agent-addressed banner', () => {