Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver hook: per-turn settings in config, per harness, plus pinned skills
garrytan44953034a455
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 2b41300bf5..5868b6a25b 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4644,7 +4644,7 @@ More: [docs/guides/skill-resolver.md#skill_resolve_timeout](../../docs/guides/sk| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000) or GBRAIN_HOME is not an absolute path. | The request itself was wrong or no longer matches the brain; nothing was changed. | Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME. | agent | `repeat the read that failed` | 1 | no |+| A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000; top_k, min_match, pinned and per_harness must be valid) or GBRAIN_HOME is not an absolute path. | The request itself was wrong or no longer matches the brain; nothing was changed. | Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME. | agent | `repeat the read that failed` | 1 | no |More: [docs/guides/skill-resolver.md#skill_resolver_config_invalid](../../docs/guides/skill-resolver.md#skill_resolver_config_invalid)diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex 3e1f026b2f..ec29026545 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -78,8 +78,9 @@ per-turn hook that puts the block in front of the model on every prompt:holds no engine, so nothing reads it as a brain.3. It adds the lane's own hook: Claude Code gets UserPromptSubmit andSessionStart entries marked `skill-resolver-v1` in `~/.claude/settings.json`;- Codex gets a UserPromptSubmit group in `hooks.json` (`--harness codex`),- trusted in `config.toml`. Both run through the existing hook launcher.+ Codex gets UserPromptSubmit and SessionStart groups in `hooks.json`+ (`--harness codex`), each trusted in `config.toml`. Both run through the+ existing hook launcher.4. It prints a sample block and `skill resolver: on; N skills; fresh`.`--dry-run` lists every write, and re-running changes nothing. A bare@@ -92,6 +93,13 @@ The lane always exits 0 and prints nothing when it cannot deliver:- **Deadline:** 50 ms from lane start. Ranking runs in a worker thread; at thedeadline the process prints nothing, exits and commits no session state.+- **Turn settings:** `skills.resolver.top_k` (1-8, default 5),+ `skills.resolver.min_match` (the weakest `match_strength` to suggest;+ default every match) and `skills.resolver.pinned` (skill ids the harness+ always loads itself, never suggested). `skills.resolver.per_harness.<harness>.top_k`+ and `.min_match` override one harness; what it leaves out falls back to the+ global key. Set them with `gbrain config set`; a bad value makes the lane+ log `skill_resolver_config_invalid` and deliver nothing.- **Payload:** at most `skills.resolver.lane_payload_chars` characters of hookoutput (default 4000, 500 to 10,000); a larger block is dropped whole andcounted as `payload_dropped`.@@ -103,8 +111,9 @@ The lane always exits 0 and prints nothing when it cannot deliver:rebuild the same way, at most once a minute;`skills.resolver.auto_rebuild false` or `GBRAIN_SKILLS_NO_AUTOREBUILD=1`stops both.-- **Compaction:** a SessionStart with `source: compact` resets the session, so- skills can be offered again.+- **Compaction:** a SessionStart with `source: compact` (Claude Code, and Codex+ 0.165 and later) resets the session, so skills can be offered again. A Codex+ install from before gets the SessionStart group on its next setup run.Each turn appends one line (outcome, error code, duration; never turn text)to `skill-index/logs/lane.jsonl`. `gbrain doctor` (`skill_resolver`, and@@ -326,8 +335,9 @@ The `--from-json` catalog or routing file is malformed or over its size bound### skill_resolver_config_invalid-`skills.resolver.session_token_budget` is not 0 or 100-50,000, or GBRAIN_HOME-is not an absolute path.+`skills.resolver.session_token_budget` is not 0 or 100-50,000, a lane turn+setting (`top_k`, `min_match`, `pinned`, `per_harness`) is out of range, or+GBRAIN_HOME is not an absolute path.### skill_resolver_config_unreadablediff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 305e1d4d8b..712377c627 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -386,7 +386,7 @@ test/shared-skills-setup.test.ts shared-skills migration recovery (#5569, #5476,test/shared-skills-setup.test.ts staged skill migration 7 readFileSynctest/shared-skills-writer-boundary.test.ts (file-level) 7 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: compiled binaries 1 readFileSync-test/skill-resolver-hook-lane.test.ts skill-resolver lane: delivery per harness 3 readFileSync+test/skill-resolver-hook-lane.test.ts skill-resolver lane: delivery per harness 4 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: fail open 6 readFileSynctest/skill-resolver-off-pin.test.ts (file-level) 1 readFileSynctest/skill-resolver-packaging.test.ts skill resolver packaging 2 bun-file,readFileSyncdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 902eb0be6b..2521083357 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -738,7 +738,7 @@ export const CODES = {skill_resolve_invalid_input: { class: 'caller', exit: 2, summary: 'The turn or build input is not valid: bad JSON, an unknown field or harness, or a value out of range.', docs: 'docs/guides/skill-resolver.md#skill_resolve_invalid_input', suggestion: 'Send input that matches docs/schemas/skill-resolver.v1.turn-input.json (or the build flags in gbrain skills index --help).' },skill_resolve_no_input: { class: 'caller', exit: 2, summary: 'gbrain skills resolve got no message: no --text, and stdin was a terminal or empty.', docs: 'docs/guides/skill-resolver.md#skill_resolve_no_input', suggestion: 'Pass --text "<message>", or pipe turn JSON to gbrain skills resolve --input-json -.' },skill_resolve_timeout: { class: 'retryable', summary: 'The skill resolver ran past its deadline, so the turn got no block and no session state was committed.', docs: 'docs/guides/skill-resolver.md#skill_resolve_timeout', suggestion: 'The turn proceeds without a block; check the catalog size with gbrain skills index status.' },- skill_resolver_config_invalid: { class: 'caller', summary: 'A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000) or GBRAIN_HOME is not an absolute path.', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_invalid', suggestion: 'Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME.' },+ skill_resolver_config_invalid: { class: 'caller', summary: 'A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000; top_k, min_match, pinned and per_harness must be valid) or GBRAIN_HOME is not an absolute path.', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_invalid', suggestion: 'Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME.' },skill_resolver_config_unreadable: { class: 'caller', summary: 'config.json exists but cannot be read or parsed, so the skill resolver lane stays silent and setup writes none of its keys (the file is never rewritten).', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable', suggestion: 'Fix or move config.json in the gbrain config directory (GBRAIN_HOME/.gbrain, else ~/.gbrain; it must be a JSON object), then run gbrain doctor --only skill_resolver.', fix: { argv: ['gbrain', 'doctor', '--only', 'skill_resolver', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolver lane state and the config problem; changes nothing.' } },skill_resolver_setup_incomplete: { class: 'caller', summary: 'gbrain setup --skill-loading resolve found no skill to index (or could not build the catalog or wire the hook), so it wrote no config keys and no hook.', docs: 'docs/guides/skill-resolver.md#skill_resolver_setup_incomplete', suggestion: 'Add a skill to one of the scanned directories (the message names them), then run setup again.' },skill_resolver_internal: { class: 'server', summary: 'The skill resolver failed unexpectedly; a scrubbed trace (no turn text) was written under skill-index/logs/.', docs: 'docs/guides/skill-resolver.md#skill_resolver_internal', suggestion: 'Run gbrain skills index status and report the trace if it repeats.', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog and its last build error; changes nothing.' } },diff --git a/src/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.tsindex 7ca525abe3..fc47929ef2 100644--- a/src/core/setup/skill-resolver-config.ts+++ b/src/core/setup/skill-resolver-config.ts@@ -7,6 +7,8 @@* 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, pinned, per_harness.<harness>.{top_k,min_match}+ * 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* a brainless install stays brainless (loadConfig decides "a brain is@@ -18,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 { validateSessionTokenBudget } from '../skills/resolver/config.ts';+import { laneTurnSettings, validateMinMatch, validatePinned, validateSessionTokenBudget, validateTopK } from '../skills/resolver/config.ts';const CONFIG_CAP_BYTES = 1024 * 1024;@@ -86,9 +88,17 @@ 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'] as const;+export const SKILL_RESOLVER_CONFIG_LEAVES = ['enabled', 'session_token_budget', 'auto_rebuild', 'lane_payload_chars', 'top_k', 'min_match', 'pinned', 'per_harness.<harness>.top_k', 'per_harness.<harness>.min_match'] as const;+const PER_HARNESS_LEAF = /^per_harness\.([a-z-]+)\.(top_k|min_match)$/;-function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean | number } | { ok: false; error: string } {+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;+ const key = `${SKILL_RESOLVER_KEY_PREFIX}${leaf}`;+ try {+ if (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 (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') {if (value === 'true' || value === 'false') return { ok: true, value: value === 'true' };return { ok: false, error: 'must be true or false' };@@ -110,31 +120,40 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanconst leaf = key.slice(SKILL_RESOLVER_KEY_PREFIX.length);const fail = (msg: string): true => { console.error(`[config] ${msg}`); setCliExitVerdict(1); return true; };if (leaf === 'harnesses') return fail(`${key} is written by gbrain setup <claude-code|codex> --skill-loading resolve (and removed by --skill-loading off); nothing was written.`);- if (!(SKILL_RESOLVER_CONFIG_LEAVES as readonly string[]).includes(leaf)) return fail(`Unknown config key "${key}". skills.resolver keys: ${SKILL_RESOLVER_CONFIG_LEAVES.join(', ')}. Nothing was written.`);+ const nested = leaf.match(PER_HARNESS_LEAF);+ if (!nested && !(SKILL_RESOLVER_CONFIG_LEAVES as readonly string[]).includes(leaf)) return fail(`Unknown config key "${key}". skills.resolver keys: ${SKILL_RESOLVER_CONFIG_LEAVES.join(', ')}. Nothing was written.`);const read = readResolverConfig(home);if (read.state === 'unreadable') return fail(`${read.path} cannot be read (${read.why}); fix it first (skill_resolver_config_unreadable). Nothing was written.`);const doc = read.state === 'ok' ? structuredClone(read.doc) : {};const section = resolverSection(doc);+ const perHarness = (section.per_harness && typeof section.per_harness === 'object' && !Array.isArray(section.per_harness) ? section.per_harness : {}) as Record<string, Record<string, unknown>>;+ const holder: Record<string, unknown> = nested ? (perHarness[nested[1]!] ??= {}) : section;+ const field = nested ? nested[2]! : leaf;if (action === 'get') {- if (section[leaf] === undefined) return fail(`Config key not found: ${key}`);- console.log(typeof section[leaf] === 'string' ? section[leaf] : JSON.stringify(section[leaf]));+ if (holder[field] === undefined) return fail(`Config key not found: ${key}`);+ console.log(typeof holder[field] === 'string' ? holder[field] : JSON.stringify(holder[field]));return true;}if (action === 'unset') {- if (!(leaf in section)) return fail(`Config key not found: ${key}`);- delete section[leaf];+ if (!(field in holder)) return fail(`Config key not found: ${key}`);+ delete holder[field];} else {const value = rest.find((a) => !a.startsWith('-'));if (value === undefined) return fail(`usage: gbrain config set ${key} <value>`);const parsed = parseLeafValue(leaf, value);if (!parsed.ok) return fail(`${key} ${parsed.error}`);- section[leaf] = parsed.value;+ holder[field] = parsed.value;+ }+ if (nested) {+ for (const [h, o] of Object.entries(perHarness)) if (Object.keys(o).length === 0) delete perHarness[h];+ if (Object.keys(perHarness).length) section.per_harness = perHarness; else delete section.per_harness;+ try { laneTurnSettings(section, nested[1]!); } catch (e) { return fail(`${(e as Error).message} Nothing was written.`); }}const skills = (doc.skills && typeof doc.skills === 'object' && !Array.isArray(doc.skills) ? doc.skills : {}) as Record<string, unknown>;if (Object.keys(section).length) skills.resolver = section; else delete skills.resolver;if (Object.keys(skills).length) doc.skills = skills; else delete doc.skills;if (Object.keys(doc).length === 0) unlinkSync(read.path);else atomicWriteTextFile(read.path, `${JSON.stringify(doc, null, 2)}\n`, { freshMode: 0o600 });- console.log(action === 'set' ? `Set ${key} = ${JSON.stringify(section[leaf])} (file plane: ${read.path})` : `Unset ${key} (file plane)`);+ console.log(action === 'set' ? `Set ${key} = ${JSON.stringify(holder[field])} (file plane: ${read.path})` : `Unset ${key} (file plane)`);return true;}diff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.tsindex 196c545931..263f740e13 100644--- a/src/core/skills/resolver/config.ts+++ b/src/core/skills/resolver/config.ts@@ -10,10 +10,23 @@* reset_session) resets a session's spend.* skills.resolver.auto_rebuild false (or GBRAIN_SKILLS_NO_AUTOREBUILD=1)* stops a stale resolve from scheduling a rebuild (no stale.stamp).+ *+ * The hook lane's turn settings (read by hook-lane.ts; a library caller+ * passes its own per turn):+ *+ * skills.resolver.top_k suggestions per turn (1..8, default 5)+ * skills.resolver.min_match the weakest match_strength to suggest+ * (default: every match)+ * skills.resolver.per_harness.<harness>.{top_k,min_match} overrides+ * for one harness; a key it leaves out falls back to the global one+ * skills.resolver.pinned skill ids the harness always loads itself,+ * never suggested (at most 1,024)*/import { readFileSync, statSync } from 'node:fs';import { join } from 'node:path';+import { HARNESSES } from './block.ts';import { ResolverError } from './errors.ts';+import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, TOP_K_MAX } from './limits.ts';export const DEFAULT_SESSION_TOKEN_BUDGET = 2000;export const MIN_SESSION_TOKEN_BUDGET = 100;@@ -48,3 +61,51 @@ export function readResolverSettings(home: string, env: NodeJS.ProcessEnv = procconst autoRebuild = env.GBRAIN_SKILLS_NO_AUTOREBUILD === '1' ? false : section.auto_rebuild !== false;return { sessionTokenBudget: budget, autoRebuild };}++/** What the hook lane adds to each turn's input. */+export interface LaneTurnSettings { top_k?: number; min_match_strength?: MatchStrength; exclude?: string[] }++function configInvalid(key: string, rule: string): ResolverError {+ return new ResolverError('skill_resolver_config_invalid', `${key} ${rule}.`, { suggestion: `Fix or unset ${key}: gbrain config unset ${key}` });+}++export function validateTopK(v: unknown, key: string): number {+ if (Number.isInteger(v) && (v as number) >= 1 && (v as number) <= TOP_K_MAX) return v as number;+ throw configInvalid(key, `must be a whole number from 1 to ${TOP_K_MAX} (default 5)`);+}++export function validateMinMatch(v: unknown, key: string): MatchStrength {+ if ((MATCH_STRENGTHS as readonly unknown[]).includes(v)) return v as MatchStrength;+ throw configInvalid(key, `must be one of ${MATCH_STRENGTHS.join(', ')}`);+}++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`);+}++/** The turn settings the lane uses for `harness`: its per_harness keys, else the global ones. Throws skill_resolver_config_invalid on a bad value anywhere in the section. */+export function laneTurnSettings(section: Record<string, unknown>, harness: string): LaneTurnSettings {+ const p = 'skills.resolver.';+ const global: LaneTurnSettings = {+ ...(section.top_k !== undefined ? { top_k: validateTopK(section.top_k, `${p}top_k`) } : {}),+ ...(section.min_match !== undefined ? { min_match_strength: validateMinMatch(section.min_match, `${p}min_match`) } : {}),+ ...(section.pinned !== undefined ? { exclude: validatePinned(section.pinned, `${p}pinned`) } : {}),+ };+ const per = section.per_harness;+ if (per === undefined) return global;+ if (!per || typeof per !== 'object' || Array.isArray(per)) throw configInvalid(`${p}per_harness`, 'must be an object keyed by harness');+ let mine: LaneTurnSettings = {};+ for (const [h, o] of Object.entries(per as Record<string, unknown>)) {+ const 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) || Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match')) throw configInvalid(key, 'may hold only top_k and min_match');+ const r = o as Record<string, unknown>;+ 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`) } : {}),+ };+ if (h === harness) mine = parsed;+ }+ return { ...global, ...mine };+}diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsindex 4332a3f507..74ffdd4a0e 100644--- a/src/core/skills/resolver/hook-lane.ts+++ b/src/core/skills/resolver/hook-lane.ts@@ -36,6 +36,10 @@* catalog is rebuilt the same way, at most once a minute per catalog, unless* skills.resolver.auto_rebuild is false or GBRAIN_SKILLS_NO_AUTOREBUILD=1.*+ * Turn settings: skills.resolver.top_k, min_match, pinned (sent as exclude)+ * and per_harness.<harness>.{top_k,min_match} (config.ts laneTurnSettings);+ * unset, a turn is top_k 5 with every match and nothing excluded.+ ** Payload: the lane's own budget (skills.resolver.lane_payload_chars, default* 4000 characters of hook JSON); a block that does not fit is dropped whole* and counted (outcome payload_dropped in the lane log).@@ -54,6 +58,7 @@ import { spawn } from '../../spawn.ts';import { claudeManagedSettingsPaths, claudeUserSettingsPath, codexHooksPath } from '../../bootstrap/host-specs.ts';import { shellWords } from '../../setup/hook-launcher.ts';import { isSkillResolverCommand, isSkillResolverEntry } from '../../setup/skill-resolver-lane.ts';+import { laneTurnSettings, type LaneTurnSettings } from './config.ts';import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';import { type CommitHold, commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';import type { TurnOutput } from './resolve.ts';@@ -122,11 +127,11 @@ export async function skillResolverOwner(harness: LaneHarness, event: 'user-promreturn undefined;}-export interface LaneSettings { state: 'absent' | 'unreadable' | 'invalid' | 'ok'; enabled: boolean; harnesses: string[]; payloadChars: number; autoRebuild: boolean }+export interface LaneSettings { state: 'absent' | 'unreadable' | 'invalid' | 'ok'; enabled: boolean; harnesses: string[]; payloadChars: number; autoRebuild: boolean; section: Record<string, unknown> }/** skills.resolver from <home>/config.json, async. absent: no file; unreadable: a file gbrain cannot read or parse. */export async function readLaneSettings(home: string, env: NodeJS.ProcessEnv): Promise<LaneSettings> {- const base: LaneSettings = { state: 'ok', enabled: false, harnesses: [], payloadChars: LANE_PAYLOAD_CHARS_DEFAULT, autoRebuild: env.GBRAIN_SKILLS_NO_AUTOREBUILD !== '1' };+ const base: LaneSettings = { state: 'ok', enabled: false, harnesses: [], payloadChars: LANE_PAYLOAD_CHARS_DEFAULT, autoRebuild: env.GBRAIN_SKILLS_NO_AUTOREBUILD !== '1', section: {} };let cfg: unknown;try { cfg = await readJsonFile(join(home, 'config.json')); } catch (e) {return { ...base, state: (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'absent' : 'unreadable' };@@ -142,6 +147,7 @@ export async function readLaneSettings(home: string, env: NodeJS.ProcessEnv): Prharnesses: Array.isArray(r.harnesses) ? r.harnesses.filter((h): h is string => typeof h === 'string') : [],payloadChars: validChars && chars !== undefined ? chars as number : LANE_PAYLOAD_CHARS_DEFAULT,autoRebuild: base.autoRebuild && r.auto_rebuild !== false,+ section: r,};}@@ -251,6 +257,8 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarif (!settings.enabled || !settings.harnesses.includes(harness)) return { outcome: 'off' };ctl.logged = true;if (settings.state === 'invalid') return { outcome: 'error', code: 'skill_resolver_config_invalid' };+ let turnSettings: LaneTurnSettings;+ try { turnSettings = laneTurnSettings(settings.section, harness); } catch { return { outcome: 'error', code: 'skill_resolver_config_invalid' }; }const raw = await readStdinBounded(io.stdin ?? process.stdin, LANE_STDIN_CAP_BYTES);let j: Record<string, unknown>;@@ -282,7 +290,7 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarconst posted = await new Promise<{ output?: TurnOutput; pending?: { key: string; delta: TurnDelta } | null; error?: { code: string } }>((resolve) => {worker.once('message', resolve);worker.once('error', () => resolve({ error: { code: 'skill_resolver_internal' } }));- worker.postMessage({ input: { message: prompt, harness, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS) } satisfies LaneWorkerTurn);+ worker.postMessage({ input: { message: prompt, harness, ...turnSettings, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS) } satisfies LaneWorkerTurn);});if (posted.error || !posted.output) return { outcome: 'error', code: posted.error?.code ?? 'skill_resolver_internal', catalogs };const out = posted.output;diff --git a/src/core/skills/resolver/limits.ts b/src/core/skills/resolver/limits.tsnew file mode 100644index 0000000000..d6f624dbbf--- /dev/null+++ b/src/core/skills/resolver/limits.ts@@ -0,0 +1,14 @@+/**+ * The turn input's bounds and the match-strength order, shared by the+ * resolver (resolve.ts) and the lane's config keys (config.ts) without+ * loading the ranker. Leaf module.+ */+export const TOP_K_DEFAULT = 5;+export const TOP_K_MAX = 8;+export const EXCLUDE_MAX = 1024;++/** The strongest way a suggestion matched the turn: named in it, then by field. A body-only match is the weakest. */+export type MatchStrength = 'named' | 'name' | 'triggers' | 'routing' | 'description' | 'body';+export const STRENGTH_FIELDS = ['name', 'triggers', 'routing', 'description', 'body'] as const;+/** Strongest first. */+export const MATCH_STRENGTHS: readonly MatchStrength[] = ['named', ...STRENGTH_FIELDS];diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex 2dd68491ae..8b96a97b55 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -33,6 +33,7 @@ import { dirFingerprintSlice, listCatalogs, readReceipt } from './catalog-files.import { readResolverSettings, validateSessionTokenBudget } from './config.ts';import { ResolverError } from './errors.ts';import { ensureDir, writeFileAtomic, writeFileDurable } from './fsutil.ts';+import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, STRENGTH_FIELDS, TOP_K_DEFAULT, TOP_K_MAX } from './limits.ts';import { IndexReader, RANKER_ID, RANKER_VERSION } from './index-format.ts';import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';import { isAcknowledgement, mentionsSkill, rankIndex, reasonText, type RankResult } from './rank.ts';@@ -40,9 +41,7 @@ import { commitSession, freshState, loadSession, sessionKey, type SessionState,export const SCHEMA_VERSION = 1;export const MESSAGE_CAP_BYTES = 8192;-export const TOP_K_DEFAULT = 5;-export const TOP_K_MAX = 8;-export const EXCLUDE_MAX = 1024;+export { EXCLUDE_MAX, MATCH_STRENGTHS, TOP_K_DEFAULT, TOP_K_MAX, type MatchStrength };export const RESUGGEST_AFTER_TURNS = 10;export const STAT_CHECK_INTERVAL_MS = 60_000;/** Stat calls one turn may spend on the freshness sweep; a larger catalog is swept over several turns. */@@ -61,11 +60,6 @@ export interface TurnInput {min_match_strength?: MatchStrength;}-/** The strongest way a suggestion matched the turn: named in it, then by field. A body-only match is the weakest. */-export type MatchStrength = 'named' | 'name' | 'triggers' | 'routing' | 'description' | 'body';-const STRENGTH_FIELDS = ['name', 'triggers', 'routing', 'description', 'body'] as const;-/** Strongest first. */-export const MATCH_STRENGTHS: readonly MatchStrength[] = ['named', ...STRENGTH_FIELDS];export interface Suggestion { id: string; name: string; score: number; summary: string; reason: string; match_strength: MatchStrength; path?: string; catalog: string }export interface TurnError { code: string; message: string; fix: { suggestion: string; command?: string } }export interface TurnOutput {diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsindex 2e6fff3aec..65ab2247eb 100644--- a/test/skill-resolver-hook-lane.test.ts+++ b/test/skill-resolver-hook-lane.test.ts@@ -187,6 +187,50 @@ describe('skill-resolver lane: deadline, measured outside the process', () => {}});+describe('skill-resolver lane: turn settings from config', () => {+ const config = async (b: Box, ...args: string[]) => {+ const r = await runCli(['config', ...args], { env: b.env, cwd: b.project });+ return r;+ };+ test('top_k, min_match and pinned apply; per_harness overrides one harness; Claude Code and Codex default to 5 with no floor', async () => {+ const b = box();+ for (const dir of [claudeSkills(b), codexSkills(b)]) {+ seedSkills(dir);+ skill(dir, 'deploy-docs', 'Deploy the docs site.');+ skill(dir, 'deploy-api', 'Deploy the api service.');+ }+ await setup(b, 'claude-code');+ await setup(b, 'codex');+ const claude = wired(b, 'claude-code'), codex = wired(b, 'codex');+ const ids = (r: Run) => [...contextOf(r).matchAll(/id: "([^"]+)"/g)].map((m) => m[1]);+ const ask = (cmd: string, s: string) => hook(b, cmd, { prompt: 'deploy the widget service', session_id: s, hook_event_name: 'UserPromptSubmit' }, WIDE);+ expect(ids(await ask(claude, 'd1')).length).toBeGreaterThanOrEqual(3);+ for (const [k, v] of [['skills.resolver.top_k', '1'], ['skills.resolver.per_harness.codex.top_k', '2'], ['skills.resolver.pinned', 'deploy-widget']]) {+ const r = await config(b, 'set', k, v);+ expect(r.exitCode, r.stderr).toBe(0);+ }+ const c = ids(await ask(claude, 'd2'));+ expect(c).toHaveLength(1);+ expect(c).not.toContain('deploy-widget');+ const x = ids(await ask(codex, 'd3'));+ expect(x).toHaveLength(2);+ expect(x).not.toContain('deploy-widget');+ expect((await config(b, 'set', 'skills.resolver.min_match', 'named')).exitCode).toBe(0);+ expect((await ask(claude, 'd4')).stdout).toBe('');+ const bad = await config(b, 'set', 'skills.resolver.per_harness.vim.top_k', '2');+ expect(bad.exitCode).not.toBe(0);+ expect(bad.stderr).toContain('names no harness');+ expect((await config(b, 'set', 'skills.resolver.top_k', '9')).exitCode).not.toBe(0);+ const cfg = JSON.parse(readFileSync(join(b.home, '.gbrain', 'config.json'), 'utf8')).skills.resolver;+ expect([cfg.top_k, cfg.min_match, cfg.pinned, cfg.per_harness]).toEqual([1, 'named', ['deploy-widget'], { codex: { top_k: 2 } }]);+ cfg.top_k = 99;+ writeFileSync(join(b.home, '.gbrain', 'config.json'), JSON.stringify({ skills: { resolver: cfg } }));+ const invalid = await ask(claude, 'd5');+ expect([invalid.exitCode, invalid.stdout]).toEqual([0, '']);+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'error', code: 'skill_resolver_config_invalid' });+ });+});+describe('skill-resolver lane: a deadline during the dedupe commit', () => {for (const stall of ['commit-held', 'commit-written'] as const) {test(`${stall}: the exit releases the session lease and removes the temp file, so the next turn commits`, async () => {