Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/first-run-settings-relayed
garrytan3a4cab215f8a
diff --cc docs/architecture/key-files/commands-5.mdindex 9090fc4e4f,5267bb69a3..e786c8e7e5--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@@ -28,7 -28,7 +28,7 @@@ Current behavior and load-bearing invar- `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 --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/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). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`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). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`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 --cc src/commands/setup.tsindex 109c93d7c3,7d646a69c4..26532af609--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@@ -364,24 -376,10 +378,10 @@@ export async function runSetup(args: streturn 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 () => {- say(out, `Creating the brain: ${initArgv.join(' ')}`);- 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 (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,- beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out); } : undefined,++ beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out, 'claude-code'); } : undefined,});for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);if (!result.changed) say(out, 'Nothing changed: this install is already wired.');@@@ -405,10 -403,162 +405,167 @@@}}- function hostedConnection(url: string, wired: boolean, name: string): OperationError {+ function liveOwnerOf(cfg: GBrainConfig | null, ours: boolean): { dataDir?: string; liveOwner: Target['live_owner'] } {+ const dataDir = cfg && cfg.engine === 'pglite' && !cfg.database_url ? cfg.database_path ?? gbrainPath('brain.pglite') : undefined;+ const lock = dataDir ? peekLock(dataDir) : null;+ return { dataDir, liveOwner: lock?.held && lock.isServe && lock.pid !== undefined+ ? { pid: lock.pid, transport: lock.http ? 'http' : 'stdio', ours: ours && !lock.http } : null };+ }++ function liveServeConflict(live: NonNullable<Target['live_owner']>, harness: SetupHarnessId, name: string): OperationError {+ const http = live.transport === 'http';+ return ownerConflict('live_serve',+ `A live gbrain ${http ? 'serve --http' : 'stdio serve'} (PID ${live.pid}) holds this PGLite brain's single-writer lock; a stdio registration would start a second server that fails on the lock.`,+ http+ ? { actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--harness', harness, '--yes'], consent: ['persistent_install', 'credentials'],+ why: `Connect ${HARNESS_LABEL[harness]} to the running shared server instead of starting a second owner.`, verify: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'] } }+ : { actor: 'user', argv: ['kill', String(live.pid)],+ why: 'Stop the server that holds the brain (quit the agent session that started it), then run setup again.',+ user_message: `gbrain's database is in use by another server (PID ${live.pid}). Please quit the agent session that started it, then I'll run setup again.`,+ verify: verifyDryRun(harness, name) });+ }+-/** Run the `gbrain init` child that creates a new keyless brain; returns its JSON notices. */-function runBrainInit(initArgv: string[], out: Out): unknown[] {++/** Run the `gbrain init --json` child that creates a new keyless brain; returns setup's form of its first-run bundle. */++function runBrainInit(initArgv: string[], out: Out, harness: SetupHarnessId): Notice[] {+ say(out, `Creating the brain: ${initArgv.join(' ')}`);+ 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) return [];- try { return (JSON.parse(initOut) as { notices?: unknown[] }).notices ?? []; } catch { process.stderr.write(initOut); return []; }++ 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}`);++ return setupFirstRunNotices(doc.notices ?? [], HARNESS_LABEL[harness]);++ } catch { process.stderr.write(initOut); return []; }+ }++ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConfig | null, brainHome: string, out: Out): Promise<number> {+ const paths = codexSetupPaths(flags.name);+ try {+ const receiptRead = readCodexSetupReceipt(paths.receiptPath);+ if (flags.remove) return await runCodexRemove(flags, receiptRead.setup, paths.receiptPath, brainHome, out);++ const hostedUrl = cfg?.remote_mcp?.mcp_url ?? receiptRead.hosted?.mcp_url ?? (receiptRead.hosted ? 'a hosted brain' : undefined);+ if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags.name, 'codex'), out);+ const prior = receiptRead.setup;+ if (prior && prior.gbrain_home !== brainHome) {+ return refuse(ownerConflict('other_install', `The '${flags.name}' connection belongs to the gbrain install at ${prior.gbrain_home}, not ${brainHome}.`, {+ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--name', `${flags.name}-2`, '--dry-run', '--json'],+ why: 'Each install owns its own MCP name and hooks; preview this install under another name.', verify: verifyDryRun('codex', flags.name) }), out);+ }++ const notes: string[] = [];+ const consent = resolveConsent(flags, prior, cfg, 'user', notes);+ const envSurface = process.env.GBRAIN_SURFACE;+ if (envSurface && !isRegistrationSurface(envSurface)) notes.push(`GBRAIN_SURFACE='${envSurface}' is not verbs, starter or full; ignored.`);+ const surface: McpSurface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined) ?? prior?.surface ?? REGISTRATION_SURFACE;+ const sourceId = flags.source ?? (process.env.GBRAIN_SOURCE && isValidSourceId(process.env.GBRAIN_SOURCE) ? process.env.GBRAIN_SOURCE : null);+ const plan: CodexSetupPlan = {+ name: flags.name, launcher, brainHome,+ ...(process.env.GBRAIN_HOME?.trim() ? { gbrainHomeEnv: process.env.GBRAIN_HOME.trim() } : {}),+ sourceId, surface, events: hookEvents<CodexSetupEvent>(consent, 'codex'),+ };+ const found = inspectCodexSetup(plan);+ if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name, 'codex'), out);++ const pluginOwner = codexPluginProvidesName(paths.configPath, flags.name);+ const { dataDir, liveOwner } = liveOwnerOf(cfg, prior?.status === 'installed' && found.mcp.state === 'current');+ const target: Target = {+ brain: !cfg ? { kind: 'new-local-pglite', path: gbrainPath('brain.pglite'), config_dir: brainHome }+ : cfg.engine === 'pglite' ? { kind: 'local-pglite', path: dataDir, config_dir: brainHome } : { kind: 'local-postgres', config_dir: brainHome },+ source: { id: sourceId, pinned: sourceId !== null, from: flags.source ? 'flag' : sourceId ? 'env' : 'brain-default' },+ transport: 'local-stdio', launcher, surface,+ registration_owner: pluginOwner ? 'plugin' : prior ? 'setup' : 'none',+ live_owner: liveOwner, scope: 'user', name: flags.name,+ config_path: found.configPath, hooks_path: found.hooksPath, receipt_path: found.receiptPath,+ };+ describeTarget(target, out, 'codex');+ describeConsent(consent, plan.events, out, 'codex');+ for (const n of notes) say(out, `note: ${n}`);++ if (liveOwner && !liveOwner.ours) return refuse(liveServeConflict(liveOwner, 'codex', flags.name), out);+ if (found.mcp.state === 'unowned' && !pluginOwner) {+ return refuse(ownerConflict('unowned_entry', `${found.configPath} already has [mcp_servers.${flags.name}] that gbrain setup did not write (or it was edited since); setup never overwrites it.`, {+ actor: 'agent', argv: ['gbrain', 'setup', 'codex', '--name', `${flags.name}-local`, '--dry-run', '--json'],+ why: 'Preview a setup under another name, or remove that table yourself and run setup again.', verify: verifyDryRun('codex', flags.name) }), out);+ }+ const harnessReceipt = readHarnessReceiptState(brainHome);+ const harnessLane = harnessReceipt.state === 'ok' && harnessReceipt.receipt.targets.some((t) => t.host === 'codex');+ const laneEvents = found.otherLaneEvents.filter((e) => (plan.events as string[]).includes(e));+ if (harnessLane || laneEvents.length > 0) {+ return refuse(ownerConflict('harness_lane', `${harnessLane ? '`gbrain bootstrap harness` already wires Codex for this install' : `${found.hooksPath} already wires ${laneEvents.join(', ')} through gbrain's bootstrap Codex lane`}; two lanes would fire every hook twice.`, {+ actor: 'agent', argv: harnessLane ? ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'] : ['gbrain', 'setup', 'codex', laneEvents.every((e) => e === 'SessionEnd') ? '--no-capture' : '--no-hooks', '--dry-run', '--json'],+ why: harnessLane ? 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.' : 'Keep the bootstrap lane for those events and preview setup without them.', verify: verifyDryRun('codex', flags.name) }), out);+ }++ 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 unchanged = found.prior?.status === 'installed' && found.hooksCurrent && found.trustCurrent && (found.mcp.state === 'current' || !!pluginOwner) && !brainCreate;+ const steps: CodexSetupStep[] = [+ { step: 'receipt', action: unchanged ? 'keep' : 'write', detail: found.receiptPath },+ ...(brainCreate ? [{ step: 'brain' as const, action: 'write' as const, detail: `would run: ${initArgv.join(' ')}` }] : []),+ { step: 'mcp', action: pluginOwner ? 'skip' : found.mcp.state === 'current' ? 'keep' : 'write', detail: `[mcp_servers.${flags.name}] in ${found.configPath}` },+ { step: 'hooks', action: found.hooksCurrent ? 'keep' : 'write', detail: plan.events.length ? `${plan.events.join(', ')} in ${found.hooksPath}` : `no hooks (${found.hooksPath})` },+ { step: 'trust', action: found.trustCurrent ? 'keep' : 'write', detail: `trust entries for setup's groups in ${found.configPath}` },+ ...Object.keys(found.edited).map((event) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),+ ];+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes });+ }+- let notices: unknown[] = [];++ let notices: Notice[] = [];+ const result = await applyCodexSetup(plan, consent, {+ pluginOwner, brainCreated: brainCreate, abortAfter: process.env.GBRAIN_SETUP_ABORT_AFTER,- beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out); } : undefined,++ beforeMcp: brainCreate ? async () => { notices = runBrainInit(initArgv, out, 'codex'); } : undefined,+ });+ for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);+ for (const n of result.notes) say(out, `note: ${n}`);+ if (!result.changed) say(out, 'Nothing changed: this install is already wired.');++ let verify: { ok: boolean; reason: string; message: string };+ if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Codex session and check /mcp lists gbrain.` };+ else if (liveOwner?.ours) verify = { ok: true, reason: 'wired_running', message: `A live stdio serve (PID ${liveOwner.pid}) started by this registration holds the brain.` };+ else {+ const entry = desiredCodexMcpEntry(plan) as { command: string; args: string[]; env?: Record<string, string> };+ verify = await smokeStdioRegistration({ harness: 'codex', source: found.configPath, kind: 'stdio', command: entry.command, args: entry.args, env: entry.env });+ }+ const push = capabilityRows('codex')[0]!.push;+ const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];+ const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved });+ return verify.ok || pluginOwner ? code : 1;+ } catch (e) {+ if (e instanceof OperationError) return refuse(e, out);+ if (e instanceof SetupAbortInjected) { process.stderr.write(`${e.message}\n`); return 1; }+ process.stderr.write(`gbrain setup: ${(e as Error).message}\n`);+ return 1;+ }+ }++ async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | null, receiptPath: string, brainHome: string, out: Out): Promise<number> {+ if (!receipt) {+ say(out, `No gbrain setup receipt at ${receiptPath}; setup owns nothing here, so nothing was removed.`);+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [] });+ }+ if (receipt.gbrain_home !== brainHome) {+ return refuse(ownerConflict('other_install', `The '${receipt.name}' connection belongs to the gbrain install at ${receipt.gbrain_home}, not ${brainHome}; --remove leaves it alone.`, {+ actor: 'user', why: `Run --remove with GBRAIN_HOME set to the install that owns it (${receipt.gbrain_home}).`, user_message: 'This setup belongs to another gbrain install; remove it from that install.' }), out);+ }+ const r = await removeCodexSetup(receipt, receiptPath, { dryRun: flags.dryRun });+ for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);+ for (const n of r.notes) say(out, `note: ${n}`);+ say(out, 'The brain, its notes and unrelated Codex settings were left as they were.');+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved });+ }++ function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {+ const label = HARNESS_LABEL[harness];return opError('setup_hosted_connection',- `This machine already reaches a hosted brain (${url})${wired ? ` and Claude Code's '${name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,- wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect Claude Code to it with \`gbrain connect ${url} --harness claude-code --install\`.`,+ `This machine already reaches a hosted brain (${url})${wired ? ` and ${label}'s '${name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,+ wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect ${label} to it with \`gbrain connect ${url} --harness ${harness} --install\`.`,{ docs: 'docs/guides/repair.md#setup-hosted-connection',fix: wired? { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the registration reaches and smoke-tests it.' }@@@ -433,23 -583,25 +590,26 @@@ async function runRemove(flags: SetupFl}async function finish(out: Out, doc: {- dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: SetupStep[]; states: string[];+ harness?: SetupHarnessId; dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: Array<{ step: string; action: string; detail: string }>; 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 harness = doc.harness ?? 'claude-code';const state = doc.states.at(-1) ?? null;if (out.json) {await writeJsonDocument(`${JSON.stringify({- harness: 'claude-code', dry_run: doc.dryRun, remove: doc.remove ?? false,+ harness, dry_run: doc.dryRun, remove: doc.remove ?? false,...(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,+ capability: capabilityRows(harness)[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.');+ if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);+ if (state && !doc.remove) say(out, harness === 'codex'+ ? 'Next: start a new Codex session (config and hooks are read at session start) and check that /mcp lists gbrain.'+ : '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 --cc src/core/behavior-change-notice.tsindex 297c93221c,67e517d102..691448105b--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -518,8 -518,8 +518,10 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.190.0', text: 'On a managed brain, a successful `gbrain sync --source <id>` settles legacy rows the pre-managed sync left in `sync-failures.jsonl` one at a time (the imported commit holds the file and a live page claims it, or the file is gone and no page claims it); rows on an unknown commit, sentinel rows, held files and files it did not index stay. Doctor `sync_failures` says how many unresolved rows are legacy and which command settles them, and `gbrain sync --retry-failed` names them instead of saying the ledger is empty.' },{ since: '0.60.190.0', text: 'The Postgres in-flight watchdog now also retires a connection whose statement keeps receiving rows or notices past its budget (`pg_connection_stuck` `reason=age`; `reason=idle` when nothing came back, which used to be the only case), and the budget is per statement: an operation that declares a longer `statement_timeout` on its connection (`SET LOCAL`, `set_config`, a session `SET` on a reserved connection) gets that timeout plus the grace, and a declared 0 has no cap, read from the statements themselves so it holds behind a transaction-mode pooler. The warn line adds `reason=` and `budget_ms=`, and `/health?deep=1` reports `pool_inflight_over_budget` only for a statement past its own budget (a long transaction that declared its timeout no longer reads as over budget).' },{ since: '0.60.190.0', text: 'Pools count reconnects of connections retired after an incident (stuck, desynced, or closed under running statements): `recovered` and `recovery_failed` in `/health?deep=1` and `getPoolDiagnostics()`, and a failed reconnect logs `pg_connection_recovery_failed`. `gbrain serve` writes its stuck, desync and recovery events to the pool-recovery audit, so `gbrain doctor --only pool_reap_health` now fails on a recovery failure and warns on a stuck or desynced connection in the last hour.' },+ // #6554 (GBRA-60 D8). `since` is provisional (current VERSION); the integrator restamps it at the merge slot.+ { since: '0.60.191.0', text: '`gbrain bootstrap harness` now wires the Codex SessionEnd transcript-capture hook (its `hooks.json` group and `config.toml` trust entry) only when capture is on: turning capture off with its no-capture flag skips it, and registrar mode (a non-loopback `--url`) skips it like every other hook, because the hook talks to the local brain rather than the registered remote serve. The consent block names the hook when it is wired. A hook an earlier run installed stays until `gbrain bootstrap harness --remove`. New: `gbrain setup codex` wires Codex MCP and read-context hooks with hash-owned entries.' },+ // 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.190.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.' },++ { since: '0.60.191.0', text: '`gbrain setup claude-code` and `gbrain setup codex` no longer print `gbrain init`\'s standalone output when they create 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. They print `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. */