Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver setup: keep extra skill directories from skills.resolver.per_harness.<harness>.dirs
garrytanf87a2f34a0fa
diff --git a/src/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.tsindex 4a1d44da94..8bf7a16c48 100644--- a/src/core/setup/skill-resolver-config.ts+++ b/src/core/setup/skill-resolver-config.ts@@ -7,7 +7,7 @@* skills.resolver.session_token_budget, skills.resolver.auto_rebuild* (PR A's settings, src/core/skills/resolver/config.ts)* skills.resolver.lane_payload_chars the hook lane's payload budget (500..10000, default 4000)- * skills.resolver.top_k, min_match, top_gate, pinned, per_harness.<harness>.{top_k,min_match,top_gate}+ * skills.resolver.top_k, min_match, top_gate, pinned, per_harness.<harness>.{top_k,min_match,top_gate,dirs}* the hook lane's turn settings (src/core/skills/resolver/config.ts)** A missing file is created with only these keys: no engine, no database, so@@ -20,7 +20,7 @@ import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs';import { join } from 'node:path';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';import { setCliExitVerdict } from '../cli-force-exit.ts';-import { laneTurnSettings, validateMinMatch, validatePinned, validateSessionTokenBudget, validateTopGate, validateTopK } from '../skills/resolver/config.ts';+import { laneTurnSettings, validateMinMatch, validatePinned, validateSessionTokenBudget, validateSkillDirs, validateTopGate, validateTopK } from '../skills/resolver/config.ts';const CONFIG_CAP_BYTES = 1024 * 1024;const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);@@ -48,7 +48,7 @@ export function readResolverConfig(home: string): ResolverConfigRead {}}-function resolverSection(doc: Record<string, unknown>): Record<string, unknown> {+export function resolverSection(doc: Record<string, unknown>): Record<string, unknown> {const r = (doc.skills as { resolver?: unknown } | undefined)?.resolver;return r && typeof r === 'object' && !Array.isArray(r) ? r as Record<string, unknown> : {};}@@ -89,8 +89,8 @@ export function setResolverHarness(read: Exclude<ResolverConfigRead, { state: 'uexport const SKILL_RESOLVER_KEY_PREFIX = 'skills.resolver.';/** The leaves `gbrain config set|unset|get` accepts (harnesses is setup's: --skill-loading resolve|off). */-export const SKILL_RESOLVER_CONFIG_LEAVES = ['enabled', 'session_token_budget', 'auto_rebuild', 'lane_payload_chars', 'top_k', 'min_match', 'top_gate', 'pinned', 'per_harness.<harness>.top_k', 'per_harness.<harness>.min_match', 'per_harness.<harness>.top_gate'] as const;-const PER_HARNESS_LEAF = /^per_harness\.([a-z-]+)\.(top_k|min_match|top_gate)$/;+export const SKILL_RESOLVER_CONFIG_LEAVES = ['enabled', 'session_token_budget', 'auto_rebuild', 'lane_payload_chars', 'top_k', 'min_match', 'top_gate', 'pinned', 'per_harness.<harness>.top_k', 'per_harness.<harness>.min_match', 'per_harness.<harness>.top_gate', 'per_harness.<harness>.dirs'] as const;+const PER_HARNESS_LEAF = /^per_harness\.([a-z-]+)\.(top_k|min_match|top_gate|dirs)$/;function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean | number | string | string[] } | { ok: false; error: string } {const turnKey = leaf.match(PER_HARNESS_LEAF)?.[2] ?? leaf;@@ -99,6 +99,7 @@ function parseLeafValue(leaf: string, value: string): { ok: true; value: booleanif (turnKey === 'top_k') return { ok: true, value: validateTopK(/^\d+$/.test(value) ? Number(value) : NaN, key) };if (turnKey === 'min_match') return { ok: true, value: validateMinMatch(value, key) };if (turnKey === 'top_gate') return { ok: true, value: validateTopGate(/^\d+(\.\d+)?$/.test(value) ? Number(value) : NaN, key) };+ if (turnKey === 'dirs') return { ok: true, value: validateSkillDirs(value.split(',').map(s => s.trim()).filter(Boolean), key) };if (leaf === 'pinned') return { ok: true, value: validatePinned(value.split(',').map(s => s.trim()).filter(Boolean), key) };} catch (e) { return { ok: false, error: (e as Error).message.slice(key.length + 1) }; }if (leaf === 'enabled' || leaf === 'auto_rebuild') {diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.tsindex a63e13bd81..c53b9d390b 100644--- a/src/core/setup/skill-resolver-setup.ts+++ b/src/core/setup/skill-resolver-setup.ts@@ -3,7 +3,8 @@* 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, for+ * ~/.claude/skills; Codex: ~/.agents/skills and CODEX_HOME/skills; plus any+ * skills.resolver.per_harness.<harness>.dirs that exist) 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).@@ -25,11 +26,12 @@ import { existsSync, rmSync } from 'node:fs';import { dirname, join } from 'node:path';import { claudeUserSkillsDir, codexConfigPath } from '../bootstrap/host-specs.ts';import { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex } from '../skills/resolver/build.ts';+import { configuredSkillDirs } from '../skills/resolver/config.ts';import { ResolverError } from '../skills/resolver/errors.ts';import { CLAUDE_PLUGINS_CATALOG, logsDir, sessionsDir, skillIndexRoot } from '../skills/resolver/paths.ts';import { resolveSkills } from '../skills/resolver/resolve.ts';import { claudePluginRoots, readDirSources } from '../skills/resolver/sources.ts';-import { readResolverConfig, resolverHarnesses, setResolverHarness } from './skill-resolver-config.ts';+import { readResolverConfig, resolverHarnesses, resolverSection, setResolverHarness } from './skill-resolver-config.ts';import { inspectSkillResolverHook, removeSkillResolverHook, syncSkillResolverHook, type ResolverHarness, type ResolverHookPaths } from './skill-resolver-hook.ts';export interface ResolverStep { step: 'catalog' | 'config' | 'hook' | 'state'; action: 'write' | 'keep' | 'remove' | 'skip'; detail: string }@@ -91,13 +93,15 @@ export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; gif (cfg.state === 'unreadable') return { ...out, error: { code: 'skill_resolver_config_unreadable', scanned: [], message: `${cfg.path} cannot be read (${cfg.why}), so setup did not touch it or anything else for the skill resolver.` } };if (!opts.gbrainBin.startsWith('/')) return { ...out, error: incomplete(null, 'no absolute gbrain binary was found for the hook (harnesses inherit no PATH); pass --gbrain-bin', 'Nothing was written.') };const catalog = userCatalog(harness);- const dirs = harnessSkillDirs(harness).filter((d) => existsSync(d));+ let wanted: string[];+ try { wanted = [...new Set([...harnessSkillDirs(harness), ...configuredSkillDirs(cfg.state === 'ok' ? resolverSection(cfg.doc) : {}, harness)])]; } catch (e) { return { ...out, error: incomplete(null, (e as Error).message.replace(/\.$/, ''), 'Nothing was written.') }; }+ const dirs = wanted.filter((d) => existsSync(d));const status = existsSync(join(skillIndexRoot(home), catalog, 'receipt.json')) ? await catalogStatus(catalog, { home }) : null;const 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);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.') };+ if (dirs.length === 0 && pluginRoots.length === 0) return { ...out, error: incomplete(wanted, 'no user-level skill directory exists', 'Nothing was written.') };const scanned = [...dirs, ...(pluginRoots.length ? [claudePluginsBase()] : [])];let skills = 0;diff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.tsindex 16b9e3b991..3de08910f5 100644--- a/src/core/skills/resolver/config.ts+++ b/src/core/skills/resolver/config.ts@@ -22,6 +22,9 @@* skills.resolver.per_harness.<harness>.{top_k,min_match,top_gate} overrides* for one harness; a key it leaves out falls back to the global one, and* an entry that is not an object (a hand-edited null) counts as unset+ * skills.resolver.per_harness.<claude-code|codex>.dirs extra absolute+ * skill directories setup adds to that harness's user catalog (at most+ * SKILL_DIRS_MAX); setup and the catalog's recorded rebuild keep them* skills.resolver.pinned skill ids the harness always loads itself,* never suggested (at most 1,024)*/@@ -35,6 +38,9 @@ export const DEFAULT_SESSION_TOKEN_BUDGET = 2000;export const MIN_SESSION_TOKEN_BUDGET = 100;export const MAX_SESSION_TOKEN_BUDGET = 50_000;const CONFIG_CAP = 1024 * 1024;+export const SKILL_DIRS_MAX = 32;+/** The harnesses whose user catalog setup builds, so the only ones a dirs key applies to. */+const DIRS_HARNESSES = ['claude-code', 'codex'];export interface ResolverSettings {sessionTokenBudget: number;@@ -87,6 +93,19 @@ export function validateTopGate(v: unknown, key: string): number {throw configInvalid(key, `must be a number from 0 to ${TOP_GATE_MAX} (0 or unset: off)`);}+export function validateSkillDirs(v: unknown, key: string): string[] {+ if (Array.isArray(v) && v.length <= SKILL_DIRS_MAX && v.every(x => typeof x === 'string' && x.startsWith('/') && x.length <= 4096 && !x.includes('\0') && !x.split('/').includes('..'))) return v as string[];+ throw configInvalid(key, `must be a list of at most ${SKILL_DIRS_MAX} absolute directory paths`);+}++/** The extra skill directories configured for one harness's user catalog (empty when none). Throws skill_resolver_config_invalid on a bad value. */+export function configuredSkillDirs(section: Record<string, unknown>, harness: string): string[] {+ const per = section.per_harness;+ const mine = per && typeof per === 'object' && !Array.isArray(per) ? (per as Record<string, unknown>)[harness] : undefined;+ const dirs = mine && typeof mine === 'object' && !Array.isArray(mine) ? (mine as Record<string, unknown>).dirs : undefined;+ return dirs === undefined ? [] : validateSkillDirs(dirs, `skills.resolver.per_harness.${harness}.dirs`);+}+export function validatePinned(v: unknown, key: string): string[] {if (Array.isArray(v) && v.length <= EXCLUDE_MAX && v.every(x => typeof x === 'string' && x.length > 0 && x.length <= 256)) return v as string[];throw configInvalid(key, `must be a list of at most ${EXCLUDE_MAX} skill ids`);@@ -109,8 +128,12 @@ export function laneTurnSettings(section: Record<string, unknown>, harness: striconst key = `${p}per_harness.${h}`;if (!(HARNESSES as readonly string[]).includes(h)) throw configInvalid(key, `names no harness (one of ${HARNESSES.join(', ')})`);if (!o || typeof o !== 'object' || Array.isArray(o)) continue;- if (Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match' && k !== 'top_gate')) throw configInvalid(key, 'may hold only top_k, min_match and top_gate');+ if (Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match' && k !== 'top_gate' && k !== 'dirs')) throw configInvalid(key, 'may hold only top_k, min_match, top_gate and dirs');const r = o as Record<string, unknown>;+ if (r.dirs !== undefined) {+ if (!DIRS_HARNESSES.includes(h)) throw configInvalid(`${key}.dirs`, `applies only to ${DIRS_HARNESSES.join(' and ')}, whose user catalog setup builds`);+ validateSkillDirs(r.dirs, `${key}.dirs`);+ }const parsed: LaneTurnSettings = {...(r.top_k !== undefined ? { top_k: validateTopK(r.top_k, `${key}.top_k`) } : {}),...(r.min_match !== undefined ? { min_match_strength: validateMinMatch(r.min_match, `${key}.min_match`) } : {}),diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.tsindex 92af383da4..74538d0903 100644--- a/test/setup-skill-resolver.test.ts+++ b/test/setup-skill-resolver.test.ts@@ -287,6 +287,55 @@ describe('doctor: an install from before the SessionStart entry', () => {}});+describe('per_harness.<harness>.dirs: extra skill directories setup keeps', () => {+ const run = (b: Box, ...args: string[]) => runCli(['config', ...args], { env: b.env, cwd: b.project });+ const receipt = (b: Box) => JSON.parse(readFileSync(join(gb(b), 'skill-index', 'claude-code-user', 'receipt.json'), 'utf8'));+ test('setup builds the user catalog from the default dir plus the configured ones; a re-run keeps them; unset drops them', async () => {+ const b = box();+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ const extra = join(b.root, 'shared-skills');+ skill(extra, 'citation-fixer', 'Fix broken citations across brain pages.');+ const set = await run(b, 'set', 'skills.resolver.per_harness.claude-code.dirs', `${extra},${join(b.root, 'not-there')}`);+ expect(set.exitCode, set.stderr).toBe(0);+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(receipt(b).catalog.source.dirs).toEqual([HARNESS['claude-code'].skills(b), extra]);+ expect(receipt(b).catalog.skill_count).toBe(2);+ expect(receipt(b).build.rebuild_argv).toContain(extra);+ const again = await setup(b, 'claude-code', ['--skill-loading', 'resolve']);+ expect(again.stdout).toMatch(/keep\s+resolver catalog: 2 skills/);+ const hit = await runCli(['skills', 'resolve', '--catalog', 'claude-code-user', '--text', 'fix the broken citations', '--json'], { env: b.env, cwd: b.project });+ expect(JSON.parse(hit.stdout).suggestions[0].id).toBe('citation-fixer');+ expect((await run(b, 'unset', 'skills.resolver.per_harness.claude-code.dirs')).exitCode).toBe(0);+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(receipt(b).catalog.source.dirs).toEqual([HARNESS['claude-code'].skills(b)]);+ });++ test('refused: a relative or .. path, more than 32 dirs, and a harness setup does not build a catalog for', async () => {+ const b = box();+ for (const [key, value, needle] of [+ ['skills.resolver.per_harness.codex.dirs', 'skills/mine', 'absolute directory paths'],+ ['skills.resolver.per_harness.codex.dirs', '/a/../b', 'absolute directory paths'],+ ['skills.resolver.per_harness.codex.dirs', Array.from({ length: 33 }, (_, i) => `/d${i}`).join(','), 'at most 32'],+ ['skills.resolver.per_harness.pi.dirs', '/opt/skills', 'applies only to claude-code and codex'],+ ]) {+ const r = await run(b, 'set', key!, value!);+ expect({ key, code: r.exitCode === 0, has: r.stderr.includes(needle!) }).toEqual({ key, code: false, has: true });+ }+ expect(read(configPath(b))).toBeNull();+ });++ test('a hand-edited bad dirs value stops setup before it writes anything of the resolver', async () => {+ const b = box();+ skill(HARNESS.codex.skills(b), 'deploy-widget', 'Deploy the widget service.');+ mkdirSync(gb(b), { recursive: true });+ writeFileSync(configPath(b), JSON.stringify({ skills: { resolver: { per_harness: { codex: { dirs: 'not-a-list' } } } } }));+ const r = await setup(b, 'codex', ['--skill-loading', 'resolve', '--json']);+ expect(r.exitCode).not.toBe(0);+ expect(`${r.stdout}${r.stderr}`).toContain('skills.resolver.per_harness.codex.dirs must be a list');+ expect(catalogs(b)).toEqual([]);+ });+});+describe('per_harness entries that are not objects', () => {for (const bad of [null, [1], 'fast', 3]) {test(`config get, set and unset treat per_harness.codex = ${JSON.stringify(bad)} as unset and replace it`, async () => {