Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
brain-first: installer lanes, doctor block status, source_ids access line
garrytan43d56682ae3a
diff --git a/src/commands/connect.ts b/src/commands/connect.tsindex fde78ecfd8..c4bd1e092a 100644--- a/src/commands/connect.ts+++ b/src/commands/connect.ts@@ -44,6 +44,7 @@ import type { ConnectProbeResult } from '../core/connect-probe.ts';import { probeBrainIdentity, DEFAULT_PROBE_TIMEOUT_MS } from '../core/connect-probe.ts';import { opencodeGlobalConfigPath } from '../core/bootstrap/host-specs.ts';import { acquireBootstrapLock } from '../core/bootstrap/lock.ts';+import { brainFirstTarget, describeBrainFirstOutcome, installerBrainFirst, isBrainFirstHarness } from '../core/setup/brain-first.ts';import {GBRAIN_REMOTE_TOKEN_ENV,reconcileOpencodeSiblingGlobal,@@ -174,7 +175,10 @@ Flags:--scopes "<s>" With --oauth --register: client scopes (default: "${DEFAULT_SCOPES}")--install Run the agent's MCP-add command, then smoke-test the token(claude-code + codex + opencode; opencode installs via a direct- config write — no binary needed, token stays out of the file)+ config write — no binary needed, token stays out of the file).+ Also writes the brain-first instruction block into the agent's+ own instruction file (CLAUDE.md / AGENTS.md)+ --no-instructions With --install, skip (and remove) the brain-first block--yes The user's approval for --install (writes a credential-bearing MCP entry); without it a non-interactive run exits 3--force On --install, replace an existing server of the same name@@ -434,6 +438,8 @@ export interface ConnectDeps {url: string,opts?: { allowReplaceOtherSource?: boolean },): { configPath: string; replacedPrior: boolean } | Promise<{ configPath: string; replacedPrior: boolean }>;+ /** After a successful registration: the brain-first block in the agent's own instruction file. Returns the line to print. */+ writeInstructions(agent: AgentId, name: string, optOut: boolean): string | null;}async function defaultPromptYesNo(question: string): Promise<boolean> {@@ -491,6 +497,13 @@ const defaultDeps: ConnectDeps = {probe: (url, token, timeoutMs) => probeBrainIdentity(url, token, { timeoutMs }),env: (name) => process.env[name],registerOAuthClient: defaultRegisterOAuthClient,+ writeInstructions: (agent, name, optOut) => {+ if (!isBrainFirstHarness(agent)) return null;+ const target = brainFirstTarget(agent);+ if ('error' in target) return null;+ const o = installerBrainFirst({ target, access: { kind: 'mcp', server: name }, writer: `gbrain connect --agent ${agent} --install`, instructions: optOut ? false : undefined });+ return `${describeBrainFirstOutcome(o, false).trim()}${o.decision.value === 'accepted' ? ' (opt out with --no-instructions)' : ''}`;+ },writeOpencodeRemoteEntry: async (name, url, opts) => {// The writer's contract: callers hold acquireBootstrapLock on the config// dir (harness.ts [X11] parity) — the user-global file is shared across@@ -537,6 +550,7 @@ interface ParsedFlags {force: boolean;json: boolean;showToken: boolean;+ noInstructions: boolean;timeoutMs: number;help: boolean;agentError?: string;@@ -555,6 +569,7 @@ function parseArgs(args: string[]): ParsedFlags {force: false,json: false,showToken: false,+ noInstructions: false,timeoutMs: DEFAULT_TIMEOUT_MS,help: false,};@@ -583,6 +598,7 @@ function parseArgs(args: string[]): ParsedFlags {case '--force': out.force = true; break;case '--json': out.json = true; break;case '--show-token': out.showToken = true; break;+ case '--no-instructions': out.noInstructions = true; break;case '--token': { const v = takeValue('--token'); if (v !== undefined) out.token = v; break; }case '--client-id': { const v = takeValue('--client-id'); if (v !== undefined) out.clientId = v; break; }case '--client-secret': { const v = takeValue('--client-secret'); if (v !== undefined) out.clientSecret = v; break; }@@ -750,6 +766,8 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDeps`Added MCP entry '${f.name}' -> ${url} in ${w.configPath}` +`${w.replacedPrior ? ' (replaced the prior gbrain entry)' : ''}. Restart opencode (config is read at session start).`,);+ const ocInstructions = deps.writeInstructions(f.agent, f.name, f.noInstructions);+ if (ocInstructions) console.error(ocInstructions);if (deps.env(ENV_VAR) !== realToken) {console.error(`opencode resolves {env:${ENV_VAR}} at read time. Add this to your shell profile so sessions can reach the brain:`);console.error(` export ${ENV_VAR}=<your-token>`);@@ -798,6 +816,8 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDepsfail(`'${binary} mcp add' failed${note}: ${redactToken(add.stderr || add.stdout, realToken)}`);}console.error(`Added MCP server '${f.name}' -> ${url}.`);+ const instructions = deps.writeInstructions(f.agent, f.name, f.noInstructions);+ if (instructions) console.error(instructions);// Codex reads the token from the env var at runtime, not from its config.// If the current env doesn't already carry it, the user must export it.diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex fae25e08fc..b92fcf0b57 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -40,6 +40,7 @@ import type { Check } from '../../doctor.ts';import { checkError, doctorVerify, infoCheck } from '../check-fix.ts';import type { DoctorContext, DoctorEntry } from '../context.ts';import { VERSION } from '../../../version.ts';+import { brainFirstTarget, inspectBrainFirst, isBrainFirstHarness, readBrainFirstLedger, renderBrainFirstBlock } from '../../../core/setup/brain-first.ts';export const HARNESS_SMOKE_TIMEOUT_MS = 15_000;export const HARNESS_HTTP_PROBE_TIMEOUT_MS = 3_000;@@ -341,8 +342,74 @@ async function smoke(r: HarnessRegistration): Promise<Check> {...(fix ? { fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }) };}-/** Registration read (full run) or registration read + smoke (`--only harness_wiring`). */+export interface InstructionBlockView {+ harness: string;+ path: string;+ state: 'current' | 'stale' | 'missing' | 'damaged' | 'opted_out';+ /** Where the record came from: the brain-first ledger, or the harness's default file for a registration with no record. */+ from: 'ledger' | 'default_path';+}++/**+ * The brain-first instruction block for every surface gbrain wrote or was+ * told to skip (the ledger), plus each registered harness with no record,+ * checked at that harness's default instruction file. Read-only.+ */+export function instructionBlockViews(regs: HarnessRegistration[]): InstructionBlockView[] {+ const state = (s: ReturnType<typeof inspectBrainFirst>['state']): InstructionBlockView['state'] =>+ s === 'current' ? 'current' : s === 'stale' ? 'stale' : s === 'damaged' ? 'damaged' : 'missing';+ const views: InstructionBlockView[] = readBrainFirstLedger().map((e) => e.status === 'declined'+ ? { harness: e.harness, path: e.path, state: 'opted_out', from: 'ledger' }+ : { harness: e.harness, path: e.path, state: state(inspectBrainFirst(e.path, renderBrainFirstBlock(e.harness, e.access)).state), from: 'ledger' });+ for (const r of regs) {+ if (views.some((v) => v.harness === r.harness) || !isBrainFirstHarness(r.harness)) continue;+ const target = brainFirstTarget(r.harness);+ if ('error' in target) continue;+ views.push({ harness: r.harness, path: target.path, state: state(inspectBrainFirst(target.path).state), from: 'default_path' });+ }+ return views;+}++const INSTRUCTION_PROBLEM: Record<'stale' | 'missing' | 'damaged', string> = {+ stale: 'is out of date', missing: 'is missing', damaged: 'has damaged markers',+};++/**+ * Fold the brain-first block into the wiring verdict: without it agents rarely+ * reach for the brain at all, so a missing, stale or damaged block turns an+ * `ok` wiring into a warn whose fix rewrites only the block. An opt-out is+ * reported, never warned on. No views: the check is returned unchanged.+ */+export function withInstructionBlocks(check: Check, views: InstructionBlockView[]): Check {+ if (views.length === 0) return check;+ const details = { ...(check.details ?? {}), instructions: views };+ const bad = views.filter((v): v is InstructionBlockView & { state: 'stale' | 'missing' | 'damaged' } => v.state === 'stale' || v.state === 'missing' || v.state === 'damaged');+ if (bad.length === 0) {+ const current = views.filter((v) => v.state === 'current').map((v) => v.harness);+ const optedOut = views.filter((v) => v.state === 'opted_out').map((v) => v.harness);+ const note = [current.length ? `brain-first instructions current for ${current.join(', ')}` : '', optedOut.length ? `opted out for ${optedOut.join(', ')}` : ''].filter(Boolean).join('; ');+ return { ...check, message: `${check.message} ${note.charAt(0).toUpperCase()}${note.slice(1)}.`, details };+ }+ const first = bad[0]!;+ const problems = bad.map((v) => `the ${v.harness} block in ${v.path} ${INSTRUCTION_PROBLEM[v.state]}`).join('; ');+ const message = `${check.message} Brain-first instructions: ${problems}, so sessions are not told to check gbrain first.`;+ if (check.status !== 'ok') return { ...check, message, details };+ const fix: Action = first.state === 'damaged'+ ? { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),+ why: `The brain-first markers in ${first.path} were hand-edited; gbrain will not guess which lines are its own.`,+ user_message: `The gbrain instruction block in ${first.path} has damaged markers. Please delete the block (both marker lines included), then I'll write a fresh one.` }+ : { argv: ['gbrain', 'setup', first.harness, '--instructions-only'], consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(NAME),+ why: `Writes or upgrades only the marked brain-first block in ${first.path}; text outside the markers is left as it is. \`--no-instructions\` opts out instead.` };+ return { name: check.name, status: 'warn', message, details, fix };+}++/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block. */export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {+ const regs = readHarnessRegistrations();+ return withInstructionBlocks(await registrationCheck(opts, regs), instructionBlockViews(regs));+}++async function registrationCheck(opts: { smoke: boolean }, regs: HarnessRegistration[]): Promise<Check> {// A shared HTTP server that answers in status-only mode outranks every registration verdict.const statusServer = (await verifiedStatusMarkers())[0];if (statusServer) {@@ -350,7 +417,6 @@ export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Checreturn { name: NAME, status: 'warn', message: entry.why, ...(entry.fix ? { fix: entry.fix } : { fix_unavailable_reason: 'no_safe_automatic_fix' as const }),details: { reason: entry.reason, transport: 'http', port: statusServer.port, pid: statusServer.pid, status_reason: statusServer.reason } };}- const regs = readHarnessRegistrations();if (regs.length === 0) {const detected = detectedHarnesses();const plugins = enabledPluginLanes('gbrain').filter((lane) => detected.includes(lane.harness));diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.tsindex 57290d6e15..ff94e6877e 100644--- a/src/commands/harness-connect.ts+++ b/src/commands/harness-connect.ts@@ -8,12 +8,12 @@ import { readHarnessConnectionStatus } from '../core/harness/status.ts';export async function runHarnessConnect(args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) {- console.log('gbrain connect <endpoint> --harness <id> --credentials-file <private-file> [--install [--fresh-token] | --remove] [--root <persistent-root>] [--name <name>] [--json]\ngbrain connect --harness <id> --status [--root <persistent-root>] [--name <name>] [--json]');+ console.log('gbrain connect <endpoint> --harness <id> --credentials-file <private-file> [--install [--fresh-token] [--no-instructions] | --remove] [--root <persistent-root>] [--name <name>] [--json]\ngbrain connect --harness <id> --status [--root <persistent-root>] [--name <name>] [--json]');return;}const value = (flag: string) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };try {- validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });+ validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token', '--no-instructions'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });if (args.includes('--status')) {const harness = value('--harness') ?? value('--agent');if (!harness) throw new Error('--harness is required for local status; no credentials or live connection are needed');@@ -27,7 +27,7 @@ export async function runHarnessConnect(args: string[]): Promise<void> {const endpoint = normalizeMcpUrl(args[0] ?? '');if (!endpoint.ok || endpoint.url !== c.mcp_url) throw new Error('Endpoint does not match the private credential handoff');const result = args.includes('--install') || args.includes('--remove')- ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path, freshToken: args.includes('--fresh-token') })+ ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path, freshToken: args.includes('--fresh-token'), ...(args.includes('--no-instructions') ? { instructions: false } : {}) }): { ...credentialReceipt(c), status: 'prepared', harness: harness.id, documentation: harness.guide, next_action: 'Run this command with --install inside the intended harness environment. Keep the credential file private.' };console.log(JSON.stringify(result, null, args.includes('--json') ? undefined : 2));const token = result as Partial<ReturnType<typeof inlineTokenReceipt>>;diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex c981dc98eb..9b68c39ea5 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -59,6 +59,7 @@ import {renderAmbientInstructionBlock,stripAmbientWritebackBlockAt,} from './instructions-block.ts';+import { brainFirstTargetAt, describeBrainFirstOutcome, installerBrainFirst, readBrainFirstLedger, removeBrainFirst } from '../setup/brain-first.ts';import { createEngine } from '../engine-factory.ts';import { isValidSourceId } from '../source-id.ts';import { ALL_SOURCES, isResolverUserError, localFederatedSourceIds, resolveSourceWithTier } from '../source-resolver.ts';@@ -160,6 +161,8 @@ export interface HarnessFlags {projects: string[];noHooks: boolean;noCapture: boolean;+ /** `--no-instructions`: skip (and remove) the brain-first instruction block. */+ noInstructions?: boolean;force: boolean;remove: boolean;/** `--remove --dry-run`: list what removal would do, write nothing. */@@ -266,6 +269,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {}out.noHooks = rest.includes('--no-hooks');out.noCapture = rest.includes('--no-capture');+ out.noInstructions = rest.includes('--no-instructions');out.force = rest.includes('--force');out.remove = rest.includes('--remove');out.dryRun = rest.includes('--dry-run');@@ -322,6 +326,8 @@ export interface HarnessDeps {codexAgentsPath?: string;/** Resolved codex AGENTS.override.md — the [OV-A4] exclusivity probe. */codexAgentsOverride?: string;+ /** Resolved opencode global AGENTS.md (the brain-first block target). */+ opencodeAgentsPath?: string;/** Engine-free file-plane config loader (ambient-writeback gate); tests* inject a fake. */loadFileConfig?: () => GBrainConfig | null;@@ -385,6 +391,7 @@ export function resolveHarnessDeps(deps: HarnessDeps): Required<Omit<HarnessDepscodexAgentsOverride:deps.codexAgentsOverride ??(deps.codexConfig ? join(dirname(deps.codexConfig), 'AGENTS.override.md') : codexAgentsOverridePath()),+ opencodeAgentsPath: deps.opencodeAgentsPath ?? join(dirname(deps.opencodeConfig ?? opencodeGlobalConfigPath()), 'AGENTS.md'),loadFileConfig: deps.loadFileConfig ?? loadConfigFileOnly,mint: deps.mint ?? mintHarnessToken,installSharedSkills: deps.installSharedSkills ?? installSharedSkillsConnection,@@ -885,6 +892,8 @@ function logAmbientPostureNotes(}}+const BOOTSTRAP_INSTRUCTIONS_WRITER = 'gbrain bootstrap harness';+export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {const d = resolveHarnessDeps(rawDeps);// stdout-for-data discipline: under --json, stdout carries ONLY the final@@ -1975,6 +1984,18 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Pconst cleanup = await convergeHarnessCleanup({ receipt, prior, current: currentSkills, wired: allConfirmed && smokeOk, skillsReady,memoryOnly: skillsPolicy === 'memory-only', leave: leaveHarnessSkills, save }, d);+ // 10b. Brain-first instructions: each host whose MCP entry is confirmed gets+ // the managed block in its own instruction file (src/core/setup/brain-first.ts).+ for (const host of hosts) {+ if (targets.find((t) => t.host === host && t.kind === 'mcp')?.state !== 'confirmed') continue;+ const path = host === 'claude-code' ? d.claudeMemoryPath+ : host === 'codex' ? (existsSync(d.codexAgentsOverride) ? d.codexAgentsOverride : d.codexAgentsPath)+ : d.opencodeAgentsPath;+ const o = installerBrainFirst({ target: brainFirstTargetAt(host, path), access: { kind: 'mcp', server: flags.name },+ writer: BOOTSTRAP_INSTRUCTIONS_WRITER, instructions: flags.noInstructions ? false : undefined });+ d.log(describeBrainFirstOutcome(o, false).trim());+ }+// 11. Degradation + skew honesty.if (health.engine === 'postgres') {d.log(@@ -2250,6 +2271,10 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):d.log('current token was supplied via --token — not revoked (not ours to revoke).');}+ for (const e of readBrainFirstLedger().filter((entry) => entry.writer === BOOTSTRAP_INSTRUCTIONS_WRITER)) {+ d.log(describeBrainFirstOutcome(removeBrainFirst({ harness: e.harness, path: e.path, dryRun: false }), false).trim());+ }+if (remaining.length === 0 && tokenDone && skillsDone) {deleteHarnessReceipt(d.gbrainHome);d.log('harness wiring fully removed; receipt consumed.');diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 3a046ef315..6f5dc91cff 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -26,7 +26,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],- 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],+ 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-instructions', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],@@ -42,7 +42,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],- 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],+ 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--instructions-only', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-instructions', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/harness/install.ts b/src/core/harness/install.tsindex fedb2c14ac..b75109ddf9 100644--- a/src/core/harness/install.ts+++ b/src/core/harness/install.ts@@ -19,9 +19,12 @@ import { installSharedSkillsConnection } from './shared-skills.ts';import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';import { harnessSharedSkillsRoot } from './status.ts';import { gitChildEnv } from '../git-env.ts';+import { brainFirstTargetAt, installerBrainFirst, renderBrainFirstSnippet, type BrainFirstHarness } from '../setup/brain-first.ts';export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;- sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean }+ sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean;+ /** false: opt out of the brain-first instruction block (removes an existing one); true: opt back in. */+ instructions?: boolean }const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');const readJson = (path: string): Record<string, any> => {assertNoSymlinks(path);@@ -92,6 +95,14 @@ function assertEntryOwned(entry: unknown, prior: Record<string, any>, connectionif (!prior.client_id || ![hash(entry), ownedEntryHash(entry, connection)].some(h => recorded.includes(h))) throw new Error('configuration_conflict: refusing to replace an unowned or edited MCP entry');}+/** The harness's own instruction file, next to the config this install writes. */+function instructionFileBeside(connection: string, configPath: string): { harness: BrainFirstHarness; path: string } {+ const dir = dirname(configPath);+ if (connection === 'codex-toml') return { harness: 'codex', path: join(dir, existsSync(join(dir, 'AGENTS.override.md')) ? 'AGENTS.override.md' : 'AGENTS.md') };+ if (connection === 'opencode-json') return { harness: 'opencode', path: join(dir, 'AGENTS.md') };+ return { harness: 'claude-code', path: process.env.CLAUDE_CONFIG_DIR?.trim() === dir ? join(dir, 'CLAUDE.md') : join(dir, '.claude', 'CLAUDE.md') };+}+/** Install only in the current environment. Foreign entries are never adopted. */export async function installHarnessConnection(c: HarnessCredentials, opts: InstallOptions) {// A cached unexpired token may be the invalidated one; every later step (config and shared skills) uses the new token.@@ -161,11 +172,14 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Instconfig.mcpServers = servers;atomicWriteTextFile(configPath, `${JSON.stringify(config, null, 2)}\n`, { forceMode: 0o600 });}+ const beside = instructionFileBeside(adapter.connection, configPath);+ const instructions = installerBrainFirst({ target: brainFirstTargetAt(beside.harness, beside.path), access: { kind: 'mcp', server: name },+ writer: `gbrain connect --harness ${adapter.id} --install`, instructions: opts.instructions, remove: opts.remove });if (opts.remove) {if (existsSync(receiptPath)) unlinkSync(receiptPath);const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });const pending = 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true;- return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending,+ return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions,next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.': 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };}@@ -173,7 +187,7 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });- return { ...nextReceipt, shared_skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };+ return { ...nextReceipt, shared_skills, instructions, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };} finally { lock.release(); }}@@ -204,7 +218,7 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, co{ path: '.gbrain/config.json', text: `${JSON.stringify(config, null, 2)}\n`, mode: 0o600 },{ path: 'bin/gbrain', text: renderAgentLauncher({ root, bunPath: process.execPath, cliPath: sourceCli.includes('$bunfs') ? undefined : sourceCli, mode: 'thin-client',repairHint: `Reinstall GBrain in this environment, then repeat: gbrain connect ${shellQuote(c.mcp_url)} --harness ${shellQuote(opts.harness)} --credentials-file <private-handoff-file> --root ${shellQuote(root)} --install` }), mode: 0o700 },- { path: 'GBRAIN-INSTRUCTIONS.md', text: `${GBRAIN_MCP_INSTRUCTIONS}\n\nRun commands with the absolute launcher: ${launcher}\nThis is a hosted connection. The host grant controls sources and permissions.\n`, mode: 0o600 },+ { path: 'GBRAIN-INSTRUCTIONS.md', text: `${opts.instructions === false ? '' : `${renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}\n`}${GBRAIN_MCP_INSTRUCTIONS}\n\nRun commands with the absolute launcher: ${launcher}\nThis is a hosted connection. The host grant controls sources and permissions.\n`, mode: 0o600 },];const owned: Record<string, string> = prior.owned_files ?? {};const pending: Record<string, { before: string | null; after: string }> = prior.pending_files ?? {};diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.tsindex c60bbc61a1..b150712042 100644--- a/src/core/setup/brain-first.ts+++ b/src/core/setup/brain-first.ts@@ -49,28 +49,32 @@ export function isBrainFirstHarness(v: string | undefined): v is BrainFirstHarneexport type BrainFirstAccess = { kind: 'mcp'; server: string; surface?: McpSurface } | { kind: 'cli'; launcher: string };/** The block interior (without markers). */-export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess): string {+export function renderBrainFirstBlock(harness: string, access: BrainFirstAccess, optOut = `gbrain setup ${harness} --instructions-only --no-instructions`): string {const tool = (mcp: string, cli: string) => (access.kind === 'mcp' ? `\`${mcp}\`` : `\`${access.launcher} ${cli}\``);const where = access.kind === 'mcp' ? `the \`${access.server}\` MCP server` : `the \`${access.launcher}\` command`;const lookup = access.kind === 'mcp' && access.surface === 'verbs'? '- Check the brain before reading files, mail or other sources one by one: `recall` for what was said or decided, `entity` for a person or company.': `- Search the brain before reading files, mail or other sources one by one: ${tool('search', 'search "<names or phrases>"')} for names and phrases, ${tool('query', 'query "<question>"')} for questions. Then read the best hit with ${tool('get_page', 'get <slug>')}.`;return [- `<!-- gbrain brain-first v${BRAIN_FIRST_VERSION}: managed by gbrain and replaced on upgrade; edit outside these markers. Opt out: gbrain setup ${harness} --instructions-only --no-instructions -->`,+ `<!-- gbrain brain-first v${BRAIN_FIRST_VERSION}: managed by gbrain and replaced on upgrade; edit outside these markers. Opt out: ${optOut} -->`,'## Memory: check GBrain first','',`GBrain (${where}) holds this user's saved notes, people, companies, meetings, decisions and past work.`,'',lookup,'- Fill gaps with your other tools. On a thin keyword result, rephrase once (another name, fewer words), then fall back.',- '- Brain results span every source the brain holds, not only this user or task, so apply your own access rules before you use or repeat them.',+ access.kind === 'cli'+ ? `- Brain results span every source the brain holds. Pass \`--source-ids <ids>\` to a search or query to narrow it to what the current requester may see, and apply your own access rules to what comes back.`+ : access.surface === 'verbs'+ ? '- Brain results span every source the token can read, so apply your own access rules to what comes back.'+ : '- Brain results span every source the token can read. Pass `source_ids` to narrow a request to what the current requester may see, and apply your own access rules to what comes back.','- Brain results add to what the user told you; they never replace it. A lookup is one step: finish the whole task.',].join('\n');}/** The full block as it appears in a file, markers included (for printing to paste by hand). */-export function renderBrainFirstSnippet(harness: string, access: BrainFirstAccess): string {- return `${BRAIN_FIRST_BEGIN}\n${renderBrainFirstBlock(harness, access)}\n${BRAIN_FIRST_END}\n`;+export function renderBrainFirstSnippet(harness: string, access: BrainFirstAccess, optOut?: string): string {+ return `${BRAIN_FIRST_BEGIN}\n${renderBrainFirstBlock(harness, access, optOut)}\n${BRAIN_FIRST_END}\n`;}const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';@@ -325,6 +329,22 @@ export function removeBrainFirst(opts: { harness: string; path: string; dryRun:}}+/** A writable harness's target at a path an installer already resolved (its own config dir, a test sandbox). */+export function brainFirstTargetAt(harness: BrainFirstHarness, path: string): BrainFirstTarget {+ const base = brainFirstTarget(harness);+ return { harness, path, role: 'error' in base ? 'instruction file' : base.role, project: false };+}++/**+ * The installer lanes (`gbrain connect --install`, `gbrain bootstrap harness`):+ * write or upgrade the block unless opted out, or strip it on removal.+ */+export function installerBrainFirst(opts: { target: BrainFirstTarget; access: BrainFirstAccess; writer: string; instructions?: boolean; remove?: boolean; dryRun?: boolean }): BrainFirstOutcome {+ if (opts.remove) return removeBrainFirst({ harness: opts.target.harness, path: opts.target.path, dryRun: opts.dryRun ?? false });+ const decision = resolveBrainFirstDecision(opts.instructions, priorBrainFirst(opts.target.harness, opts.target.path));+ return syncBrainFirst({ target: opts.target, access: opts.access, decision, writer: opts.writer, dryRun: opts.dryRun ?? false });+}+/** One human line per outcome, matching setup's step lines. */export function describeBrainFirstOutcome(o: BrainFirstOutcome, dryRun: boolean): string {return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'instructions'.padEnd(7)} ${o.detail}`;diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.tsindex 34f5238d64..292f07d06d 100644--- a/test/bootstrap-harness.serial.test.ts+++ b/test/bootstrap-harness.serial.test.ts@@ -58,6 +58,7 @@ import type { GBrainConfig } from '../src/core/config.ts';import { VERSION } from '../src/version.ts';import { withEnv } from './helpers/with-env.ts';import { SourceTargetError } from '../src/core/source-resolver.ts';+import { renderBrainFirstSnippet } from '../src/core/setup/brain-first.ts';const TOKEN_A = `gbrain_${'a'.repeat(64)}`;const TOKEN_B = `gbrain_${'b'.repeat(64)}`;@@ -164,6 +165,7 @@ function makeFake(opts: {userSettingsPath: userSettings,codexConfig,opencodeConfig,+ opencodeAgentsPath: join(dir, 'opencode', 'AGENTS.md'),mint: async (o) => {mintCalls.push(o as { name: string; scopes: string[]; sourceGrant?: string[] });const m = mintQueue[mintIdx++];@@ -1508,7 +1510,8 @@ describe('ambient-writeback instruction blocks (kind: instructions, WP3)', () =>// speaks for the LOCAL brain — a block here would order agents to save// into the remote brain without its brain-scoped opt-in).expect(readFileSync(f.codexConfig, 'utf8')).toContain('http://192.168.1.50:3131/mcp');- expect(existsSync(agentsPath(f))).toBe(false);+ // Only the read-side brain-first block lands (it orders no writes).+ expect(readFileSync(agentsPath(f), 'utf8')).toBe(renderBrainFirstSnippet('codex', { kind: 'mcp', server: 'gbrain' }));expect(instrTargets(f.home)).toEqual([]);expect(f.out.join('\n')).toContain('registrar mode: ambient-writeback instruction blocks are NOT installed');});@@ -1551,8 +1554,9 @@ describe('ambient-writeback instruction blocks (kind: instructions, WP3)', () =>// preload-pinned GBRAIN_HOME scratch has no config.json → off).expect(await applyHarness(flags(), f.deps)).toBe(0);// Non-block content restored EXACTLY; the files are never deleted.- expect(readFileSync(memoryPath(f), 'utf8')).toBe('# mine\n');- expect(readFileSync(agentsPath(f), 'utf8')).toBe('# agents\n');+ // The brain-first block (default on, independent of writeback) stays.+ expect(readFileSync(memoryPath(f), 'utf8')).toBe(`# mine\n${renderBrainFirstSnippet('claude-code', { kind: 'mcp', server: 'gbrain' })}`);+ expect(readFileSync(agentsPath(f), 'utf8')).toBe(`# agents\n${renderBrainFirstSnippet('codex', { kind: 'mcp', server: 'gbrain' })}`);expect(instrTargets(f.home)).toEqual([]);expect(f.out.join('\n')).toMatch(/ambient writeback off — enable with `gbrain config set memory\.auto_writeback salient` and re-run\./,diff --git a/test/connect.test.ts b/test/connect.test.tsindex 378d92b282..aa65dacfef 100644--- a/test/connect.test.ts+++ b/test/connect.test.ts@@ -508,6 +508,7 @@ function installDeps(over: Partial<ConnectDeps> = {}): ConnectDeps {env: () => undefined, // tests control the env; real GBRAIN_REMOTE_TOKEN must not leak inregisterOAuthClient: () => ({ ok: true, clientId: 'gbrain_cl_minted', clientSecret: 'gbrain_cs_minted' }),writeOpencodeRemoteEntry: (name) => ({ configPath: `/tmp/xdg/opencode/opencode.jsonc (${name})`, replacedPrior: false }),+ writeInstructions: (agent, name, optOut) => (optOut ? null : `write instructions brain-first block for ${agent} '${name}'`),...over,};}diff --git a/test/doctor-harness-smoke.test.ts b/test/doctor-harness-smoke.test.tsindex 965725aa3e..fc2df8aca9 100644--- a/test/doctor-harness-smoke.test.ts+++ b/test/doctor-harness-smoke.test.ts@@ -17,11 +17,12 @@* Serial: spawns `gbrain serve` subprocesses against one PGLite brain.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';import { peekLock } from '../src/core/pglite-lock.ts';+import { renderBrainFirstSnippet } from '../src/core/setup/brain-first.ts';import { makeDoctorHome, runGbrain, type DoctorHome } from './helpers/doctor-json-golden.ts';const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');@@ -31,6 +32,9 @@ function register(command: string, args: string[]): void {writeFileSync(join(h.home, '.claude.json'), JSON.stringify({mcpServers: { gbrain: { type: 'stdio', command, args, env: { GBRAIN_HOME: h.home, GBRAIN_SKIP_STARTUP_HOOKS: '1' } } },}));+ // A complete wiring also carries the brain-first block, or harness_wiring warns on it.+ mkdirSync(join(h.home, '.claude'), { recursive: true });+ writeFileSync(join(h.home, '.claude', 'CLAUDE.md'), renderBrainFirstSnippet('claude-code', { kind: 'mcp', server: 'gbrain' }));}function harnessCheck(run: { json: unknown; stdout: string }): Record<string, unknown> {diff --git a/test/harness-wiring-redaction-6453.test.ts b/test/harness-wiring-redaction-6453.test.tsindex 0b7b10a8e5..7264a0dc09 100644--- a/test/harness-wiring-redaction-6453.test.ts+++ b/test/harness-wiring-redaction-6453.test.ts@@ -29,6 +29,7 @@ import { harnessWiringCheck } from '../src/commands/doctor/checks/harness-wiringconst mod = () => import('../src/commands/doctor/checks/harness-wiring.ts');import { withEnv } from './helpers/with-env.ts';+import { renderBrainFirstSnippet } from '../src/core/setup/brain-first.ts';const USER = 'alice-example';const USERINFO_PART = 'userinfo-6453-fixture';@@ -62,6 +63,9 @@ const PGLITE = { engine: 'pglite', database_path: '/nonexistent/brain.pglite' };function register(b: Box, url: string, extra: Record<string, unknown> = {}): void {writeFileSync(join(b.env.HOME!, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: { type: 'http', url, ...extra } } }));+ // A complete wiring also carries the brain-first block, or harness_wiring warns on it.+ mkdirSync(b.env.CLAUDE_CONFIG_DIR!, { recursive: true });+ writeFileSync(join(b.env.CLAUDE_CONFIG_DIR!, 'CLAUDE.md'), renderBrainFirstSnippet('claude-code', { kind: 'mcp', server: 'gbrain' }));}interface Hit { path: string; query: string; authorization: string | null }diff --git a/test/setup-brain-first.test.ts b/test/setup-brain-first.test.tsnew file mode 100644index 0000000000..3e2c338f84--- /dev/null+++ b/test/setup-brain-first.test.ts@@ -0,0 +1,358 @@+/**+ * The brain-first instruction block (src/core/setup/brain-first.ts): every+ * install lane writes one marked block into the harness's own instruction+ * file by default. Per writable harness this pins:+ * - preservation: text outside the markers is byte-identical after install,+ * upgrade and removal; the identity/persona text is never touched;+ * - idempotence: a second run keeps the file byte-for-byte;+ * - upgrade in place: a stale block is replaced, never duplicated;+ * - opt-out: --no-instructions (or GBRAIN_AGENT_INSTRUCTIONS=0) removes the+ * block and is remembered; --instructions opts back in;+ * - removal: --remove strips the block and deletes only a file gbrain created;+ * - dry-run writes nothing.+ * Spawns \`bun src/cli.ts setup\` against a temp HOME / GBRAIN_HOME.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';+import {+ BRAIN_FIRST_BEGIN,+ BRAIN_FIRST_END,+ renderBrainFirstBlock,+ renderBrainFirstSnippet,+} from '../src/core/setup/brain-first.ts';+import { harnessWiringCheck } from '../src/commands/doctor/checks/harness-wiring.ts';+import { installHarnessConnection } from '../src/core/harness/install.ts';+import type { HarnessCredentials } from '../src/core/harness/credentials.ts';++const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { root: string; home: string; project: string; bin: string; env: Record<string, string | undefined> }++function box(): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-brain-first-'));+ roots.push(root);+ const home = join(root, 'home');+ const project = join(root, 'project');+ mkdirSync(home, { recursive: true });+ mkdirSync(project, { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ mkdirSync(join(root, 'bin'));+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ return { root, home, project, bin, env: {+ HOME: home, GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,+ OPENCLAW_STATE_DIR: undefined, OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, HERMES_HOME: undefined,+ GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_SURFACE: undefined, GBRAIN_SOURCE: undefined, GBRAIN_HOOKS: undefined,+ } };+}++async function setup(b: Box, args: string[], env: Record<string, string | undefined> = {}) {+ const r = await runCli(['setup', ...args, '--json'], { env: { ...b.env, ...env }, cwd: b.project });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc };+}++const read = (p: string) => readFileSync(p, 'utf8');+const blocks = (text: string) => text.split('\n').filter((l) => l === BRAIN_FIRST_BEGIN).length;+const ledger = (b: Box) => JSON.parse(read(join(b.home, '.gbrain', 'agent-instructions.json'))).entries as any[];++interface Lane { harness: string; file: (b: Box) => string; args?: string[]; prepare?: (b: Box) => void; existing: string }++const LANES: Lane[] = [+ { harness: 'claude-code', file: (b) => join(b.home, '.claude', 'CLAUDE.md'), args: ['--instructions-only'], existing: '# My rules\n\nAlways answer in French.\n' },+ { harness: 'codex', file: (b) => join(b.home, '.codex', 'AGENTS.md'), args: ['--instructions-only'], existing: '# Codex house rules\n- run the tests\n' },+ { harness: 'opencode', file: (b) => join(b.home, '.config', 'opencode', 'AGENTS.md'), existing: 'Prefer small diffs.\n' },+ { harness: 'openclaw', file: (b) => join(b.home, '.openclaw', 'workspace', 'AGENTS.md'), existing: '# AGENTS.md\n\n## Tools\nUse the calendar skill.\n' },+ { harness: 'hermes', file: (b) => join(b.home, '.hermes', 'SOUL.md'), existing: 'You are Hermes, a careful assistant named alice-example.\n' },+ { harness: 'cursor', file: (b) => join(b.project, '.cursor', 'rules', 'gbrain-brain-first.mdc'), existing: '---\ndescription: team rule\nalwaysApply: true\n---\nUse tabs.\n' },+];++for (const lane of LANES) {+ describe(`brain-first block: ${lane.harness}`, () => {+ const run = (b: Box, extra: string[] = [], env: Record<string, string | undefined> = {}) => setup(b, [lane.harness, ...(lane.args ?? []), ...extra], env);++ test('default install appends the block after the existing text, which stays byte-identical; a re-run keeps the file', async () => {+ const b = box();+ const path = lane.file(b);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, lane.existing);+ const first = await run(b);+ expect(first.exitCode).toBe(0);+ expect(first.doc.instructions).toMatchObject({ action: 'write', path, decision: { value: 'accepted', source: 'default' } });+ const text = read(path);+ expect(text.startsWith(lane.existing)).toBe(true);+ expect(blocks(text)).toBe(1);+ expect(text).toContain('Search the brain before reading files');+ expect(text).toContain('apply your own access rules');+ expect(text).toContain('finish the whole task');+ expect(ledger(b)).toEqual([expect.objectContaining({ harness: lane.harness, path, status: 'installed', created_file: false })]);++ const second = await run(b);+ expect(second.doc.instructions.action).toBe('keep');+ expect(read(path)).toBe(text);+ });++ test('a stale block is upgraded in place: one block, outside text untouched before and after it', async () => {+ const b = box();+ const path = lane.file(b);+ mkdirSync(dirname(path), { recursive: true });+ const tail = '\n## Notes after the block\nkeep me\n';+ writeFileSync(path, `${lane.existing}${BRAIN_FIRST_BEGIN}\n<!-- gbrain brain-first v0 -->\nold advice\n${BRAIN_FIRST_END}\n${tail}`);+ const r = await run(b);+ expect(r.doc.instructions).toMatchObject({ action: 'write', state_before: 'stale' });+ const text = read(path);+ expect(blocks(text)).toBe(1);+ expect(text).not.toContain('old advice');+ expect(text.startsWith(lane.existing)).toBe(true);+ expect(text.endsWith(tail)).toBe(true);+ });++ test('--no-instructions removes the block and is remembered; GBRAIN_AGENT_INSTRUCTIONS=0 never writes; --instructions opts back in', async () => {+ const b = box();+ const path = lane.file(b);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, lane.existing);+ await run(b);+ const out = await run(b, ['--no-instructions']);+ expect(out.doc.instructions).toMatchObject({ action: 'remove', decision: { value: 'declined', source: 'flag' } });+ expect(read(path)).toBe(lane.existing);+ expect(ledger(b)[0]).toMatchObject({ status: 'declined' });+ const again = await run(b);+ expect(again.doc.instructions).toMatchObject({ action: 'skip', decision: { value: 'declined', source: 'prior' } });+ expect(read(path)).toBe(lane.existing);+ const back = await run(b, ['--instructions']);+ expect(back.doc.instructions).toMatchObject({ action: 'write', decision: { value: 'accepted', source: 'flag' } });++ const fresh = box();+ const env = await run(fresh, [], { GBRAIN_AGENT_INSTRUCTIONS: '0' });+ expect(env.doc.instructions).toMatchObject({ action: 'skip', decision: { value: 'declined', source: 'opt_out' } });+ expect(existsSync(lane.file(fresh))).toBe(false);+ });++ test('--remove strips the block, leaves the user text exactly as it was, and deletes only a file gbrain created', async () => {+ const b = box();+ const path = lane.file(b);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, lane.existing);+ await run(b);+ const rm = await run(b, ['--remove']);+ expect(rm.doc.instructions.action).toBe('remove');+ expect(read(path)).toBe(lane.existing);++ const created = box();+ const write = await run(created);+ expect(write.doc.instructions.detail).toContain('new file');+ expect(existsSync(lane.file(created))).toBe(true);+ await run(created, ['--remove']);+ expect(existsSync(lane.file(created))).toBe(false);+ });++ test('--dry-run reports the write and changes nothing', async () => {+ const b = box();+ const r = await run(b, ['--dry-run']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.instructions).toMatchObject({ action: 'write', state_before: 'no_file' });+ expect(existsSync(lane.file(b))).toBe(false);+ expect(existsSync(join(b.home, '.gbrain', 'agent-instructions.json'))).toBe(false);+ });+ });+}++describe('brain-first block: placement rules', () => {+ test('codex: AGENTS.override.md wins when it exists (Codex ignores AGENTS.md then)', async () => {+ const b = box();+ mkdirSync(join(b.home, '.codex'), { recursive: true });+ writeFileSync(join(b.home, '.codex', 'AGENTS.override.md'), 'override rules\n');+ const r = await setup(b, ['codex', '--instructions-only']);+ expect(r.doc.instructions.path).toBe(join(b.home, '.codex', 'AGENTS.override.md'));+ expect(existsSync(join(b.home, '.codex', 'AGENTS.md'))).toBe(false);+ });++ test('claude-code --scope project writes CLAUDE.local.md and keeps it out of git', async () => {+ const b = box();+ const git = Bun.spawnSync(['git', 'init', '-q', b.project]);+ expect(git.exitCode).toBe(0);+ const r = await setup(b, ['claude-code', '--instructions-only', '--scope', 'project']);+ expect(r.doc.instructions.path).toBe(join(b.project, 'CLAUDE.local.md'));+ expect(read(join(b.project, '.git', 'info', 'exclude'))).toContain('/CLAUDE.local.md');+ });++ test('openclaw: agents.defaults.workspace in JSON5 config is honored; a multi-agent roster needs --workspace', async () => {+ const b = box();+ mkdirSync(join(b.home, '.openclaw'), { recursive: true });+ writeFileSync(join(b.home, '.openclaw', 'openclaw.json'), '{ agents: { defaults: { workspace: "~/agent-ws" } } }\n');+ const r = await setup(b, ['openclaw']);+ expect(r.doc.instructions.path).toBe(join(b.home, 'agent-ws', 'AGENTS.md'));+ writeFileSync(join(b.home, '.openclaw', 'openclaw.json'), '{ agents: { list: [{ id: "a" }, { id: "b" }] } }\n');+ const multi = await setup(b, ['openclaw']);+ expect(multi.exitCode).toBe(2);+ expect(multi.doc.code).toBe('invalid_params');+ const named = await setup(b, ['openclaw', '--workspace', join(b.home, 'ws-b')]);+ expect(named.doc.instructions.path).toBe(join(b.home, 'ws-b', 'AGENTS.md'));+ });++ test('hermes: the identity text in SOUL.md stays first and unchanged', async () => {+ const b = box();+ mkdirSync(join(b.home, '.hermes'), { recursive: true });+ const soul = 'You are Hermes.\nTone: dry.\n';+ writeFileSync(join(b.home, '.hermes', 'SOUL.md'), soul);+ await setup(b, ['hermes']);+ expect(read(join(b.home, '.hermes', 'SOUL.md')).startsWith(soul)).toBe(true);+ });++ test('a damaged block is preserved and reported, never guessed through', async () => {+ const b = box();+ const path = join(b.home, '.claude', 'CLAUDE.md');+ mkdirSync(dirname(path), { recursive: true });+ const damaged = `mine\n${BRAIN_FIRST_BEGIN}\nhalf a block\n`;+ writeFileSync(path, damaged);+ const r = await setup(b, ['claude-code', '--instructions-only']);+ expect(r.exitCode).toBe(1);+ expect(r.doc.instructions).toMatchObject({ action: 'preserve', state_before: 'damaged' });+ expect(read(path)).toBe(damaged);+ });++ test('a client with no writable instruction file gets the block printed to paste', async () => {+ const b = box();+ const r = await setup(b, ['chatgpt', '--instructions-only']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.instructions.action).toBe('print');+ expect(r.doc.instructions.snippet).toBe(renderBrainFirstSnippet('chatgpt', { kind: 'mcp', server: 'gbrain' }));+ });+});++describe('brain-first block: text', () => {+ test('names the tools the surface lists: search/query/get_page, recall/entity on verbs, the CLI on a thin client', () => {+ const full = renderBrainFirstBlock('codex', { kind: 'mcp', server: 'gbrain', surface: 'full' });+ expect(full).toContain('`search`');+ expect(full).toContain('`get_page`');+ const verbs = renderBrainFirstBlock('codex', { kind: 'mcp', server: 'gbrain', surface: 'verbs' });+ expect(verbs).toContain('`recall`');+ expect(verbs).not.toContain('get_page');+ const cli = renderBrainFirstBlock('openclaw', { kind: 'cli', launcher: '/opt/agent/bin/gbrain' });+ expect(cli).toContain('`/opt/agent/bin/gbrain search');+ expect(cli).toContain('`/opt/agent/bin/gbrain get <slug>`');+ });++ test('stays short: it loads into every turn', () => {+ const words = renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'full' }).split(/\s+/).length;+ expect(words).toBeLessThan(160);+ });+});++describe('brain-first block: full setup and the installer lanes', () => {+ test('gbrain setup claude-code writes the block by default; --remove takes it out with the MCP entry', async () => {+ const b = box();+ const first = await runCli(['setup', 'claude-code', '--json', '--gbrain-bin', b.bin], { env: b.env });+ expect(first.exitCode).toBe(0);+ const doc = JSON.parse(first.stdout);+ expect(doc.instructions).toMatchObject({ action: 'write', path: join(b.home, '.claude', 'CLAUDE.md') });+ expect(read(join(b.home, '.claude', 'CLAUDE.md'))).toContain('the `gbrain` MCP server');+ const second = JSON.parse((await runCli(['setup', 'claude-code', '--json', '--gbrain-bin', b.bin], { env: b.env })).stdout);+ expect(second.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);+ expect(second.instructions.action).toBe('keep');+ const rm = JSON.parse((await runCli(['setup', 'claude-code', '--remove', '--json', '--gbrain-bin', b.bin], { env: b.env })).stdout);+ expect(rm.instructions.action).toBe('remove');+ expect(existsSync(join(b.home, '.claude', 'CLAUDE.md'))).toBe(false);+ });++ test('gbrain setup codex --no-instructions wires MCP and hooks but no block', async () => {+ const b = box();+ const r = await runCli(['setup', 'codex', '--no-instructions', '--json', '--gbrain-bin', b.bin], { env: b.env });+ expect(r.exitCode).toBe(0);+ expect(JSON.parse(r.stdout).instructions).toMatchObject({ action: 'skip', decision: { value: 'declined' } });+ expect(existsSync(join(b.home, '.codex', 'AGENTS.md'))).toBe(false);+ });++ const credentials: HarnessCredentials = { version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'gbrain_cl_fixture', client_secret: 'fixture-secret-not-real', access_token: 'fixture-token-not-real' };++ for (const [harness, config, instructions] of [+ ['claude-code', '.claude.json', join('.claude', 'CLAUDE.md')],+ ['codex', join('.codex', 'config.toml'), join('.codex', 'AGENTS.md')],+ ['opencode', join('.config', 'opencode', 'opencode.jsonc'), join('.config', 'opencode', 'AGENTS.md')],+ ] as const) {+ test(`connect --install (${harness}) writes the block beside its config; --remove and instructions:false take it out`, async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const configPath = join(b.home, config);+ const instructionPath = join(b.home, instructions);+ mkdirSync(dirname(instructionPath), { recursive: true });+ writeFileSync(instructionPath, 'house rules\n');+ const installed = await installHarnessConnection(credentials, { harness, configPath });+ expect((installed as any).instructions).toMatchObject({ action: 'write', path: instructionPath });+ expect(blocks(read(instructionPath))).toBe(1);+ const again = await installHarnessConnection(credentials, { harness, configPath });+ expect((again as any).instructions.action).toBe('keep');+ const optedOut = await installHarnessConnection(credentials, { harness, configPath, instructions: false });+ expect((optedOut as any).instructions.action).toBe('remove');+ expect(read(instructionPath)).toBe('house rules\n');+ await installHarnessConnection(credentials, { harness, configPath, instructions: true });+ const removed = await installHarnessConnection(credentials, { harness, configPath, remove: true });+ expect((removed as any).instructions.action).toBe('remove');+ expect(read(instructionPath)).toBe('house rules\n');+ });+ });+ }++ test('thin-client install (OpenClaw) puts the CLI-flavored block first in GBRAIN-INSTRUCTIONS.md', async () => {+ const b = box();+ const root = join(b.root, 'thin');+ await withEnv(b.env, async () => {+ await installHarnessConnection(credentials, { harness: 'openclaw', root });+ });+ const text = read(join(root, 'GBRAIN-INSTRUCTIONS.md'));+ expect(text.startsWith(BRAIN_FIRST_BEGIN)).toBe(true);+ expect(text).toContain(`\`${join(root, 'bin', 'gbrain')} search`);+ });+});++describe('doctor harness_wiring reports the block', () => {+ function stdioRegistration(b: Box): void {+ writeFileSync(join(b.home, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: { type: 'stdio', command: b.bin, args: ['serve'] } } }));+ }+ const env = (b: Box) => ({ ...b.env, CLAUDECODE: undefined, CLAUDE_CODE_ENTRYPOINT: undefined, CODEX_SANDBOX: undefined, CODEX_CI: undefined, OPENCODE: undefined, OPENCODE_PID: undefined });++ test('a registration without the block warns, with a fix that writes only the block; current reads ok', async () => {+ const b = box();+ stdioRegistration(b);+ await withEnv(env(b), async () => {+ const missing = await harnessWiringCheck({ smoke: false });+ expect(missing.status).toBe('warn');+ expect(missing.details?.instructions).toEqual([{ harness: 'claude-code', path: join(b.home, '.claude', 'CLAUDE.md'), state: 'missing', from: 'default_path' }]);+ expect(missing.fix?.argv).toEqual(['gbrain', 'setup', 'claude-code', '--instructions-only']);+ });+ await setup(b, ['claude-code', '--instructions-only']);+ await withEnv(env(b), async () => {+ const current = await harnessWiringCheck({ smoke: false });+ expect(current.status).toBe('ok');+ expect(current.message).toContain('Brain-first instructions current for claude-code.');+ expect(current.details?.instructions).toEqual([expect.objectContaining({ state: 'current', from: 'ledger' })]);+ });+ });++ test('a hand-edited (stale) block warns; an opt-out is reported, never warned on', async () => {+ const b = box();+ stdioRegistration(b);+ await setup(b, ['claude-code', '--instructions-only']);+ const path = join(b.home, '.claude', 'CLAUDE.md');+ writeFileSync(path, read(path).replace('finish the whole task', 'stop after the lookup'));+ await withEnv(env(b), async () => {+ const stale = await harnessWiringCheck({ smoke: false });+ expect(stale.status).toBe('warn');+ expect(stale.message).toContain('is out of date');+ });+ await setup(b, ['claude-code', '--instructions-only', '--no-instructions']);+ await withEnv(env(b), async () => {+ const opted = await harnessWiringCheck({ smoke: false });+ expect(opted.status).toBe('ok');+ expect(opted.details?.instructions).toEqual([expect.objectContaining({ state: 'opted_out' })]);+ });+ });+});diff --git a/test/setup.test.ts b/test/setup.test.tsindex c0acaa41f7..856fb2b8f8 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -432,12 +432,12 @@ describe('gbrain setup: consent and refusals', () => {});for (const [harness, guide] of [['openclaw', 'docs/mcp/OPENCLAW.md'], ['hermes', 'docs/mcp/HERMES.md']] as const) {- test(`${harness} is a coded refusal that names its guide`, async () => {+ test(`${harness}: setup writes only the brain-first block and names its guide for the MCP step`, async () => {const b = box();- const r = await setup(b, [harness, '--json']);- expect(r.exitCode).toBe(2);- expect(r.doc.code).toBe('setup_harness_unsupported');- expect(r.doc.message).toContain(guide);+ const r = await setup(b, [harness, '--json'], { OPENCLAW_STATE_DIR: undefined, OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, HERMES_HOME: undefined });+ expect(r.exitCode).toBe(0);+ expect(r.doc).toMatchObject({ harness, instructions_only: true, mcp: { setup: 'manual', docs: guide }, instructions: { action: 'write' } });+ expect(r.doc.instructions.path).toBe(harness === 'openclaw' ? join(b.home, '.openclaw', 'workspace', 'AGENTS.md') : join(b.home, '.hermes', 'SOUL.md'));expect(existsSync(claudeJson(b))).toBe(false);});}