Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(skills): spring-loaded skill resolver: embedded bundled skills, get_skill bundled:true, skills index block, setup --skill-loading
garrytan4f52139b6f3f
diff --git a/scripts/generate-bundled-skills.ts b/scripts/generate-bundled-skills.tsnew file mode 100644index 0000000000..e9111e7149--- /dev/null+++ b/scripts/generate-bundled-skills.ts@@ -0,0 +1,97 @@+#!/usr/bin/env bun+/**+ * Generate src/core/skills/bundled-skills.generated.ts: gbrain's bundled+ * skills (the plugin lane, skills/plugin-lanes.json) embedded as text imports,+ * so the spring-loaded skill index and `get_skill bundled:true` work from a+ * compiled binary with no skills/ directory beside it.+ *+ * bun run scripts/generate-bundled-skills.ts write+ * bun run scripts/generate-bundled-skills.ts --check exit 1 when stale+ *+ * Per skill: name, description, triggers (from SKILL.md frontmatter), the+ * audience (`owner`: the plugin lane, for agents on the brain host;+ * `downstream`: also in openclaw.plugin.json#skills, whose curation keeps+ * host-only workflows out), and its assets: files in its own folder plus the+ * shared deps its body names.+ */+import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';+import { basename, join, resolve } from 'node:path';+import { loadBundleManifest, pathSlug } from '../src/core/skillpack/bundle.ts';+import { computeLaneSet } from '../src/core/skillpack/personas.ts';+import { parseSkillFrontmatter } from '../src/core/skill-frontmatter.ts';+import { oneLineDescription } from '../src/core/skill-catalog.ts';++const ROOT = resolve(import.meta.dir, '..');+const OUT = join(ROOT, 'src/core/skills/bundled-skills.generated.ts');+const SKILLS = join(ROOT, 'skills');+const SKIP_OWN = new Set(['SKILL.md', 'routing-eval.jsonl']);++function walk(absDir: string, rel: string, out: string[]): void {+ for (const e of readdirSync(absDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {+ if (e.name.startsWith('.')) continue;+ if (e.isDirectory()) walk(join(absDir, e.name), `${rel}/${e.name}`, out);+ else if (e.isFile()) out.push(`${rel}/${e.name}`);+ }+}++export function renderBundledSkillsModule(): string {+ const manifest = loadBundleManifest(ROOT);+ const owner = [...computeLaneSet(ROOT)].sort();+ const lanes = JSON.parse(readFileSync(join(SKILLS, 'plugin-lanes.json'), 'utf8')) as { base_exclusions?: Record<string, string> };+ const downstream = new Set(manifest.skills.map(pathSlug).filter(s => !(s in (lanes.base_exclusions ?? {}))));+ const shared: string[] = [];+ for (const dep of manifest.shared_deps) {+ const abs = join(ROOT, dep);+ if (!existsSync(abs)) continue;+ const rel = dep.replace(/^skills\//, '');+ if (statSync(abs).isDirectory()) walk(abs, rel, shared); else shared.push(rel);+ }+ const files = new Set<string>();+ const skills = owner.filter(name => existsSync(join(SKILLS, name, 'SKILL.md'))).map(name => {+ const text = readFileSync(join(SKILLS, name, 'SKILL.md'), 'utf8');+ const fm = parseSkillFrontmatter(text);+ const own: string[] = [];+ walk(join(SKILLS, name), name, own);+ const assets = [...own.filter(p => !SKIP_OWN.has(basename(p))), ...shared.filter(p => text.includes(p))].sort();+ files.add(`${name}/SKILL.md`);+ for (const a of assets) files.add(a);+ return {+ name,+ description: oneLineDescription(fm?.raw ?? '', text.replace(/^---\n[\s\S]*?\n---\n?/, '')).replace(/\s+/g, ' ').trim(),+ triggers: (fm?.triggers ?? []).map(t => String(t).trim()).filter(Boolean),+ audience: downstream.has(name) ? 'downstream' : 'owner',+ assets,+ };+ });+ const sorted = [...files].sort();+ const lines = [+ '// GENERATED by scripts/generate-bundled-skills.ts from skills/ — do not edit. Regenerate: bun run regen:all',+ '/* eslint-disable */',+ ...sorted.map((f, i) => `import f${i} from '../../../skills/${f}' with { type: 'text' };`),+ '',+ 'export interface BundledSkillMeta { name: string; description: string; triggers: string[]; audience: \'owner\' | \'downstream\'; assets: string[] }',+ '',+ `export const BUNDLED_SKILLS: readonly BundledSkillMeta[] = ${JSON.stringify(skills, null, 2)};`,+ '',+ 'export const BUNDLED_SKILL_FILES: Readonly<Record<string, string>> = {',+ // A .json file imported as text is still typed as its parsed JSON; at runtime it is the text.+ ...sorted.map((f, i) => ` ${JSON.stringify(f)}: ${f.endsWith('.json') ? `f${i} as unknown as string` : `f${i}`},`),+ '};',+ '',+ ];+ return lines.join('\n');+}++if (import.meta.main) {+ const next = renderBundledSkillsModule();+ const current = existsSync(OUT) ? readFileSync(OUT, 'utf8') : '';+ if (process.argv.includes('--check')) {+ if (current !== next) {+ console.error('src/core/skills/bundled-skills.generated.ts is stale: run bun run regen:all');+ process.exit(1);+ }+ } else if (current !== next) {+ writeFileSync(OUT, next);+ console.log('wrote src/core/skills/bundled-skills.generated.ts');+ }+}diff --git a/scripts/regen-all.ts b/scripts/regen-all.tsindex a19a19d621..c5e31e4d8a 100644--- a/scripts/regen-all.ts+++ b/scripts/regen-all.ts@@ -45,6 +45,7 @@ export const ARTIFACTS: Artifact[] = [{ name: 'operation manifest', regen: ['bun', 'run', 'scripts/build-operation-manifest.ts'], check: [...BUN_TEST, 'test/operation-manifest.test.ts'] },{ name: 'MCP tool catalog', regen: ['bun', 'run', 'scripts/generate-tool-catalog.ts'], check: ['bash', 'scripts/check-tool-catalog-fresh.sh'] },{ name: 'skills manifest', regen: ['bun', 'run', 'scripts/generate-skills-manifest.ts'], check: ['bash', 'scripts/check-skills-manifest-fresh.sh'] },+ { name: 'bundled skills module', regen: ['bun', 'run', 'scripts/generate-bundled-skills.ts'], check: ['bun', 'run', 'scripts/generate-bundled-skills.ts', '--check'] },{ name: 'eval metric glossary', regen: ['bun', 'run', 'scripts/generate-metric-glossary.ts'], check: ['bash', 'scripts/check-eval-glossary-fresh.sh'] },{ name: 'CLI flag registry', regen: ['bun', 'run', 'scripts/generate-flag-registry.ts'], check: [...BUN_TEST, 'test/generate-flag-registry.test.ts'] },{ name: 'plugin tree + persona variants', regen: ['bun', 'run', 'scripts/generate-plugin-tree.ts', '--out', 'plugin', '--variants-out', 'plugin-variants'], check: ['bash', 'scripts/check-plugin-tree.sh'] },diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex ae1ee7fb47..b6555072f4 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -73,6 +73,17 @@ import {type CodexSetupStep,} from '../core/setup/codex.ts';import type { CodexSetupEvent } from '../core/bootstrap/codex-hooks.ts';+import {+ describeSkillsBlockOutcome,+ isSkillLoading,+ priorSkillLoading,+ readSkillLoadingLedger,+ removeSkillsBlock,+ resolveSkillLoading,+ syncSkillsBlock,+ type SkillLoading,+ type SkillsBlockOutcome,+} from '../core/setup/skills-block.ts';import {brainFirstTarget,describeBrainFirstOutcome,@@ -129,6 +140,12 @@ Flags:Works for a hosted connection too, and for any harness below.--workspace DIR OpenClaw: the agent workspace whose AGENTS.md gets the block(default: agents.defaults.workspace, then ~/.openclaw/workspace).+ --skill-loading M off (default) or spring. spring adds a compact index of+ gbrain's bundled skills beside the brain-first block (about+ 1.4k tokens) and loads a skill's full text only when a task+ matches (get_skill bundled: true, or gbrain skill <name>+ --bundled). off removes an index an earlier run wrote. The+ choice is remembered; GBRAIN_SKILL_LOADING sets it too.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@@ -180,9 +197,10 @@ interface SetupFlags {instructions?: boolean;instructionsOnly: boolean;workspace?: string;+ skillLoading?: SkillLoading;}-const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace']);+const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading']);function parseFlags(args: string[]): SetupFlags | string {const value = (flag: string): string | undefined => {@@ -203,6 +221,8 @@ function parseFlags(args: string[]): SetupFlags | string {if (args.includes('--instructions') && args.includes('--no-instructions')) return 'pass --instructions or --no-instructions, not both';const workspace = value('--workspace');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`;return {harness: positionals[0],dryRun: args.includes('--dry-run'),@@ -219,6 +239,7 @@ function parseFlags(args: string[]): SetupFlags | string {instructions: args.includes('--instructions') ? true : args.includes('--no-instructions') ? false : undefined,instructionsOnly: args.includes('--instructions-only'),workspace,+ skillLoading: skillLoading as SkillLoading | undefined,};}@@ -433,7 +454,8 @@ export async function runSetup(args: string[]): Promise<number> {...Object.entries(found.edited).map(([event]) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),];const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir });- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions });+ const skills = skillsFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir }, instructions);+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills });}let notices: Notice[] = [];@@ -443,7 +465,8 @@ export async function runSetup(args: string[]): Promise<number> {});for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir });- if (!result.changed && !instructionsChanged(instructions)) say(out, 'Nothing changed: this install is already wired.');+ const skills = skillsFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface }, { scope, projectDir }, instructions);+ if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills)) say(out, 'Nothing changed: this install is already wired.');let verify: { ok: boolean; reason: string; message: string } | null;if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Claude Code session and check /mcp lists gbrain.` };@@ -454,7 +477,7 @@ export async function runSetup(args: string[]): Promise<number> {}const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions });+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills });return verify.ok || pluginOwner ? code : 1;} catch (e) {if (e instanceof OperationError) return refuse(e, out);@@ -576,7 +599,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon...Object.keys(found.edited).map((event) => ({ step: 'hooks' as const, action: 'preserve' as const, detail: `${event} was edited after setup wrote it; kept` })),];const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {});- return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions });+ const skills = skillsFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {}, instructions);+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills });}let notices: Notice[] = [];@@ -587,7 +611,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConfor (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);for (const n of result.notes) say(out, `note: ${n}`);const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {});- if (!result.changed && !instructionsChanged(instructions)) say(out, 'Nothing changed: this install is already wired.');+ const skills = skillsFor('codex', flags, { kind: 'mcp', server: flags.name, surface }, {}, instructions);+ if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills)) say(out, 'Nothing changed: this install is already wired.');let verify: { ok: boolean; reason: string; message: string };if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Codex session and check /mcp lists gbrain.` };@@ -599,7 +624,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConconst push = capabilityRows('codex')[0]!.push;const states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,- steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions });+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills });return verify.ok || pluginOwner ? code : 1;} catch (e) {if (e instanceof OperationError) return refuse(e, out);@@ -622,8 +647,9 @@ async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | nufor (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);for (const n of r.notes) say(out, `note: ${n}`);const instructions = removeBrainFirstFor('codex', {}, flags);+ const skills = removeSkillsFor('codex', {}, flags);say(out, 'The brain, its notes and unrelated Codex settings were left as they were.');- return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions });+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions, skills });}function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {@@ -651,8 +677,9 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,const r = await removeClaudeSetup(receipt, receiptPath, { dryRun: flags.dryRun });for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);const instructions = removeBrainFirstFor('claude-code', { scope: receipt.scope, projectDir: receipt.project_dir }, flags);+ const skills = removeSkillsFor('claude-code', { scope: receipt.scope, projectDir: receipt.project_dir }, flags);say(out, 'The brain, its notes and unrelated Claude Code settings were left as they were.');- return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved, instructions });+ return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved, instructions, skills });}/** The brain-first block for this run: decided from flags, env and the ledger, then applied (or previewed under --dry-run). */@@ -670,7 +697,26 @@ function removeBrainFirstFor(harness: BrainFirstHarness, where: { scope?: Wiringreturn path ? removeBrainFirst({ harness, path, dryRun: flags.dryRun }) : null;}-const instructionsChanged = (o: BrainFirstOutcome | null): boolean => !!o && (o.action === 'write' || o.action === 'remove');+/**+ * The skills index for this run (--skill-loading, GBRAIN_SKILL_LOADING, the ledger; off by default).+ * It sits beside the brain-first block, so declining that block (--no-instructions) removes the index too.+ */+function skillsFor(harness: BrainFirstHarness, flags: SetupFlags, access: BrainFirstAccess, 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, access, decision, writer: `gbrain setup ${harness}`, 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;+ return path ? removeSkillsBlock({ harness, path, dryRun: flags.dryRun }) : null;+}++const instructionsChanged = (o: BrainFirstOutcome | SkillsBlockOutcome | null): boolean => !!o && (o.action === 'write' || o.action === 'remove');function describeInstructions(o: BrainFirstOutcome, dryRun: boolean): string {const how = o.decision.value === 'accepted' ? 'opt out with --no-instructions' : 'opt back in with --instructions';@@ -712,18 +758,23 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>return refuse(opError('invalid_params', target.error, 'Pass --workspace <absolute dir> for the agent whose AGENTS.md should carry the block.'), out);}let instructions: BrainFirstOutcome | null;- if (flags.remove) instructions = removeBrainFirstFor(harness, where, flags);- else {+ let skills: SkillsBlockOutcome | null;+ if (flags.remove) {+ instructions = removeBrainFirstFor(harness, where, flags);+ skills = removeSkillsFor(harness, where, flags);+ } else {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, access, where, instructions);}- const code = instructions?.action === 'preserve' ? 1 : 0;+ const code = instructions?.action === 'preserve' || skillsFailed(skills) ? 1 : 0;if (out.json) {- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, skills, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));return code;}if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));+ if (skills && (skills.decision.value === 'spring' || skills.action !== 'skip')) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');return code;@@ -733,20 +784,23 @@ 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[];instructions?: BrainFirstOutcome | null;+ skills?: SkillsBlockOutcome | null;}): Promise<number> {const harness = doc.harness ?? 'claude-code';const state = doc.states.at(-1) ?? null;+ const code = skillsFailed(doc.skills ?? null) ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({harness, dry_run: doc.dryRun, remove: doc.remove ?? false,...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),- steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, states: doc.states, state, verify: doc.verify,+ steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, skills: doc.skills ?? null, states: doc.states, state, verify: doc.verify,capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),}, null, 2)}\n`, (t) => process.stdout.write(t));- return 0;+ return code;}if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));+ if (doc.skills && (doc.skills.decision.value === 'spring' || doc.skills.action !== 'skip')) say(out, describeSkillsBlockOutcome(doc.skills, doc.dryRun));if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);if (state && !doc.remove) say(out, harness === 'codex'@@ -756,5 +810,8 @@ async function finish(out: Out, doc: {+ 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');writeCliNotices(doc.notices.filter((n) => n.code !== 'hosted_option'));if (doc.notices.some((n) => n.code === 'hosted_option')) writeHostedOption('setup', new Set());- return 0;+ return code;}++/** 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.source === 'flag';diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 391c39cbe3..5b03409638 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -121,7 +121,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', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--bundled', '--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'],'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/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 2ee7cf1e52..36bfbc7f75 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -2710,6 +2710,18 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["source_id": {"type": "string","description": "Brain-resident pack skill from this source."+ },+ "bundled": {+ "type": "boolean",+ "description": "true: read a skill gbrain itself ships (its skill index names them), not this brain's catalog."+ },+ "intent": {+ "type": "string",+ "description": "With bundled: a task in your words; returns up to 5 matching bundled skill names to fetch."+ },+ "asset": {+ "type": "string",+ "description": "With bundled and name: one file the skill lists in assets, e.g. conventions/brain-first.md."}},"scope": "read",diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.tsindex bdd81a17b7..43ce1b46f3 100644--- a/src/core/ops/skills-catalog.ts+++ b/src/core/ops/skills-catalog.ts@@ -95,27 +95,49 @@ const get_skill: Operation = {type: 'string',description: 'Brain-resident pack skill from this source.',},+ bundled: {+ type: 'boolean',+ description: 'true: read a skill gbrain itself ships (its skill index names them), not this brain\'s catalog.',+ },+ intent: {+ type: 'string',+ description: 'With bundled: a task in your words; returns up to 5 matching bundled skill names to fetch.',+ },+ asset: {+ type: 'string',+ description: 'With bundled and name: one file the skill lists in assets, e.g. conventions/brain-first.md.',+ },},handler: async (ctx, p) => {- if (p.schema_version === 2) return (await import('../shared-skills/catalog.ts')).getSharedSkill(ctx, sharedSkillReadSelector(p));+ // A miss on a name gbrain ships as a bundled skill says how to load that one; it never substitutes it.+ const pointBundled = async (err: unknown) => (await import('../skills/bundled-op.ts')).pointAtBundled(ctx, p, err);+ if (p.schema_version === 2) return (await import('../shared-skills/catalog.ts')).getSharedSkill(ctx, sharedSkillReadSelector(p)).catch(pointBundled);if (p.expected_brain_id !== undefined) throw opError('invalid_params', 'expected_brain_id requires schema_version 2; it asserts identity and never selects a brain connection.', 'Pass schema_version: 2 with expected_brain_id, or drop expected_brain_id.');if (p.schema_version !== undefined && p.schema_version !== 1) throw invalidParam(ctx, 'get_skill', 'schema_version', 'Supported skill catalog schema versions are 1 and 2.', { choices: ['1', '2'], example: 2 });+ if (p.bundled !== undefined || p.intent !== undefined || p.asset !== undefined) {+ return (await import('../skills/bundled-op.ts')).bundledSkillRequest(ctx, p);+ }+ const sourceId = typeof p.source_id === 'string' && p.source_id.length > 0 ? p.source_id : undefined;const compatibility = await import('../shared-skills/compatibility.ts');- if (await compatibility.sharedCatalogActive(ctx)) return compatibility.getLegacySharedSkill(ctx, p.name, typeof p.source_id === 'string' ? p.source_id : undefined);+ if (await compatibility.sharedCatalogActive(ctx)) return compatibility.getLegacySharedSkill(ctx, p.name, sourceId).catch(pointBundled);const sc = await import('../skill-catalog.ts');const publish = await sc.readMcpPublishSkills(ctx);sc.assertPublishEnabled(ctx, publish);// Brain-resident path: when source_id is supplied, fetch the per-source pack// skill (confined to that source's pack root) rather than the host catalog.- if (typeof p.source_id === 'string' && p.source_id.length > 0) {+ if (sourceId) {const brl = await import('../skillpack/brain-resident-locate.ts');const slug = typeof p.name === 'string' ? p.name : '';- return brl.getResidentSkillDetail(ctx, p.source_id, slug);+ return brl.getResidentSkillDetail(ctx, sourceId, slug);}- const override = await sc.readMcpSkillsDir(ctx);- const { dir } = sc.resolveSkillsDir(ctx, override);const name = typeof p.name === 'string' ? p.name : '';- return sc.getSkillDetail(ctx, dir, name, { gateDisabled: await sc.readSkillToolGates(ctx) });+ try {+ const override = await sc.readMcpSkillsDir(ctx);+ const { dir } = sc.resolveSkillsDir(ctx, override);+ return sc.getSkillDetail(ctx, dir, name, { gateDisabled: await sc.readSkillToolGates(ctx) });+ } catch (err) {+ return pointBundled(err);+ }},scope: 'read',cliHints: { name: 'skill', positional: ['name'] },diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.tsnew file mode 100644index 0000000000..a142957fb0--- /dev/null+++ b/src/core/setup/skills-block.ts@@ -0,0 +1,235 @@+/**+ * setup/skills-block.ts — the managed `gbrain:skills` block: the always-loaded+ * half of the spring-loaded skill resolver, written beside the brain-first+ * block (brain-first.ts) in the same harness instruction file.+ *+ * Selectable: `--skill-loading spring` (or GBRAIN_SKILL_LOADING=spring) writes+ * it; `off`, the default, writes nothing and strips a block an earlier run+ * wrote. `--no-instructions` strips it with the brain-first block. The block+ * is a compact index of gbrain's bundled skills plus one sentence on loading a+ * skill on demand (spring-index.ts); the skill bodies stay out of the context+ * until a task matches.+ *+ * Ownership is by markers (managed-block.ts): the interior is gbrain's, text+ * outside the markers is never touched. Decisions live in their own ledger,+ * <configDir>/skill-loading.json, keyed on (harness, path), so brain-first's+ * ledger stays as it is. created_file is true when gbrain created the file,+ * through either block, so whichever block is removed last deletes a file+ * nothing else was written into.+ */+import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+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 { bundledSkills, type SkillAudience } from '../skills/bundled.ts';+import { renderSkillIndexBlock, SKILL_INDEX_VERSION, type SkillIndexAccess } from '../skills/spring-index.ts';+import { BRAIN_FIRST_END, CURSOR_HEAD, direntExists, readBrainFirstLedger, writeUnlessChanged, type BrainFirstAccess, 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 LEDGER_FILE = 'skill-loading.json';++export function isSkillLoading(v: unknown): v is SkillLoading {+ return (SKILL_LOADING_MODES as readonly unknown[]).includes(v);+}++/** The access the block names. A verbs-only MCP surface has no get_skill, so it gets the CLI form. */+export function skillIndexAccess(access: BrainFirstAccess): SkillIndexAccess {+ if (access.kind === 'cli') return access;+ return access.surface === 'verbs' ? { kind: 'cli', launcher: 'gbrain' } : { kind: 'mcp', server: access.server };+}++/** The block interior for a harness. Local installs run on the brain host and index every bundled skill. */+export function renderSkillsBlock(harness: string, access: BrainFirstAccess, audience: SkillAudience = 'owner'): string {+ return renderSkillIndexBlock(bundledSkills(audience), skillIndexAccess(access), `gbrain setup ${harness} --instructions-only --skill-loading off`);+}++// ── Ledger ────────────────────────────────────────────────────────────────++export interface SkillLoadingLedgerEntry {+ harness: string;+ path: string;+ mode: SkillLoading;+ block_version: number;+ access: BrainFirstAccess;+ writer: string;+ created_file: boolean;+ updated_at: string;+}++export function skillLoadingLedgerPath(): string { return join(configDir(), LEDGER_FILE); }++export function readSkillLoadingLedger(): SkillLoadingLedgerEntry[] {+ const path = skillLoadingLedgerPath();+ if (!existsSync(path)) return [];+ 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 [];+ }+}++function writeLedger(entries: SkillLoadingLedgerEntry[]): void {+ atomicWriteTextFile(skillLoadingLedgerPath(), `${JSON.stringify({ version: 1, entries }, null, 2)}\n`, { freshMode: 0o600 });+}++function upsertLedger(entry: SkillLoadingLedgerEntry): void {+ writeLedger([...readSkillLoadingLedger().filter((e) => !(e.harness === entry.harness && e.path === entry.path)), entry]);+}++function dropLedger(harness: string, path: string): void {+ const all = readSkillLoadingLedger();+ const rest = all.filter((e) => !(e.harness === harness && e.path === path));+ if (rest.length !== all.length) writeLedger(rest);+}++export function priorSkillLoading(harness: string, path: string): SkillLoadingLedgerEntry | undefined {+ return readSkillLoadingLedger().find((e) => e.harness === harness && e.path === path);+}++// ── 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. */+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 (prior) return { value: prior.mode, source: 'prior' };+ return { value: 'off', source: 'default' };+}++export type SkillsBlockState = 'no_file' | 'absent' | 'current' | 'stale' | 'damaged';++export function inspectSkillsBlock(path: string, expected?: string): { state: SkillsBlockState; version?: number } {+ if (!existsSync(path)) return { state: 'no_file' };+ const probe = probeBlock(MARKERS, readFileSync(path, 'utf8'));+ if (probe.state !== 'present') return { state: probe.state };+ const version = Number(/gbrain skills v(\d+)/.exec(probe.interior ?? '')?.[1] ?? 0);+ const current = expected !== undefined ? probe.interior === expected : version === SKILL_INDEX_VERSION;+ return { state: current ? 'current' : 'stale', version };+}++export interface SkillsBlockOutcome {+ harness: string;+ path: string;+ decision: SkillLoadingDecision;+ action: 'write' | 'keep' | 'remove' | 'skip' | 'preserve';+ state_before: SkillsBlockState;+ detail: string;+}++function ownedEmptyFile(createdFile: boolean, path: string, stripped: string): boolean {+ return createdFile && !lstatSync(path).isSymbolicLink() && (stripped.trim() === '' || stripped === CURSOR_HEAD);+}++/** Splice the block in place; a new block goes right after the brain-first block when there is one, else at the end. */+export function placeSkillsBlock(existing: string, body: string): string {+ if (probeBlock(MARKERS, existing).state === 'present') return spliceBlock(MARKERS, existing, body);+ const lines = existing.split('\n');+ const at = lines.findIndex((l) => l.replace(/\r$/, '') === BRAIN_FIRST_END);+ if (at < 0) return spliceBlock(MARKERS, existing, body);+ const block = spliceBlock(MARKERS, '', body).replace(/\n$/, '').split('\n');+ return [...lines.slice(0, at + 1), ...block, ...lines.slice(at + 1)].join('\n');+}++/**+ * 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.+ */+export function syncSkillsBlock(opts: { target: BrainFirstTarget; access: BrainFirstAccess; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience }): SkillsBlockOutcome {+ const { target, access, decision } = opts;+ const body = renderSkillsBlock(target.harness, access, opts.audience);+ 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) => {+ 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, access, 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`);+ }+ 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 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}`);+ }+ 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`);+ }+ 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`);+ }+ const created = before.state === 'no_file' && !direntExists(target.path);+ if (!opts.dryRun) {+ 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 */ }+ }+ }+ 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}`);+ } catch (e) {+ return out('preserve', `${target.path} could not be updated (${e instanceof Error ? e.message : String(e)}); nothing else was changed`);+ }+}++/** 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 });+ 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) {+ const existing = readFileSync(opts.path, 'utf8');+ const stripped = removeBlock(MARKERS, existing).text;+ const 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)' : ''}`);+ }+ 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)})`);+ }+}++/** One human line per outcome, matching setup's step lines. */+export function describeSkillsBlockOutcome(o: SkillsBlockOutcome, dryRun: boolean): string {+ const how = o.decision.value === 'spring' ? 'turn off with --skill-loading off' : 'turn on with --skill-loading spring';+ return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'skills'.padEnd(7)} ${o.detail} [${o.decision.source}; ${how}]`;+}diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.tsindex 27c4381a28..1c2bc5ecdb 100644--- a/src/core/skill-catalog.ts+++ b/src/core/skill-catalog.ts@@ -624,6 +624,16 @@ export function getSkillDetail(`Skill ${name} is over ${MAX_SKILL_MD_BYTES} bytes, so it is not served. The brain host's operator can raise GBRAIN_MAX_SKILL_MD_BYTES if it is legitimately large.`);}+ return skillDetailFromText(ctx, name, content, opts);+}++/** The get_skill result for one SKILL.md text (host catalog or gbrain's bundled skills). */+export function skillDetailFromText(+ ctx: OperationContext,+ name: string,+ content: string,+ opts: { gateDisabled?: ReadonlySet<string> } = {},+): GetSkillResult {const parsed = parseSkillFrontmatter(content);const raw = parsed?.raw ?? '';const body = stripFrontmatterFence(content);diff --git a/src/core/skills/bundled-op.ts b/src/core/skills/bundled-op.tsnew file mode 100644index 0000000000..bc9b14ec9d--- /dev/null+++ b/src/core/skills/bundled-op.ts@@ -0,0 +1,93 @@+/**+ * skills/bundled-op.ts — the `get_skill` path for gbrain's own bundled skills+ * (`bundled: true`, `intent`, `asset`): the on-demand half of the+ * spring-loaded skill resolver. The always-loaded half is the index the+ * install lanes write (spring-index.ts).+ *+ * Explicit by design: a plain `get_skill {name}` keeps reading this brain's+ * own catalog, so a bundled skill never silently stands in for a published,+ * withheld or withdrawn one of the same name.+ *+ * Checks: read scope (the op's), name-shape validation and embedded-map+ * lookups (no filesystem path is ever built from input). Audience: the local+ * CLI and stdio connections run on the brain host and see every bundled+ * skill. HTTP callers see the downstream set only, and only when the owner+ * publishes skills (`mcp.publish_skills`, the gate get_skill already applies+ * to remote callers): serving gbrain's bundled text over HTTP is the one+ * change to the skill catalog's trust memo (skill-catalog.ts, item 5).+ */+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { invalidParam } from '../ops/op-fix.ts';+import { VERSION } from '../../version.ts';+import { bundledSkillAsset, bundledSkills, bundledSkillText, findBundledSkill, type SkillAudience } from './bundled.ts';++const MAX_INTENT_CHARS = 500;+const INTENT_LIMIT = 5;++export function bundledAudience(ctx: OperationContext): SkillAudience {+ return ctx.remote === false || ctx.transport === 'stdio' ? 'owner' : 'downstream';+}++export async function bundledSkillRequest(ctx: OperationContext, p: Record<string, unknown>): Promise<unknown> {+ if (p.bundled !== undefined && p.bundled !== true) {+ throw invalidParam(ctx, 'get_skill', 'bundled', 'intent and asset read gbrain\'s bundled skills; pass bundled: true, or drop them to read this brain\'s catalog.', { example: true });+ }+ if (p.source_id !== undefined || p.revision !== undefined || p.qualified_id !== undefined) {+ throw opError('invalid_params', 'bundled skills ship with gbrain and have no source or revision.', 'Drop source_id, revision and qualified_id, or drop bundled to read this brain\'s catalog.');+ }+ const sc = await import('../skill-catalog.ts');+ const audience = bundledAudience(ctx);+ if (audience === 'downstream') sc.assertPublishEnabled(ctx, await sc.readMcpPublishSkills(ctx));++ if (p.intent !== undefined) {+ if (typeof p.intent !== 'string' || p.intent.trim() === '' || p.intent.length > MAX_INTENT_CHARS) {+ throw invalidParam(ctx, 'get_skill', 'intent', `intent is the task in your own words, 1-${MAX_INTENT_CHARS} characters.`, { example: 'turn this meeting transcript into brain pages' });+ }+ const intent = p.intent;+ const candidates = bundledSkills(audience)+ .map(s => ({ s, match: sc.scoreSkillMatch(s, intent) }))+ .filter((x): x is { s: typeof x.s; match: NonNullable<typeof x.match> } => x.match !== null)+ .sort((a, b) => b.match.score - a.match.score || a.s.name.localeCompare(b.s.name))+ .slice(0, INTENT_LIMIT)+ .map(({ s, match }) => ({ name: s.name, description: s.description.length > 240 ? `${s.description.slice(0, 239)}…` : s.description, match }));+ return { schema_version: 1, bundled: true, gbrain_version: VERSION, intent, candidates,+ next: candidates.length ? 'Fetch the best fit with get_skill {bundled: true, name}. Word overlap ranks these; skip any that does not fit the task.' : 'No bundled skill matches; continue without one.' };+ }++ const name = p.name;+ if (typeof name !== 'string' || name === '' || name.length > 128 || /[/\\\0]|\.\./.test(name)) {+ throw invalidParam(ctx, 'get_skill', 'name', 'name is a bundled skill name from the gbrain skill index, with no slashes or "..".', { example: 'meeting-ingestion' });+ }+ const skill = findBundledSkill(name, audience);+ if (!skill) {+ throw opError('skill_not_found', `gbrain has no bundled skill named ${name} for this connection.`,+ audience === 'owner' ? 'Pick a name from the gbrain skill index, or call get_skill {bundled: true, intent} to find one.'+ : 'Pick a name from the gbrain skill index, or call get_skill {bundled: true, intent} to find one; skills for maintaining the brain host are offered only on the host.');+ }+ if (p.asset !== undefined) {+ const content = typeof p.asset === 'string' ? bundledSkillAsset(skill, p.asset) : undefined;+ if (content === undefined) {+ throw opError('skill_not_found', `${name} lists no asset ${typeof p.asset === 'string' ? p.asset : ''}.`,+ `Fetch the skill first and pass one of its assets exactly: ${skill.assets.join(', ') || 'it has none'}.`);+ }+ return { schema_version: 1, bundled: true, gbrain_version: VERSION, name, asset: p.asset, content };+ }+ const detail = sc.skillDetailFromText(ctx, name, bundledSkillText(skill), { gateDisabled: await sc.readSkillToolGates(ctx) });+ return { ...detail, bundled: true, gbrain_version: VERSION, assets: skill.assets };+}++/**+ * Rethrow a catalog miss (`skill_not_found`, `page_not_found`, or no host+ * skills dir) on a name gbrain ships as a bundled skill this caller may read,+ * with a fix that names the bundled call. The original error is kept for+ * every other case, and nothing is ever served in its place.+ */+export async function pointAtBundled(ctx: OperationContext, p: Record<string, unknown>, err: unknown): Promise<never> {+ const code = (err as { code?: string })?.code;+ const name = typeof p.name === 'string' ? p.name : undefined;+ if (!name || p.source_id !== undefined || !['skill_not_found', 'page_not_found', 'storage_error'].includes(code ?? '') || !findBundledSkill(name, bundledAudience(ctx))) throw err;+ const message = err instanceof Error ? err.message : String(err);+ throw opError(code === 'storage_error' ? 'skill_not_found' : code as 'skill_not_found', `${message} gbrain also ships a bundled skill named ${name}.`,+ `To read gbrain's bundled ${name}, call get_skill {bundled: true, name: "${name}"} (CLI: gbrain skill ${name} --bundled).`);+}diff --git a/src/core/skills/bundled-skills.generated.ts b/src/core/skills/bundled-skills.generated.tsnew file mode 100644index 0000000000..8f4537410b--- /dev/null+++ b/src/core/skills/bundled-skills.generated.ts@@ -0,0 +1,1562 @@+// GENERATED by scripts/generate-bundled-skills.ts from skills/ — do not edit. Regenerate: bun run regen:all+/* eslint-disable */+import f0 from '../../../skills/_brain-filing-rules.json' with { type: 'text' };+import f1 from '../../../skills/_brain-filing-rules.md' with { type: 'text' };+import f2 from '../../../skills/_output-rules.md' with { type: 'text' };+import f3 from '../../../skills/academic-verify/SKILL.md' with { type: 'text' };+import f4 from '../../../skills/archive-crawler/SKILL.md' with { type: 'text' };+import f5 from '../../../skills/article-enrichment/SKILL.md' with { type: 'text' };+import f6 from '../../../skills/ask-user/SKILL.md' with { type: 'text' };+import f7 from '../../../skills/blog-ingest/SKILL.md' with { type: 'text' };+import f8 from '../../../skills/book-mirror/SKILL.md' with { type: 'text' };+import f9 from '../../../skills/brain-ingest-gate/SKILL.md' with { type: 'text' };+import f10 from '../../../skills/brain-link-discipline/SKILL.md' with { type: 'text' };+import f11 from '../../../skills/brain-ops/SKILL.md' with { type: 'text' };+import f12 from '../../../skills/brain-pdf/SKILL.md' with { type: 'text' };+import f13 from '../../../skills/brain-taxonomist/SKILL.md' with { type: 'text' };+import f14 from '../../../skills/briefing/SKILL.md' with { type: 'text' };+import f15 from '../../../skills/bulk-ingestion/MANIFEST-PATTERN.md' with { type: 'text' };+import f16 from '../../../skills/bulk-ingestion/SKILL.md' with { type: 'text' };+import f17 from '../../../skills/capture/SKILL.md' with { type: 'text' };+import f18 from '../../../skills/chat-connectors/SKILL.md' with { type: 'text' };+import f19 from '../../../skills/citation-fixer/SKILL.md' with { type: 'text' };+import f20 from '../../../skills/citation-graph-ingest/SKILL.md' with { type: 'text' };+import f21 from '../../../skills/cold-start/SKILL.md' with { type: 'text' };+import f22 from '../../../skills/company-brainify/SKILL.md' with { type: 'text' };+import f23 from '../../../skills/concept-synthesis/SKILL.md' with { type: 'text' };+import f24 from '../../../skills/context-audit/SKILL.md' with { type: 'text' };+import f25 from '../../../skills/conventions/agent-operator-protocol.md' with { type: 'text' };+import f26 from '../../../skills/conventions/brain-first.md' with { type: 'text' };+import f27 from '../../../skills/conventions/brain-routing.md' with { type: 'text' };+import f28 from '../../../skills/conventions/cron-via-minions.md' with { type: 'text' };+import f29 from '../../../skills/conventions/cross-modal.yaml' with { type: 'text' };+import f30 from '../../../skills/conventions/exec-output.md' with { type: 'text' };+import f31 from '../../../skills/conventions/model-routing.md' with { type: 'text' };+import f32 from '../../../skills/conventions/quality.md' with { type: 'text' };+import f33 from '../../../skills/conventions/regex-discipline.md' with { type: 'text' };+import f34 from '../../../skills/conventions/schema-evolution.md' with { type: 'text' };+import f35 from '../../../skills/conventions/subagent-routing.md' with { type: 'text' };+import f36 from '../../../skills/conventions/test-before-bulk.md' with { type: 'text' };+import f37 from '../../../skills/conventions/untrusted-content.md' with { type: 'text' };+import f38 from '../../../skills/conversation-archive/SKILL.md' with { type: 'text' };+import f39 from '../../../skills/correction-pipeline/SKILL.md' with { type: 'text' };+import f40 from '../../../skills/cron-scheduler/SKILL.md' with { type: 'text' };+import f41 from '../../../skills/cross-modal-review/SKILL.md' with { type: 'text' };+import f42 from '../../../skills/daily-task-manager/SKILL.md' with { type: 'text' };+import f43 from '../../../skills/daily-task-prep/SKILL.md' with { type: 'text' };+import f44 from '../../../skills/data-loss-gate/SKILL.md' with { type: 'text' };+import f45 from '../../../skills/data-research/SKILL.md' with { type: 'text' };+import f46 from '../../../skills/db-repair/SKILL.md' with { type: 'text' };+import f47 from '../../../skills/draft-in-voice/SKILL.md' with { type: 'text' };+import f48 from '../../../skills/eiirp/SKILL.md' with { type: 'text' };+import f49 from '../../../skills/enrich/SKILL.md' with { type: 'text' };+import f50 from '../../../skills/fact-check/SKILL.md' with { type: 'text' };+import f51 from '../../../skills/frontmatter-guard/SKILL.md' with { type: 'text' };+import f52 from '../../../skills/functional-area-resolver/SKILL.md' with { type: 'text' };+import f53 from '../../../skills/gbrain-advisor/SKILL.md' with { type: 'text' };+import f54 from '../../../skills/gbrain-upgrade/SKILL.md' with { type: 'text' };+import f55 from '../../../skills/google-loops/SKILL.md' with { type: 'text' };+import f56 from '../../../skills/idea-ingest/SKILL.md' with { type: 'text' };+import f57 from '../../../skills/idea-lineage/SKILL.md' with { type: 'text' };+import f58 from '../../../skills/ingest/SKILL.md' with { type: 'text' };+import f59 from '../../../skills/maintain/SKILL.md' with { type: 'text' };+import f60 from '../../../skills/mcp-access/SKILL.md' with { type: 'text' };+import f61 from '../../../skills/measure-before-you-fix/SKILL.md' with { type: 'text' };+import f62 from '../../../skills/media-ingest/SKILL.md' with { type: 'text' };+import f63 from '../../../skills/meeting-ingestion/SKILL.md' with { type: 'text' };+import f64 from '../../../skills/migrate/SKILL.md' with { type: 'text' };+import f65 from '../../../skills/minion-orchestrator/SKILL.md' with { type: 'text' };+import f66 from '../../../skills/perplexity-research/SKILL.md' with { type: 'text' };+import f67 from '../../../skills/postgres-adopt/SKILL.md' with { type: 'text' };+import f68 from '../../../skills/publish/SKILL.md' with { type: 'text' };+import f69 from '../../../skills/query/SKILL.md' with { type: 'text' };+import f70 from '../../../skills/remote-mcp/SKILL.md' with { type: 'text' };+import f71 from '../../../skills/repo-architecture/SKILL.md' with { type: 'text' };+import f72 from '../../../skills/reports/SKILL.md' with { type: 'text' };+import f73 from '../../../skills/research-compendium/SKILL.md' with { type: 'text' };+import f74 from '../../../skills/resolve-before-asking/SKILL.md' with { type: 'text' };+import f75 from '../../../skills/schema-author/SKILL.md' with { type: 'text' };+import f76 from '../../../skills/schema-unify/SKILL.md' with { type: 'text' };+import f77 from '../../../skills/setup/SKILL.md' with { type: 'text' };+import f78 from '../../../skills/signal-detector/SKILL.md' with { type: 'text' };+import f79 from '../../../skills/skill-creator/SKILL.md' with { type: 'text' };+import f80 from '../../../skills/skill-optimizer/SKILL.md' with { type: 'text' };+import f81 from '../../../skills/skill-optimizer/skillopt-benchmark.jsonl' with { type: 'text' };+import f82 from '../../../skills/skillpack-check/SKILL.md' with { type: 'text' };+import f83 from '../../../skills/smoke-test/SKILL.md' with { type: 'text' };+import f84 from '../../../skills/soul-audit/SKILL.md' with { type: 'text' };+import f85 from '../../../skills/strategic-reading/SKILL.md' with { type: 'text' };+import f86 from '../../../skills/two-tier-extraction/SKILL.md' with { type: 'text' };+import f87 from '../../../skills/voice-note-ingest/SKILL.md' with { type: 'text' };+import f88 from '../../../skills/webhook-transforms/SKILL.md' with { type: 'text' };++export interface BundledSkillMeta { name: string; description: string; triggers: string[]; audience: 'owner' | 'downstream'; assets: string[] }++export const BUNDLED_SKILLS: readonly BundledSkillMeta[] = [+ {+ "name": "academic-verify",+ "description": "Verify a research claim or academic citation by tracing it through publication → methodology → raw data → independent replication. Routes through perplexity-research for the actual web lookup, then formats results as a citation-checked brain page. Use when a book/article/conversation cites a study and you want to confirm the claim is real, replicated, and accurately characterized.",+ "triggers": [+ "verify this academic claim",+ "check this study",+ "academic verify",+ "validate citation",+ "is this study real",+ "Retraction Watch"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "archive-crawler",+ "description": "Universal archivist for personal file archives (Dropbox/B2/Gmail-takeout/local-mount/hard-drive-dump). Filters for high-value content (the user's own writing, ideas, relationships) and surfaces it interactively. REFUSES TO RUN without an explicit gbrain.yml `archive-crawler.scan_paths:` allow-list.",+ "triggers": [+ "crawl my archive",+ "find gold in my archive",+ "archive crawler",+ "scan my dropbox for",+ "mine my old files for"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.json",+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "article-enrichment",+ "description": "Transform raw article text dumps in the brain into structured pages with executive summary, verbatim quotes, key insights, why-it-matters, and cross-references. Replaces walls-of-text with quotable, actionable brain pages.",+ "triggers": [+ "enrich this article",+ "enrich the article",+ "enriching the article",+ "enrich brain pages",+ "batch enrich",+ "enrich pass",+ "make brain pages useful"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "ask-user",+ "description": "Reusable pattern for presenting the user with explicit choices and gating execution until they respond. Used by other skills when a decision point requires human input before proceeding. Platform-agnostic — works on Telegram (inline buttons), Discord, CLI, or any agent with a message tool.",+ "triggers": [+ "present options",+ "ask before proceeding",+ "choice gate",+ "user decision"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "blog-ingest",+ "description": "Feed and whole-publication ingestion: turn an entire blog, newsletter, or RSS/Atom archive into brain source pages. Covers feed discovery, pagination walking, normalization to a common article shape, canonical-URL dedup, idempotent re-runs, 429 pacing, and empty-husk repair. This is the PUBLICATION-scope skill — a single article URL routes to idea-ingest instead. Per-article enrichment hands off to the brain-ingest-gate skill; public posts only (gated content is skipped, never worked around).",+ "triggers": [+ "ingest this publication",+ "ingest this whole blog",+ "ingest this feed",+ "ingest this newsletter archive",+ "save this whole substack",+ "backfill this blog",+ "walk this RSS feed",+ "ingest every post from"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/regex-discipline.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "book-mirror",+ "description": "Take any book (EPUB/PDF), produce a personalized chapter-by-chapter analysis. Each chapter is preserved in detail (The Chapter) and mirrored back to the reader's actual life (The Mirror) using brain context. The mirror observes and resonates — a friend pointing out parallels, NOT a consultant rearranging the reader's life, NOT a therapist assigning homework. The reader decides what to do about it. Layout is a top-aligned HTML table or stacked sections, never a bare markdown pipe table (pipe tables center-misalign uneven columns). Output is a single brain page at media/books/<slug>-personalized.md plus an optional PDF via brain-pdf.",+ "triggers": [+ "personalized version of this book",+ "mirror this book",+ "two-column book analysis",+ "apply this book to my life",+ "how does this book apply to me"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/cross-modal.yaml",+ "conventions/quality.md"+ ]+ },+ {+ "name": "brain-ingest-gate",+ "description": "Pre-write quality gate for content entering the brain. No raw copies: a bare cp/mv into the brain repo is a bug. Before any new page lands, resolve named entities registry-first (a vector score is a floor for prose, never a gate for named things), then run the read-the-top-hit dedup decision tree (clear-dup / plausible-dup / clear). Owns dedup; delegates enrichment to the shipped ingestion skills. Routing convention, not an operation-boundary enforcement.",+ "triggers": [+ "move this to brain",+ "migrate to brain",+ "copy these files into the brain",+ "is this already in the brain",+ "check for duplicates before writing",+ "dedup before saving",+ "raw copy to brain"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "brain-link-discipline",+ "description": "When you report a brain page to the user — created, edited, committed, or relayed from a subagent — a working link is part of the deliverable, in the SAME message. Derive the path mechanically (git ls-files --full-name), push BEFORE linking, verify the link resolves when a hosted remote exists, and degrade through a defined fallback chain when it doesn't. Inside brain pages the rule inverts: relative links preserve the link graph; absolute URLs are for chat deliverables only.",+ "triggers": [+ "give me the link",+ "where is the page",+ "why does this link 404",+ "brain link discipline",+ "rewrite subagent paths",+ "report the pages you created",+ "send me a clickable link",+ "link the page in the same message"+ ],+ "audience": "downstream",+ "assets": [+ "_output-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/subagent-routing.md"+ ]+ },+ {+ "name": "brain-ops",+ "description": "Brain knowledge base operations. The core read/write cycle: brain-first lookup, read-enrich-write loop, source attribution, ambient enrichment, back-linking. Read this before any brain interaction.",+ "triggers": [+ "any brain read/write/lookup/citation"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "brain-pdf",+ "description": "Generate a publication-quality PDF from any brain page via the gstack make-pdf binary. Strips YAML frontmatter, sanitizes emoji, applies running headers and page numbers. Brain page is always the source of truth; PDF is a rendering.",+ "triggers": [+ "make pdf from brain",+ "brain pdf",+ "convert brain page to pdf",+ "publish this page as pdf",+ "export brain page"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "brain-taxonomist",+ "description": "Filing gate for ALL brain writes. Consulted before creating any new brain page to determine the correct path. Reads the ACTIVE schema pack via `gbrain schema show --json` — no hardcoded directory table. Also runs periodic taxonomy drift detection via `gbrain schema review-orphans`.",+ "triggers": [+ "where does this brain page go",+ "file this in the brain",+ "brain taxonomist",+ "taxonomy check",+ "refile brain page",+ "create brain page",+ "which directory does this go",+ "which directory does this page go"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "briefing",+ "description": "Compile daily briefing with meeting context, active deals, and citation tracking",+ "triggers": [+ "daily briefing",+ "morning briefing",+ "what's happening today",+ "brain pulse",+ "pre-briefing pull"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "bulk-ingestion",+ "description": "End-to-end discipline for turning any large data source (audio libraries, email takeouts, document corpora, chat exports, API dumps) into brain pages at scale. The lifecycle spine: SCHEMA → ACCESS → TRIAL → EVALUATE → IMPROVE → CODIFY → TEST → SKILLIFY → BULK → MONITOR. State is tracked in a durable JSON manifest (see MANIFEST-PATTERN.md) so any crash, session boundary, or subagent fan-out resumes from ground truth instead of memory.",+ "triggers": [+ "bulk ingest",+ "bulk import",+ "ingest all",+ "ingestion pipeline",+ "mass ingestion",+ "bulk backfill",+ "make a manifest",+ "processing manifest",+ "track a large ingest"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "bulk-ingestion/MANIFEST-PATTERN.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/cron-via-minions.md",+ "conventions/quality.md",+ "conventions/subagent-routing.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "capture",+ "description": "Save any thought or content into the brain via one CLI command. The single human-facing entrypoint that replaces \"put_page vs commit-then-sync vs autopilot-wait\" with one command that just works.",+ "triggers": [+ "capture this",+ "save this thought",+ "remember this",+ "ingest this into my brain",+ "drop this in the inbox",+ "save to brain"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "chat-connectors",+ "description": "Connect a ChatGPT or Claude account and sync its conversation history into the brain automatically. Cookie paste-in is the primary lane; sync is incremental (watermark + trailing-window gap-heal), and can run on a schedule via autopilot or host cron. Distinct from the export-file lane (that lives in conversation-archive) — this is the LIVE, account-connected, auto-scraping path.",+ "triggers": [+ "connect my chatgpt",+ "connect my claude account",+ "sync my chat history",+ "chatgpt oauth",+ "auto-import my chats",+ "keep my conversations synced"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "citation-fixer",+ "description": "Audit and fix citation formatting across brain pages. Ensures every fact has an inline [Source: ...] citation matching the standard format. Extended in v0.25.1: scans for broken tweet/post references that lack actual URLs and resolves them via the host's X / Twitter API integration.",+ "triggers": [+ "fix citations",+ "fix broken citations",+ "citation audit",+ "check citations",+ "citation fixer"+ ],+ "audience": "downstream",+ "assets": [+ "_output-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "citation-graph-ingest",+ "description": "Build a TYPED citation/reference graph over an ingested corpus — not just embeddings. Flat similarity retrieval cannot tell you that document A *overrules* B, *distinguishes* C, or *relies_on* D. This skill extracts every inter-document reference, classifies the edge TYPE with LLM judgment, and writes first-class typed edges via `gbrain link`, so `gbrain graph-query --type` can walk the argument (\"everything this brief relies on, minus anything overruled since\"). Every cite-heavy corpus is the same shape: law, academic papers, patents, regulatory filings, a book's bibliography.",+ "triggers": [+ "citation graph",+ "citation graph ingest",+ "typed citation graph",+ "build a reference graph",+ "graph over a corpus",+ "overrules / distinguishes graph",+ "reason over a domain corpus",+ "trace the argument through these documents"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/regex-discipline.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "cold-start",+ "description": "Day-one data bootstrapping for a new brain. Sequences the highest-leverage data sources to go from empty brain to useful brain in one session. Uses ClawVisor for safe credential handling — the agent never holds raw API keys. Covers Gmail import, calendar sync, contacts seeding, X/Twitter archive, conversation imports, and file archives. Use when a user has just finished gbrain setup and asks \"now what?\"",+ "triggers": [+ "cold start",+ "fill my brain",+ "bootstrap brain",+ "bootstrap my data",+ "import my data",+ "day one",+ "get started",+ "what should I import first",+ "populate brain",+ "now what?"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "company-brainify",+ "description": "Extract a sanitized shared team/company brain from a personal brain. Strips internal ratings, compensation, performance assessments, retention and political dynamics from pages, takes, and facts across the full scan scope (people, companies, meetings, dailies, cross-references — not just people/), verifies with grep + retrieval passes, and purges sensitive git history behind the data-loss-gate confirmation card. Also runs as a report-only re-audit on an existing shared brain.",+ "triggers": [+ "company brain",+ "team brain",+ "brainify",+ "sanitize the brain",+ "share my brain with the team",+ "strip sensitive data from the brain",+ "scrub employee data",+ "audit the shared brain",+ "make the brain safe to share"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/cron-via-minions.md",+ "conventions/regex-discipline.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "concept-synthesis",+ "description": "Deduplicate and synthesize raw concept stubs into a tiered intellectual map (T1 Canon to T4 Riff), tracing idea evolution across sources over time. Transforms thousands of raw concept pages into a curated intellectual fingerprint. Includes a reversible curation cull pass (Phase 5) with hard keep/delete/merge verdicts, substance gates, grounding labels, cluster budgets, and merge-with-backlinks salience promotion.",+ "triggers": [+ "concept synthesis",+ "synthesize my concepts",+ "find patterns across my notes",+ "build my intellectual map",+ "trace idea evolution",+ "canon vs riff",+ "cull my concepts",+ "which concepts to keep",+ "concept quality rubric"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "context-audit",+ "description": "Token-hygiene audit of the always-loaded context stack — CLAUDE.md, AGENTS.md, auto-memory MEMORY.md, and the bootstrap-rendered identity files (SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md) or their harness equivalents. Finds redundancy, contradictions, stale content, compression candidates, and skill-extraction candidates; produces a ranked action list sorted by token savings with a risk class per finding. REPORT-ONLY: this skill never edits any audited file. Recommendations for bootstrap-rendered files target the interview answer bank / templates, never the rendered output. Judging routes through `gbrain eval cross-modal` (single cheap model by default; full multi-model panel is explicit opt-in).",+ "triggers": [+ "context audit",+ "context diet",+ "system prompt audit",+ "prompt compression",+ "reduce context size",+ "audit my context stack",+ "context is too big",+ "token hygiene"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "conversation-archive",+ "description": "Import AI-assistant chat exports (ChatGPT, Claude, Perplexity) and agent session transcripts into the brain as one dated page per conversation under conversations/, validate each page against the native conversation parser, extract facts via the native conversation-facts flow, and keep the archive gap-free with a detect-and-backfill loop. Then answer archive questions: \"when did I first discuss X\", trace how an idea evolved across past conversations, pull a specific thread.",+ "triggers": [+ "chatgpt export",+ "claude export",+ "perplexity export",+ "conversation history",+ "import my conversations",+ "search my conversations",+ "when did I first discuss",+ "archive my session transcripts",+ "backfill missing conversations"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "correction-pipeline",+ "description": "When the user corrects a factual error, root-cause it immediately. Don't just note the correction — trace the error to its source, fix the source, and prevent recurrence. Every factual error is either a data error (bad brain page, bad memory file, bad rendered SOUL/USER identity, bad facts row) or a hallucination (LLM confabulated from partial signals).",+ "triggers": [+ "that's wrong",+ "that's not true",+ "I never said that",+ "where did you get that",+ "you got that wrong",+ "correct that fact",+ "root-cause this error"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md"+ ]+ },+ {+ "name": "cron-scheduler",+ "description": "Schedule management with staggering, quiet hours, and wake-up override. Validates schedules, prevents collisions, and gates delivery during quiet hours.",+ "triggers": [+ "schedule a job",+ "cron",+ "quiet hours",+ "what jobs are running"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/cron-via-minions.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "cross-modal-review",+ "description": "Quality gate via second model. Spawn a different AI model to review work before committing. Includes refusal routing: if one model refuses, switch silently to the next. Extended in v0.25.1 with structured review-mode gating (when to invoke vs not) and a Codex code-review handoff for the diff-review case.",+ "triggers": [+ "second opinion",+ "cross-modal review",+ "double check this",+ "get another perspective",+ "challenge this code",+ "adversarial review"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/cross-modal.yaml",+ "conventions/model-routing.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "daily-task-manager",+ "description": "Task lifecycle management with stable task IDs. Add, complete, defer, remove, and review tasks with deterministic action routing and fail-closed ambiguity handling. Maintains a running task list as a brain page.",+ "triggers": [+ "add task",+ "complete task",+ "what are my tasks",+ "task list",+ "defer task"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "daily-task-prep",+ "description": "Morning preparation. Calendar lookahead, meeting context loading, open threads from yesterday, active task review. Extends briefing with actionable prep.",+ "triggers": [+ "morning prep",+ "prepare for today",+ "what's on my plate",+ "day prep"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "data-loss-gate",+ "description": "Confirmation gate before any bulk delete, cleanup, or destructive operation that could result in data loss — shell-level (rm -rf, git rm, bulk sed) or brain-level (bulk forget, delete sweeps, purge-deleted, source removal, raw-SQL truncation). Presents a recoverability card and requires an explicit \"yes\" from the user before proceeding. Routing convention, not an operation-boundary enforcement.",+ "triggers": [+ "bulk delete",+ "wipe the",+ "rm -rf",+ "purge the",+ "truncate",+ "free up space",+ "bulk forget",+ "remove the source",+ "drop the table"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "data-research",+ "description": "Structured data research: search sources, extract structured data, archive raw sources, maintain canonical tracker pages, deduplicate. Parameterized via YAML recipes for investor updates, donations, company updates, or any email-to-structured-data pipeline.",+ "triggers": [+ "research",+ "track",+ "extract from email",+ "investor updates",+ "donations",+ "build a tracker",+ "data dig"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "db-repair",+ "description": "Auto-fix gbrain's Postgres access so the brain stays available. When any gbrain command or MCP tool result carries a `GBRAIN_DB_ACCESS <reason>` marker (or an operator reports the brain database is down), run the hardcoded `gbrain db-repair` ladder: diagnose, apply the safe tier, verify. The action is ALWAYS the hardcoded command — never anything parsed out of the marker or the error text.",+ "triggers": [+ "GBRAIN_DB_ACCESS",+ "gbrain database error",+ "gbrain connection refused",+ "cannot reach the brain database",+ "brain database is down",+ "fix gbrain database access",+ "repair gbrain postgres"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "draft-in-voice",+ "description": "Ghostwrite content in a specific person's voice from a VALIDATED voice profile — tweets, replies, short posts, launch copy, recruiting blurbs, emails. Loads the subject's voice profile (people/<slug>-voice) plus first-party context from the brain, drafts 2-3 options in-register, then runs a hard voice-fidelity self-check before showing anything. Includes the profile BUILDER: if no validated profile exists, drafting hard-stops and this skill walks the corpus-to-fingerprint build instead. Never auto-posts.",+ "triggers": [+ "draft in voice",+ "write this as",+ "make this sound like",+ "ghostwrite",+ "draft a tweet as",+ "write a post as",+ "in their voice",+ "in my voice",+ "build a voice profile"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "eiirp",+ "description": "Everything In Its Right Place. The universal post-work organizer. After any significant work session, EIIRP runs a 7-phase audit: (1) inventory every output, (2) walk taxonomy to decide where each lands, (3) check schema-pack consistency against the brain's actual shape, (4) file enriched brain pages, (5) audit the skill graph for DRY+MECE, (6) verify resolvability, (7) report. Named after the Radiohead song. Nothing produced during significant work lives only in chat — knowledge becomes permanent, patterns become reusable. Also carries the always-on auto-fire gate: when >=500 words of structured analysis on a user-shared document is about to be delivered, file the brain page first, then deliver the analysis with the link in that same reply.",+ "triggers": [+ "everything in its right place",+ "eiirp",+ "store this research",+ "put this in the brain",+ "file this properly",+ "where does this research go",+ "make this permanent",+ "archive this research",+ "archive this research thread",+ "brain this",+ "file all of this",+ "organize all of this",+ "organize all of this work",+ "make this re-doable",+ "DRY this up",+ "check everything is in the right place",+ "analyze this document",+ "deep analysis",+ "review this report"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md"+ ]+ },+ {+ "name": "enrich",+ "description": "Enrich brain pages with tiered enrichment protocol. Creates and updates person/company pages with compiled truth, timeline, and cross-links. Use when a new entity is mentioned or an existing page needs updating.",+ "triggers": [+ "enrich",+ "create person page",+ "update company page",+ "who is this person",+ "look up this company"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "fact-check",+ "description": "Systematic claim-by-claim verification for any content before it ships. Modeled on professional fact-checking desks (The New Yorker, ProPublica, IFCN standards): extract every verifiable claim, check each against live citable sources (never training data), assign a 6-level confidence status, apply corrections, and produce a scored pass/fail report. Includes a data-derived-claims gate for outputs produced FROM the brain or a database: PRODUCER ≠ VERIFIER (re-derive each claim via a different query path) and AFFILIATION ≠ AUTHORSHIP (person→thing claims resolve through typed edges), with delivery hard-blocked on unsupported claims.",+ "triggers": [+ "fact check",+ "fact-check",+ "verify the facts",+ "check the claims",+ "is this accurate",+ "source check",+ "verify this output claim by claim",+ "is this output hallucinating",+ "re-derive every claim"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "frontmatter-guard",+ "description": "Validate and auto-repair YAML frontmatter on brain pages. Catches malformed pages before they enter the brain (missing closing ---, nested quotes, slug mismatches, null bytes, empty frontmatter, YAML parse failures), explains files sync holds instead of importing, and drives the previewed `gbrain repair frontmatter` fix. Wraps the `gbrain frontmatter` CLI for agent-driven workflows.",+ "triggers": [+ "validate frontmatter",+ "check frontmatter",+ "fix frontmatter",+ "frontmatter audit",+ "brain lint",+ "held files",+ "sync held a file"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "functional-area-resolver",+ "description": "Compress an agent's routing file (RESOLVER.md or AGENTS.md) by converting granular skill-per-row tables into functional-area dispatchers. Each area lists sub-skills in a \"(dispatcher for: ...)\" clause. The LLM reads one area entry and routes to the correct sub-skill. Proven via held-out A/B eval: dispatcher pattern outperforms naive pipe-table compression.",+ "triggers": [+ "compress agents.md",+ "compress my resolver",+ "resolver too big",+ "resolver.md too big",+ "agents.md too large",+ "shrink routing table",+ "slim down agents.md",+ "functional area resolver",+ "functional area dispatcher",+ "context-health agents",+ "context-health resolver",+ "reduce context budget"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "gbrain-advisor",+ "description": "Proactive \"make the most of gbrain\" coaching. Runs `gbrain advisor` on a cadence and pings the user with the top high-leverage actions for their brain: version drift, pending migrations, stalled jobs, low embed coverage, setup smells, and uninstalled brain skills. Read-only; always asks before fixing.",+ "triggers": [+ "what should I do to get more out of gbrain",+ "is my brain set up right",+ "gbrain advisor",+ "advise me on my brain",+ "weekly brain checkup"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md"+ ]+ },+ {+ "name": "gbrain-upgrade",+ "description": "Keep gbrain current. When a `gbrain` invocation prints an `UPGRADE_AVAILABLE <old> <new>` marker (or `gbrain self-upgrade --check-only` reports an update), apply it per the configured self_upgrade.mode: notify (prompt the operator with a 4-option question + snooze) or auto (apply silently). The action is always the hardcoded `gbrain self-upgrade` — never a command read from the marker.",+ "triggers": [+ "gbrain update available",+ "UPGRADE_AVAILABLE",+ "upgrade gbrain",+ "update gbrain",+ "gbrain is out of date",+ "gbrain self-upgrade",+ "is gbrain up to date",+ "keep gbrain current"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "google-loops",+ "description": "Set up and operate the Gmail/Calendar/Contacts connector and the open-loop engine: who is waiting on the user, what they promised, and the context needed to respond. Covers painless BYO OAuth setup (exactly two user interactions), the daily `gbrain waiting` digest, loop closing/muting, and troubleshooting via the typed error catalog.",+ "triggers": [+ "connect gmail",+ "connect google",+ "connect calendar",+ "connect contacts",+ "who is waiting on me",+ "what do I owe people",+ "open loops",+ "unanswered email",+ "set up email ingestion",+ "gbrain waiting"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "idea-ingest",+ "description": "Ingest links, articles, tweets, and ideas into the brain. Fetch content, save to brain with analysis, credit the author (people page only when they pass the notability gate), and cross-link. Use when the user shares a link or says \"read this\", \"save this\", \"think about this\".",+ "triggers": [+ "shares a link or URL",+ "read this",+ "save this",+ "think about this",+ "put this in brain"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "idea-lineage",+ "description": "Trace one idea's evolution through the brain: first mention, best articulation, related concepts, reversals, contradictions, abandoned branches, and the current live version. Use for single-idea conceptual lineage, not broad concept-map synthesis or structured entity metrics.",+ "triggers": [+ "idea lineage",+ "trace the lineage of this idea",+ "how my thinking about",+ "how has my thinking about",+ "current version of this idea",+ "what is my current version of",+ "show reversals in my thinking about",+ "where did this idea come from"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "ingest",+ "description": "Route content to specialized ingestion skills. Detects input type and delegates.",+ "triggers": [+ "ingest this",+ "save this to brain",+ "process this meeting"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "maintain",+ "description": "Brain health checks: back-link enforcement, citation audit, filing validation, stale info detection, orphan pages, and benchmarks. Use when asked to check brain health, run maintenance, or audit quality.",+ "triggers": [+ "brain health",+ "check backlinks",+ "maintenance",+ "orphan pages",+ "stale pages",+ "extract links",+ "build link graph",+ "populate timeline",+ "populate links",+ "backfill graph",+ "extract timeline entries",+ "retriage the backlog",+ "re-score the triage",+ "run dream",+ "process today's session",+ "process yesterday's transcripts",+ "synthesize my conversations",+ "what patterns did you see",+ "did the dream cycle run",+ "consolidate yesterday's conversations"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.json",+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "mcp-access",+ "description": "Open the GBrain owner dashboard, manage MCP clients and permissions, or connect a native OAuth harness. Distinguishes owner administration from ordinary MCP access.",+ "triggers": [+ "GBrain admin login link",+ "open the MCP admin panel",+ "manage MCP clients",+ "register an MCP client",+ "set up MCP OAuth",+ "connect this harness to my hosted brain",+ "invalidate MCP tokens",+ "revoke an MCP client",+ "delete an MCP client",+ "edit MCP access levels"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "measure-before-you-fix",+ "description": "Before fixing a slow/stale/timeout alert, measure the step yourself. Kill the theory with a stopwatch, not a code change. Measure-first ops triage for temporal alerts (stale, timeout, freshness, wedged, N hours behind) from gbrain doctor, autopilot, sync, and cron monitors — runs BEFORE any timeout raise, threshold change, or pipeline rewrite.",+ "triggers": [+ "keeps timing out",+ "ETIMEDOUT",+ "why is this data stale",+ "freshness alert",+ "wedged",+ "job is slow",+ "sync is stuck",+ "raise the timeout"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/test-before-bulk.md"+ ]+ },+ {+ "name": "media-ingest",+ "description": "Ingest video, audio, PDF, book, screenshot, and GitHub repo content into the brain. Multi-format handling with entity extraction and backlink propagation. Covers video-ingest, youtube-ingest, and book-ingest subtypes.",+ "triggers": [+ "watch this video",+ "process this YouTube link",+ "ingest this PDF",+ "save this podcast",+ "process this book",+ "PDF book",+ "summarize this book",+ "ingest it into my brain",+ "what's in this screenshot",+ "check out this repo"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "meeting-ingestion",+ "description": "Ingest meeting transcripts from ANY meeting recorder into brain pages with attendee enrichment, entity propagation, and timeline merge. One unified pipeline: normalize the source into a standard transcript record, split multi-meeting recordings, resolve speakers by evidence, create the page, pass every surprising claim through the consistency check (transcript + brain + plausibility), enrich every entity, then run the verification checklist — substance AND sequence. A meeting is NOT fully ingested until the enrich skill has processed every entity AND the verification checklist passes, including the sequence verify (PASS or explicit user waive).",+ "triggers": [+ "meeting transcript",+ "process this meeting",+ "meeting notes",+ "meeting recorder",+ "ingest this recording",+ "capture meetings",+ "audit this meeting",+ "check the sequence",+ "did I get the order right",+ "meeting transcript received"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "migrate",+ "description": "Universal migration from Obsidian, Notion, Logseq, markdown, CSV, JSON, Roam",+ "triggers": [+ "migrate from",+ "import from obsidian",+ "import from notion",+ "connect our company brain",+ "connect our existing company brain",+ "import an existing company brain"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-routing.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "minion-orchestrator",+ "description": "Unified Minions skill for both deterministic shell jobs and LLM subagent orchestration. Replaces the older `gbrain-jobs` routing intent. Use when: submitting gbrain jobs, shell/background tasks, spawning subagents, checking progress, steering running work, pausing/resuming, parallel fan-out. One durable, observable, steerable queue interface. Also carries the durable-execution doctrine for any operation expected to exceed ~2 minutes: capability ladder, deadman checks that verify the result was reported, and content-addressed stage checkpoints for expensive pipelines.",+ "triggers": [+ "gbrain jobs submit",+ "submit a gbrain job",+ "submit a shell job",+ "shell job",+ "run shell command in background",+ "deterministic background task",+ "spawn agent",+ "background task",+ "run in background",+ "check on agent",+ "agent progress",+ "what's running",+ "steer agent",+ "change direction",+ "tell the agent",+ "pause agent",+ "stop agent",+ "resume agent",+ "parallel tasks",+ "fan out",+ "do these in parallel",+ "long operation",+ "durable execution",+ "arm a deadman",+ "the job went silent",+ "operation died in the background",+ "make this pipeline resumable"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/exec-output.md",+ "conventions/subagent-routing.md"+ ]+ },+ {+ "name": "perplexity-research",+ "description": "Brain-augmented web research. Sends brain context about a topic to Perplexity, which searches the web with citations and returns what is NEW vs what the brain already knows. Use for entity enrichment, current-state checks, deal monitoring, and freshness deltas. NOT for simple URL fetches (use web_fetch) or brain-only queries (use gbrain query).",+ "triggers": [+ "perplexity research",+ "perplexity-research",+ "what's new about",+ "current state of",+ "web research",+ "what changed about",+ "surface new developments"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "postgres-adopt",+ "description": "Detect which gbrain engine is in use (PGLite vs Postgres), prefer Postgres for agent-harness installs, install/provision Postgres (Supabase discovery via SUPABASE_ACCESS_TOKEN, local Postgres, opt-in Docker), and move an existing PGLite brain to Postgres with its history (plan, ask, run). Detection is one engine-free command; the install ladder is one flag.",+ "triggers": [+ "which gbrain engine",+ "pglite or postgres",+ "gbrain engine status",+ "upgrade to postgres",+ "switch gbrain to postgres",+ "install postgres for gbrain",+ "move my brain to supabase",+ "set up postgres for the brain"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "publish",+ "description": "Share brain pages as beautiful password-protected HTML with zero LLM calls",+ "triggers": [+ "share this page",+ "publish page",+ "create shareable link"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "query",+ "description": "Answer questions using the brain's knowledge with 3-layer search, synthesis, and citation propagation. Use when the user asks a question, wants a lookup, or needs information from the brain.",+ "triggers": [+ "what do we know about",+ "tell me about",+ "who is",+ "what happened",+ "search for",+ "look up",+ "background on",+ "notes on",+ "who knows who",+ "relationship between",+ "connections",+ "graph query"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md"+ ]+ },+ {+ "name": "remote-mcp",+ "description": "Publish the user's own gbrain over MCP so other devices, desktop apps and cloud agents can reach it. `gbrain mcp expose` installs and signs in Tailscale, publishes the running `gbrain serve --http` on the tailnet (HTTPS, tailnet-only by default; Funnel only when a client lives in a vendor cloud), keeps the server alive as a user service, and hands back the MCP URL. Then register one least-privilege client per consumer, choose native OAuth/PKCE or a private machine handoff for that client, and verify the connection inside the intended harness.",+ "triggers": [+ "use my brain over mcp",+ "serve my brain over mcp",+ "expose my brain over mcp",+ "gbrain mcp server",+ "remote mcp access to my brain",+ "put my brain on tailscale",+ "connect grok bot to my brain",+ "connect muse to my brain",+ "connect claude desktop to my brain",+ "reach my brain from my phone",+ "gbrain mcp expose"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "repo-architecture",+ "description": "Where new brain files go. Decision protocol for filing brain pages by primary subject, not by format or source. Reference for all brain-writing skills.",+ "triggers": [+ "where does this go",+ "filing rules",+ "create new page",+ "which directory"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "reports",+ "description": "Save and load timestamped reports. Keyword routing for fast lookup. Cron jobs save output as reports; the agent or user queries them by keyword. Includes the Actionability Gate: delivery-time link checks (Broken/Dead/Indirect/ Missing) for briefings, meeting digests, and research reports.",+ "triggers": [+ "save report",+ "load latest report",+ "what's the latest briefing",+ "show me the pulse",+ "report quality",+ "link quality check",+ "validate report links"+ ],+ "audience": "downstream",+ "assets": [+ "_output-rules.md",+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "research-compendium",+ "description": "Deep-research a topic end to end and produce a permanent, reusable knowledge asset: archive every primary source verbatim (gated by the user's privacy/retention posture), write one 1:1 summary per source, then synthesize a single self-contained compendium page. Depth is a dial (base synthesis → grounded primaries → books + counter-canon → saturation), each level an idempotent superset of the one below. Distinct from data-research (structured trackers) and perplexity-research (web deltas): this produces prose knowledge synthesis backed by an archived source corpus.",+ "triggers": [+ "compendium",+ "research everything about",+ "read them all and summarize",+ "definitive guide",+ "comprehensive guide to",+ "deep research and write up",+ "archive the sources then summarize",+ "deepen the compendium"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/quality.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "resolve-before-asking",+ "description": "Gate on identity questions to the user. Before any \"who is X?\" (or role / relationship question) reaches the user, exhaust the brain's lookup chain: think → search + page read → mounted sources → timeline/graph → web. If escalation survives the chain, ask WITH a hypothesis, never a bare unknown. Also owns the no-placeholders-at-ingest rule: pages created during bulk ingestion get their relationship/role resolved immediately.",+ "triggers": [+ "resolve before asking",+ "before asking the user",+ "unidentified contact",+ "unknown relationship",+ "should I ask who",+ "don't know who this is",+ "to be filled by content analysis",+ "placeholder on this page"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md"+ ]+ },+ {+ "name": "schema-author",+ "description": "Evolve your brain's schema pack. Add page types, propose new ones from corpus scans, backfill page.type on existing pages, audit pack health. Triggers when an agent notices untyped pages, custom domains needing typed entities (researcher, contract, deposition), or wants to see what types the pack declares.",+ "triggers": [+ "add a page type",+ "add a type to my schema",+ "my brain has untyped pages",+ "schema isn't matching my notes",+ "propose new types from my corpus",+ "backfill page types",+ "evolve my schema",+ "extend the schema pack",+ "create a custom type for",+ "researcher type",+ "make X an expert type",+ "schema pack add",+ "schema mutate",+ "schema sync",+ "schema author"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/schema-evolution.md"+ ]+ },+ {+ "name": "schema-unify",+ "description": "Migrate a brain from gbrain-base (or any pack) to gbrain-base-v2's 14-canonical-type taxonomy via gbrain onboard --check + the unify-types Minion handler. Collapses 94 noisy types to 15 canonical with subtypes, alias rows, and link rows. Triggers when an agent notices pack_upgrade_available, type_proliferation, or asks \"what is the canonical taxonomy / how do I clean up my page types\".",+ "triggers": [+ "unify my types",+ "migrate to gbrain-base-v2",+ "94 types to 14",+ "apply canonical taxonomy",+ "clean up my page types",+ "pack upgrade",+ "shrink type proliferation",+ "what does the canonical taxonomy look like",+ "consolidate page types",+ "retype pages to canonical"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "setup",+ "description": "Add keyless GBrain memory to an existing agent, or connect a hosted brain while preserving identity and configuration",+ "triggers": [+ "set up gbrain",+ "initialize brain",+ "gbrain setup",+ "install gbrain into this agent workspace",+ "add gbrain to my agent"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "signal-detector",+ "description": "Opt-in ambient signal capture. After explicit enablement, applies on substantive inbound messages to detect original thinking and entity mentions. Use an authorized sub-agent where supported; otherwise detect inline. Aim to never block the main response.",+ "triggers": [+ "every substantive inbound message after automatic-capture opt-in"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "skill-creator",+ "description": "Create new skills following the GBrain conformance standard. Generates SKILL.md with frontmatter, Contract, Phases, Output Format, and Anti-Patterns. Checks MECE against existing skills. Updates manifest and resolver.",+ "triggers": [+ "create a skill",+ "new skill",+ "improve this skill"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "skill-optimizer",+ "description": "Self-evolving skill optimization via SkillOpt-paper-grounded text-space optimizer.",+ "triggers": [+ "optimize this skill",+ "tune the skill against the benchmark",+ "make the skill better",+ "run skillopt",+ "skillopt for"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md",+ "skill-optimizer/skillopt-benchmark.jsonl"+ ]+ },+ {+ "name": "skillpack-check",+ "description": "Run `gbrain skillpack-check` to produce an agent-readable JSON health report for the gbrain install. Wraps `gbrain doctor` + `gbrain apply-migrations --list` so a host agent (your OpenClaw's morning-briefing, any OpenClaw cron) can see at a glance whether the skillpack needs attention. Use when the user asks \"is gbrain healthy?\", when a cron fires a morning check, or proactively when something seems off (jobs not running, brain not updating, autopilot silent).",+ "triggers": [+ "skillpack check",+ "is gbrain healthy",+ "gbrain health",+ "check the brain",+ "is the brain working"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "smoke-test",+ "description": "Health smoke tests + auto-fix for gbrain installs (and OpenClaw services when present). Run after machine/container restarts or whenever something seems broken. Tests critical services, auto-fixes bounded local issues, and reports worker topology without starting daemons. Extensible via user-defined test scripts in ~/.gbrain/smoke-tests.d/*.sh.",+ "triggers": [+ "smoke test",+ "run smoke tests",+ "container restart check",+ "health check",+ "did the restart break anything",+ "did the container restart break anything"+ ],+ "audience": "owner",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "soul-audit",+ "description": "Re-run or deepen the agent's identity interview. Drives the SHARED bootstrap answer bank (state/interview.json) via `gbrain bootstrap interview --set/--show/--confirm`, then re-renders the identity files with `gbrain bootstrap render --only <FILE> --force`. One answer store, two surfaces: first-boot bootstrap and this re-run skill write the same bank, so an updated answer flows into SOUL.md, USER.md, ACCESS_POLICY.md, and HEARTBEAT.md without hand-editing rendered files. Every answer is the user's own words — never invented.",+ "triggers": [+ "soul audit",+ "customize agent",+ "who am I",+ "set up identity",+ "change my agent's personality"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ },+ {+ "name": "strategic-reading",+ "description": "Read a book, article, transcript, or case study through the lens of a specific strategic problem you're facing. Produces an applied playbook that maps the source onto the problem and gives short/medium/long-term recommendations. NOT for general book summaries.",+ "triggers": [+ "strategic reading",+ "read this through the lens of",+ "apply this to my problem",+ "what can I learn from this about",+ "extract a playbook from"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "two-tier-extraction",+ "description": "Tiered LLM extraction pattern for large corpus processing (email archives, document dumps, transcript libraries). A utility-tier model triages and classifies at speed; the reasoning tier does the default deep read; the deep tier is the escalation for the highest-value content. Prevents spending deep-tier money on noise while ensuring the important content gets the best eyes. A deterministic privacy wall runs before any LLM call.",+ "triggers": [+ "two-tier extraction",+ "triage then deep read",+ "smart model routing",+ "cheap triage expensive analysis",+ "model escalation pattern",+ "route models by content value",+ "which model tier for bulk extraction"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/brain-first.md",+ "conventions/model-routing.md",+ "conventions/regex-discipline.md",+ "conventions/test-before-bulk.md",+ "conventions/untrusted-content.md"+ ]+ },+ {+ "name": "voice-note-ingest",+ "description": "Ingest a voice note with exact-phrasing preservation (never paraphrased). Routes content to originals/, concepts/, people/, companies/, ideas/, personal/, or voice-notes/ based on a decision tree. The user's exact words are the signal.",+ "triggers": [+ "voice note",+ "ingest this voice memo",+ "transcribe and file",+ "voice note ingest",+ "save this audio note",+ "audio message"+ ],+ "audience": "downstream",+ "assets": [+ "_brain-filing-rules.md",+ "conventions/agent-operator-protocol.md",+ "conventions/quality.md"+ ]+ },+ {+ "name": "webhook-transforms",+ "description": "Generic framework for converting external events (SMS, meetings, social mentions) into brain-ingestible signals. Define a transform function, register a webhook URL, and incoming events get processed through the brain pipeline.",+ "triggers": [+ "set up webhook",+ "process webhook event",+ "transform this event"+ ],+ "audience": "downstream",+ "assets": [+ "conventions/agent-operator-protocol.md"+ ]+ }+];++export const BUNDLED_SKILL_FILES: Readonly<Record<string, string>> = {+ "_brain-filing-rules.json": f0 as unknown as string,+ "_brain-filing-rules.md": f1,+ "_output-rules.md": f2,+ "academic-verify/SKILL.md": f3,+ "archive-crawler/SKILL.md": f4,+ "article-enrichment/SKILL.md": f5,+ "ask-user/SKILL.md": f6,+ "blog-ingest/SKILL.md": f7,+ "book-mirror/SKILL.md": f8,+ "brain-ingest-gate/SKILL.md": f9,+ "brain-link-discipline/SKILL.md": f10,+ "brain-ops/SKILL.md": f11,+ "brain-pdf/SKILL.md": f12,+ "brain-taxonomist/SKILL.md": f13,+ "briefing/SKILL.md": f14,+ "bulk-ingestion/MANIFEST-PATTERN.md": f15,+ "bulk-ingestion/SKILL.md": f16,+ "capture/SKILL.md": f17,+ "chat-connectors/SKILL.md": f18,+ "citation-fixer/SKILL.md": f19,+ "citation-graph-ingest/SKILL.md": f20,+ "cold-start/SKILL.md": f21,+ "company-brainify/SKILL.md": f22,+ "concept-synthesis/SKILL.md": f23,+ "context-audit/SKILL.md": f24,+ "conventions/agent-operator-protocol.md": f25,+ "conventions/brain-first.md": f26,+ "conventions/brain-routing.md": f27,+ "conventions/cron-via-minions.md": f28,+ "conventions/cross-modal.yaml": f29,+ "conventions/exec-output.md": f30,+ "conventions/model-routing.md": f31,+ "conventions/quality.md": f32,+ "conventions/regex-discipline.md": f33,+ "conventions/schema-evolution.md": f34,+ "conventions/subagent-routing.md": f35,+ "conventions/test-before-bulk.md": f36,+ "conventions/untrusted-content.md": f37,+ "conversation-archive/SKILL.md": f38,+ "correction-pipeline/SKILL.md": f39,+ "cron-scheduler/SKILL.md": f40,+ "cross-modal-review/SKILL.md": f41,+ "daily-task-manager/SKILL.md": f42,+ "daily-task-prep/SKILL.md": f43,+ "data-loss-gate/SKILL.md": f44,+ "data-research/SKILL.md": f45,+ "db-repair/SKILL.md": f46,+ "draft-in-voice/SKILL.md": f47,+ "eiirp/SKILL.md": f48,+ "enrich/SKILL.md": f49,+ "fact-check/SKILL.md": f50,+ "frontmatter-guard/SKILL.md": f51,+ "functional-area-resolver/SKILL.md": f52,+ "gbrain-advisor/SKILL.md": f53,+ "gbrain-upgrade/SKILL.md": f54,+ "google-loops/SKILL.md": f55,+ "idea-ingest/SKILL.md": f56,+ "idea-lineage/SKILL.md": f57,+ "ingest/SKILL.md": f58,+ "maintain/SKILL.md": f59,+ "mcp-access/SKILL.md": f60,+ "measure-before-you-fix/SKILL.md": f61,+ "media-ingest/SKILL.md": f62,+ "meeting-ingestion/SKILL.md": f63,+ "migrate/SKILL.md": f64,+ "minion-orchestrator/SKILL.md": f65,+ "perplexity-research/SKILL.md": f66,+ "postgres-adopt/SKILL.md": f67,+ "publish/SKILL.md": f68,+ "query/SKILL.md": f69,+ "remote-mcp/SKILL.md": f70,+ "repo-architecture/SKILL.md": f71,+ "reports/SKILL.md": f72,+ "research-compendium/SKILL.md": f73,+ "resolve-before-asking/SKILL.md": f74,+ "schema-author/SKILL.md": f75,+ "schema-unify/SKILL.md": f76,+ "setup/SKILL.md": f77,+ "signal-detector/SKILL.md": f78,+ "skill-creator/SKILL.md": f79,+ "skill-optimizer/SKILL.md": f80,+ "skill-optimizer/skillopt-benchmark.jsonl": f81,+ "skillpack-check/SKILL.md": f82,+ "smoke-test/SKILL.md": f83,+ "soul-audit/SKILL.md": f84,+ "strategic-reading/SKILL.md": f85,+ "two-tier-extraction/SKILL.md": f86,+ "voice-note-ingest/SKILL.md": f87,+ "webhook-transforms/SKILL.md": f88,+};diff --git a/src/core/skills/bundled.ts b/src/core/skills/bundled.tsnew file mode 100644index 0000000000..a26fc1606f--- /dev/null+++ b/src/core/skills/bundled.ts@@ -0,0 +1,39 @@+/**+ * skills/bundled.ts — gbrain's own bundled skills, embedded at build time+ * (bundled-skills.generated.ts), so they are the same on a source install and+ * a compiled binary and never come from the caller's working directory or a+ * host skills dir.+ *+ * The set is the plugin lane (skills/plugin-lanes.json), the curated set the+ * Claude Code and Codex plugins publish; repo-development skills are never in+ * it. Each skill carries an audience: `downstream` skills are also in+ * openclaw.plugin.json#skills, whose curation keeps host-only workflows+ * (migrate, setup, db-repair, upgrades, …) away from agents that do not run+ * on the brain host; `owner` skills are offered only to callers on the host.+ *+ * Every read is a key lookup in the embedded map: a client-supplied name or+ * asset is a lookup key, never a path.+ */+import { BUNDLED_SKILLS, BUNDLED_SKILL_FILES, type BundledSkillMeta } from './bundled-skills.generated.ts';++export type BundledSkill = BundledSkillMeta;+export type SkillAudience = 'owner' | 'downstream';++/** The bundled skills an audience may see: an owner (on the brain host) sees all of them. */+export function bundledSkills(audience: SkillAudience): readonly BundledSkill[] {+ return audience === 'owner' ? BUNDLED_SKILLS : BUNDLED_SKILLS.filter(s => s.audience === 'downstream');+}++export function findBundledSkill(name: string, audience: SkillAudience): BundledSkill | undefined {+ return bundledSkills(audience).find(s => s.name === name);+}++/** The SKILL.md text of a bundled skill. */+export function bundledSkillText(skill: BundledSkill): string {+ return BUNDLED_SKILL_FILES[`${skill.name}/SKILL.md`] ?? '';+}++/** One file the skill lists in its assets; undefined for anything else. */+export function bundledSkillAsset(skill: BundledSkill, asset: string): string | undefined {+ return skill.assets.includes(asset) ? BUNDLED_SKILL_FILES[asset] : undefined;+}diff --git a/src/core/skills/spring-index.ts b/src/core/skills/spring-index.tsnew file mode 100644index 0000000000..6fbd97186e--- /dev/null+++ b/src/core/skills/spring-index.ts@@ -0,0 +1,71 @@+/**+ * skills/spring-index.ts — the spring-loaded skill resolver's always-loaded+ * half: a compact index of gbrain's bundled skills, one line per skill with+ * its trigger phrases, plus the one sentence that says how to load a skill+ * on demand. The full SKILL.md is fetched only when a task matches+ * (get_skill over MCP, `gbrain skill <name>` on the CLI).+ *+ * Generated from each skill's frontmatter `triggers:` (the canonical routing+ * signal; skills/RESOLVER.md is the human map of the same data), so there is+ * no second list to keep in sync. The rendered block is held under+ * SKILL_INDEX_BUDGET_BYTES: lines keep up to three triggers, and when the+ * whole block would exceed the budget every line drops to two, then one.+ * A skill is never dropped. test/spring-skill-index.test.ts pins the budget+ * against the real skills tree.+ */+import type { BundledSkill } from './bundled.ts';++export const SKILL_INDEX_VERSION = 1;+/** Upper bound for the whole managed block interior: it is loaded on every turn. */+export const SKILL_INDEX_BUDGET_BYTES = 6144;+const MAX_TRIGGER_CHARS = 60;++/** How the agent reaches the brain; mirrors BrainFirstAccess in setup/brain-first.ts. */+export type SkillIndexAccess = { kind: 'mcp'; server: string } | { kind: 'cli'; launcher: string };++function cleanTrigger(t: string): string {+ const s = t.replace(/["`]/g, '').replace(/\s+/g, ' ').trim();+ return s.length > MAX_TRIGGER_CHARS ? `${s.slice(0, MAX_TRIGGER_CHARS - 1).trimEnd()}…` : s;+}++function indexLine(skill: BundledSkill, perSkill: number): string {+ const seen = new Set<string>();+ const triggers: string[] = [];+ for (const t of skill.triggers) {+ const c = cleanTrigger(t);+ const words = c.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);+ if (words.length === 0 || words.every((w) => seen.has(w))) continue;+ for (const w of words) seen.add(w);+ triggers.push(c);+ if (triggers.length === perSkill) break;+ }+ const when = triggers.length ? triggers.join('; ') : cleanTrigger(skill.description);+ return `- ${skill.name}: ${when}`;+}++function header(access: SkillIndexAccess, optOut: string): string[] {+ const load = access.kind === 'mcp'+ ? `call \`get_skill\` on ${access.server} with \`bundled: true\` and the skill's \`name\``+ : `run \`${access.launcher} skill <name> --bundled\``;+ const asset = access.kind === 'mcp'+ ? 'the same way with `asset` added'+ : `with \`${access.launcher} skill <name> --bundled --asset <path>\``;+ return [+ `<!-- gbrain skills v${SKILL_INDEX_VERSION}: managed by gbrain and replaced on upgrade; edit outside these markers. Opt out: ${optOut} -->`,+ '## GBrain skills: load on demand',+ '',+ `GBrain ships step-by-step procedures for brain work. When a task matches a line below, ${load}, then follow it before acting. Load files a skill names ${asset}. Load nothing for a task no line matches.`,+ '',+ ];+}++/** The block interior (without markers). */+export function renderSkillIndexBlock(skills: readonly BundledSkill[], access: SkillIndexAccess, optOut: string, budget = SKILL_INDEX_BUDGET_BYTES): string {+ const head = header(access, optOut);+ let text = '';+ for (const perSkill of [3, 2, 1]) {+ text = [...head, ...skills.map(s => indexLine(s, perSkill))].join('\n');+ if (Buffer.byteLength(text, 'utf8') <= budget) return text;+ }+ return text;+}diff --git a/test/get-skill-bundled.test.ts b/test/get-skill-bundled.test.tsnew file mode 100644index 0000000000..aef3199695--- /dev/null+++ b/test/get-skill-bundled.test.ts@@ -0,0 +1,144 @@+/**+ * GBRA-194: `get_skill {bundled: true}` serves gbrain's own bundled skills+ * (the spring-loaded resolver's on-demand fetch), independent of this+ * brain's catalog.+ *+ * Protects: a fresh brain (shared catalog active, 3 memory skills) can still+ * load meeting-ingestion and the rest by name; remote callers pass the same+ * gates as get_skill (publish gate, name shape) and HTTP callers see only the+ * downstream set; assets are exact lookups; intent ranks candidates.+ * Fails when: bundled requests fall through to the shared catalog, the+ * publish gate is skipped for remote callers, an owner-only skill reaches an+ * HTTP caller, or an asset outside a skill's list is served.+ */+import { describe, expect, test } from 'bun:test';+import { join } from 'node:path';+import { skillsCatalogOperations } from '../src/core/ops/skills-catalog.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { BUNDLED_SKILLS, BUNDLED_SKILL_FILES } from '../src/core/skills/bundled-skills.generated.ts';++const getSkill = skillsCatalogOperations.find(op => op.name === 'get_skill')!;++/** A brain whose shared catalog is active (a fresh `gbrain init`); any catalog read fails the test. */+function ctx(o: { remote: boolean; transport?: 'stdio' | 'http'; publish?: boolean }): OperationContext {+ const engine = {+ getConfig: async (key: string) => (key === 'mcp.publish_skills' ? String(o.publish ?? true) : null),+ executeRaw: async (sql: string) => {+ if (sql.includes('FROM persistence_brain')) return [{ skill_bundles_enabled: true }];+ throw new Error(`bundled request read the catalog: ${sql}`);+ },+ };+ return {+ engine: engine as never, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false,+ remote: o.remote, sourceId: 'default', ...(o.transport ? { transport: o.transport } : {}),+ ...(o.remote ? { auth: { token: 't', clientId: 'c', scopes: ['read'] } as never } : {}),+ } as OperationContext;+}++const call = (c: OperationContext, p: Record<string, unknown>) => getSkill.handler(c, p) as Promise<Record<string, unknown>>;+const err = (p: Promise<unknown>) => p.then(() => { throw new Error('expected a refusal'); }, (e: { code?: string }) => e);++describe('get_skill bundled: true', () => {+ test('a fresh brain serves a bundled skill by name without reading its catalog', async () => {+ const r = await call(ctx({ remote: false }), { name: 'meeting-ingestion', bundled: true });+ expect(r.bundled).toBe(true);+ expect(r.name).toBe('meeting-ingestion');+ expect(String(r.body)).toContain('# ');+ expect(String(r.body)).not.toStartWith('---');+ expect(r.assets).toContain('conventions/brain-first.md');+ expect(typeof r.gbrain_version).toBe('string');+ });++ test('remote=true over stdio (the owner\'s local harness) sees every bundled skill, owner-only included', async () => {+ const r = await call(ctx({ remote: true, transport: 'stdio' }), { name: 'db-repair', bundled: true });+ expect(r.name).toBe('db-repair');+ });++ test('remote=true over HTTP sees the downstream set only; an owner-only skill is not found', async () => {+ const ok = await call(ctx({ remote: true, transport: 'http' }), { name: 'meeting-ingestion', bundled: true });+ expect(ok.name).toBe('meeting-ingestion');+ const ownerOnly = BUNDLED_SKILLS.filter(s => s.audience === 'owner').map(s => s.name);+ expect(ownerOnly).toContain('db-repair');+ for (const name of ownerOnly) {+ expect(await err(call(ctx({ remote: true, transport: 'http' }), { name, bundled: true }))).toMatchObject({ code: 'skill_not_found' });+ }+ });++ test('HTTP callers need mcp.publish_skills; the local CLI and the owner\'s stdio harness do not', async () => {+ expect(await err(call(ctx({ remote: true, transport: 'http', publish: false }), { name: 'query', bundled: true }))).toMatchObject({ code: 'permission_denied' });+ expect(await err(call(ctx({ remote: true, transport: 'http', publish: false }), { bundled: true, intent: 'meeting notes' }))).toMatchObject({ code: 'permission_denied' });+ expect(await err(call(ctx({ remote: true, transport: 'http', publish: false }), { name: 'query', bundled: true, asset: 'conventions/brain-first.md' }))).toMatchObject({ code: 'permission_denied' });+ expect((await call(ctx({ remote: true, transport: 'stdio', publish: false }), { name: 'query', bundled: true })).name).toBe('query');+ expect((await call(ctx({ remote: false, publish: false }), { name: 'query', bundled: true })).name).toBe('query');+ });++ test('remote=true with no transport recorded is treated as HTTP (downstream, gated)', async () => {+ expect(await err(call(ctx({ remote: true, publish: false }), { name: 'query', bundled: true }))).toMatchObject({ code: 'permission_denied' });+ expect(await err(call(ctx({ remote: true }), { name: 'db-repair', bundled: true }))).toMatchObject({ code: 'skill_not_found' });+ });++ test('names are lookup keys: paths, traversal and unknown names are refused', async () => {+ for (const name of ['../query', 'query/SKILL.md', '..', '', 'x'.repeat(129)]) {+ expect(await err(call(ctx({ remote: true, transport: 'http' }), { name, bundled: true }))).toMatchObject({ code: 'invalid_params' });+ }+ expect(await err(call(ctx({ remote: false }), { name: 'testing', bundled: true }))).toMatchObject({ code: 'skill_not_found' });+ expect(await err(call(ctx({ remote: false }), { name: 'no-such-skill', bundled: true }))).toMatchObject({ code: 'skill_not_found' });+ });++ test('assets: only files the skill lists are served, JSON as text', async () => {+ const c = ctx({ remote: true, transport: 'http' });+ const a = await call(c, { name: 'meeting-ingestion', bundled: true, asset: 'conventions/brain-first.md' });+ expect(a.content).toBe(BUNDLED_SKILL_FILES['conventions/brain-first.md']);+ for (const asset of ['../../../etc/passwd', 'meeting-ingestion/SKILL.md', 'conventions/', 'query/SKILL.md', 'conventions/../RESOLVER.md']) {+ expect(await err(call(c, { name: 'meeting-ingestion', bundled: true, asset }))).toMatchObject({ code: 'skill_not_found' });+ }+ const json = BUNDLED_SKILLS.find(s => s.assets.some(p => p.endsWith('.json')));+ if (json) {+ const path = json.assets.find(p => p.endsWith('.json'))!;+ const r = await call(c.transport === 'http' && json.audience === 'owner' ? ctx({ remote: false }) : c, { name: json.name, bundled: true, asset: path });+ expect(typeof r.content).toBe('string');+ expect(() => JSON.parse(String(r.content))).not.toThrow();+ }+ });++ test('intent ranks bundled candidates (names, no bodies); no match returns an empty list', async () => {+ const r = await call(ctx({ remote: false }), { bundled: true, intent: 'ingest this meeting transcript into the brain' });+ const candidates = r.candidates as Array<{ name: string; body?: string }>;+ expect(candidates[0]!.name).toBe('meeting-ingestion');+ expect(candidates.length).toBeLessThanOrEqual(5);+ expect(candidates.every(c => c.body === undefined)).toBe(true);+ expect((await call(ctx({ remote: false }), { intent: 'zxqv plorth' })).candidates).toEqual([]);+ expect(await err(call(ctx({ remote: false }), { bundled: true, intent: ' ' }))).toMatchObject({ code: 'invalid_params' });+ });++ test('bundled is explicit and has no source or revision', async () => {+ expect(await err(call(ctx({ remote: false }), { bundled: false, intent: 'meeting' }))).toMatchObject({ code: 'invalid_params' });+ expect(await err(call(ctx({ remote: false }), { bundled: true, name: 'query', source_id: 'default' }))).toMatchObject({ code: 'invalid_params' });+ expect(await err(call(ctx({ remote: false }), { bundled: true, name: 'query', revision: 'abc' }))).toMatchObject({ code: 'invalid_params' });+ });++ test('a plain get_skill miss on a bundled name names the bundled call and serves nothing in its place', async () => {+ const hostCatalog = (name: string) => ({+ engine: {+ getConfig: async (key: string) => (key === 'mcp.publish_skills' ? 'true' : key === 'mcp.skills_dir' ? join(import.meta.dir, 'fixtures', 'skill-catalog-query', 'skills') : null),+ executeRaw: async (sql: string) => (sql.includes('FROM persistence_brain') ? [{ skill_bundles_enabled: false }] : []),+ } as never,+ config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: true, transport: 'http' as const,+ auth: { token: 't', clientId: 'c', scopes: ['read'] } as never, sourceId: 'default',+ }) as OperationContext;+ const miss = await err(call(hostCatalog('meeting-ingestion'), { name: 'meeting-ingestion' })) as { code?: string; suggestion?: string; message?: string };+ expect(miss.code).toBe('page_not_found');+ expect(String(miss.message)).toContain('bundled skill named meeting-ingestion');+ expect(JSON.stringify(miss)).toContain('bundled: true');+ const ownerOnly = await err(call(hostCatalog('db-repair'), { name: 'db-repair' })) as { message?: string };+ expect(String(ownerOnly.message)).not.toContain('bundled');+ const unknown = await err(call(hostCatalog('no-such-skill'), { name: 'no-such-skill' })) as { message?: string };+ expect(String(unknown.message)).not.toContain('bundled');+ });++ test('the bundled set is the plugin lane: repo-development skills never ship', () => {+ const names = BUNDLED_SKILLS.map(s => s.name);+ for (const dev of ['testing', 'skillify', 'skill-autobench', 'skillpack-harvest']) expect(names).not.toContain(dev);+ expect(names.length).toBeGreaterThan(60);+ });+});diff --git a/test/setup-skill-loading.test.ts b/test/setup-skill-loading.test.tsnew file mode 100644index 0000000000..2f7a468cc7--- /dev/null+++ b/test/setup-skill-loading.test.ts@@ -0,0 +1,163 @@+/**+ * GBRA-194: `--skill-loading spring` writes the spring-loaded skill index+ * (src/core/setup/skills-block.ts) beside the brain-first block in each+ * writable harness's instruction file; `off` (the default) writes nothing.+ * Per harness this pins:+ * - placement: the index lands right after the brain-first block, text+ * outside both blocks is byte-identical;+ * - default off: a plain install writes no index;+ * - idempotence and remembered choice: a re-run without the flag keeps the+ * recorded mode; `off` strips the index and is remembered;+ * - --no-instructions strips both blocks; --remove strips both and deletes a+ * file only gbrain created once nothing else is in it, in either order;+ * - Hermes: SOUL.md is never created;+ * - dry-run writes nothing; GBRAIN_SKILL_LOADING selects the mode; a bad+ * value is refused.+ * 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 { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { BRAIN_FIRST_BEGIN, BRAIN_FIRST_END } from '../src/core/setup/brain-first.ts';+import { renderSkillsBlock, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';++const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { home: string; project: string; env: Record<string, string | undefined> }+function box(): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-skill-loading-'));+ roots.push(root);+ const home = join(root, 'home'), project = join(root, 'project');+ mkdirSync(home, { recursive: true });+ mkdirSync(project, { recursive: true });+ return { home, project, env: {+ HOME: home, GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,+ OPENCLAW_STATE_DIR: undefined, OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, HERMES_HOME: undefined,+ GBRAIN_AGENT_INSTRUCTIONS: undefined, GBRAIN_SURFACE: undefined, GBRAIN_SKILL_LOADING: undefined,+ } };+}+async function setup(b: Box, args: string[], env: Record<string, string | undefined> = {}) {+ const r = await runCli(['setup', ...args, '--json'], { env: { ...b.env, ...env }, cwd: b.project });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc };+}+const read = (p: string) => readFileSync(p, 'utf8');+const count = (text: string, line: string) => text.split('\n').filter((l) => l === line).length;+const outside = (text: string) => text+ .replace(new RegExp(`${BRAIN_FIRST_BEGIN}[\\s\\S]*?${BRAIN_FIRST_END}\\n`), '')+ .replace(new RegExp(`${SKILLS_BLOCK_BEGIN}[\\s\\S]*?${SKILLS_BLOCK_END}\\n`), '');++interface Lane { harness: string; file: (b: Box) => string; existing: string; refusesCreate?: boolean }+const LANES: Lane[] = [+ { harness: 'claude-code', file: (b) => join(b.home, '.claude', 'CLAUDE.md'), existing: '# My rules\n\nAlways answer in French.\n' },+ { harness: 'codex', file: (b) => join(b.home, '.codex', 'AGENTS.md'), existing: '# Codex house rules\n- run the tests\n' },+ { harness: 'opencode', file: (b) => join(b.home, '.config', 'opencode', 'AGENTS.md'), existing: 'Prefer small diffs.\n' },+ { harness: 'openclaw', file: (b) => join(b.home, '.openclaw', 'workspace', 'AGENTS.md'), existing: '# AGENTS.md\n\n## Tools\nUse the calendar skill.\n' },+ { harness: 'hermes', file: (b) => join(b.home, '.hermes', 'SOUL.md'), existing: 'You are Hermes, a careful assistant named alice-example.\n', refusesCreate: true },+ { harness: 'cursor', file: (b) => join(b.project, '.cursor', 'rules', 'gbrain-brain-first.mdc'), existing: '---\ndescription: team rule\nalwaysApply: true\n---\nUse tabs.\n' },+];++for (const lane of LANES) {+ describe(`skill loading: ${lane.harness}`, () => {+ const run = (b: Box, extra: string[] = [], env: Record<string, string | undefined> = {}) => setup(b, [lane.harness, '--instructions-only', ...extra], env);+ const seed = (b: Box) => { mkdirSync(dirname(lane.file(b)), { recursive: true }); writeFileSync(lane.file(b), lane.existing); };++ test('default off writes no index; spring places it right after brain-first and keeps outside text', async () => {+ const b = box(); seed(b);+ const plain = await run(b);+ expect(plain.exitCode).toBe(0);+ expect(read(lane.file(b))).not.toContain(SKILLS_BLOCK_BEGIN);+ expect(plain.doc.skills.decision).toEqual({ value: 'off', source: 'default' });+ expect(existsSync(join(b.home, '.gbrain', 'skill-loading.json'))).toBe(false);++ const r = await run(b, ['--skill-loading', 'spring']);+ expect(r.exitCode).toBe(0);+ expect(r.doc.skills.action).toBe('write');+ const text = read(lane.file(b));+ expect(count(text, SKILLS_BLOCK_BEGIN)).toBe(1);+ const lines = text.split('\n');+ expect(lines.indexOf(SKILLS_BLOCK_BEGIN)).toBe(lines.indexOf(BRAIN_FIRST_END) + 1);+ expect(text).toContain(renderSkillsBlock(lane.harness, { kind: 'mcp', server: 'gbrain' }));+ expect(outside(text)).toBe(lane.existing);+ });++ test('the choice is remembered; off strips and is remembered; a re-run is byte-identical', async () => {+ const b = box(); seed(b);+ await run(b, ['--skill-loading', 'spring']);+ const once = read(lane.file(b));+ const again = await run(b);+ expect(again.doc.skills).toMatchObject({ action: 'keep', decision: { value: 'spring', source: 'prior' } });+ expect(read(lane.file(b))).toBe(once);+ const off = await run(b, ['--skill-loading', 'off']);+ expect(off.doc.skills.action).toBe('remove');+ expect(read(lane.file(b))).not.toContain(SKILLS_BLOCK_BEGIN);+ expect(read(lane.file(b))).toContain(BRAIN_FIRST_BEGIN);+ expect((await run(b)).doc.skills.decision).toEqual({ value: 'off', source: 'prior' });+ expect(read(lane.file(b))).not.toContain(SKILLS_BLOCK_BEGIN);+ });++ test('--no-instructions strips both blocks; --dry-run writes nothing', async () => {+ const b = box(); seed(b);+ const dry = await run(b, ['--skill-loading', 'spring', '--dry-run']);+ expect(dry.exitCode).toBe(0);+ expect(read(lane.file(b))).toBe(lane.existing);+ expect(existsSync(join(b.home, '.gbrain', 'skill-loading.json'))).toBe(false);+ await run(b, ['--skill-loading', 'spring']);+ const r = await run(b, ['--no-instructions']);+ expect(r.doc.skills).toMatchObject({ action: 'remove', decision: { value: 'off', source: 'instructions_off' } });+ expect(read(lane.file(b))).toBe(lane.existing);+ });++ test(lane.refusesCreate ? 'a missing SOUL.md is never created' : 'a file gbrain created goes away only when both blocks are removed, in either order', async () => {+ const b = box();+ const r = await run(b, ['--skill-loading', 'spring']);+ if (lane.refusesCreate) {+ expect(existsSync(lane.file(b))).toBe(false);+ expect(r.doc.skills.action).toBe('skip');+ return;+ }+ expect(read(lane.file(b))).toContain(SKILLS_BLOCK_BEGIN);+ await run(b, ['--skill-loading', 'off']);+ expect(existsSync(lane.file(b))).toBe(true);+ await run(b, ['--skill-loading', 'spring']);+ const removed = await run(b, ['--remove']);+ expect(removed.exitCode).toBe(0);+ expect(existsSync(lane.file(b))).toBe(false);++ const c = box();+ await run(c, ['--skill-loading', 'spring']);+ await run(c, ['--no-instructions']);+ expect(existsSync(lane.file(c))).toBe(false);+ });+ });+}++describe('skill loading: selection', () => {+ test('GBRAIN_SKILL_LOADING=spring selects it; the flag wins over the env', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--instructions-only'], { GBRAIN_SKILL_LOADING: 'spring' });+ expect(r.doc.skills.decision).toEqual({ value: 'spring', source: 'env' });+ const off = await setup(b, ['claude-code', '--instructions-only', '--skill-loading', 'off'], { GBRAIN_SKILL_LOADING: 'spring' });+ expect(off.doc.skills.decision).toEqual({ value: 'off', source: 'flag' });+ });++ test('an unknown --skill-loading value is refused before anything is written', async () => {+ const b = box();+ const r = await setup(b, ['claude-code', '--instructions-only', '--skill-loading', 'lazy']);+ expect(r.exitCode).not.toBe(0);+ expect(r.stdout + r.stderr).toContain('--skill-loading');+ expect(existsSync(join(b.home, '.claude', 'CLAUDE.md'))).toBe(false);+ });++ test('a verbs-only surface has no get_skill, so the index names the CLI fetch', async () => {+ const b = box();+ await setup(b, ['claude-code', '--instructions-only', '--skill-loading', 'spring', '--surface', 'verbs']);+ const text = read(join(b.home, '.claude', 'CLAUDE.md'));+ expect(text).toContain('gbrain skill <name> --bundled');+ expect(text).not.toContain('`bundled: true`');+ });+});diff --git a/test/spring-skill-index.test.ts b/test/spring-skill-index.test.tsnew file mode 100644index 0000000000..59bea34337--- /dev/null+++ b/test/spring-skill-index.test.ts@@ -0,0 +1,58 @@+/**+ * GBRA-194: the spring-loaded skill index (the always-loaded half of the+ * resolver) stays inside its byte budget for the real bundled skills tree.+ *+ * Protects: the per-turn cost of `--skill-loading spring`. Every bundled+ * skill keeps a line; trigger phrases are what the line carries; the block+ * names the fetch for the access it was written for.+ * Fails when: a new or longer skill pushes the block past+ * SKILL_INDEX_BUDGET_BYTES, a skill drops out of the index, or the fetch+ * sentence stops naming bundled: true / --bundled.+ */+import { describe, expect, test } from 'bun:test';+import { bundledSkills } from '../src/core/skills/bundled.ts';+import { renderSkillIndexBlock, SKILL_INDEX_BUDGET_BYTES } from '../src/core/skills/spring-index.ts';+import { renderBundledSkillsModule } from '../scripts/generate-bundled-skills.ts';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const OPT_OUT = 'gbrain setup claude-code --instructions-only --skill-loading off';+const bytes = (s: string) => Buffer.byteLength(s, 'utf8');++describe('spring-loaded skill index', () => {+ for (const audience of ['owner', 'downstream'] as const) {+ for (const access of [{ kind: 'mcp', server: 'gbrain' }, { kind: 'cli', launcher: '/home/alice-example/.gbrain-agent/bin/gbrain' }] as const) {+ test(`${audience} / ${access.kind}: under budget with every skill on its own line`, () => {+ const skills = bundledSkills(audience);+ const block = renderSkillIndexBlock(skills, access, OPT_OUT);+ expect(bytes(block)).toBeLessThanOrEqual(SKILL_INDEX_BUDGET_BYTES);+ const lines = block.split('\n').filter(l => l.startsWith('- '));+ expect(lines.map(l => l.slice(2, l.indexOf(':')))).toEqual(skills.map(s => s.name));+ expect(block).toContain(access.kind === 'mcp' ? '`bundled: true`' : 'skill <name> --bundled');+ });+ }+ }++ test('the full three-trigger rendering of the owner set fits without the budget guard', () => {+ const skills = bundledSkills('owner');+ const roomy = renderSkillIndexBlock(skills, { kind: 'mcp', server: 'gbrain' }, OPT_OUT, Number.MAX_SAFE_INTEGER);+ expect(renderSkillIndexBlock(skills, { kind: 'mcp', server: 'gbrain' }, OPT_OUT)).toBe(roomy);+ });++ test('over budget, lines drop to fewer triggers but no skill is dropped', () => {+ const skills = bundledSkills('owner');+ const tight = renderSkillIndexBlock(skills, { kind: 'mcp', server: 'gbrain' }, OPT_OUT, 4096);+ expect(tight.split('\n').filter(l => l.startsWith('- '))).toHaveLength(skills.length);+ expect(tight.split('\n').filter(l => l.startsWith('- ')).every(l => !l.includes('; '))).toBe(true);+ });++ test('deterministic and free of quotes that would break the markdown', () => {+ const a = renderSkillIndexBlock(bundledSkills('owner'), { kind: 'mcp', server: 'gbrain' }, OPT_OUT);+ expect(renderSkillIndexBlock(bundledSkills('owner'), { kind: 'mcp', server: 'gbrain' }, OPT_OUT)).toBe(a);+ expect(a.split('\n').filter(l => l.startsWith('- ')).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());+ });+});