Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver catalogs: OpenClaw skills list, folder bodies, 4 KB body trim, Claude Code plugins
garrytan2fd1376f5b6e
diff --git a/docs/schemas/skill-resolver.v1.build-input.json b/docs/schemas/skill-resolver.v1.build-input.jsonindex b826e6e1f7..f15d9447bb 100644--- a/docs/schemas/skill-resolver.v1.build-input.json+++ b/docs/schemas/skill-resolver.v1.build-input.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "skill-resolver.v1.build-input.json","title": "gbrain skill resolver: catalog snapshot for `skills index build --from-json` (schema_version 1)",- "description": "An adapter's skill list: an array of skills, or {\"skills\": [...]}. At most 10,000 entries and 8 MB. A stdin snapshot is kept as source.json beside the index and is never rebuilt automatically.",+ "description": "An adapter's skill list: an array of skills, {\"skills\": [...]}, or OpenClaw's `skills list --json` document as is (its entries have no id: the name is the id, and an entry that is not eligible, is disabled, blocked by the allowlist or the agent filter, or not model-visible is skipped as ineligible). At most 10,000 entries and 64 MB; bodies are trimmed to the 4 KB the ranker reads, and a snapshot over 8 MB is kept trimmed. A stdin snapshot is kept as source.json beside the index and is never rebuilt automatically.","$defs": {"skill": {"type": "object",@@ -56,6 +56,57 @@"items": {"$ref": "#/$defs/skill"}+ },+ "openclawSkill": {+ "type": "object",+ "additionalProperties": true,+ "required": [+ "name"+ ],+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "description": "The skill's name, which skills_read({name}) takes; also its id."+ },+ "description": {+ "type": "string"+ },+ "body": {+ "type": "string"+ },+ "path": {+ "type": "string"+ },+ "triggers": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "routing": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "eligible": {+ "type": "boolean"+ },+ "disabled": {+ "type": "boolean"+ },+ "blockedByAllowlist": {+ "type": "boolean"+ },+ "blockedByAgentFilter": {+ "type": "boolean"+ },+ "modelVisible": {+ "type": "boolean"+ }+ }}},"anyOf": [@@ -72,6 +123,34 @@"$ref": "#/$defs/list"}}+ },+ {+ "type": "object",+ "required": [+ "skills"+ ],+ "anyOf": [+ {+ "required": [+ "workspaceDir"+ ]+ },+ {+ "required": [+ "managedSkillsDir"+ ]+ }+ ],+ "properties": {+ "skills": {+ "type": "array",+ "maxItems": 10000,+ "items": {+ "$ref": "#/$defs/openclawSkill"+ }+ }+ },+ "description": "OpenClaw's skills list --json output."}]}diff --git a/docs/schemas/skill-resolver.v1.build-receipt.json b/docs/schemas/skill-resolver.v1.build-receipt.jsonindex a2dbc71011..942028f47e 100644--- a/docs/schemas/skill-resolver.v1.build-receipt.json+++ b/docs/schemas/skill-resolver.v1.build-receipt.json@@ -64,7 +64,8 @@"enum": ["dir","bundled",- "json"+ "json",+ "claude_plugins"]},"dirs": {@@ -85,6 +86,10 @@"bundled_skills": {"type": "integer","minimum": 0+ },+ "claude_dir": {+ "type": "string",+ "description": "claude_plugins: the Claude Code config directory whose enabled user-scope plugins were indexed."}}},diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.tsindex 20441c14e9..5f26cd735a 100644--- a/src/commands/skill-resolver.ts+++ b/src/commands/skill-resolver.ts@@ -18,6 +18,7 @@ import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';import { readStdinBounded } from '../core/interaction.ts';import { opError } from '../core/ops/contract.ts';import type { RegistryCode } from '../core/error-registry.ts';+import { JSON_INPUT_CAP_BYTES } from '../core/skills/resolver/sources.ts';import {buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, resolveSkills, resolverHome, sessionStatus,ResolverError, HARNESSES, errorTurnOutput, GBRAIN_VERSION, type BuildInput, type TurnInput,@@ -28,8 +29,8 @@ const HELP_INDEX = `Usage: gbrain skills index <build|status|remove> [options]Build, inspect or remove a skill catalog's index (under GBRAIN_HOME/skill-index/).No brain connection is needed.- gbrain skills index build --catalog <name> (--dir <d>... | --bundled | --from-json <file|->)- [--routing <file>] [--harness <h>] [--scope user|project] [--json]+ gbrain skills index build --catalog <name> (--dir <d>... | --bundled | --from-json <file|-> [--dir <d>...]+ | --claude-plugins <dir>) [--routing <file>] [--harness <h>] [--scope user|project] [--json]gbrain skills index status [--catalog <name>] [--session <id> [--harness <h>] [--shadow]] [--json]gbrain skills index remove --catalog <name> [--json]@@ -37,6 +38,10 @@ No brain connection is needed.--dir <d> a SKILL.md directory (repeatable; earlier wins on duplicate ids)--bundled gbrain's own bundled skills--from-json <f|-> an adapter's skill list ([{id, name, description, triggers?, path?, eligible?}])+ or OpenClaw's skills list --json output as is; with --dir, each listed skill+ takes its body, path and triggers from the folder skill of the same name+ --claude-plugins <dir> the skills of the enabled user-scope Claude Code plugins under+ <dir> (~/.claude), named <plugin>:<skill>--routing <file> one RESOLVER-style routing table; rows add trigger text to skills--harness <h> openclaw, claude-code, codex, hermes, qm, pi or cursor (recorded in the receipt)--scope project a cloned repository's skills: blocks show ids and names only@@ -125,7 +130,7 @@ async function readStdinCapped(max: number): Promise<string | null> {const r = await readStdinBounded({ maxBytes: max });if (r.kind === 'data') return r.text;if (r.kind === 'empty') return '';- usage(r.kind === 'timeout' ? 'stdin sent no data before the read timed out.' : 'stdin could not be read: ' + (r.kind === 'error' ? r.error.message : 'cancelled') + '.', 'Send one turn (or one catalog of at most 8 MB) on stdin and close it.');+ usage(r.kind === 'timeout' ? 'stdin sent no data before the read timed out.' : 'stdin could not be read: ' + (r.kind === 'error' ? r.error.message : 'cancelled') + '.', 'Send one turn (or one catalog of at most 64 MB) on stdin and close it.');}function write(text: string): Promise<boolean> {@@ -147,7 +152,7 @@ async function runIndex(args: string[]): Promise<void> {if (sub === undefined || sub === 'help' || sub === '--help' || sub === '-h') { process.stdout.write(HELP_INDEX); return; }usage(`Unknown subcommand "skills index ${sub}".`, 'Use gbrain skills index build, status or remove.');}- const p = parseFlags(args.slice(1), ['--catalog', '--dir', '--from-json', '--routing', '--harness', '--scope', '--session'], ['--bundled', '--json', '--shadow'], HELP_INDEX);+ const p = parseFlags(args.slice(1), ['--catalog', '--dir', '--from-json', '--claude-plugins', '--routing', '--harness', '--scope', '--session'], ['--bundled', '--json', '--shadow'], HELP_INDEX);const json = p.bools.has('--json');if (p.positionals.length) usage(`Unexpected argument "${p.positionals[0]}".`, 'Pass options as flags; see gbrain skills index --help.');try {@@ -156,10 +161,11 @@ async function runIndex(args: string[]): Promise<void> {if (!catalog) usage('skills index build needs --catalog <name>.', 'Example: gbrain skills index build --catalog claude-user --dir ~/.claude/skills');const fromJson = one(p, '--from-json');const input: BuildInput = { catalog: catalog!, ...(p.flags.get('--dir') ? { dirs: p.flags.get('--dir') } : {}), ...(p.bools.has('--bundled') ? { bundled: true } : {}),+ ...(one(p, '--claude-plugins') !== undefined ? { claudePlugins: one(p, '--claude-plugins') } : {}),...(one(p, '--routing') ? { routing: one(p, '--routing') } : {}), ...(one(p, '--harness') ? { harness: one(p, '--harness') } : {}),...(one(p, '--scope') ? { scope: one(p, '--scope') as 'user' | 'project' } : {}) };if (fromJson === '-') {- const text = await readStdinCapped(8 * 1024 * 1024);+ const text = await readStdinCapped(JSON_INPUT_CAP_BYTES);if (!text) exitCliError(toOpError(new ResolverError('skill_resolve_no_input', 'No catalog JSON arrived on stdin.', { suggestion: 'Pipe the skill list: <adapter> | gbrain skills index build --catalog <name> --from-json -' })), CMD);input.fromJson = text!;input.fromJsonStdin = true;diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.tsindex eebfe227c6..d04668d4f0 100644--- a/src/core/setup/skill-resolver-setup.ts+++ b/src/core/setup/skill-resolver-setup.ts@@ -3,8 +3,9 @@* resolve` (and its undo, `--skill-loading off|spring` and `setup --remove`).** On: build the harness's user-level catalog (<harness>-user, from- * ~/.claude/skills; Codex: ~/.agents/skills and CODEX_HOME/skills), and only- * when that build indexed at least one skill, write the file-plane keys+ * ~/.claude/skills; Codex: ~/.agents/skills and CODEX_HOME/skills) and, for+ * Claude Code, claude-code-plugins from its enabled user-scope plugins; only+ * when those builds indexed at least one skill, write the file-plane keys* (skill-resolver-config.ts) and the lane's hook (skill-resolver-hook.ts).* Otherwise nothing is written and the result carries* skill_resolver_setup_incomplete with the scanned directories. A re-run with@@ -27,7 +28,7 @@ import { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex } from 'import { ResolverError } from '../skills/resolver/errors.ts';import { logsDir, sessionsDir, skillIndexRoot } from '../skills/resolver/paths.ts';import { resolveSkills } from '../skills/resolver/resolve.ts';-import { readDirSources } from '../skills/resolver/sources.ts';+import { claudePluginRoots, readDirSources } from '../skills/resolver/sources.ts';import { readResolverConfig, resolverHarnesses, setResolverHarness } from './skill-resolver-config.ts';import { inspectSkillResolverHook, removeSkillResolverHook, syncSkillResolverHook, type ResolverHarness, type ResolverHookPaths } from './skill-resolver-hook.ts';@@ -43,7 +44,34 @@ export interface ResolverSetupResult {}export const userCatalog = (harness: ResolverHarness) => `${harness}-user`;-const isHarnessCatalog = (harness: ResolverHarness, name: string) => name === userCatalog(harness) || name.startsWith(`${harness}-project-`);+export const CLAUDE_PLUGINS_CATALOG = 'claude-code-plugins';+const isHarnessCatalog = (harness: ResolverHarness, name: string) => name === userCatalog(harness) || name === `${harness}-plugins` || name.startsWith(`${harness}-project-`);++/** The Claude Code config directory whose plugins the plugin catalog indexes. */+export const claudePluginsBase = () => dirname(claudeUserSkillsDir());++/** Build, keep or drop claude-code-plugins; returns its skill count and the step (null when there is nothing either way). */+async function syncPluginCatalog(home: string, dryRun: boolean): Promise<{ skills: number; step: ResolverStep | null }> {+ const base = claudePluginsBase();+ const where = join(skillIndexRoot(home), CLAUDE_PLUGINS_CATALOG);+ const built = existsSync(join(where, 'receipt.json'));+ const roots = claudePluginRoots(base).roots;+ const drop = async (): Promise<{ skills: number; step: ResolverStep | null }> => {+ if (!built) return { skills: 0, step: null };+ if (!dryRun) await removeSkillIndex(CLAUDE_PLUGINS_CATALOG, { home });+ return { skills: 0, step: { step: 'catalog', action: 'remove', detail: `${where} (no enabled plugin has a model-invocable skill)` } };+ };+ if (roots.length === 0) return drop();+ const status = built ? await catalogStatus(CLAUDE_PLUGINS_CATALOG, { home }) : null;+ if (status?.fresh && (status.receipt?.skill_count ?? 0) > 0) return { skills: status.receipt!.skill_count, step: { step: 'catalog', action: 'keep', detail: `${status.receipt!.skill_count} plugin skills from ${base} in ${where}` } };+ if (dryRun) {+ const n = readDirSources(roots).skills.length;+ return n ? { skills: n, step: { step: 'catalog', action: 'write', detail: `${n} plugin skills from ${base} into ${where}` } } : drop();+ }+ const n = (await buildSkillIndex({ catalog: CLAUDE_PLUGINS_CATALOG, claudePlugins: base, harness: 'claude-code' }, { home })).catalog.skill_count;+ if (n < 1) { await removeSkillIndex(CLAUDE_PLUGINS_CATALOG, { home }); return { skills: 0, step: built ? { step: 'catalog', action: 'remove', detail: where } : null }; }+ return { skills: n, step: { step: 'catalog', action: 'write', detail: `${n} plugin skills from ${base} into ${where}` } };+}/** The user-level skill directories a harness loads natively, whether or not they exist. */export function harnessSkillDirs(harness: ResolverHarness): string[] {@@ -69,25 +97,37 @@ export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; gconst sameDirs = JSON.stringify(status?.receipt?.source.dirs ?? null) === JSON.stringify(dirs);const fresh = !!status?.fresh && sameDirs && (status.receipt?.skill_count ?? 0) > 0;const where = join(skillIndexRoot(home), catalog);- if (dirs.length === 0) return { ...out, error: incomplete(harnessSkillDirs(harness), 'no user-level skill directory exists', 'Nothing was written.') };+ const pluginRoots = harness === 'claude-code' ? claudePluginRoots(claudePluginsBase()).roots : [];+ if (dirs.length === 0 && pluginRoots.length === 0) return { ...out, error: incomplete(harnessSkillDirs(harness), 'no user-level skill directory exists', 'Nothing was written.') };+ const scanned = [...dirs, ...(pluginRoots.length ? [claudePluginsBase()] : [])];- let skills = status?.receipt?.skill_count ?? 0;- if (dryRun) {- if (!fresh) skills = readDirSources(dirs).skills.length;- if (skills < 1) return { ...out, error: incomplete(dirs, 'the scan found no model-invocable skill', 'Nothing would be written.') };- out.steps.push({ step: 'catalog', action: fresh ? 'keep' : 'write', detail: `${skills} skills from ${dirs.join(', ')} into ${where}` });- } else if (!fresh) {+ let skills = 0;+ if (dirs.length && dryRun) {+ skills = fresh ? status!.receipt!.skill_count : readDirSources(dirs).skills.length;+ if (skills > 0) out.steps.push({ step: 'catalog', action: fresh ? 'keep' : 'write', detail: `${skills} skills from ${dirs.join(', ')} into ${where}` });+ } else if (dirs.length && !fresh) {try {skills = (await buildSkillIndex({ catalog, dirs, harness }, { home })).catalog.skill_count;} catch (e) {return { ...out, error: incomplete(dirs, `the catalog build failed (${e instanceof ResolverError ? e.code : (e as Error).message})`, 'Nothing else was written.') };}- if (skills < 1) {- await removeSkillIndex(catalog, { home });- return { ...out, error: incomplete(dirs, 'the scan found no model-invocable skill', `The empty catalog at ${where} was removed; nothing else was written.`) };+ if (skills < 1) await removeSkillIndex(catalog, { home });+ else out.steps.push({ step: 'catalog', action: 'write', detail: `${skills} skills from ${dirs.join(', ')} into ${where}` });+ } else if (dirs.length) {+ skills = status!.receipt!.skill_count;+ out.steps.push({ step: 'catalog', action: 'keep', detail: `${skills} skills from ${dirs.join(', ')} in ${where}` });+ }+ let pluginSkills = 0;+ if (harness === 'claude-code') {+ try {+ const r = await syncPluginCatalog(home, dryRun);+ pluginSkills = r.skills;+ if (r.step) out.steps.push(r.step);+ } catch (e) {+ return { ...out, error: incomplete(scanned, `the plugin catalog build failed (${e instanceof ResolverError ? e.code : (e as Error).message})`, skills ? `The catalog at ${where} was written; nothing else was.` : 'Nothing else was written.') };}- out.steps.push({ step: 'catalog', action: 'write', detail: `${skills} skills from ${dirs.join(', ')} into ${where}` });- } else out.steps.push({ step: 'catalog', action: 'keep', detail: `${skills} skills from ${dirs.join(', ')} in ${where}` });+ }+ if (skills + pluginSkills < 1) return { ...out, error: incomplete(scanned, 'the scan found no model-invocable skill', dryRun ? 'Nothing would be written.' : dirs.length ? `The empty catalog at ${where} was removed; nothing else was written.` : 'Nothing was written.') };const keys = setResolverHarness(cfg, harness, true, dryRun);out.steps.push({ step: 'config', action: keys.changed ? 'write' : 'keep', detail: `skills.resolver.enabled = true, skills.resolver.harnesses includes ${harness} in ${cfg.path}` });@@ -96,11 +136,13 @@ export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; gout.steps.push({ step: 'hook', action: hook.action === 'keep' ? 'keep' : 'write', detail: hook.detail });if (dryRun) return out;- const after = await catalogStatus(catalog, { home });- const sampleText = readDirSources(dirs).skills[0]?.description ?? '';- const sample = sampleText ? (await resolveSkills({ message: sampleText, harness }, { home, catalogs: [catalog], failOpen: true })).output.block : '';- const n = after.receipt?.skill_count ?? skills;- return { ...out, sample, status: { catalog, skills: n, fresh: after.fresh === true, line: `skill resolver: on; ${n} skills; ${after.fresh ? 'fresh' : 'stale'}` } };+ const built = [...(skills ? [catalog] : []), ...(pluginSkills ? [CLAUDE_PLUGINS_CATALOG] : [])];+ const after = await Promise.all(built.map((c) => catalogStatus(c, { home })));+ const sampleText = (readDirSources(skills ? dirs : pluginRoots).skills[0]?.description) ?? '';+ const sample = sampleText ? (await resolveSkills({ message: sampleText, harness }, { home, catalogs: built, failOpen: true })).output.block : '';+ const n = after.reduce((t, s) => t + (s.receipt?.skill_count ?? 0), 0);+ const allFresh = after.every((s) => s.fresh === true);+ return { ...out, sample, status: { catalog: built[0]!, skills: n, fresh: allFresh, line: `skill resolver: on; ${n} skills; ${allFresh ? 'fresh' : 'stale'}` } };}/** Whether anything of the resolver's exists for this harness (keys, hook or catalogs). */diff --git a/src/core/skills/resolver/build.ts b/src/core/skills/resolver/build.tsindex bff6ca9b00..54cddfa9b7 100644--- a/src/core/skills/resolver/build.ts+++ b/src/core/skills/resolver/build.ts@@ -22,7 +22,7 @@ import { listCatalogs, readReceipt } from './catalog-files.ts';import { acquireLease, holdsLease, releaseLease, tryAcquireLease } from './lock.ts';import { catalogDir, catalogFile, resolverHome, skillIndexRoot, validCatalogName, assertCatalogName } from './paths.ts';import { gcSessions, loadSession, sessionKey } from './session.ts';-import { applyRouting, readBundledSource, readDirSources, readJsonSource, type DirFingerprint, type SkillRecord, type SkippedSkill, type SourceRead } from './sources.ts';+import { applyRouting, JSON_INPUT_CAP_BYTES, mergeSkillFolders, readBundledSource, readClaudePluginSources, readDirSources, readJsonSource, type DirFingerprint, type SkillRecord, type SkippedSkill, type SourceRead } from './sources.ts';import { TOKENIZER_ID } from './tokenize.ts';import { BLOCK_TOKEN_CAP, BLOCK_TOKENIZER, HARNESSES } from './block.ts';import { readResolverSettings } from './config.ts';@@ -39,6 +39,8 @@ export interface BuildInput {/** A file path, or the JSON text itself when read from stdin (fromJsonStdin). */fromJson?: string;fromJsonStdin?: boolean;+ /** A Claude Code config directory (~/.claude): the skills of its enabled user-scope plugins. */+ claudePlugins?: string;routing?: string;harness?: string;/** project: a cloned repository's skills; its hints are never shown. */@@ -52,7 +54,7 @@ export interface BuildReceipt {catalog: {name: string;catalog_hash: string;- source: { kind: 'dir' | 'bundled' | 'json'; dirs?: string[]; stdin?: boolean; file?: string; snapshot?: 'source.json'; bundled_skills?: number };+ source: { kind: 'dir' | 'bundled' | 'json' | 'claude_plugins'; dirs?: string[]; stdin?: boolean; file?: string; snapshot?: 'source.json'; bundled_skills?: number; claude_dir?: string };fingerprint_sha256: string | null;skill_count: number;skipped: SkippedSkill[];@@ -107,6 +109,7 @@ export function buildArgs(input: BuildInput): { args: string[]; fix: string[] |for (const d of input.dirs ?? []) args.push('--dir', resolve(d));if (input.bundled) args.push('--bundled');if (input.fromJson !== undefined) args.push('--from-json', input.fromJsonStdin ? '-' : resolve(input.fromJson));+ if (input.claudePlugins !== undefined) args.push('--claude-plugins', resolve(input.claudePlugins));if (input.routing) args.push('--routing', resolve(input.routing));if (input.harness) args.push('--harness', input.harness);if (input.scope === 'project') args.push('--scope', 'project');@@ -115,8 +118,9 @@ export function buildArgs(input: BuildInput): { args: string[]; fix: string[] |function validateBuild(input: BuildInput): void {assertCatalogName(input.catalog);- const kinds = [input.dirs?.length ? 1 : 0, input.bundled ? 1 : 0, input.fromJson !== undefined ? 1 : 0].reduce((a, b) => a + b, 0);- if (kinds !== 1) throw new ResolverError('skill_resolve_invalid_input', 'Pass exactly one source: --dir <d> (repeatable), --bundled or --from-json <file|->.', { suggestion: 'Example: gbrain skills index build --catalog claude-user --dir ~/.claude/skills' });+ const json = input.fromJson !== undefined;+ const kinds = [input.dirs?.length && !json ? 1 : 0, input.bundled ? 1 : 0, json ? 1 : 0, input.claudePlugins !== undefined ? 1 : 0].reduce((a, b) => a + b, 0);+ if (kinds !== 1) throw new ResolverError('skill_resolve_invalid_input', 'Pass exactly one source: --dir <d> (repeatable), --bundled, --from-json <file|-> (optionally with --dir folders to take bodies from) or --claude-plugins <dir>.', { suggestion: 'Example: gbrain skills index build --catalog claude-user --dir ~/.claude/skills' });if (input.harness !== undefined && !(HARNESSES as readonly string[]).includes(input.harness)) {throw new ResolverError('skill_resolve_invalid_input', `Unknown harness "${input.harness}".`, { suggestion: `Use one of: ${HARNESSES.join(', ')}.` });}@@ -124,14 +128,16 @@ function validateBuild(input: BuildInput): void {}async function readSource(input: BuildInput): Promise<SourceRead> {- if (input.dirs?.length) return readDirSources(input.dirs);+ if (input.claudePlugins !== undefined) return readClaudePluginSources(input.claudePlugins);+ if (input.fromJson === undefined && input.dirs?.length) return readDirSources(input.dirs);if (input.bundled) return readBundledSource();const text = input.fromJsonStdin ? input.fromJson! : (() => {- const b = readBounded(input.fromJson!, 8 * 1024 * 1024);- if (b === 'too_large') throw new ResolverError('skill_source_invalid', 'The JSON catalog is over 8 MB.', { suggestion: 'Pass at most 10,000 skills in at most 8 MB.' });+ const b = readBounded(input.fromJson!, JSON_INPUT_CAP_BYTES);+ if (b === 'too_large') throw new ResolverError('skill_source_invalid', 'The JSON catalog is over 64 MB.', { suggestion: 'Pass at most 10,000 skills in at most 64 MB; bodies past 4 KB are trimmed.' });return b.toString('utf8');})();- return readJsonSource(text);+ const json = readJsonSource(text);+ return input.dirs?.length ? mergeSkillFolders(json, readDirSources(input.dirs)) : json;}interface Prepared { records: SkillRecord[]; skipped: SkippedSkill[]; source: SourceRead; routing: BuildReceipt['catalog']['routing']; catalog_hash: string }@@ -195,7 +201,8 @@ export async function buildSkillIndex(input: BuildInput, opts: { home?: string;name: input.catalog, catalog_hash: p.catalog_hash,source: p.source.kind === 'dir' ? { kind: 'dir', dirs: input.dirs!.map(d => resolve(d)) }: p.source.kind === 'bundled' ? { kind: 'bundled', bundled_skills: p.records.length }- : { kind: 'json', snapshot: 'source.json', ...(input.fromJsonStdin ? { stdin: true } : { file: resolve(input.fromJson!) }) },+ : p.source.kind === 'claude_plugins' ? { kind: 'claude_plugins', claude_dir: resolve(input.claudePlugins!) }+ : { kind: 'json', snapshot: 'source.json', ...(input.fromJsonStdin ? { stdin: true } : { file: resolve(input.fromJson!) }), ...(input.dirs?.length ? { dirs: input.dirs.map(d => resolve(d)) } : {}) },fingerprint_sha256: p.source.fingerprint ? sha(JSON.stringify(p.source.fingerprint)) : null,skill_count: p.records.length, skipped: p.skipped, scope, hints: scope === 'project' ? 'names_only' : 'shown', harness: input.harness ?? null, routing: p.routing,},@@ -271,7 +278,7 @@ export async function catalogStatus(name: string, opts: { home?: string } = {}):if (!staleReason) {try {const src = r.catalog.source;- const input: BuildInput = { catalog: name, ...(src.kind === 'dir' ? { dirs: src.dirs } : src.kind === 'bundled' ? { bundled: true } : { fromJson: join(dir, 'source.json') }), ...(r.catalog.routing ? { routing: r.catalog.routing.file } : {}), scope: r.catalog.scope };+ const input: BuildInput = { catalog: name, ...(src.kind === 'dir' ? { dirs: src.dirs } : src.kind === 'bundled' ? { bundled: true } : src.kind === 'claude_plugins' ? { claudePlugins: src.claude_dir } : { fromJson: join(dir, 'source.json'), ...(src.dirs?.length ? { dirs: src.dirs } : {}) }), ...(r.catalog.routing ? { routing: r.catalog.routing.file } : {}), scope: r.catalog.scope };const p = await prepare(input);if (p.catalog_hash !== r.catalog.catalog_hash) staleReason = src.kind === 'json' ? 'snapshot_changed' : 'source_changed';} catch (e) {diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex ee79efce6d..125881c450 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -193,7 +193,7 @@ function loadCatalog(home: string, name: string, now: number, autoRebuild: booleif (again && again.index.size === size) receipt = again; else stale = 'publishing';}if (!stale && receipt.gbrain_version !== VERSION) stale = 'gbrain_version_changed';- if (!stale && receipt.catalog.source.kind === 'dir') {+ if (!stale && (receipt.catalog.source.kind === 'dir' || receipt.catalog.source.kind === 'claude_plugins')) {const stamp = catalogFile(home, name, 'stat-check');let last: { verdict: 'fresh' | 'stale'; cursor: number } | null = null;let age = Infinity;diff --git a/src/core/skills/resolver/sources.ts b/src/core/skills/resolver/sources.tsindex 339faca2b1..239833b64a 100644--- a/src/core/skills/resolver/sources.ts+++ b/src/core/skills/resolver/sources.ts@@ -5,6 +5,21 @@* list of normalized skill records, the skills it skipped (with a reason)* and, for directories, a stat fingerprint the turn path compares cheaply.*+ * JSON: an adapter's list ([{id, name, ...}] or {skills: [...]}) or, as is,+ * OpenClaw's `skills list --json` document ({workspaceDir, managedSkillsDir,+ * skills: [{name, description, eligible, disabled, ...}]}), whose entries+ * have no id: the name is the id and a skill OpenClaw would not show the+ * model is skipped as ineligible. Bodies are trimmed to the 4 KB the ranker+ * reads, so a list of up to JSON_INPUT_CAP_BYTES is accepted; a snapshot over+ * JSON_SOURCE_CAP_BYTES is kept trimmed. With --dir beside it, the JSON list+ * stays the catalog and each entry takes its body, path and triggers from the+ * folder skill of the same name (mergeSkillFolders).+ *+ * Claude Code plugins: the enabled user-scope plugins in+ * <claude dir>/plugins/installed_plugins.json (enabledPlugins in+ * <claude dir>/settings.json), each install path read as a --dir root whose+ * skills are namespaced `<plugin>:<skill>` (readClaudePluginSources).+ ** Directories: only real paths are read. A symlink whose target leaves the* root is skipped (symlink_outside_root); loops are cut by real path. Skills* are visited breadth-first (shallower first, then path order) and the --dir@@ -25,6 +40,8 @@ export const MAX_SKILLS = 10_000;export const MAX_DIRS_VISITED = 100_000;export const MAX_DEPTH = 12;export const JSON_SOURCE_CAP_BYTES = 8 * 1024 * 1024;+export const JSON_INPUT_CAP_BYTES = 64 * 1024 * 1024;+const CLAUDE_PLUGIN_FILE_CAP_BYTES = 4 * 1024 * 1024;export const ROUTING_FILE_CAP_BYTES = 1024 * 1024;const MAX_ID = 256;const MAX_NAME = 256;@@ -51,7 +68,7 @@ export interface SkippedSkill { reason: SkipReason; id?: string; path?: string;export interface DirFingerprint { dirs: [string, number][]; files: [string, number, number][] }export interface SourceRead {- kind: 'dir' | 'bundled' | 'json';+ kind: 'dir' | 'bundled' | 'json' | 'claude_plugins';skills: SkillRecord[];skipped: SkippedSkill[];fingerprint?: DirFingerprint;@@ -69,6 +86,8 @@ function tooLarge(what: string): ResolverError {return new ResolverError('skill_catalog_too_large', `The catalog is over its bound: ${what}.`, { suggestion: `Index at most ${MAX_SKILLS.toLocaleString('en-US')} skills per catalog; split the source into several catalogs.` });}+const PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;+function pluginNamespace(skillDir: string, root: string, cache: Map<string, string | null>): string | undefined {for (let d = skillDir; d === root || d.startsWith(root + sep); d = dirname(d)) {let ns = cache.get(d);@@ -79,7 +98,7 @@ function pluginNamespace(skillDir: string, root: string, cache: Map<string, stritry {const b = readBounded(manifest, 64 * 1024);const name = b === 'too_large' ? undefined : (JSON.parse(b.toString('utf8')) as { name?: unknown }).name;- if (typeof name === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name)) ns = name;+ if (typeof name === 'string' && PLUGIN_NAME.test(name)) ns = name;} catch { /* not a plugin manifest */ }}cache.set(d, ns);@@ -90,8 +109,8 @@ function pluginNamespace(skillDir: string, root: string, cache: Map<string, strireturn undefined;}-/** Read --dir sources in precedence order. */-export function readDirSources(dirs: readonly string[]): SourceRead {+/** Read --dir sources in precedence order; rootNamespaces[i] names dirs[i]'s skills when no plugin manifest does. */+export function readDirSources(dirs: readonly string[], rootNamespaces: readonly (string | undefined)[] = []): SourceRead {const skills: SkillRecord[] = [];const skipped: SkippedSkill[] = [];const fp: DirFingerprint = { dirs: [], files: [] };@@ -99,7 +118,7 @@ export function readDirSources(dirs: readonly string[]): SourceRead {const nsCache = new Map<string, string | null>();let visited = 0;let files = 0;- for (const given of dirs) {+ for (const [di, given] of dirs.entries()) {let root: string;try {root = realpathSync(given);@@ -144,7 +163,7 @@ export function readDirSources(dirs: readonly string[]): SourceRead {const doc = parseSkillDoc(text);const skillDir = dirname(real);const name0 = cut(doc.name ?? basename(skillDir), MAX_NAME);- const ns = pluginNamespace(skillDir, root, nsCache);+ const ns = pluginNamespace(skillDir, root, nsCache) ?? rootNamespaces[di];const id = cut(ns ? `${ns}:${name0}` : name0, MAX_ID);if (!doc.modelInvocable) { skipped.push({ reason: 'not_model_invocable', id, path: real }); continue; }if (!doc.eligible) { skipped.push({ reason: 'ineligible', id, path: real }); continue; }@@ -175,32 +194,51 @@ export async function readBundledSource(): Promise<SourceRead> {}function invalid(message: string): ResolverError {- return new ResolverError('skill_source_invalid', message, { suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects (at most 10,000 entries, 8 MB).' });+ return new ResolverError('skill_source_invalid', message, { suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects, or OpenClaw\'s skills list --json output as is (at most 10,000 entries, 64 MB).' });}const optStr = (v: unknown) => v === undefined || typeof v === 'string';const optStrList = (v: unknown) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === 'string'));+const optBool = (v: unknown) => v === undefined || typeof v === 'boolean';+const OPENCLAW_HIDDEN = ['disabled', 'blockedByAllowlist', 'blockedByAgentFilter'] as const;-/** An adapter's catalog snapshot: `[{id, name, description, triggers?, routing?, body?, path?, eligible?}]` (or `{skills: [...]}`). */+/** The first field that makes entry `o` invalid, or null. OpenClaw entries carry no id: the name stands in. */+function badField(o: Record<string, unknown>, openclaw: boolean): string | null {+ if (!openclaw && (typeof o.id !== 'string' || !o.id.trim() || o.id.length > MAX_ID)) return `id (a required string of at most ${MAX_ID} characters)`;+ if (typeof o.name !== 'string' || !o.name.trim() || (openclaw && o.name.length > MAX_ID)) return 'name (a required string)';+ for (const f of ['description', 'body', 'path'] as const) if (!optStr(o[f])) return `${f} (a string)`;+ for (const f of ['triggers', 'routing'] as const) if (!optStrList(o[f])) return `${f} (an array of strings)`;+ for (const f of ['eligible', ...(openclaw ? [...OPENCLAW_HIDDEN, 'modelVisible'] : [])]) if (!optBool(o[f])) return `${f} (a boolean)`;+ return null;+}++/**+ * An adapter's catalog snapshot: `[{id, name, description, triggers?, routing?, body?, path?, eligible?}]`,+ * `{skills: [...]}`, or OpenClaw's `skills list --json` document.+ */export function readJsonSource(text: string): SourceRead {- if (Buffer.byteLength(text, 'utf8') > JSON_SOURCE_CAP_BYTES) throw invalid('The JSON catalog is over 8 MB.');+ const bytes = Buffer.byteLength(text, 'utf8');+ if (bytes > JSON_INPUT_CAP_BYTES) throw invalid('The JSON catalog is over 64 MB.');let parsed: unknown;try { parsed = JSON.parse(text); } catch { throw invalid('The JSON catalog does not parse.'); }- const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === 'object' && Array.isArray((parsed as { skills?: unknown }).skills) ? (parsed as { skills: unknown[] }).skills : null;+ const doc = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;+ const list = Array.isArray(parsed) ? parsed : doc && Array.isArray(doc.skills) ? doc.skills as unknown[] : null;if (!list) throw invalid('The JSON catalog must be an array of skills (or {"skills": [...]}).');if (list.length > MAX_SKILLS) throw invalid(`The JSON catalog has ${list.length} skills; the bound is ${MAX_SKILLS}.`);+ const openclaw = !!doc && ('workspaceDir' in doc || 'managedSkillsDir' in doc);const skills: SkillRecord[] = [];const skipped: SkippedSkill[] = [];const seen = new Map<string, string>();list.forEach((e, i) => {const o = e as Record<string, unknown>;- if (!o || typeof o !== 'object' || typeof o.id !== 'string' || !o.id.trim() || o.id.length > MAX_ID || typeof o.name !== 'string' || !o.name.trim()- || !optStr(o.description) || !optStr(o.body) || !optStr(o.path) || !optStrList(o.triggers) || !optStrList(o.routing)- || (o.eligible !== undefined && typeof o.eligible !== 'boolean')) {- throw invalid(`Entry ${i} is not a valid skill: id and name are required strings (id at most ${MAX_ID} characters); description, body and path are strings; triggers and routing are string arrays; eligible is a boolean.`);+ const bad = o && typeof o === 'object' && !Array.isArray(o) ? badField(o, openclaw) : 'the entry (an object)';+ if (bad) {+ const named = o && typeof o === 'object' && typeof o.name === 'string' ? ` (${cut(cleanText(o.name), 64)})` : '';+ const hint = !openclaw && o && typeof o === 'object' && o.id === undefined && typeof o.name === 'string' ? ' OpenClaw\'s skills list --json output is accepted as is, with its workspaceDir and managedSkillsDir.' : '';+ throw invalid(`Entry ${i}${named} is not a valid skill: ${bad} is wrong or missing.${hint}`);}- const id = o.id.trim();- if (o.eligible === false) { skipped.push({ reason: 'ineligible', id }); return; }+ const id = (openclaw ? o.name as string : o.id as string).trim();+ if (o.eligible === false || (openclaw && (OPENCLAW_HIDDEN.some(f => o[f] === true) || o.modelVisible === false))) { skipped.push({ reason: 'ineligible', id }); return; }if (seen.has(id)) { skipped.push({ reason: 'duplicate_id', id, kept: id }); return; }seen.set(id, id);skills.push({ id, name: cut(cleanText(o.name), MAX_NAME), description: cut(cleanText(o.description ?? ''), MAX_DESCRIPTION),@@ -208,7 +246,80 @@ export function readJsonSource(text: string): SourceRead {routing: ((o.routing as string[] | undefined) ?? []).map(cleanText).filter(Boolean).slice(0, MAX_ROUTING_ROWS),body: typeof o.body === 'string' ? boundBody(o.body) : '', ...(typeof o.path === 'string' && o.path ? { path: o.path } : {}) });});- return { kind: 'json', skills, skipped, snapshot: text };+ if (bytes <= JSON_SOURCE_CAP_BYTES) return { kind: 'json', skills, skipped, snapshot: text };+ for (const e of list) { const o = e as Record<string, unknown>; if (typeof o.body === 'string') o.body = boundBody(o.body); }+ return { kind: 'json', skills, skipped, snapshot: JSON.stringify(parsed) };+}++/**+ * Fill a JSON list's skills from SKILL.md folders, matched by name (or the+ * skill's directory name): the JSON list stays the catalog, and a folder+ * skill supplies the body, path and triggers the entry lacks. Folder skills+ * the list does not name are left out.+ */+export function mergeSkillFolders(json: SourceRead, folders: SourceRead): SourceRead {+ const byName = new Map<string, SkillRecord>();+ for (const s of folders.skills) {+ if (!byName.has(s.name)) byName.set(s.name, s);+ const dirName = s.path ? basename(dirname(s.path)) : undefined;+ if (dirName && !byName.has(dirName)) byName.set(dirName, s);+ }+ const skills = json.skills.map((s) => {+ const f = byName.get(s.name) ?? byName.get(s.id);+ if (!f) return s;+ return { ...s, description: s.description || f.description, ...(s.whenToUse ?? f.whenToUse ? { whenToUse: s.whenToUse ?? f.whenToUse } : {}),+ triggers: s.triggers.length ? s.triggers : f.triggers, body: s.body || f.body, ...(s.path ?? f.path ? { path: s.path ?? f.path } : {}) };+ });+ return { ...json, skills };+}++function readSmallJson(path: string): unknown {+ try {+ const b = readBounded(path, CLAUDE_PLUGIN_FILE_CAP_BYTES);+ return b === 'too_large' ? null : JSON.parse(b.toString('utf8'));+ } catch { return null; }+}++/**+ * Claude Code's enabled user-scope plugins as SKILL.md roots: `{plugin}@{marketplace}` ids+ * that settings.json's enabledPlugins sets true and installed_plugins.json+ * (version 2: a list of installs per id; version 1: one install) records+ * with an existing installPath. A plugin's skills are namespaced by its+ * manifest name, else by the id's plugin part.+ */+export function claudePluginRoots(claudeDir: string): { roots: string[]; namespaces: (string | undefined)[]; files: string[] } {+ const settingsPath = join(claudeDir, 'settings.json');+ const installedPath = join(claudeDir, 'plugins', 'installed_plugins.json');+ const enabled = (readSmallJson(settingsPath) as { enabledPlugins?: Record<string, unknown> } | null)?.enabledPlugins;+ const installed = (readSmallJson(installedPath) as { plugins?: Record<string, unknown> } | null)?.plugins;+ const files = [settingsPath, installedPath].filter(f => existsSync(f));+ const roots: string[] = [];+ const namespaces: (string | undefined)[] = [];+ if (!enabled || typeof enabled !== 'object' || !installed || typeof installed !== 'object') return { roots, namespaces, files };+ for (const id of Object.keys(installed).sort()) {+ if (!Object.hasOwn(enabled, id) || enabled[id] !== true) continue;+ const raw = installed[id];+ const installs = (Array.isArray(raw) ? raw : [raw]) as { scope?: unknown; installPath?: unknown }[];+ const install = installs.find(x => x && typeof x === 'object' && (x.scope === undefined || x.scope === 'user') && typeof x.installPath === 'string' && x.installPath.startsWith('/'));+ if (!install) continue;+ const path = install.installPath as string;+ try { if (!statSync(path).isDirectory()) continue; } catch { continue; }+ const plugin = id.split('@')[0]!;+ roots.push(path);+ namespaces.push(PLUGIN_NAME.test(plugin) ? plugin : undefined);+ }+ return { roots, namespaces, files };+}++/** The skills of Claude Code's enabled user-scope plugins; the fingerprint also covers the two plugin records. */+export function readClaudePluginSources(claudeDir: string): SourceRead {+ const { roots, namespaces, files } = claudePluginRoots(claudeDir);+ const read = roots.length ? readDirSources(roots, namespaces) : { kind: 'dir' as const, skills: [], skipped: [], fingerprint: { dirs: [], files: [] } };+ const fp = read.fingerprint!;+ const pluginsDir = join(claudeDir, 'plugins');+ try { fp.dirs.unshift([pluginsDir, statSync(pluginsDir).mtimeMs]); } catch { /* no plugins yet */ }+ for (const f of files) { try { const st = statSync(f); fp.files.unshift([f, st.size, st.mtimeMs]); } catch { /* raced away */ } }+ return { ...read, kind: 'claude_plugins' };}/** Attach a routing file's rows to skills by name (or directory name); returns rows that matched no skill. */diff --git a/test/skill-resolver-catalogs.test.ts b/test/skill-resolver-catalogs.test.tsnew file mode 100644index 0000000000..f5a81d0217--- /dev/null+++ b/test/skill-resolver-catalogs.test.ts@@ -0,0 +1,191 @@+/**+ * GBRA-399 core PR 2: catalog sources beyond plain SKILL.md directories.+ *+ * 1. Protects: OpenClaw's `skills list --json` document builds as is (the+ * name is the id; a skill OpenClaw hides from the model is skipped as+ * ineligible); a JSON list with --dir folders takes each skill's body,+ * path and triggers from the folder skill of the same name and adds no+ * folder-only skill; an invalid entry names itself and the field; the+ * enabled user-scope Claude Code plugins index as <plugin>:<skill>, and+ * enabling or installing one makes the catalog stale; setup claude-code+ * builds claude-code-plugins (also with no ~/.claude/skills) and off+ * removes it.+ * 2. Fails when: the OpenClaw shape refuses again, hidden skills index,+ * folder skills leak into a JSON catalog, a disabled, project-scope or+ * missing plugin indexes, or setup leaves the plugin catalog behind.+ */+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { buildSkillIndex, catalogStatus, resolveSkills, ResolverError } from '../src/core/skills/resolver/index.ts';++setDefaultTimeout(60_000);+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });+const tmp = (p = 'skres-cat-') => { const d = mkdtempSync(join(tmpdir(), p)); dirs.push(d); return d; };+function skill(root: string, rel: string, name: string, description: string, body = 'Steps.'): string {+ const d = join(root, rel);+ mkdirSync(d, { recursive: true });+ writeFileSync(join(d, 'SKILL.md'), `---\nname: ${name}\ndescription: ${JSON.stringify(description)}\n---\n${body}\n`);+ return join(d, 'SKILL.md');+}+async function codeAndMessage(p: Promise<unknown>): Promise<[string, string]> {+ try { await p; return ['resolved', '']; } catch (e) { return e instanceof ResolverError ? [e.code, e.message] : ['other', (e as Error).message]; }+}+const OPENCLAW = (skills: Record<string, unknown>[]) => JSON.stringify({ workspaceDir: '/work/acme-example', managedSkillsDir: '/work/acme-example/.openclaw/skills', skills });++describe('OpenClaw skills list --json', () => {+ test('builds as is: the name is the id, and a skill OpenClaw hides from the model is skipped as ineligible', async () => {+ const home = tmp();+ const rec = await buildSkillIndex({ catalog: 'oc', fromJson: OPENCLAW([+ { name: 'deploy-widget', description: 'Deploy the widget service', emoji: 'x', eligible: true, disabled: false, blockedByAllowlist: false, blockedByAgentFilter: false, modelVisible: true, source: 'managed', bundled: false },+ { name: 'off-eligible', description: 'a', eligible: false },+ { name: 'off-disabled', description: 'a', eligible: true, disabled: true },+ { name: 'off-allowlist', description: 'a', eligible: true, blockedByAllowlist: true },+ { name: 'off-agent', description: 'a', eligible: true, blockedByAgentFilter: true },+ { name: 'off-hidden', description: 'a', eligible: true, modelVisible: false },+ ]), fromJsonStdin: true }, { home });+ expect(rec.catalog.skill_count).toBe(1);+ expect(rec.catalog.skipped.map((s) => [s.id, s.reason]).sort()).toEqual([['off-agent', 'ineligible'], ['off-allowlist', 'ineligible'], ['off-disabled', 'ineligible'], ['off-eligible', 'ineligible'], ['off-hidden', 'ineligible']]);+ const t = await resolveSkills({ message: 'deploy the widget service', harness: 'openclaw' }, { home, catalogs: ['oc'] });+ expect(t.output.suggestions[0]?.id).toBe('deploy-widget');+ });++ test('with --dir folders: bodies, paths and triggers come from the folder skill of the same name; folder-only skills stay out', async () => {+ const home = tmp();+ const root = tmp('skres-oc-dir-');+ const path = skill(root, 'deploy-widget', 'deploy-widget', 'Deploy the widget service', 'Run the zebrafinch rollout.');+ skill(root, 'not-listed', 'not-listed', 'A skill OpenClaw did not list');+ const file = join(tmp(), 'skills.json');+ writeFileSync(file, OPENCLAW([{ name: 'deploy-widget', description: 'Deploy the widget service', eligible: true }, { name: 'no-folder', description: 'Listed without a folder', eligible: true }]));+ const rec = await buildSkillIndex({ catalog: 'oc', fromJson: file, dirs: [root], harness: 'openclaw' }, { home });+ expect(rec.catalog.skill_count).toBe(2);+ expect(rec.catalog.source).toMatchObject({ kind: 'json', dirs: [root] });+ expect(rec.build.rebuild_argv).toEqual(['gbrain', 'skills', 'index', 'build', '--catalog', 'oc', '--dir', root, '--from-json', file, '--harness', 'openclaw']);+ const t = await resolveSkills({ message: 'zebrafinch rollout' }, { home, catalogs: ['oc'] });+ expect(t.output.suggestions.map((s) => [s.id, s.path])).toEqual([['deploy-widget', path]]);+ expect((await resolveSkills({ message: 'not listed skill' }, { home, catalogs: ['oc'] })).output.suggestions.map((s) => s.id)).not.toContain('not-listed');+ expect((await catalogStatus('oc', { home })).fresh).toBe(true);+ });++ test('an invalid entry names itself and the field; an id-less plain list points at the OpenClaw shape', async () => {+ const home = tmp();+ const [code, msg] = await codeAndMessage(buildSkillIndex({ catalog: 'x', fromJson: JSON.stringify([{ id: 'a', name: 'alpha', triggers: 'deploy' }]), fromJsonStdin: true }, { home }));+ expect(code).toBe('skill_source_invalid');+ expect(msg).toContain('Entry 0 (alpha)');+ expect(msg).toContain('triggers (an array of strings)');+ const [code2, msg2] = await codeAndMessage(buildSkillIndex({ catalog: 'x', fromJson: JSON.stringify({ skills: [{ name: 'beta' }] }), fromJsonStdin: true }, { home }));+ expect(code2).toBe('skill_source_invalid');+ expect(msg2).toContain('id (a required string');+ expect(msg2).toContain('OpenClaw');+ });+});++/** A Claude config dir with plugins: acme (manifest name acme-tools, enabled), beta (no manifest, enabled), gamma (installed, disabled), delta (project scope). */+function claudeDir(): { dir: string; cache: string } {+ const dir = tmp('skres-claude-');+ const cache = join(dir, 'plugins', 'cache', 'market-a');+ const acme = join(cache, 'acme', '1.0.0');+ mkdirSync(join(acme, '.claude-plugin'), { recursive: true });+ writeFileSync(join(acme, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: 'acme-tools' }));+ skill(join(acme, 'skills'), 'deploy', 'deploy', 'Deploy a service with the acme rollout');+ skill(join(cache, 'beta', '2.0.0', 'skills'), 'notes', 'notes', 'Take meeting notes');+ skill(join(cache, 'gamma', '1.0.0', 'skills'), 'gamma-skill', 'gamma-skill', 'A disabled plugin skill');+ skill(join(cache, 'delta', '1.0.0', 'skills'), 'delta-skill', 'delta-skill', 'A project plugin skill');+ writeFileSync(join(dir, 'plugins', 'installed_plugins.json'), JSON.stringify({ version: 2, plugins: {+ 'acme@market-a': [{ scope: 'user', installPath: acme, version: '1.0.0' }],+ 'beta@market-a': [{ scope: 'user', installPath: join(cache, 'beta', '2.0.0'), version: '2.0.0' }],+ 'gamma@market-a': [{ scope: 'user', installPath: join(cache, 'gamma', '1.0.0'), version: '1.0.0' }],+ 'delta@market-a': [{ scope: 'project', installPath: join(cache, 'delta', '1.0.0'), version: '1.0.0', projectPath: '/work/acme-example' }],+ 'gone@market-a': [{ scope: 'user', installPath: join(cache, 'gone', '1.0.0'), version: '1.0.0' }],+ } }));+ writeFileSync(join(dir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'acme@market-a': true, 'beta@market-a': true, 'gamma@market-a': false, 'delta@market-a': true, 'gone@market-a': true } }));+ return { dir, cache };+}++describe('Claude Code plugin skills (--claude-plugins)', () => {+ test('enabled user-scope plugins index as <plugin>:<skill>; disabled, project-scope and missing installs do not', async () => {+ const home = tmp();+ const { dir } = claudeDir();+ const rec = await buildSkillIndex({ catalog: 'claude-code-plugins', claudePlugins: dir, harness: 'claude-code' }, { home });+ expect(rec.catalog.source).toEqual({ kind: 'claude_plugins', claude_dir: dir });+ expect(rec.build.rebuild_argv).toEqual(['gbrain', 'skills', 'index', 'build', '--catalog', 'claude-code-plugins', '--claude-plugins', dir, '--harness', 'claude-code']);+ const ids = (await resolveSkills({ message: 'deploy a service with the acme rollout, take meeting notes', top_k: 8 }, { home, catalogs: ['claude-code-plugins'] })).output.suggestions.map((s) => s.id).sort();+ expect(ids).toEqual(['acme-tools:deploy', 'beta:notes']);+ expect(rec.catalog.skill_count).toBe(2);+ expect((await catalogStatus('claude-code-plugins', { home })).fresh).toBe(true);+ });++ test('enabling a plugin makes the catalog stale, and the recorded rebuild picks it up', async () => {+ const home = tmp();+ const { dir } = claudeDir();+ await buildSkillIndex({ catalog: 'claude-code-plugins', claudePlugins: dir }, { home });+ await new Promise((r) => setTimeout(r, 30));+ writeFileSync(join(dir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'acme@market-a': true, 'beta@market-a': true, 'gamma@market-a': true } }));+ const s = await catalogStatus('claude-code-plugins', { home });+ expect(s.fresh).toBe(false);+ expect((await resolveSkills({ message: 'disabled plugin skill' }, { home, catalogs: ['claude-code-plugins'] })).output.meta.index_stale).toBe(true);+ const again = await buildSkillIndex({ catalog: 'claude-code-plugins', claudePlugins: s.receipt!.source.claude_dir! }, { home });+ expect(again.catalog.skill_count).toBe(3);+ });++ test('no plugin records: an empty catalog, no error', async () => {+ const home = tmp();+ const rec = await buildSkillIndex({ catalog: 'p', claudePlugins: tmp('skres-claude-empty-') }, { home });+ expect(rec.catalog.skill_count).toBe(0);+ });+});++describe('setup claude-code --skill-loading resolve with plugins', () => {+ function box() {+ const root = tmp('gbrain-skres-plugins-setup-');+ const home = join(root, 'home'), project = join(root, 'project');+ mkdirSync(project, { recursive: true });+ mkdirSync(join(root, 'bin'), { recursive: true });+ const bin = join(root, 'bin', 'gbrain');+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ const claude = join(home, '.claude');+ mkdirSync(claude, { recursive: true });+ const env = { HOME: home, GBRAIN_HOME: home, PATH: '/usr/bin:/bin', CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,+ GBRAIN_SKILL_LOADING: undefined, GBRAIN_HOOK_LANE: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined };+ return { home, project, bin, claude, env };+ }+ const index = (home: string) => { const d = join(home, '.gbrain', 'skill-index'); return existsSync(d) ? readdirSync(d).filter((n) => !n.startsWith('.') && n !== 'logs' && n !== 'sessions').sort() : []; };+ function plugins(claude: string) {+ const p = join(claude, 'plugins', 'cache', 'market-a', 'acme', '1.0.0');+ mkdirSync(join(p, '.claude-plugin'), { recursive: true });+ writeFileSync(join(p, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: 'acme-tools' }));+ skill(join(p, 'skills'), 'deploy', 'deploy', 'Deploy a service with the acme rollout');+ writeFileSync(join(claude, 'plugins', 'installed_plugins.json'), JSON.stringify({ version: 2, plugins: { 'acme@market-a': [{ scope: 'user', installPath: p }] } }));+ writeFileSync(join(claude, 'settings.json'), JSON.stringify({ enabledPlugins: { 'acme@market-a': true } }));+ }+ const run = (b: ReturnType<typeof box>, extra: string[]) => runCli(['setup', 'claude-code', '--instructions-only', '--gbrain-bin', b.bin, ...extra], { env: b.env, cwd: b.project });++ test('plugins only (no ~/.claude/skills): turns on with claude-code-plugins; off removes it', async () => {+ const b = box();+ plugins(b.claude);+ const on = await run(b, ['--skill-loading', 'resolve']);+ expect(on.exitCode, on.stderr).toBe(0);+ expect(index(b.home)).toEqual(['claude-code-plugins']);+ expect(on.stdout).toContain('skill resolver: on; 1 skills; fresh');+ const again = await run(b, ['--skill-loading', 'resolve']);+ expect(again.stdout).toContain('keep');+ const off = await run(b, ['--skill-loading', 'off']);+ expect(off.exitCode, off.stderr).toBe(0);+ expect(index(b.home)).toEqual([]);+ });++ test('user skills and plugins: both catalogs', async () => {+ const b = box();+ plugins(b.claude);+ skill(join(b.claude, 'skills'), 'notes', 'notes', 'Take meeting notes');+ const on = await run(b, ['--skill-loading', 'resolve']);+ expect(on.exitCode, on.stderr).toBe(0);+ expect(index(b.home)).toEqual(['claude-code-plugins', 'claude-code-user']);+ expect(on.stdout).toContain('skill resolver: on; 2 skills; fresh');+ });+});diff --git a/test/skill-resolver-contract.test.ts b/test/skill-resolver-contract.test.tsindex ce05e2411d..5af5806c64 100644--- a/test/skill-resolver-contract.test.ts+++ b/test/skill-resolver-contract.test.ts@@ -48,7 +48,12 @@ describe('turn input', () => {describe('build input (the --from-json catalog)', () => {test('accepted catalogs validate; refused ones do not', () => {- for (const g of [SKILLS, { skills: SKILLS }, []]) { expect(validate(CATALOG, g)).toEqual([]); expect(() => readJsonSource(JSON.stringify(g))).not.toThrow(); }+ const openclaw = { workspaceDir: '/work/acme-example', managedSkillsDir: '/work/acme-example/skills', skills: [{ name: 'deploy', description: 'Ship it', eligible: true, disabled: false, modelVisible: true, emoji: 'x' }] };+ for (const g of [SKILLS, { skills: SKILLS }, [], openclaw]) { expect(validate(CATALOG, g)).toEqual([]); expect(() => readJsonSource(JSON.stringify(g))).not.toThrow(); }+ for (const b of [{ workspaceDir: '/w', skills: [{ description: 'no name' }] }, { workspaceDir: '/w', skills: [{ name: 'a', disabled: 'yes' }] }]) {+ expect(validate(CATALOG, b).length).toBeGreaterThan(0);+ expect(() => readJsonSource(JSON.stringify(b))).toThrow();+ }for (const b of [[{ id: 'a' }], [{ id: '', name: 'b' }], [{ id: 'a', name: 'b', triggers: 'x' }], [{ id: 'a', name: 'b', eligible: 'no' }], { list: [] }, 'x']) {expect(validate(CATALOG, b).length).toBeGreaterThan(0);expect(() => readJsonSource(JSON.stringify(b))).toThrow();@@ -67,7 +72,10 @@ describe('turn output and build receipt', () => {writeFileSync(join(root, 'lint', 'SKILL.md'), '---\nname: lint\ndescription: Run the linters before a deploy\n---\nSteps.\n');const r2 = await buildSkillIndex({ catalog: 'two', dirs: [root], scope: 'project', harness: 'codex' }, { home });const r3 = await buildSkillIndex({ catalog: 'three', fromJson: JSON.stringify(SKILLS), fromJsonStdin: true }, { home });- for (const r of [r1, r2, r3]) expect(validate(RECEIPT, JSON.parse(JSON.stringify(r)))).toEqual([]);+ const r4 = await buildSkillIndex({ catalog: 'four', fromJson: f, dirs: [root] }, { home });+ mkdirSync(join(root, '..', 'claude', 'plugins'), { recursive: true });+ const r5 = await buildSkillIndex({ catalog: 'five', claudePlugins: join(root, '..', 'claude') }, { home });+ for (const r of [r1, r2, r3, r4, r5]) expect(validate(RECEIPT, JSON.parse(JSON.stringify(r)))).toEqual([]);const results = [await resolveSkills({ message: 'deploy the service', session_id: 's', harness: 'codex' }, { home, catalogs: ['one'] }),await resolveSkills({ message: 'thanks' }, { home, catalogs: ['one'] }),diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.tsindex 77588a4f36..04b996d9e6 100644--- a/test/skill-resolver.test.ts+++ b/test/skill-resolver.test.ts@@ -541,17 +541,31 @@ describe('catalog sources and bounds', () => {}});- test('bounds: 10,000 skills build, 10,001 refuse; over 8 MB refuses; the body is capped at 4 KB', async () => {+ test('bounds: 10,000 skills build, 10,001 refuse; over 64 MB refuses; the body is capped at 4 KB', async () => {const home = tmp();const many = Array.from({ length: 10_000 }, (_, i) => ({ id: `s${i}`, name: `skill-${i}`, description: `${word(i, 9)} task` }));const rec = await buildSkillIndex({ catalog: 'big', fromJson: JSON.stringify(many), fromJsonStdin: true }, { home });expect(rec.catalog.skill_count).toBe(10_000);expect(await codeOf(buildSkillIndex({ catalog: 'big2', fromJson: JSON.stringify([...many, { id: 'one-more', name: 'x' }]), fromJsonStdin: true }, { home }))).toBe('skill_source_invalid');- expect(await codeOf(buildSkillIndex({ catalog: 'huge', fromJson: JSON.stringify([{ id: 'a', name: 'a', description: 'x'.repeat(9 * 1024 * 1024) }]), fromJsonStdin: true }, { home }))).toBe('skill_source_invalid');+ expect(await codeOf(buildSkillIndex({ catalog: 'huge', fromJson: JSON.stringify([{ id: 'a', name: 'a', description: 'x'.repeat(65 * 1024 * 1024) }]), fromJsonStdin: true }, { home }))).toBe('skill_source_invalid');await jsonCatalog(home, 'body', [{ id: 'b', name: 'b', description: 'd', body: `${'filler '.repeat(700)} zebrafinch` }]);expect((await resolveSkills({ message: 'zebrafinch' }, { home, catalogs: ['body'] })).output.no_skill_reason).toBe('no_match');});+ test('a JSON catalog over 8 MB of full bodies builds: bodies are trimmed to 4 KB, the snapshot is kept trimmed and stays fresh', async () => {+ const home = tmp();+ const full = Array.from({ length: 300 }, (_, i) => ({ id: `s${i}`, name: `skill-${i}`, description: `${word(i, 9)} task`, body: `${i === 7 ? 'zebrafinch ' : ''}${'filler text '.repeat(3000)}` }));+ const text = JSON.stringify(full);+ expect(Buffer.byteLength(text)).toBeGreaterThan(8 * 1024 * 1024);+ const rec = await buildSkillIndex({ catalog: 'full', fromJson: text, fromJsonStdin: true }, { home });+ expect(rec.catalog.skill_count).toBe(300);+ const snap = readFileSync(join(home, 'skill-index', 'full', 'source.json'), 'utf8');+ expect(Buffer.byteLength(snap)).toBeLessThan(2 * 1024 * 1024);+ expect((JSON.parse(snap) as { body: string }[])[0]!.body.length).toBeLessThanOrEqual(4096);+ expect((await catalogStatus('full', { home })).fresh).toBe(true);+ expect((await resolveSkills({ message: 'zebrafinch' }, { home, catalogs: ['full'] })).output.suggestions[0]?.id).toBe('s7');+ });+test('a SKILL.md over 64 KB is skipped as unreadable, not read whole', async () => {const home = tmp();const root = tmp('skres-dir-');