Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(skills): launcher catalog check, Claude Code loader rule, --skills-index-only refresh, typed refusals, connect --gbrain-bin, lane tests, docs
garrytan1266918056ab
diff --git a/AGENTS.md b/AGENTS.mdindex d878104033..3ae459eb23 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -271,6 +271,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contto opt out). Non-metric event rows (`meeting`, `job_change`,`location_change`) ride through the same pipeline via `facts.event_type`;pass `kind: 'event'` or `'all'` to `find_trajectory` to query them.+- **Load gbrain's skills only when a task needs them (opt-in):**+ `gbrain setup <harness> --skill-loading spring` adds a compact skills index+ beside the brain-first block; the agent loads a matching skill with+ `gbrain bundled-skill <name>` (no brain or MCP needed). Default off.+ [Skill loading](docs/guides/setup.md#skill-loading-opt-in).- **Answer "who is waiting on me?":** connect the user's Google account once(`gbrain google setup` — two user interactions; relay the `[SHOW USER]`blocks verbatim), then `gbrain waiting --json` returns the ranked peoplediff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex cdd08a0a1e..5d7277d733 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -179,6 +179,34 @@ install, and the thin-client `GBRAIN-INSTRUCTIONS.md` starts with it.`gbrain doctor` (`harness_wiring`) warns when a registered harness's block ismissing, stale or damaged, with a fix that rewrites only the block.+## Skill loading (opt-in)++GBrain ships step-by-step skills (meeting ingestion, fact-checking, the+bulk-delete gate, filing rules, …). By default no install lane hands them to+the agent. `--skill-loading spring` adds a second marked block+(`<!-- gbrain:skills:begin -->` … `<!-- gbrain:skills:end -->`) right after+the brain-first block in the same file: a compact index of the bundled skills,+one line per skill with its trigger phrases (about 1.5k tokens, capped at+6,144 bytes). The full skill is loaded only when a task matches, with++ <launcher> bundled-skill <name> # the SKILL.md, then the files it names+ <launcher> bundled-skill <name> --asset <path> # one of those files++`gbrain bundled-skill` reads the skills built into gbrain itself: it opens no+brain and needs no MCP server or skill publication, so it works on a thin+client and from a compiled binary. The index names the absolute launcher the+install recorded, so the index and the skills it loads come from the same+gbrain. MCP `get_skill` is unchanged.++| | |+|---|---|+| Select | `--skill-loading off\|spring` on `gbrain setup <harness>`, `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness`; or `GBRAIN_SKILL_LOADING`. Flag, then env, then the recorded choice, then `off`. |+| Default | `off`: no index is written, and `off` removes one an earlier run wrote. |+| Which skills | Host installs (`setup`, `bootstrap harness`) list all bundled skills; hosted and thin-client connections leave out the host-maintenance ones. |+| Opt out | `--skill-loading off`; `--no-instructions` removes both blocks; `--remove` takes both out and deletes a file only gbrain created once nothing else is in it. |+| After an upgrade | The block records the skill catalog it indexes. `gbrain doctor` (`harness_wiring`) names a stale index and the refresh command (`gbrain setup <harness> --skills-index-only`, which rewrites only the skills block, keeping its recorded file, launcher and skill set). It never warns on a stale index alone, and nothing rewrites the file during an upgrade. |+| Choice record | `~/.gbrain/skill-loading.json` (harness, file, mode, launcher, audience, catalog). |+## Harness capability tableThe table is data (`src/core/setup/capabilities.ts`, version 2). Push is neverdiff --git a/llms-full.txt b/llms-full.txtindex 3924df4807..5410997fa6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2030,6 +2030,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contto opt out). Non-metric event rows (`meeting`, `job_change`,`location_change`) ride through the same pipeline via `facts.event_type`;pass `kind: 'event'` or `'all'` to `find_trajectory` to query them.+- **Load gbrain's skills only when a task needs them (opt-in):**+ `gbrain setup <harness> --skill-loading spring` adds a compact skills index+ beside the brain-first block; the agent loads a matching skill with+ `gbrain bundled-skill <name>` (no brain or MCP needed). Default off.+ [Skill loading](docs/guides/setup.md#skill-loading-opt-in).- **Answer "who is waiting on me?":** connect the user's Google account once(`gbrain google setup` — two user interactions; relay the `[SHOW USER]`blocks verbatim), then `gbrain waiting --json` returns the ranked peoplediff --git a/src/cli/commands/bundled-skill.ts b/src/cli/commands/bundled-skill.tsindex 718f7069b3..a006ab1270 100644--- a/src/cli/commands/bundled-skill.ts+++ b/src/cli/commands/bundled-skill.ts@@ -43,12 +43,24 @@ export async function run(args: string[]): Promise<void> {return;}const json = args.includes('--json');- const assetAt = args.findIndex(a => a === '--asset' || a.startsWith('--asset='));- const asset = assetAt < 0 ? undefined : args[assetAt].startsWith('--asset=') ? args[assetAt].slice('--asset='.length) : args[assetAt + 1];- if (assetAt >= 0 && (asset === undefined || asset === '' || asset.startsWith('--'))) {- exitCliError(usageError('--asset requires a file path the skill lists.', 'Run `gbrain bundled-skill <name>` to see the files it names.'), 'bundled-skill');+ let asset: string | undefined;+ const names: string[] = [];+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === '--json') continue;+ if (a === '--asset' || a.startsWith('--asset=')) {+ const v = a === '--asset' ? args[++i] : a.slice('--asset='.length);+ if (asset !== undefined) exitCliError(usageError('--asset was given twice.', 'Pass one file per call.'), 'bundled-skill');+ if (v === undefined || v === '' || v.startsWith('--')) exitCliError(usageError('--asset requires a file path the skill lists.', 'Run the same command without --asset to see the files the skill names.'), 'bundled-skill');+ asset = v;+ } else if (a.startsWith('-')) {+ exitCliError(usageError(`unknown flag ${a} for gbrain bundled-skill.`, 'Usage: gbrain bundled-skill [<name>] [--asset <path>] [--json]', { code: 'unknown_flag' }), 'bundled-skill');+ } else {+ names.push(a);+ }}- const name = args.filter((a, i) => !a.startsWith('-') && !(assetAt >= 0 && i === assetAt + 1))[0];+ if (names.length > 1) exitCliError(usageError(`gbrain bundled-skill takes one skill name, got ${names.length}.`, 'Usage: gbrain bundled-skill [<name>] [--asset <path>] [--json]'), 'bundled-skill');+ const name = names[0];const audience = bundledSkillAudience();if (name === undefined) {@@ -64,7 +76,7 @@ export async function run(args: string[]): Promise<void> {if (!skill) {const nearest = suggestNearest(name, bundledSkills(audience).map(s => s.name));exitCliError(opError('skill_not_found', `gbrain ${VERSION} has no bundled skill named ${name}${audience === 'downstream' ? ' for this thin-client install' : ''}.${nearest ? ` Did you mean "${nearest}"?` : ''}`,- 'Run `gbrain bundled-skill` to list them. A skills index from another gbrain version may name a renamed skill; refresh it with `gbrain setup <harness> --instructions-only`.'), 'bundled-skill');+ 'Run the same command with no name to list them. A skills index from another gbrain version may name a renamed skill; refresh it with `gbrain setup <harness> --skills-index-only`.'), 'bundled-skill');}if (asset !== undefined) {@@ -83,7 +95,7 @@ export async function run(args: string[]): Promise<void> {return;}const files = skill.assets.length- ? `\n---\nFiles this skill names (print one with \`gbrain bundled-skill ${name} --asset <path>\`):\n${skill.assets.map(a => `- ${a}`).join('\n')}\n`+ ? `\n---\nFiles this skill names (print one by re-running this command with --asset <path>):\n${skill.assets.map(a => `- ${a}`).join('\n')}\n`: '';await writeStdoutFinal(`${content.endsWith('\n') ? content : `${content}\n`}${files}`);}diff --git a/src/commands/connect.ts b/src/commands/connect.tsindex 4dc9c71f71..636b382839 100644--- a/src/commands/connect.ts+++ b/src/commands/connect.ts@@ -45,8 +45,8 @@ import { probeBrainIdentity, DEFAULT_PROBE_TIMEOUT_MS } from '../core/connect-primport { 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 { describeSkillsBlockOutcome, installerSkillsBlock, isSkillLoading, type SkillLoading } from '../core/setup/skills-block.ts';-import { resolveGbrainBin } from '../core/gbrain-bin.ts';+import { describeSkillsBlockOutcome, indexLauncher, installerSkillsBlock, isSkillLoading, skillsOutcomeFailed, type SkillLoading } from '../core/setup/skills-block.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';import {GBRAIN_REMOTE_TOKEN_ENV,reconcileOpencodeSiblingGlobal,@@ -184,6 +184,8 @@ Flags:--skill-loading M With --install: off (default) or spring, a compact index ofgbrain's bundled skills beside that block, each loaded ondemand with gbrain bundled-skill <name>. Remembered.+ --gbrain-bin PATH With --skill-loading spring: the absolute gbrain the index+ names (default: this gbrain, else the one on PATH).--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@@ -444,7 +446,7 @@ export interface ConnectDeps {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, skillLoading?: SkillLoading): string | null;+ writeInstructions(agent: AgentId, name: string, optOut: boolean, skillLoading?: SkillLoading, gbrainBin?: string): string | null;}async function defaultPromptYesNo(question: string): Promise<boolean> {@@ -502,15 +504,16 @@ const defaultDeps: ConnectDeps = {probe: (url, token, timeoutMs) => probeBrainIdentity(url, token, { timeoutMs }),env: (name) => process.env[name],registerOAuthClient: defaultRegisterOAuthClient,- writeInstructions: (agent, name, optOut, skillLoading) => {+ writeInstructions: (agent, name, optOut, skillLoading, gbrainBin) => {if (!isBrainFirstHarness(agent)) return null;const target = brainFirstTarget(agent);if ('error' in target) return null;const writer = `gbrain connect --agent ${agent} --install`;const o = installerBrainFirst({ target, access: { kind: 'mcp', server: name }, writer, instructions: optOut ? false : undefined });- const skills = installerSkillsBlock({ target, launcher: resolveGbrainBin() ?? 'gbrain', writer, brainFirstDeclined: o.decision.value === 'declined', skillLoading, audience: 'downstream' });+ const skills = installerSkillsBlock({ target, launcher: gbrainBin ?? indexLauncher() ?? 'gbrain', writer, brainFirstDeclined: o.decision.value === 'declined', skillLoading, audience: 'downstream' });const lines = [`${describeBrainFirstOutcome(o, false).trim()}${o.decision.value === 'accepted' ? ' (opt out with --no-instructions)' : ''}`];if (skills.decision.value === 'spring' || skills.action !== 'skip') lines.push(describeSkillsBlockOutcome(skills, false).trim());+ if (skillsOutcomeFailed(skills)) setCliExitVerdict(1);return lines.join('\n');},writeOpencodeRemoteEntry: async (name, url, opts) => {@@ -561,6 +564,7 @@ interface ParsedFlags {showToken: boolean;noInstructions: boolean;skillLoading?: SkillLoading;+ gbrainBin?: string;timeoutMs: number;help: boolean;agentError?: string;@@ -609,6 +613,7 @@ function parseArgs(args: string[]): ParsedFlags {case '--json': out.json = true; break;case '--show-token': out.showToken = true; break;case '--no-instructions': out.noInstructions = true; break;+ case '--gbrain-bin': { const v = takeValue('--gbrain-bin'); if (v !== undefined) out.gbrainBin = v; break; }case '--skill-loading': {const v = takeValue('--skill-loading');if (v === undefined) break;@@ -783,7 +788,7 @@ 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);+ const ocInstructions = deps.writeInstructions(f.agent, f.name, f.noInstructions, f.skillLoading, f.gbrainBin);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:`);@@ -833,7 +838,7 @@ 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);+ const instructions = deps.writeInstructions(f.agent, f.name, f.noInstructions, f.skillLoading, f.gbrainBin);if (instructions) console.error(instructions);// Codex reads the token from the env var at runtime, not from its config.diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 2afd4715ee..3bf78efe9e 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -24,7 +24,7 @@* Doctor seeds nothing; the only file it removes is a status marker whose* process is gone.*/-import { skillsIndexViews, type SkillsBlockState, type SkillsIndexView } from '../../../core/setup/skills-block.ts';+import type { SkillsBlockState, SkillsIndexView } from '../../../core/setup/skills-block.ts';import { existsSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, isAbsolute, join } from 'node:path';@@ -453,6 +453,7 @@ function repairArgv(v: InstructionBlockView): Action {/** 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();+ const { skillsIndexViews } = await import('../../../core/setup/skills-block.ts');return withSkillsIndex(withInstructionBlocks(await registrationCheck(opts, regs), instructionBlockViews(regs)), skillsIndexViews());}diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.tsindex 52fb472b14..b025ce150e 100644--- a/src/commands/harness-connect.ts+++ b/src/commands/harness-connect.ts@@ -5,16 +5,16 @@ import { installHarnessConnection, type inlineTokenReceipt } from '../core/harneimport { normalizeMcpUrl } from '../core/mcp-registration.ts';import { validateHarnessArguments } from '../core/harness/arguments.ts';import { readHarnessConnectionStatus } from '../core/harness/status.ts';-import { isSkillLoading } from '../core/setup/skills-block.ts';+import { isSkillLoading, skillsOutcomeFailed, type SkillsBlockOutcome } from '../core/setup/skills-block.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] [--no-instructions] [--skill-loading off|spring] | --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] [--skill-loading off|spring [--gbrain-bin <path>]] | --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', '--skill-loading'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token', '--no-instructions'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });+ validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name', '--skill-loading', '--gbrain-bin'], 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');@@ -30,7 +30,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'), ...(args.includes('--no-instructions') ? { instructions: false } : {}), ...(skillLoading ? { skillLoading } : {}) })+ ? 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 } : {}), ...(skillLoading ? { skillLoading } : {}), ...(value('--gbrain-bin') ? { gbrainBin: value('--gbrain-bin') } : {}) }): { ...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>>;@@ -39,8 +39,7 @@ export async function runHarnessConnect(args: string[]): Promise<void> {console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);}- const skills = (result as { skills?: { action: string; decision: { value: string } } }).skills;- if (skills?.action === 'preserve' && skills.decision.value === 'spring') setCliExitVerdict(1);+ if (skillsOutcomeFailed((result as { skills?: SkillsBlockOutcome }).skills)) setCliExitVerdict(1);else if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);} catch (error) {console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 12165a35f0..47f6d6a764 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -77,14 +77,18 @@ import {describeSkillsBlockOutcome,isSkillLoading,priorSkillLoading,+ indexLauncher,readSkillLoadingLedger,+ refreshSkillsIndexes,removeSkillsBlock,resolveSkillLoading,- syncSkillsBlock,+ installerSkillsBlock,+ skillsOutcomeFailed,type SkillLoading,type SkillsBlockOutcome,} from '../core/setup/skills-block.ts';import {+ BRAIN_FIRST_HARNESSES,brainFirstTarget,describeBrainFirstOutcome,isBrainFirstHarness,@@ -146,6 +150,9 @@ Flags:matches (gbrain bundled-skill <name>, from this gbrain).off removes an index an earlier run wrote. Thechoice is remembered; GBRAIN_SKILL_LOADING sets it too.+ --skills-index-only Refresh every skills index recorded for this harness (its+ file, launcher and skill set as recorded) and change+ nothing else; with --skill-loading off, remove them.Brain-first instructions: registering MCP is not enough; agents use a brain theyare told about. By default setup also writes one short marked block into the@@ -196,6 +203,7 @@ interface SetupFlags {gbrainBin?: string;instructions?: boolean;instructionsOnly: boolean;+ skillsIndexOnly: boolean;workspace?: string;skillLoading?: SkillLoading;}@@ -223,6 +231,8 @@ function parseFlags(args: string[]): SetupFlags | string {if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';const skillLoading = value('--skill-loading');if (skillLoading !== undefined && !isSkillLoading(skillLoading)) return `unknown --skill-loading '${skillLoading}'; pass off or spring`;+ const envLoading = process.env.GBRAIN_SKILL_LOADING?.trim();+ if (skillLoading === undefined && envLoading && !isSkillLoading(envLoading)) return `GBRAIN_SKILL_LOADING='${envLoading}' is not a skill-loading mode; set it to off or spring, or unset it`;return {harness: positionals[0],dryRun: args.includes('--dry-run'),@@ -238,6 +248,7 @@ function parseFlags(args: string[]): SetupFlags | string {gbrainBin: value('--gbrain-bin'),instructions: args.includes('--instructions') ? true : args.includes('--no-instructions') ? false : undefined,instructionsOnly: args.includes('--instructions-only'),+ skillsIndexOnly: args.includes('--skills-index-only'),workspace,skillLoading: skillLoading as SkillLoading | undefined,};@@ -347,6 +358,7 @@ export async function runSetup(args: string[]): Promise<number> {const flags = parsed;const adapter = HARNESS_ADAPTERS.find((a) => a.id === flags.harness);const mcpWired = flags.harness === 'claude-code' || flags.harness === 'codex';+ if (flags.skillsIndexOnly) return runSkillsIndexOnly(flags, out);if ((flags.instructionsOnly && (isBrainFirstHarness(flags.harness) || adapter)) || (isBrainFirstHarness(flags.harness) && !mcpWired)) {return runInstructionsOnly(flags, out);}@@ -704,15 +716,17 @@ function removeBrainFirstFor(harness: BrainFirstHarness, where: { scope?: Wiringfunction skillsFor(harness: BrainFirstHarness, flags: SetupFlags, launcher: string, where: { scope?: WiringScope; projectDir?: string }, brainFirst: BrainFirstOutcome | null): SkillsBlockOutcome | null {const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });if ('error' in target) return null;- const decision = brainFirst?.decision.value === 'declined'- ? { value: 'off' as const, source: 'instructions_off' as const }- : resolveSkillLoading(flags.skillLoading, priorSkillLoading(harness, target.path));- return syncSkillsBlock({ target, launcher, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });+ return installerSkillsBlock({ target, launcher, writer: `gbrain setup ${harness}`, brainFirstDeclined: brainFirst?.decision.value === 'declined', skillLoading: flags.skillLoading, dryRun: flags.dryRun });}function removeSkillsFor(harness: BrainFirstHarness, where: { scope?: WiringScope; projectDir?: string }, flags: SetupFlags): SkillsBlockOutcome | null {const target = brainFirstTarget(harness, { ...where, workspace: flags.workspace });- const path = 'error' in target ? readSkillLoadingLedger().find((e) => e.harness === harness)?.path : target.path;+ let path: string | undefined;+ try {+ path = 'error' in target ? readSkillLoadingLedger().find((e) => e.harness === harness)?.path : target.path;+ } catch {+ path = 'error' in target ? undefined : target.path;+ }return path ? removeSkillsBlock({ harness, path, dryRun: flags.dryRun }) : null;}@@ -766,7 +780,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>say(out, `Target (${adapter.label}): ${target.path} (${target.role})`);const decision = resolveBrainFirstDecision(flags.instructions, priorBrainFirst(harness, target.path));instructions = syncBrainFirst({ target, access, decision, writer: `gbrain setup ${harness}`, dryRun: flags.dryRun });- skills = skillsFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? 'gbrain', where, instructions);+ skills = skillsFor(harness, flags, flags.gbrainBin ?? indexLauncher() ?? 'gbrain', where, instructions);}const code = instructions?.action === 'preserve' || skillsFailed(skills) ? 1 : 0;if (out.json) {@@ -780,6 +794,23 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>return code;}+/** --skills-index-only: refresh (or, with --skill-loading off, remove) the recorded skills indexes for one harness; nothing else is touched. */+async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number> {+ const harness = flags.harness;+ if (!isBrainFirstHarness(harness)) {+ return refuse(opError('invalid_params', `--skills-index-only needs a harness with an instruction file: ${BRAIN_FIRST_HARNESSES.join(', ')}`, 'Pass the harness whose skills index to refresh, e.g. gbrain setup claude-code --skills-index-only.'), out);+ }+ const outcomes = refreshSkillsIndexes(harness, { off: flags.skillLoading === 'off', launcher: flags.gbrainBin, dryRun: flags.dryRun });+ const code = outcomes.some((o) => o.action === 'preserve') ? 1 : 0;+ if (out.json) {+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes }, null, 2)}\n`, (t) => process.stdout.write(t));+ return code;+ }+ if (outcomes.length === 0) say(out, `No skills index is recorded for ${harness}. Add one with: gbrain setup ${harness} --skill-loading spring`);+ for (const o of outcomes) say(out, describeSkillsBlockOutcome(o, flags.dryRun));+ return code;+}+async function finish(out: Out, doc: {harness?: SetupHarnessId; dryRun: boolean; remove?: boolean; target?: Target; consent?: SetupConsent; steps: Array<{ step: string; action: string; detail: string }>; states: string[];verify: { ok: boolean; reason: string; message: string } | null; notices: Notice[]; notes: string[]; preserved?: unknown[];@@ -814,4 +845,4 @@ async function finish(out: Out, doc: {}/** An index the user asked for by flag that could not be written fails the run (the rest of the install still finished). */-const skillsFailed = (o: SkillsBlockOutcome | null): boolean => o?.action === 'preserve' && (o.decision.value === 'spring' || o.decision.source !== 'default');+const skillsFailed = (o: SkillsBlockOutcome | null): boolean => skillsOutcomeFailed(o);diff --git a/src/core/bootstrap/harness-skills-index.ts b/src/core/bootstrap/harness-skills-index.tsindex 09aa25015b..769fbeb944 100644--- a/src/core/bootstrap/harness-skills-index.ts+++ b/src/core/bootstrap/harness-skills-index.ts@@ -7,7 +7,8 @@* bundled skill. Removal strips only the indexes this lane recorded.*/import { brainFirstTargetAt, codexInstructionFile, readBrainFirstLedger } from '../setup/brain-first.ts';-import { describeSkillsBlockOutcome, installerSkillsBlock, removeSkillsBlocksBy, type SkillLoading, type SkillsBlockOutcome } from '../setup/skills-block.ts';+import { describeSkillsBlockOutcome, installerSkillsBlock, removeSkillsBlocksBy, skillsOutcomeFailed, type SkillLoading, type SkillsBlockOutcome } from '../setup/skills-block.ts';+import { setCliExitVerdict } from '../cli-force-exit.ts';import type { BrainFirstHost, HarnessInstructionPaths } from './harness-brain-first.ts';const WRITER = 'gbrain bootstrap harness';@@ -21,10 +22,14 @@ export function writeHarnessSkillsIndex(opts: { hosts: readonly BrainFirstHost[]const declined = opts.optOut || readBrainFirstLedger().find((e) => e.harness === host && e.path === path)?.status === 'declined';const o = installerSkillsBlock({ target: brainFirstTargetAt(host, path), launcher: opts.launcher, writer: WRITER, brainFirstDeclined: declined, skillLoading: opts.skillLoading, audience: 'owner' });if (o.decision.value === 'spring' || o.action !== 'skip') opts.log(describeSkillsBlockOutcome(o, false).trim());+ if (skillsOutcomeFailed(o)) setCliExitVerdict(1);return o;});}export function removeHarnessSkillsIndex(log: (line: string) => void): void {- for (const o of removeSkillsBlocksBy(WRITER)) log(describeSkillsBlockOutcome(o, false).trim());+ for (const o of removeSkillsBlocksBy(WRITER)) {+ log(describeSkillsBlockOutcome(o, false).trim());+ if (skillsOutcomeFailed(o)) setCliExitVerdict(1);+ }}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 300ca85a7e..71c8576006 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -28,7 +28,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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', '--keep-checkout', '--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', '--skill-loading', '--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'],- 'bundled-skill': ['--asset', '--brain', '--help', '--instructions-only', '--json', '--skill-loading', '--source'],+ 'bundled-skill': ['--asset', '--brain', '--help', '--json', '--skill-loading', '--skills-index-only', '--source'],'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'],'call': ['--brain', '--help', '--json', '--source'],@@ -43,7 +43,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', '--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', '--skill-loading', '--source', '--source-ids', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],+ 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--gbrain-bin', '--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', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--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'],@@ -51,7 +51,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', '--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', '--skill-loading', '--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', '--source-ids', '--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', '--gbrain-bin', '--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', '--skill-loading', '--skills-dir', '--skills-index-only', '--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', '--source-ids', '--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'],@@ -122,7 +122,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--skill-loading', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],diff --git a/src/core/harness/install.ts b/src/core/harness/install.tsindex d76ad955c4..fa211b9b52 100644--- a/src/core/harness/install.ts+++ b/src/core/harness/install.ts@@ -20,15 +20,16 @@ import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';import { harnessSharedSkillsRoot } from './status.ts';import { gitChildEnv } from '../git-env.ts';import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';-import { installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, type SkillLoading } from '../setup/skills-block.ts';-import { resolveGbrainBin } from '../gbrain-bin.ts';+import { indexLauncher, installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, type SkillLoading } from '../setup/skills-block.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;/** false: opt out of the brain-first instruction block (removes an existing one); true: opt back in. */instructions?: boolean;/** The spring-loaded skills index beside the brain-first block (off by default; GBRAIN_SKILL_LOADING and the recorded choice apply). */- skillLoading?: SkillLoading }+ skillLoading?: SkillLoading;+ /** The absolute gbrain the native-config index names (default: this gbrain, else the one on PATH). */+ gbrainBin?: string }const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');const readJson = (path: string): Record<string, any> => {assertNoSymlinks(path);@@ -179,7 +180,7 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Instconst 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 });- const skills = installerSkillsBlock({ target: brainFirstTargetAt(beside.harness, beside.path), launcher: resolveGbrainBin() ?? 'gbrain',+ const skills = installerSkillsBlock({ target: brainFirstTargetAt(beside.harness, beside.path), launcher: opts.gbrainBin ?? indexLauncher() ?? 'gbrain',writer: `gbrain connect --harness ${adapter.id} --install`, brainFirstDeclined: instructions.decision.value === 'declined', skillLoading: opts.skillLoading, audience: 'downstream', remove: opts.remove });if (opts.remove) {if (existsSync(receiptPath)) unlinkSync(receiptPath);@@ -224,11 +225,12 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, coconst skillLoading = brainFirst === 'declined' ? 'off' : resolveSkillLoading(opts.skillLoading, isSkillLoading(prior.skill_loading) ? { mode: prior.skill_loading } : undefined).value;const rerun = `gbrain connect ${shellQuote(c.mcp_url)} --harness ${shellQuote(opts.harness)} --credentials-file <private-handoff-file> --root ${shellQuote(root)} --install`;const skillsIndex = skillLoading === 'spring' ? renderSkillsSnippet(opts.harness, launcher, 'downstream', { refresh: rerun, optOut: `${rerun} --skill-loading off` }) : '';+ const instructionsHead = `${brainFirst === 'declined' ? '' : renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}${skillsIndex}`;const files = [{ 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: `${brainFirst === 'declined' ? '' : `${renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}\n`}${skillsIndex}${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: `${instructionsHead ? `${instructionsHead}\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/skills-block.ts b/src/core/setup/skills-block.tsindex f7e3562819..6290192ae7 100644--- a/src/core/setup/skills-block.ts+++ b/src/core/setup/skills-block.ts@@ -21,30 +21,62 @@* nothing else was written into.*/import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';-import { join } from 'node:path';+import { basename, isAbsolute, join } from 'node:path';+import { resolveGbrainBin } from '../gbrain-bin.ts';+import { addPermissionsAllowEntry, removePermissionsAllowEntry } from '../bootstrap/hooks.ts';+import { claudeUserSettingsPath } from '../bootstrap/host-specs.ts';+import { spawnSync } from '../spawn.ts';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';import { configDir } from '../config.ts';import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';import { ensureGitExcluded } from '../context/compiled-core.ts';import { bundledCatalogId, bundledSkills, type SkillAudience } from '../skills/bundled.ts';-import { renderSkillIndexBlock, SKILL_INDEX_VERSION, SkillIndexTooLarge, skillIndexCatalog } from '../skills/spring-index.ts';-import { BRAIN_FIRST_END, CURSOR_HEAD, direntExists, readBrainFirstLedger, writeUnlessChanged, type BrainFirstTarget } from './brain-first.ts';+import { renderSkillIndexBlock, shellWord, SKILL_INDEX_VERSION, SkillIndexTooLarge, skillIndexCatalog } from '../skills/spring-index.ts';+import { BRAIN_FIRST_END, brainFirstTargetAt, CURSOR_HEAD, direntExists, readBrainFirstLedger, writeUnlessChanged, type BrainFirstHarness, type BrainFirstTarget } from './brain-first.ts';export const SKILLS_BLOCK_BEGIN = '<!-- gbrain:skills:begin -->';export const SKILLS_BLOCK_END = '<!-- gbrain:skills:end -->';export const SKILL_LOADING_ENV = 'GBRAIN_SKILL_LOADING';export const SKILL_LOADING_MODES = ['off', 'spring'] as const;export type SkillLoading = (typeof SKILL_LOADING_MODES)[number];-const MARKERS: BlockMarkers = { begin: SKILLS_BLOCK_BEGIN, end: SKILLS_BLOCK_END, label: 'skills', rerun: 'gbrain setup <harness> --instructions-only --skill-loading spring' };+const MARKERS: BlockMarkers = { begin: SKILLS_BLOCK_BEGIN, end: SKILLS_BLOCK_END, label: 'skills', rerun: 'gbrain setup <harness> --skills-index-only' };const LEDGER_FILE = 'skill-loading.json';export function isSkillLoading(v: unknown): v is SkillLoading {return (SKILL_LOADING_MODES as readonly unknown[]).includes(v);}-/** The command that refreshes an index after an upgrade; the recorded mode makes a bare re-run keep it. */+/**+ * The command that refreshes every index recorded for a harness after an+ * upgrade: it rewrites only the skills block, at the recorded file, with the+ * recorded launcher and audience, and never touches brain-first.+ */export function skillsRefreshCommand(harness: string): string {- return `gbrain setup ${harness} --instructions-only`;+ return `gbrain setup ${harness} --skills-index-only`;+}++/** The absolute gbrain an index should name when no --gbrain-bin is given: this compiled binary, else the one on PATH. */+export function indexLauncher(): string | null {+ if (basename(process.execPath).startsWith('gbrain')) return process.execPath;+ return resolveGbrainBin();+}++/**+ * The catalog identity the launcher actually serves (`<launcher> bundled-skill+ * --json`), so an index is never written naming a gbrain whose skills differ+ * from the ones indexed (another install earlier on PATH, a stale+ * --gbrain-bin). Engine-free and read-only on the launcher's side.+ */+export function launcherCatalog(launcher: string): { catalog: string } | { error: string } {+ if (!isAbsolute(launcher)) return { error: `${launcher} is not an absolute path (GUI-launched harnesses inherit no PATH)` };+ const r = spawnSync(launcher, ['bundled-skill', '--json'], { encoding: 'utf8', timeout: 20_000 }) as { status: number | null; stdout?: string; stderr?: string; error?: Error };+ if (r.status !== 0) return { error: `${launcher} bundled-skill --json failed: ${(r.error?.message ?? r.stderr ?? '').trim().split('\n')[0] || `exit ${r.status}`}` };+ try {+ const catalog = (JSON.parse(r.stdout ?? '') as { catalog?: unknown }).catalog;+ return typeof catalog === 'string' ? { catalog } : { error: `${launcher} reported no skill catalog (a gbrain without bundled-skill)` };+ } catch {+ return { error: `${launcher} bundled-skill --json printed no JSON` };+ }}/**@@ -54,7 +86,7 @@ export function skillsRefreshCommand(harness: string): string {* SkillIndexTooLarge rather than return a block over budget.*/export function renderSkillsBlock(harness: string, launcher: string, audience: SkillAudience = 'owner', how?: { refresh: string; optOut: string }): string {- return renderSkillIndexBlock(bundledSkills(audience), launcher, how ?? { refresh: skillsRefreshCommand(harness), optOut: `gbrain setup ${harness} --instructions-only --skill-loading off` });+ return renderSkillIndexBlock(bundledSkills(audience), launcher, how ?? { refresh: skillsRefreshCommand(harness), optOut: `${skillsRefreshCommand(harness)} --skill-loading off` });}/** The block with its markers, for a file gbrain writes whole (the thin-client GBRAIN-INSTRUCTIONS.md). */@@ -73,6 +105,9 @@ export interface SkillLoadingLedgerEntry {catalog?: string;launcher?: string;audience?: SkillAudience;+ /** Claude Code: the permissions.allow rule that lets sessions run the loader, and whether gbrain added it. */+ allow_rule?: string;+ allow_owned?: boolean;writer: string;created_file: boolean;updated_at: string;@@ -80,15 +115,25 @@ export interface SkillLoadingLedgerEntry {export function skillLoadingLedgerPath(): string { return join(configDir(), LEDGER_FILE); }+/** A ledger gbrain cannot read: ownership is unknown, so nothing that depends on it is changed. */+export class SkillLedgerUnreadable extends Error {+ constructor(readonly path: string, why: string) {+ super(`${path} is unreadable (${why}); gbrain will not guess which skills indexes and permission rules it owns. Fix the JSON or move the file aside, then re-run`);+ }+}++/** The recorded choices; [] when there is no ledger. Throws SkillLedgerUnreadable for a file it cannot parse. */export function readSkillLoadingLedger(): SkillLoadingLedgerEntry[] {const path = skillLoadingLedgerPath();if (!existsSync(path)) return [];+ let raw: { version?: unknown; entries?: unknown };try {- const raw = JSON.parse(readFileSync(path, 'utf8')) as { entries?: SkillLoadingLedgerEntry[] };- return Array.isArray(raw?.entries) ? raw.entries.filter((e) => e && typeof e.path === 'string' && typeof e.harness === 'string' && isSkillLoading(e.mode)) : [];- } catch {- return [];+ raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw;+ } catch (e) {+ throw new SkillLedgerUnreadable(path, e instanceof Error ? e.message : String(e));}+ if (raw?.version !== 1 || !Array.isArray(raw.entries)) throw new SkillLedgerUnreadable(path, 'not a version-1 ledger');+ return (raw.entries as SkillLoadingLedgerEntry[]).filter((e) => e && typeof e.path === 'string' && typeof e.harness === 'string' && isSkillLoading(e.mode));}function writeLedger(entries: SkillLoadingLedgerEntry[]): void {@@ -109,16 +154,61 @@ export function priorSkillLoading(harness: string, path: string): SkillLoadingLereturn readSkillLoadingLedger().find((e) => e.harness === harness && e.path === path);}+// ── Loader permission (Claude Code) ───────────────────────────────────────++/**+ * Claude Code asks before every Bash call it has no rule for, and headless+ * runs deny it, so a spring index on Claude Code comes with one narrow rule+ * in the user settings: the recorded launcher's `bundled-skill` subcommand+ * only, written exactly as the index writes the command. Ownership lives in+ * the ledger (allow_owned): gbrain removes the rule only when it added it and+ * no other recorded index still uses it.+ */+export function loaderAllowRule(launcher: string): string {+ return `Bash(${shellWord(launcher)} bundled-skill:*)`;+}++type Grant = Pick<SkillLoadingLedgerEntry, 'allow_rule' | 'allow_owned'>;++/** Add the rule after the block is in place; returns the ownership to record. Throws when settings cannot be updated. */+function grantLoader(harness: string, launcher: string, prior: SkillLoadingLedgerEntry | undefined): Grant {+ if (harness !== 'claude-code') return {};+ const rule = loaderAllowRule(launcher);+ const added = addPermissionsAllowEntry(claudeUserSettingsPath(), rule).added === true;+ return { allow_rule: rule, allow_owned: added || (prior?.allow_rule === rule && prior.allow_owned === true) };+}++/** Remove a rule gbrain owns once nothing else uses it. Returns why it could not, or undefined when done (or nothing to do). */+function revokeLoader(entry: SkillLoadingLedgerEntry | undefined, keepRule?: string): string | undefined {+ if (!entry?.allow_rule || entry.allow_owned !== true || entry.allow_rule === keepRule) return undefined;+ const stillUsed = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_rule === entry.allow_rule && !(e.harness === entry.harness && e.path === entry.path));+ if (stillUsed) return undefined;+ const settings = claudeUserSettingsPath();+ const r = removePermissionsAllowEntry(settings, entry.allow_rule);+ const warning = r.notes.find((n) => n.startsWith('WARNING'));+ return warning ? `the Claude Code permission rule ${entry.allow_rule} that gbrain added is still in ${settings}: ${warning}` : undefined;+}+// ── Decision, inspection, sync, removal ───────────────────────────────────export type SkillLoadingSource = 'flag' | 'env' | 'prior' | 'default' | 'instructions_off';export interface SkillLoadingDecision { value: SkillLoading; source: SkillLoadingSource }-/** --skill-loading wins, then GBRAIN_SKILL_LOADING, then the recorded choice, then off. */+/** GBRAIN_SKILL_LOADING holds something other than off or spring. */+export class InvalidSkillLoadingEnv extends Error {+ constructor(readonly value: string) {+ super(`${SKILL_LOADING_ENV}='${value}' is not a skill-loading mode; set it to off or spring, or unset it`);+ }+}++/** --skill-loading wins, then GBRAIN_SKILL_LOADING, then the recorded choice, then off. An invalid env value throws. */export function resolveSkillLoading(flag: SkillLoading | undefined, prior: Pick<SkillLoadingLedgerEntry, 'mode'> | undefined): SkillLoadingDecision {if (flag !== undefined) return { value: flag, source: 'flag' };const env = process.env[SKILL_LOADING_ENV]?.trim();- if (isSkillLoading(env)) return { value: env, source: 'env' };+ if (env) {+ if (!isSkillLoading(env)) throw new InvalidSkillLoadingEnv(env);+ return { value: env, source: 'env' };+ }if (prior) return { value: prior.mode, source: 'prior' };return { value: 'off', source: 'default' };}@@ -141,6 +231,10 @@ export function inspectSkillsBlock(path: string, expected?: string): { state: Skreturn { state: current ? 'current' : 'stale', version, ...(catalog ? { catalog } : {}) };}+/** Why an outcome is `preserve` (or a skip that needs the user), stable for JSON consumers. */+export type SkillsBlockReason = 'damaged_markers' | 'index_too_large' | 'launcher_unusable' | 'launcher_catalog_mismatch'+ | 'ledger_unreadable' | 'invalid_env' | 'permission_update_failed' | 'write_failed' | 'recorded_partially' | 'hermes_soul_missing';+export interface SkillsBlockOutcome {harness: string;path: string;@@ -148,8 +242,15 @@ export interface SkillsBlockOutcome {action: 'write' | 'keep' | 'remove' | 'skip' | 'preserve';state_before: SkillsBlockState;detail: string;+ reason?: SkillsBlockReason;+ /** Claude Code: the loader rule this run added to (or removed from) the user settings. */+ permission?: { rule: string; settings: string; change: 'added' | 'removed' };}+/** A spring request (or an explicit off) that left the surface unchanged: the install did not do what was asked. */+export const skillsOutcomeFailed = (o: SkillsBlockOutcome | null | undefined): boolean =>+ !!o && o.action === 'preserve' && (o.decision.value === 'spring' || o.decision.source !== 'default');+function ownedEmptyFile(createdFile: boolean, path: string, stripped: string): boolean {return createdFile && !lstatSync(path).isSymbolicLink() && (stripped.trim() === '' || stripped === CURSOR_HEAD);}@@ -164,12 +265,15 @@ export function placeSkillsBlock(existing: string, body: string): string {return [...lines.slice(0, at + 1), ...block, ...lines.slice(at + 1)].join('\n');}+const message = (e: unknown) => (e instanceof Error ? e.message : String(e));+/*** Make the surface match the decision: write or refresh the block for- * `spring`, strip it for `off`. Never throws: a damaged block or an- * unwritable file is reported as `preserve` and the install carries on.+ * `spring`, strip it for `off`. Never throws: every refusal is a `preserve`+ * outcome with a reason, and the file is left as it was unless the detail+ * says otherwise.*/-export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience }): SkillsBlockOutcome {+export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; verifyLauncher?: boolean }): SkillsBlockOutcome {const { target, launcher, decision } = opts;const audience = opts.audience ?? 'owner';let body: string | undefined;@@ -181,84 +285,133 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stritooLarge = e;}const before = inspectSkillsBlock(target.path, body);- const out = (action: SkillsBlockOutcome['action'], detail: string): SkillsBlockOutcome =>- ({ harness: target.harness, path: target.path, decision, action, state_before: before.state, detail });- const prior = priorSkillLoading(target.harness, target.path);- const record = (mode: SkillLoading, created: boolean) => {+ const out = (action: SkillsBlockOutcome['action'], detail: string, extra: Partial<SkillsBlockOutcome> = {}): SkillsBlockOutcome =>+ ({ harness: target.harness, path: target.path, decision, action, state_before: before.state, detail, ...extra });+ let prior: SkillLoadingLedgerEntry | undefined;+ try {+ prior = priorSkillLoading(target.harness, target.path);+ } catch (e) {+ return out('preserve', `${message(e)}; ${target.path} was left as it was`, { reason: 'ledger_unreadable' });+ }+ const record = (mode: SkillLoading, created: boolean, grant: Grant = {}) => {if (opts.dryRun) return;if (mode === 'off' && decision.source === 'default' && !prior) return;- upsertLedger({ harness: target.harness, path: target.path, mode, block_version: SKILL_INDEX_VERSION, ...(mode === 'spring' ? { catalog: bundledCatalogId(), launcher, audience } : {}), writer: opts.writer, created_file: created, updated_at: new Date().toISOString() });+ upsertLedger({ harness: target.harness, path: target.path, mode, block_version: SKILL_INDEX_VERSION, ...(mode === 'spring' ? { catalog: bundledCatalogId(), launcher, audience, ...grant } : {}), writer: opts.writer, created_file: created, updated_at: new Date().toISOString() });};- try {- if (before.state === 'damaged') {- return out('preserve', `the skills markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`);+ const revoked = (rule: string | undefined): Partial<SkillsBlockOutcome> =>+ rule ? { permission: { rule, settings: claudeUserSettingsPath(), change: 'removed' } } : {};++ if (before.state === 'damaged') {+ return out('preserve', `the skills markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`, { reason: 'damaged_markers' });+ }+ if (decision.value === 'off') {+ if (!opts.dryRun) {+ const stuck = revokeLoader(prior);+ if (stuck) return out('preserve', `${stuck}; remove it by hand, then re-run. ${target.path} was left as it was`, { reason: 'permission_update_failed' });}- if (decision.value === 'off') {- if (before.state === 'no_file' || before.state === 'absent') {- record('off', false);- return out('skip', `skill loading off: no skills index in ${target.path}`);- }+ const ownedRule = prior?.allow_owned ? prior.allow_rule : undefined;+ if (before.state === 'no_file' || before.state === 'absent') {+ try { record('off', false); } catch (e) { return out('preserve', `recording the opt-out failed: ${message(e)}`, { reason: 'write_failed' }); }+ return out('skip', `skill loading off: no skills index in ${target.path}`, revoked(ownedRule));+ }+ try {const existing = readFileSync(target.path, 'utf8');if (!opts.dryRun) {const stripped = removeBlock(MARKERS, existing).text;if (ownedEmptyFile(prior?.created_file ?? false, target.path, stripped)) unlinkSync(target.path);else writeUnlessChanged(target.path, existing, false, stripped);}- record('off', false);- return out('remove', `skills index from ${target.path}`);- }- if (body === undefined) {- return out('preserve', `${tooLarge!.message}; ${target.path} was left as it was`);+ } catch (e) {+ return out('preserve', `${target.path} could not be updated (${message(e)}); the skills index is still there`, { reason: 'write_failed' });}- const brainFirstCreated = readBrainFirstLedger().find((e) => e.harness === target.harness && e.path === target.path)?.created_file ?? false;- if (before.state === 'current') {- record('spring', (prior?.created_file ?? false) || brainFirstCreated);- return out('keep', `skills index in ${target.path} is current`);+ try { record('off', false); } catch (e) {+ return out('preserve', `the skills index was removed from ${target.path}, but recording the opt-out in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it`, { reason: 'recorded_partially' });}- if (target.harness === 'hermes' && (before.state === 'no_file' || readFileSync(target.path, 'utf8').trim() === '')) {- return out('skip', `${target.path} is missing or empty, and Hermes uses a non-empty SOUL.md instead of its default identity; start Hermes once (it seeds SOUL.md) or write your identity there, then re-run`);+ return out('remove', `skills index from ${target.path}`, revoked(ownedRule));+ }++ if (body === undefined) return out('preserve', `${tooLarge!.message}; ${target.path} was left as it was`, { reason: 'index_too_large' });+ if (opts.verifyLauncher !== false) {+ const served = launcherCatalog(launcher);+ if ('error' in served) return out('preserve', `${served.error}; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>`, { reason: 'launcher_unusable' });+ if (served.catalog !== bundledCatalogId()) {+ return out('preserve', `${launcher} serves skill catalog ${served.catalog}, not this gbrain's ${bundledCatalogId()}, so the index would load other text than it lists; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>, or upgrade that install`, { reason: 'launcher_catalog_mismatch' });}- const created = before.state === 'no_file' && !direntExists(target.path);- if (!opts.dryRun) {+ }+ if (target.harness === 'hermes' && (before.state === 'no_file' || readFileSync(target.path, 'utf8').trim() === '')) {+ return out('skip', `${target.path} is missing or empty, and Hermes uses a non-empty SOUL.md instead of its default identity; start Hermes once (it seeds SOUL.md) or write your identity there, then re-run`, { reason: 'hermes_soul_missing' });+ }+ const brainFirstCreated = readBrainFirstLedger().find((e) => e.harness === target.harness && e.path === target.path)?.created_file ?? false;+ const created = before.state === 'no_file' && !direntExists(target.path);+ const createdFile = created || (prior?.created_file ?? false) || brainFirstCreated;+ if (before.state !== 'current' && !opts.dryRun) {+ try {const existing = before.state === 'no_file' ? (created && target.harness === 'cursor' ? CURSOR_HEAD : '') : readFileSync(target.path, 'utf8');writeUnlessChanged(target.path, existing, before.state === 'no_file', placeSkillsBlock(existing, body));if (created && target.project) {try { ensureGitExcluded(target.path); } catch { /* a project file outside git stays as written */ }}+ } catch (e) {+ return out('preserve', `${target.path} could not be updated (${message(e)}); nothing was changed`, { reason: 'write_failed' });}- record('spring', created || (prior?.created_file ?? false) || brainFirstCreated);- return out('write', `skills index ${before.state === 'stale' ? 'refreshed in' : created ? 'in new file' : 'added to'} ${target.path}`);+ }+ const done = before.state === 'current'+ ? out('keep', `skills index in ${target.path} is current`)+ : out('write', `skills index ${before.state === 'stale' ? 'refreshed in' : created ? 'in new file' : 'added to'} ${target.path}`);+ if (opts.dryRun) return done;+ let grant: Grant = {};+ let permissionProblem: string | undefined;+ try {+ grant = grantLoader(target.harness, launcher, prior);+ permissionProblem = revokeLoader(prior, grant.allow_rule);} catch (e) {- return out('preserve', `${target.path} could not be updated (${e instanceof Error ? e.message : String(e)}); nothing else was changed`);+ permissionProblem = `the Claude Code permission rule ${loaderAllowRule(launcher)} could not be added to ${claudeUserSettingsPath()} (${message(e)}), so Claude Code will ask before each skill load`;}+ try {+ record('spring', createdFile, grant);+ } catch (e) {+ return out('preserve', `the skills index is in ${target.path}, but recording it in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it${grant.allow_owned ? ` (gbrain also added ${grant.allow_rule} to ${claudeUserSettingsPath()})` : ''}`, { reason: 'recorded_partially' });+ }+ if (permissionProblem) return { ...done, action: 'preserve', detail: `${done.detail}; ${permissionProblem}`, reason: 'permission_update_failed' };+ const added = grant.allow_rule && grant.allow_owned && prior?.allow_rule !== grant.allow_rule;+ return added ? { ...done, detail: `${done.detail}; Claude Code may now run ${grant.allow_rule}`, permission: { rule: grant.allow_rule!, settings: claudeUserSettingsPath(), change: 'added' } } : done;}/** The uninstall path: strip the block, delete the file only when gbrain created it and nothing else is left, forget the record. */export function removeSkillsBlock(opts: { harness: string; path: string; dryRun: boolean }): SkillsBlockOutcome {- const prior = priorSkillLoading(opts.harness, opts.path);const before = inspectSkillsBlock(opts.path);const decision: SkillLoadingDecision = { value: 'off', source: 'flag' };- const out = (action: SkillsBlockOutcome['action'], detail: string): SkillsBlockOutcome =>- ({ harness: opts.harness, path: opts.path, decision, action, state_before: before.state, detail });+ const out = (action: SkillsBlockOutcome['action'], detail: string, extra: Partial<SkillsBlockOutcome> = {}): SkillsBlockOutcome =>+ ({ harness: opts.harness, path: opts.path, decision, action, state_before: before.state, detail, ...extra });+ let prior: SkillLoadingLedgerEntry | undefined;try {- if (before.state === 'damaged') return out('preserve', `the skills markers in ${opts.path} were hand-edited; remove the block by hand`);- if (before.state === 'no_file' || before.state === 'absent') {- if (!opts.dryRun) dropLedger(opts.harness, opts.path);- return out('skip', `no skills index in ${opts.path}`);- }- if (!opts.dryRun) {+ prior = priorSkillLoading(opts.harness, opts.path);+ } catch (e) {+ return out('preserve', `${message(e)}; ${opts.path} was left as it was`, { reason: 'ledger_unreadable' });+ }+ if (before.state === 'damaged') return out('preserve', `the skills markers in ${opts.path} were hand-edited; remove the block by hand`, { reason: 'damaged_markers' });+ if (opts.dryRun) return before.state === 'no_file' || before.state === 'absent' ? out('skip', `no skills index in ${opts.path}`) : out('remove', `skills index from ${opts.path}`);+ const stuck = revokeLoader(prior);+ if (stuck) return out('preserve', `${stuck}; remove it by hand, then re-run. ${opts.path} was left as it was`, { reason: 'permission_update_failed' });+ const permission: Partial<SkillsBlockOutcome> = prior?.allow_owned && prior.allow_rule ? { permission: { rule: prior.allow_rule, settings: claudeUserSettingsPath(), change: 'removed' } } : {};+ let deleteFile = false;+ if (before.state !== 'no_file' && before.state !== 'absent') {+ try {const existing = readFileSync(opts.path, 'utf8');const stripped = removeBlock(MARKERS, existing).text;- const deleteFile = ownedEmptyFile(prior?.created_file ?? false, opts.path, stripped);+ deleteFile = ownedEmptyFile(prior?.created_file ?? false, opts.path, stripped);if (deleteFile) unlinkSync(opts.path);else writeUnlessChanged(opts.path, existing, false, stripped);- dropLedger(opts.harness, opts.path);- return out('remove', `skills index from ${opts.path}${deleteFile ? ' (file removed: gbrain created it and nothing else was in it)' : ''}`);+ } catch (e) {+ return out('preserve', `${opts.path} could not be updated (${message(e)}); the skills index is still there`, { reason: 'write_failed' });}- return out('remove', `skills index from ${opts.path}`);- } catch (e) {- return out('preserve', `${opts.path} could not be updated (${e instanceof Error ? e.message : String(e)})`);}+ try { dropLedger(opts.harness, opts.path); } catch (e) {+ return out('preserve', `the skills index was removed from ${opts.path}, but ${skillLoadingLedgerPath()} could not be updated (${message(e)}); re-run to finish`, { reason: 'recorded_partially' });+ }+ return before.state === 'no_file' || before.state === 'absent'+ ? out('skip', `no skills index in ${opts.path}`, permission)+ : out('remove', `skills index from ${opts.path}${deleteFile ? ' (file removed: gbrain created it and nothing else was in it)' : ''}`, permission);}/** One human line per outcome, matching setup's step lines. */@@ -278,14 +431,32 @@ export function installerSkillsBlock(opts: {skillLoading?: SkillLoading; audience?: SkillAudience; remove?: boolean; dryRun?: boolean;}): SkillsBlockOutcome {if (opts.remove) return removeSkillsBlock({ harness: opts.target.harness, path: opts.target.path, dryRun: opts.dryRun ?? false });- const decision: SkillLoadingDecision = opts.brainFirstDeclined- ? { value: 'off', source: 'instructions_off' }- : resolveSkillLoading(opts.skillLoading, priorSkillLoading(opts.target.harness, opts.target.path));+ let decision: SkillLoadingDecision;+ try {+ decision = opts.brainFirstDeclined+ ? { value: 'off', source: 'instructions_off' }+ : resolveSkillLoading(opts.skillLoading, priorSkillLoading(opts.target.harness, opts.target.path));+ } catch (e) {+ const reason: SkillsBlockReason = e instanceof InvalidSkillLoadingEnv ? 'invalid_env' : 'ledger_unreadable';+ return { harness: opts.target.harness, path: opts.target.path, decision: { value: 'off', source: 'flag' }, action: 'preserve', state_before: inspectSkillsBlock(opts.target.path).state, detail: `${message(e)}; ${opts.target.path} was left as it was`, reason };+ }return syncSkillsBlock({ target: opts.target, launcher: opts.launcher, decision, writer: opts.writer, dryRun: opts.dryRun ?? false, audience: opts.audience });}+/** A preserve outcome when the ledger cannot be read, else undefined. */+function ledgerProblem(): SkillsBlockOutcome | undefined {+ try {+ readSkillLoadingLedger();+ return undefined;+ } catch (e) {+ return { harness: '*', path: skillLoadingLedgerPath(), decision: { value: 'off', source: 'flag' }, action: 'preserve', state_before: 'damaged', detail: message(e), reason: 'ledger_unreadable' };+ }+}+/** Removal for a lane that records its writer: strip every index that writer wrote. */export function removeSkillsBlocksBy(writer: string, dryRun = false): SkillsBlockOutcome[] {+ const unreadable = ledgerProblem();+ if (unreadable) return [unreadable];return readSkillLoadingLedger().filter((e) => e.writer === writer && e.mode === 'spring').map((e) => removeSkillsBlock({ harness: e.harness, path: e.path, dryRun }));}@@ -298,8 +469,29 @@ export interface SkillsIndexView { harness: string; path: string; state: SkillsB* by name, so doctor names the refresh command and never warns on it.*/export function skillsIndexViews(): SkillsIndexView[] {+ if (ledgerProblem()) return [{ harness: '*', path: skillLoadingLedgerPath(), state: 'damaged', refresh: `fix the JSON in ${skillLoadingLedgerPath()} or move it aside, then re-run gbrain setup <harness> --skill-loading spring` }];return readSkillLoadingLedger().filter((e) => e.mode === 'spring').map((e) => ({harness: e.harness, path: e.path, state: inspectSkillsBlock(e.path).state, refresh: skillsRefreshCommand(e.harness),}));}++/**+ * `gbrain setup <harness> --skills-index-only` (the refresh the block header+ * and doctor name): re-render every index the ledger records for the+ * harness, in its recorded file, with its recorded launcher (or+ * --gbrain-bin), audience and writer. Brain-first and every other file are+ * left alone. `off` strips them all and records the opt-out.+ */+export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { off: boolean; launcher?: string; dryRun: boolean }): SkillsBlockOutcome[] {+ const unreadable = ledgerProblem();+ if (unreadable) return [unreadable];+ return readSkillLoadingLedger().filter((e) => e.harness === harness && (opts.off || e.mode === 'spring')).map((e) => syncSkillsBlock({+ target: brainFirstTargetAt(harness, e.path),+ launcher: opts.launcher ?? e.launcher ?? indexLauncher() ?? 'gbrain',+ audience: e.audience ?? 'owner',+ decision: opts.off ? { value: 'off', source: 'flag' } : { value: 'spring', source: 'prior' },+ writer: e.writer,+ dryRun: opts.dryRun,+ }));+}diff --git a/src/core/skills/bundled.ts b/src/core/skills/bundled.tsindex 0bc6b2e5a5..07495fae7f 100644--- a/src/core/skills/bundled.ts+++ b/src/core/skills/bundled.ts@@ -55,9 +55,14 @@ export function bundledSkillAsset(skill: BundledSkill, asset: string): string |return skill.assets.includes(asset) ? BUNDLED_SKILL_FILES[asset] : undefined;}-/** Content identity of the embedded catalog (metadata and every file); the skills index records it so doctor can tell a stale index. */+/**+ * Identity of what the skills index shows and what `bundled-skill` accepts:+ * each skill's name, audience, triggers and file list. A body-only edit keeps+ * it, so it does not mark installed indexes stale; a renamed, added or removed+ * skill, a trigger change or a new file changes it.+ */export function bundledCatalogId(): string {- const h = createHash('sha256').update(JSON.stringify(BUNDLED_SKILLS));- for (const key of Object.keys(BUNDLED_SKILL_FILES).sort()) h.update(`\0${key}\0${BUNDLED_SKILL_FILES[key]}`);+ const h = createHash('sha256');+ for (const s of BUNDLED_SKILLS) h.update(JSON.stringify([s.name, s.audience, bundledSkillTriggers(s), s.assets]));return h.digest('hex').slice(0, 12);}diff --git a/src/core/skills/spring-index.ts b/src/core/skills/spring-index.tsindex 6bb511c3d7..f54d2da9d3 100644--- a/src/core/skills/spring-index.ts+++ b/src/core/skills/spring-index.ts@@ -53,12 +53,18 @@ function distinctTriggers(skill: BundledSkill): string[] {const line = (name: string, triggers: string[]) => (triggers.length ? `- ${name}: ${triggers.join('; ')}` : `- ${name}`);+/** The launcher as one shell word: as-is when it is plain, else single-quoted. */+export function shellWord(s: string): string {+ return /^[A-Za-z0-9_\/.,:@%+=-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\''")}'`;+}+export function skillIndexHeader(launcher: string, refresh: string, optOut: string): string[] {+ const run = shellWord(launcher);return [`<!-- gbrain skills v${SKILL_INDEX_VERSION} catalog ${bundledCatalogId()}: managed by gbrain; edit outside these markers. Refresh: ${refresh}. Opt out: ${optOut} -->`,'## GBrain skills: load on demand','',- `GBrain ships step-by-step procedures for brain work. When a task matches a line below, run \`${launcher} bundled-skill <name>\` and follow the procedure it prints before acting. Print a file the skill names with \`${launcher} bundled-skill <name> --asset <path>\`. Load nothing for a task no line matches.`,+ `GBrain ships step-by-step procedures for brain work. When a task matches a line below, run \`${run} bundled-skill <name>\` and follow the procedure it prints before acting. Print a file the skill names with \`${run} bundled-skill <name> --asset <path>\`. Load nothing for a task no line matches.`,'',];}diff --git a/test/bundled-skill-cli.test.ts b/test/bundled-skill-cli.test.tsindex 348ee77fae..6e9ded15df 100644--- a/test/bundled-skill-cli.test.ts+++ b/test/bundled-skill-cli.test.ts@@ -97,3 +97,15 @@ describe('gbrain bundled-skill', () => {expect((await cli(home, ['meeting-ingestion'])).exitCode).toBe(0);});});++describe('gbrain bundled-skill: argument order', () => {+ test('--asset=<path> before the name, and a second name or unknown flag is refused', async () => {+ const home = emptyHome();+ const r = await cli(home, ['--asset=_brain-filing-rules.md', 'meeting-ingestion']);+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toBe(readFileSync(join(SKILLS, '_brain-filing-rules.md'), 'utf8'));+ expect((await cli(home, ['meeting-ingestion', 'data-loss-gate'])).exitCode).not.toBe(0);+ expect((await cli(home, ['meeting-ingestion', '--bogus'])).exitCode).not.toBe(0);+ expect((await cli(home, ['meeting-ingestion', '--asset', 'a', '--asset', 'b'])).exitCode).not.toBe(0);+ });+});diff --git a/test/setup-skill-loading.test.ts b/test/setup-skill-loading.test.tsindex ddf7872a60..c8e21296ed 100644--- a/test/setup-skill-loading.test.ts+++ b/test/setup-skill-loading.test.ts@@ -16,17 +16,26 @@* Spawns `bun src/cli.ts setup` against a temp HOME / GBRAIN_HOME.*/import { afterAll, describe, expect, test } from 'bun:test';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';import { BRAIN_FIRST_BEGIN, BRAIN_FIRST_END } from '../src/core/setup/brain-first.ts';-import { inspectSkillsBlock, renderSkillsBlock, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';+import { inspectSkillsBlock, loaderAllowRule, renderSkillsBlock, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';import { bundledCatalogId } from '../src/core/skills/bundled.ts';-const LAUNCHER = '/opt/alice-example/bin/gbrain';+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const BIN_DIR = mkdtempSync(join(tmpdir(), 'gbrain-skill-bin-'));+const LAUNCHER = join(BIN_DIR, 'gbrain');+writeFileSync(LAUNCHER, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+chmodSync(LAUNCHER, 0o755);+/** A gbrain that serves another skill catalog (a different install on PATH, a stale --gbrain-bin). */+const OTHER = join(BIN_DIR, 'gbrain-other');+writeFileSync(OTHER, '#!/bin/sh\necho \'{"schema_version":1,"catalog":"000000000000","skills":[]}\'\n');+chmodSync(OTHER, 0o755);const roots: string[] = [];-afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });+afterAll(() => { for (const r of [...roots, BIN_DIR]) rmSync(r, { recursive: true, force: true }); });interface Box { home: string; project: string; env: Record<string, string | undefined> }function box(): Box {@@ -181,3 +190,72 @@ describe('skill loading: selection', () => {expect(inspectSkillsBlock(file).state).toBe('current');});});++describe('skill loading: launcher, permission and refresh', () => {+ test('an index is never written naming a gbrain that serves another catalog, or a bare name', async () => {+ const b = box();+ const other = await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', OTHER, '--skill-loading', 'spring']);+ expect(other.exitCode).toBe(1);+ expect(other.doc.skills.action).toBe('preserve');+ expect(other.doc.skills.detail).toContain('000000000000');+ expect(read(join(b.home, '.claude', 'CLAUDE.md'))).not.toContain(SKILLS_BLOCK_BEGIN);+ const bare = await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', 'gbrain', '--skill-loading', 'spring']);+ expect(bare.exitCode).toBe(1);+ expect(bare.doc.skills.detail).toContain('not an absolute path');+ });++ test('Claude Code: spring adds one narrow allow rule for the loader; off removes it; a rule the user had stays', async () => {+ const b = box();+ const settings = join(b.home, '.claude', 'settings.json');+ const rule = loaderAllowRule(LAUNCHER);+ await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring']);+ expect(JSON.parse(read(settings)).permissions.allow).toEqual([rule]);+ await setup(b, ['claude-code', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'off']);+ expect(JSON.parse(read(settings)).permissions?.allow ?? []).not.toContain(rule);++ const c = box();+ const cSettings = join(c.home, '.claude', 'settings.json');+ mkdirSync(dirname(cSettings), { recursive: true });+ writeFileSync(cSettings, JSON.stringify({ permissions: { allow: [rule, 'Read'] } }));+ await setup(c, ['claude-code', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring']);+ await setup(c, ['claude-code', '--instructions-only', '--gbrain-bin', LAUNCHER, '--remove']);+ expect(JSON.parse(read(cSettings)).permissions.allow).toEqual([rule, 'Read']);+ });++ test('codex gets no permission edit (its sandbox runs the read-only loader)', async () => {+ const b = box();+ await setup(b, ['codex', '--instructions-only', '--gbrain-bin', LAUNCHER, '--skill-loading', 'spring']);+ expect(existsSync(join(b.home, '.claude', 'settings.json'))).toBe(false);+ });++ test('--skills-index-only refreshes only the skills block, keeping the recorded file, launcher, audience and the brain-first block', async () => {+ const b = box();+ const file = join(b.home, '.codex', 'AGENTS.md');+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, '# house rules\n');+ const team = await withEnv(b.env, async () => {+ const { installerBrainFirst, brainFirstTargetAt } = await import('../src/core/setup/brain-first.ts');+ const { installerSkillsBlock } = await import('../src/core/setup/skills-block.ts');+ const target = brainFirstTargetAt('codex', file);+ installerBrainFirst({ target, access: { kind: 'mcp', server: 'team-a' }, writer: 'gbrain connect --agent codex --install' });+ return installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'gbrain connect --agent codex --install', brainFirstDeclined: false, skillLoading: 'spring', audience: 'downstream' });+ });+ expect(team.action).toBe('write');+ const written = read(file);+ const stale = written.replace(/catalog [0-9a-f]{12}/, 'catalog 000000000000');+ writeFileSync(file, stale);+ const r = await setup(b, ['codex', '--skills-index-only']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.skills).toHaveLength(1);+ expect(r.doc.skills[0]).toMatchObject({ action: 'write', state_before: 'stale' });+ expect(read(file)).toBe(written);+ expect(read(file)).toContain('team-a');+ const off = await setup(b, ['codex', '--skills-index-only', '--skill-loading', 'off']);+ expect(off.doc.skills[0].action).toBe('remove');+ expect(read(file)).not.toContain(SKILLS_BLOCK_BEGIN);+ expect(read(file)).toContain('team-a');+ const none = await setup(box(), ['codex', '--skills-index-only']);+ expect(none.exitCode).toBe(0);+ expect(none.doc.skills).toEqual([]);+ });+});diff --git a/test/skill-loading-lanes.test.ts b/test/skill-loading-lanes.test.tsnew file mode 100644index 0000000000..63b6e6a78a--- /dev/null+++ b/test/skill-loading-lanes.test.ts@@ -0,0 +1,218 @@+/**+ * GBRA-194: the spring-loaded skills index on the installer lanes beside+ * setup: `gbrain connect --harness … --install` (native config files and the+ * thin-client GBRAIN-INSTRUCTIONS.md), `gbrain bootstrap harness`, the+ * shared installer decision, and doctor's informational report.+ *+ * Protects: every lane writes the index right after the brain-first block+ * only when spring is selected, a hosted or thin connection lists only the+ * skills that are not host-only, opt-outs and removal take the index out,+ * and doctor names a stale index's refresh command without changing status.+ * Fails when: a lane writes an index by default, indexes host-only skills+ * for a remote connection, leaves an index after --remove or+ * --no-instructions, or doctor warns on (or hides) a stale index.+ */+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 } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { BRAIN_FIRST_END, brainFirstTargetAt } from '../src/core/setup/brain-first.ts';+import { installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';+import { installHarnessConnection } from '../src/core/harness/install.ts';+import { removeHarnessSkillsIndex, writeHarnessSkillsIndex } from '../src/core/bootstrap/harness-skills-index.ts';+import { withSkillsIndex } from '../src/commands/doctor/checks/harness-wiring.ts';+import { bundledSkills } from '../src/core/skills/bundled.ts';+import type { HarnessCredentials } from '../src/core/harness/credentials.ts';++const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const BIN_DIR = mkdtempSync(join(tmpdir(), 'gbrain-skill-bin-'));+const LAUNCHER = join(BIN_DIR, 'gbrain');+writeFileSync(LAUNCHER, '#!/bin/sh\nexec \'' + process.execPath + '\' --no-env-file \'' + CLI + '\' "$@"\n');+chmodSync(LAUNCHER, 0o755);+const roots: string[] = [];+afterAll(() => { for (const r of [...roots, BIN_DIR]) rmSync(r, { recursive: true, force: true }); });+function box() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-skill-lanes-'));+ roots.push(root);+ const home = join(root, 'home');+ mkdirSync(home, { recursive: true });+ return { root, home, 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_SKILL_LOADING: undefined, GBRAIN_SURFACE: undefined,+ } };+}+const read = (p: string) => readFileSync(p, 'utf8');+const lines = (t: string) => t.split('\n');+const hostOnly = bundledSkills('owner').filter(s => s.audience === 'owner').map(s => s.name);+const indexed = (t: string) => lines(t.slice(t.indexOf(SKILLS_BLOCK_BEGIN), t.indexOf(SKILLS_BLOCK_END))).filter(l => l.startsWith('- ')).map(l => l.slice(2).split(':')[0]);+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' };++describe('connect --harness --install', () => {+ 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(`${harness}: off by default; spring indexes the non-host skills after brain-first; opt-out and --remove take it out`, async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const configPath = join(b.home, config);+ const file = join(b.home, instructions);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, 'house rules\n');+ const plain = await installHarnessConnection(credentials, { harness, configPath });+ expect((plain as any).skills.decision).toEqual({ value: 'off', source: 'default' });+ expect(read(file)).not.toContain(SKILLS_BLOCK_BEGIN);++ const spring = await installHarnessConnection(credentials, { harness, configPath, skillLoading: 'spring', gbrainBin: LAUNCHER });+ expect((spring as any).skills.action).toBe('write');+ const text = read(file);+ expect(lines(text).indexOf(SKILLS_BLOCK_BEGIN)).toBe(lines(text).indexOf(BRAIN_FIRST_END) + 1);+ expect(indexed(text)).toEqual(bundledSkills('downstream').map(s => s.name));+ expect(indexed(text).filter(n => hostOnly.includes(n))).toEqual([]);++ expect(((await installHarnessConnection(credentials, { harness, configPath, gbrainBin: LAUNCHER })) as any).skills).toMatchObject({ action: 'keep', decision: { source: 'prior' } });+ const optedOut = await installHarnessConnection(credentials, { harness, configPath, instructions: false });+ expect((optedOut as any).skills).toMatchObject({ action: 'remove', decision: { source: 'instructions_off' } });+ expect(read(file)).toBe('house rules\n');++ await installHarnessConnection(credentials, { harness, configPath, instructions: true, skillLoading: 'spring', gbrainBin: LAUNCHER });+ expect(read(file)).toContain(SKILLS_BLOCK_BEGIN);+ const removed = await installHarnessConnection(credentials, { harness, configPath, remove: true });+ expect((removed as any).skills.action).toBe('remove');+ expect(read(file)).toBe('house rules\n');+ });+ });+ }++ test('thin client: GBRAIN-INSTRUCTIONS.md carries the index after brain-first with the root launcher; the choice is kept', async () => {+ const b = box();+ const root = join(b.root, 'thin');+ await withEnv(b.env, async () => {+ const off = await installHarnessConnection(credentials, { harness: 'openclaw', root });+ expect((off as any).skill_loading).toBe('off');+ expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).not.toContain(SKILLS_BLOCK_BEGIN);+ const on = await installHarnessConnection(credentials, { harness: 'openclaw', root, skillLoading: 'spring' });+ expect((on as any).skill_loading).toBe('spring');+ const text = read(join(root, 'GBRAIN-INSTRUCTIONS.md'));+ expect(lines(text).indexOf(SKILLS_BLOCK_BEGIN)).toBe(lines(text).indexOf(BRAIN_FIRST_END) + 1);+ expect(text).toContain('\`' + join(root, 'bin', 'gbrain') + ' bundled-skill <name>\`');+ expect(indexed(text)).toEqual(bundledSkills('downstream').map(s => s.name));+ await installHarnessConnection(credentials, { harness: 'openclaw', root });+ expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).toBe(text);+ await installHarnessConnection(credentials, { harness: 'openclaw', root, instructions: false });+ expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).not.toContain(SKILLS_BLOCK_BEGIN);+ });+ });+});++describe('bootstrap harness', () => {+ test('spring writes a host index (every bundled skill) beside each confirmed host; removal strips only this lane\'s (deleting a file only the index was in)', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const paths = { claudeMemoryPath: join(b.home, '.claude', 'CLAUDE.md'), codexAgentsPath: join(b.home, '.codex', 'AGENTS.md'),+ codexAgentsOverride: join(b.home, '.codex', 'AGENTS.override.md'), opencodeAgentsPath: join(b.home, '.config', 'opencode', 'AGENTS.md') };+ const log: string[] = [];+ const off = writeHarnessSkillsIndex({ hosts: ['claude-code'], launcher: LAUNCHER, optOut: false, paths, log: (l) => log.push(l) });+ expect(off[0].action).toBe('skip');+ expect(log).toEqual([]);+ const on = writeHarnessSkillsIndex({ hosts: ['claude-code', 'codex'], launcher: LAUNCHER, optOut: false, skillLoading: 'spring', paths, log: (l) => log.push(l) });+ expect(on.map(o => o.action)).toEqual(['write', 'write']);+ expect(indexed(read(paths.claudeMemoryPath))).toEqual(bundledSkills('owner').map(s => s.name));+ expect(read(paths.codexAgentsPath)).toContain('\`' + LAUNCHER + ' bundled-skill <name>\`');++ const other = join(b.home, 'other', 'AGENTS.md');+ installerSkillsBlock({ target: brainFirstTargetAt('opencode', other), launcher: LAUNCHER, writer: 'gbrain setup opencode', brainFirstDeclined: false, skillLoading: 'spring' });+ removeHarnessSkillsIndex(() => {});+ expect(existsSync(paths.claudeMemoryPath)).toBe(false);+ expect(read(other)).toContain(SKILLS_BLOCK_BEGIN);+ expect(readSkillLoadingLedger().map(e => e.writer)).toEqual(['gbrain setup opencode']);+ });+ });+});++describe('installer decision', () => {+ test('flag, then GBRAIN_SKILL_LOADING, then the recorded choice; a declined brain-first block forces off', async () => {+ const b = box();+ const target = brainFirstTargetAt('opencode', join(b.home, 'agents', 'AGENTS.md'));+ const base = { target, launcher: LAUNCHER, writer: 'test' };+ await withEnv({ ...b.env, GBRAIN_SKILL_LOADING: 'spring' }, async () => {+ expect(installerSkillsBlock({ ...base, brainFirstDeclined: false }).decision).toEqual({ value: 'spring', source: 'env' });+ expect(installerSkillsBlock({ ...base, brainFirstDeclined: false, skillLoading: 'off' }).decision).toEqual({ value: 'off', source: 'flag' });+ expect(installerSkillsBlock({ ...base, brainFirstDeclined: true, skillLoading: 'spring' }).decision).toEqual({ value: 'off', source: 'instructions_off' });+ });+ await withEnv(b.env, async () => {+ installerSkillsBlock({ ...base, brainFirstDeclined: false, skillLoading: 'spring' });+ expect(installerSkillsBlock({ ...base, brainFirstDeclined: false }).decision).toEqual({ value: 'spring', source: 'prior' });+ });+ });+});++describe('doctor: skills index', () => {+ const check = { name: 'harness_wiring', status: 'ok' as const, message: 'Claude Code is wired.' };+ test('a stale or missing index is named with its refresh command and never changes the status', () => {+ const out = withSkillsIndex(check, [+ { harness: 'claude-code', path: '/home/alice-example/.claude/CLAUDE.md', state: 'stale', refresh: 'gbrain setup claude-code --skills-index-only' },+ { harness: 'codex', path: '/home/alice-example/.codex/AGENTS.md', state: 'current', refresh: 'gbrain setup codex --skills-index-only' },+ ]);+ expect(out.status).toBe('ok');+ expect(out.message).toContain('claude-code skills index');+ expect(out.message).toContain('`gbrain setup claude-code --skills-index-only`');+ expect(out.message).not.toContain('codex skills index');+ expect((out.details as any).skills_index).toHaveLength(2);+ const warn = withSkillsIndex({ ...check, status: 'warn' as any }, [{ harness: 'cursor', path: '/p/.cursor/rules/x.mdc', state: 'absent', refresh: 'gbrain setup cursor --instructions-only' }]);+ expect(warn.status).toBe('warn');+ });+ test('no index on: the check is returned unchanged; all current: only details are added', () => {+ expect(withSkillsIndex(check, [])).toBe(check);+ const cur = withSkillsIndex(check, [{ harness: 'codex', path: '/x', state: 'current', refresh: 'r' }]);+ expect(cur.message).toBe(check.message);+ });+});++describe('refusals keep everything as it was', () => {+ test('an invalid GBRAIN_SKILL_LOADING is refused with the allowed values, before any write', async () => {+ const b = box();+ const target = brainFirstTargetAt('opencode', join(b.home, 'agents', 'AGENTS.md'));+ await withEnv({ ...b.env, GBRAIN_SKILL_LOADING: 'lazy' }, async () => {+ const o = installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false });+ expect(o).toMatchObject({ action: 'preserve', reason: 'invalid_env' });+ expect(o.detail).toContain('off or spring');+ expect(existsSync(target.path)).toBe(false);+ });+ });++ test('an unreadable ledger is never treated as no record', async () => {+ const b = box();+ const file = join(b.home, 'agents', 'AGENTS.md');+ const target = brainFirstTargetAt('opencode', file);+ await withEnv(b.env, async () => {+ installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });+ const written = read(file);+ writeFileSync(join(b.home, '.gbrain', 'skill-loading.json'), '{not json');+ const off = installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'off' });+ expect(off).toMatchObject({ action: 'preserve', reason: 'ledger_unreadable' });+ expect(read(file)).toBe(written);+ expect(read(join(b.home, '.gbrain', 'skill-loading.json'))).toBe('{not json');+ });+ });++ test('Claude Code: a permission rule gbrain added but cannot remove fails the opt-out and keeps the record', async () => {+ const b = box();+ const file = join(b.home, '.claude', 'CLAUDE.md');+ const settings = join(b.home, '.claude', 'settings.json');+ const target = brainFirstTargetAt('claude-code', file);+ await withEnv(b.env, async () => {+ const on = installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });+ expect(on.permission).toMatchObject({ change: 'added', rule: loaderAllowRule(LAUNCHER) });+ writeFileSync(settings, '{broken');+ const off = installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'off' });+ expect(off).toMatchObject({ action: 'preserve', reason: 'permission_update_failed' });+ expect(off.detail).toContain(loaderAllowRule(LAUNCHER));+ expect(read(file)).toContain(SKILLS_BLOCK_BEGIN);+ expect(readSkillLoadingLedger()[0]).toMatchObject({ mode: 'spring', allow_owned: true });+ });+ });+});diff --git a/test/spring-skill-index.test.ts b/test/spring-skill-index.test.tsindex 2bd28e9a13..7eab9b46a0 100644--- a/test/spring-skill-index.test.ts+++ b/test/spring-skill-index.test.ts@@ -68,8 +68,11 @@ describe('spring-loaded skill index', () => {expect(entries(a).some(l => /["`]/.test(l))).toBe(false);});- test('the embedded bundled-skills module is fresh', () => {- expect(readFileSync(join(import.meta.dir, '../src/core/skills/bundled-skills.generated.ts'), 'utf8')).toBe(renderBundledSkillsModule());+ test('the embedded bundled-skills module is fresh and imports no .json as text (a compiled binary hands it back parsed)', () => {+ const mod = readFileSync(join(import.meta.dir, '../src/core/skills/bundled-skills.generated.ts'), 'utf8');+ expect(mod).toBe(renderBundledSkillsModule());+ expect(mod).not.toMatch(/\.json' with \{ type: 'text' \}/);+ for (const [path, text] of Object.entries(BUNDLED_SKILL_FILES)) expect(typeof text, path).toBe('string');});test('each skill carries every file under skills/ that its files link to, transitively (a linked bundled skill loads by name)', () => {