Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
skill resolver: hook lane for Claude Code and Codex (WIP)
garrytan3af52a9e2ce0
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 3e1aa50d1c..084061882a 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -152,7 +152,7 @@ jobs:# release runner is a flakier duplicate gate — it blocked the first# release on ambient-env tests (run 30698650484). The build job's gate# is the artifact itself: compile, then smoke-test the binary.- - run: bun build --compile --no-compile-autoload-bunfig --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts+ - run: bun build --compile --no-compile-autoload-bunfig --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts src/core/skills/resolver/hook-worker.ts- name: Verify Darwin executable signature before executionif: runner.os == 'macOS'run: codesign --verify --strict --verbose=2 "bin/${{ matrix.artifact }}"diff --git a/package.json b/package.jsonindex 965d010452..e3752c079e 100644--- a/package.json+++ b/package.json@@ -48,8 +48,8 @@},"scripts": {"dev": "bun run src/cli.ts",- "build": "bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts",- "build:all": "bun build --compile --no-compile-autoload-bunfig --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts && bun build --compile --no-compile-autoload-bunfig --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts",+ "build": "bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts src/core/skills/resolver/hook-worker.ts",+ "build:all": "bun build --compile --no-compile-autoload-bunfig --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts src/core/skills/resolver/hook-worker.ts && bun build --compile --no-compile-autoload-bunfig --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts src/core/skills/resolver/hook-worker.ts","build:admin": "cd admin && bun run build && cd .. && bun run scripts/build-admin-embedded.ts","build:admin-embedded": "bun run scripts/build-admin-embedded.ts","build:schema": "bun run scripts/build-schema.ts",diff --git a/src/commands/config.ts b/src/commands/config.tsindex ade7bb21ad..d6331662b6 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -77,9 +77,16 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([* never written to a DB row nothing reads. */const SELF_UPGRADE_KEY_PREFIX = 'self_upgrade.';+/** GBRA-377: skills.resolver.* (src/core/setup/skill-resolver-config.ts) are read only from the file plane, by the engine-free hook lane and resolver; config set|unset|get handle them before any engine (tryRunConfigEngineFree). */+const SKILL_RESOLVER_KEY_PREFIX = 'skills.resolver.';+async function runSkillResolverKey(args: string[]): Promise<boolean> {+ const [{ runSkillResolverConfigKey }, { configDir }] = await Promise.all([import('../core/setup/skill-resolver-config.ts'), import('../core/config.ts')]);+ return runSkillResolverConfigKey(args, configDir());+}+/** The single membership test the get/set/unset lanes share. */function isFilePlaneDottedKey(key: string): boolean {- return FILE_PLANE_DOTTED_KEYS.has(key) || key.startsWith(SELF_UPGRADE_KEY_PREFIX) || isConsentConfigKey(key);+ return FILE_PLANE_DOTTED_KEYS.has(key) || key.startsWith(SELF_UPGRADE_KEY_PREFIX) || key.startsWith(SKILL_RESOLVER_KEY_PREFIX) || isConsentConfigKey(key);}/** Delete the DB-plane row of a file-plane key: a `config set` from before@@ -361,6 +368,7 @@ export async function handleDbPlaneRoutedKeys(key: string, value: string): Promi* to change when the engine can't connect. Returns true when handled.*/export async function tryRunConfigEngineFree(args: string[]): Promise<boolean> {+ if (args[1]?.startsWith(SKILL_RESOLVER_KEY_PREFIX)) return runSkillResolverKey(args);if (args[0] !== 'set') return false;const key = args[1];const value = args.slice(2).find((a) => !a.startsWith('-'));@@ -623,6 +631,7 @@ async function setFilePlaneKey(key: string, value: string, tail: string[]): Prom* refusal. Returns true when handled.*/export async function tryRunConfigThinClient(args: string[]): Promise<boolean> {+ if (args[1]?.startsWith(SKILL_RESOLVER_KEY_PREFIX)) return runSkillResolverKey(args);const [action, key, ...rest] = args;if (!key || !key.startsWith(SELF_UPGRADE_KEY_PREFIX) || rest.some((a) => a.startsWith('-'))) return false;if (action === 'set' && rest.length === 1) {diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 85e7806a11..0d04d433db 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -668,16 +668,26 @@ async function registrationCheck(opts: { smoke: boolean }, regs: HarnessRegistraasync function runHarnessWiring(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];+ const { describeSkillResolver, skillResolverCheck, skillResolverView } = await import('./skill-resolver.ts');+ let resolver: Awaited<ReturnType<typeof skillResolverView>> = null;try {- checks.push(await harnessWiringCheck({ smoke: !!ctx.only?.has('harness_wiring') }));+ resolver = await skillResolverView();+ } catch (e) {+ checks.push(checkError('skill_resolver', 'read the skill resolver state', e));+ }+ try {+ const check = await harnessWiringCheck({ smoke: !!ctx.only?.has('harness_wiring') });+ checks.push(resolver ? { ...check, message: `${check.message} ${describeSkillResolver(resolver)}`, details: { ...(check.details ?? {}), skill_resolver: resolver } } : check);} catch (e) {checks.push(checkError('harness_wiring', 'read the harness registrations', e));}+ const own = skillResolverCheck(resolver);+ if (own) checks.push(own);return checks;}export const harnessWiringDoctorEntry: DoctorEntry = {name: 'harness_wiring',- emits: ['harness_wiring'],+ emits: ['harness_wiring', 'skill_resolver'],run: runHarnessWiring,};diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.tsnew file mode 100644index 0000000000..cfbbaafe45--- /dev/null+++ b/src/commands/doctor/checks/skill-resolver.ts@@ -0,0 +1,115 @@+/**+ * `skill_resolver` (GBRA-377 PR B): the skill-resolver hook lane that+ * `gbrain setup <claude-code|codex> --skill-loading resolve` turns on+ * (src/core/skills/resolver/hook-lane.ts). Per harness it reports the lane's+ * hook (wired, untrusted in Codex, or missing), each catalog's freshness+ * (the content tier: source re-read, index re-hashed) and the recent+ * outcomes and error codes from the lane log. It emits nothing when the+ * resolver is not configured: no keys, no hook, no catalog and no lane log.+ * harness_wiring carries the same view in its details.+ *+ * Read-only apart from catalogStatus's session sweep; warns, never fails.+ */+import { existsSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import type { Check } from '../../doctor.ts';+import { doctorVerify } from '../check-fix.ts';+import { configDir } from '../../../core/config.ts';+import { catalogStatus, listCatalogs } from '../../../core/skills/resolver/build.ts';+import { logsDir } from '../../../core/skills/resolver/paths.ts';+import { LANE_LOG_FILE, projectCatalogPrefix, userCatalogName, type LaneHarness } from '../../../core/skills/resolver/hook-lane.ts';+import { readResolverConfig, resolverHarnesses } from '../../../core/setup/skill-resolver-config.ts';+import { inspectSkillResolverHook } from '../../../core/setup/skill-resolver-hook.ts';++const NAME = 'skill_resolver';+const HARNESSES: LaneHarness[] = ['claude-code', 'codex'];+/** Lane-log lines doctor reads (the newest), and the tail it reads them from. */+const RECENT_LINES = 200;+const LOG_TAIL_BYTES = 64 * 1024;++export interface SkillResolverCatalogView { name: string; fresh: boolean | null; stale_reason: string | null; skills: number }+export interface SkillResolverHarnessView { harness: LaneHarness; on: boolean; hook: 'wired' | 'untrusted' | 'absent'; catalogs: SkillResolverCatalogView[] }+export interface SkillResolverView {+ config: 'ok' | 'absent' | 'unreadable';+ harnesses: SkillResolverHarnessView[];+ recent: { turns: number; outcomes: Record<string, number>; errors: Record<string, number> };+}++function recentLane(home: string): SkillResolverView['recent'] | null {+ const p = join(logsDir(home), LANE_LOG_FILE);+ if (!existsSync(p)) return null;+ let text = '';+ try {+ const size = statSync(p).size;+ text = readFileSync(p, 'utf8');+ if (size > LOG_TAIL_BYTES) text = text.slice(-LOG_TAIL_BYTES);+ } catch { return null; }+ const outcomes: Record<string, number> = {};+ const errors: Record<string, number> = {};+ const lines = text.split('\n').filter(Boolean).slice(-RECENT_LINES);+ let turns = 0;+ for (const line of lines) {+ let j: { outcome?: unknown; code?: unknown };+ try { j = JSON.parse(line); } catch { continue; }+ if (typeof j.outcome !== 'string') continue;+ turns++;+ outcomes[j.outcome] = (outcomes[j.outcome] ?? 0) + 1;+ if (typeof j.code === 'string') errors[j.code] = (errors[j.code] ?? 0) + 1;+ }+ return { turns, outcomes, errors };+}++/** The resolver's state for doctor, or null when nothing of it exists. */+export async function skillResolverView(home = configDir()): Promise<SkillResolverView | null> {+ const cfg = readResolverConfig(home);+ const on = cfg.state === 'ok' ? resolverHarnesses(cfg.doc) : [];+ const catalogs = listCatalogs(home);+ const recent = recentLane(home);+ const harnesses: SkillResolverHarnessView[] = [];+ for (const harness of HARNESSES) {+ const hook = inspectSkillResolverHook(harness).state;+ const mine = catalogs.filter((n) => n === userCatalogName(harness) || n.startsWith(projectCatalogPrefix(harness)));+ if (!on.includes(harness) && hook === 'absent' && mine.length === 0) continue;+ const views: SkillResolverCatalogView[] = [];+ for (const name of mine) {+ const s = await catalogStatus(name, { home });+ views.push({ name, fresh: s.fresh, stale_reason: s.stale_reason, skills: s.receipt?.skill_count ?? 0 });+ }+ harnesses.push({ harness, on: on.includes(harness), hook, catalogs: views });+ }+ if (harnesses.length === 0 && !recent && !(cfg.state === 'ok' && on.length)) return null;+ return { config: cfg.state, harnesses, recent: recent ?? { turns: 0, outcomes: {}, errors: {} } };+}++const setupArgv = (harness: string) => ['gbrain', 'setup', harness, '--skill-loading', 'resolve'];++/** One line for harness_wiring's message. */+export function describeSkillResolver(v: SkillResolverView): string {+ if (v.config === 'unreadable') return 'Skill resolver: the config file cannot be read (skill_resolver_config_unreadable).';+ const parts = v.harnesses.map((h) => {+ const user = h.catalogs.find((c) => c.name === userCatalogName(h.harness));+ const fresh = !user ? 'no catalog' : user.fresh ? 'fresh' : `stale (${user.stale_reason})`;+ return `${h.harness} ${h.on ? 'on' : 'off'}, hook ${h.hook}, ${user?.skills ?? 0} skills, ${fresh}`;+ });+ const errs = Object.entries(v.recent.errors).map(([c, n]) => `${c} x${n}`).join(', ');+ return `Skill resolver: ${parts.join('; ') || 'no harness on'}${v.recent.turns ? `; last ${v.recent.turns} turns${errs ? ` with ${errs}` : ' without errors'}` : ''}.`;+}++export function skillResolverCheck(v: SkillResolverView | null): Check | null {+ if (!v) return null;+ const details = { ...v };+ if (v.config === 'unreadable') {+ return { name: NAME, status: 'warn', message: `${describeSkillResolver(v)} The hook lane prints nothing until it can read it.`, details: { ...details, code: 'skill_resolver_config_unreadable' },+ fix: { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME), docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable',+ why: 'gbrain never rewrites a config file it cannot parse; the lane and setup leave it alone.',+ user_message: `gbrain's config file (${join(configDir(), 'config.json')}) is not valid JSON, so the skill resolver is paused. Fix or move it, then run: gbrain setup <claude-code|codex> --skill-loading resolve` } };+ }+ const broken = v.harnesses.find((h) => h.on && (h.hook !== 'wired' || !h.catalogs.some((c) => c.name === userCatalogName(h.harness))));+ if (broken) {+ const what = broken.hook === 'untrusted' ? 'its Codex hook is not trusted' : broken.hook === 'absent' ? 'its hook entry is missing' : 'its user catalog is missing';+ return { name: NAME, status: 'warn', message: `${describeSkillResolver(v)} ${broken.harness}: the resolver is on but ${what}, so no skills block is added.`, details,+ fix: { argv: setupArgv(broken.harness), consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(NAME),+ why: `Rebuilds the ${broken.harness} user catalog and rewrites only the skill-resolver hook entry; --skill-loading off removes it instead.` } };+ }+ return { name: NAME, status: 'ok', message: describeSkillResolver(v), details };+}diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex b964aadd02..f670f9975e 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -124,6 +124,7 @@ import { HOOK_SUBCOMMANDS as HOOK_EVENTS, ROUTERS, subcommandHelpRequested } froimport { isManagedFilesystemPath } from '../core/persistence/filesystem-guard.ts';import { brainFirstTurnRule } from '../core/setup/brain-first.ts';import { TURN_RULE_LANE, turnRuleHookYields } from '../core/setup/turn-hook.ts';+import { SKILL_RESOLVER_LANE } from '../core/setup/skill-resolver-lane.ts';import { captureHookSessionCwd, hookSessionCwd } from '../core/setup/hook-launcher.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -305,6 +306,12 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>// for silence, and a disabled hook writing telemetry would be a lie).if (process.env.GBRAIN_HOOKS === '0') return 0;+ // Skill-resolver lane (src/core/skills/resolver/hook-lane.ts): its own entry, its own output (only the skills block), its own yield rule.+ if (process.env.GBRAIN_HOOK_LANE === SKILL_RESOLVER_LANE) {+ const { runSkillResolverLane } = await import('../core/skills/resolver/hook-lane.ts');+ return runSkillResolverLane(event, io.harness === 'codex' ? 'codex' : 'claude-code', io.cwd ? { cwd: io.cwd } : {});+ }+// #4043 harness-lane defer guard: Claude Code MERGES user- and// project-scope hook settings, so a machine wired by `bootstrap harness`// (user scope) plus a real workspace bootstrap install (settings.local.json,diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex acbed945e0..d09cde155d 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -38,6 +38,8 @@ import { configDir, gbrainPath, isThinClient, loadConfig, type GBrainConfig } frimport { resolveGbrainBin } from '../core/gbrain-bin.ts';import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from '../core/mcp-registration.ts';import { hookLauncherPath } from '../core/setup/hook-launcher.ts';+import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';+import { describeResolverSetup, removeSkillResolverSetup, syncSkillResolverSetup, type ResolverSetupResult } from '../core/setup/skill-resolver-setup.ts';import { isValidSourceId } from '../core/source-id.ts';import { peekLock } from '../core/pglite-lock.ts';import { claudePluginProvidesName, codexPluginProvidesName } from '../core/bootstrap/plugin-lanes.ts';@@ -155,11 +157,15 @@ Flags:Works for a hosted connection too, and for any harness below.--workspace DIR OpenClaw: the agent workspace whose AGENTS.md gets the block(default: agents.defaults.workspace, then ~/.openclaw/workspace).- --skill-loading M off (default) or spring. spring adds a compact index of+ --skill-loading M off (default), spring or resolve. spring adds a compact index ofgbrain's bundled skills beside the brain-first block (about1.5k tokens) and loads a skill's full text only when a taskmatches (gbrain bundled-skill <name>, from this gbrain).- off removes an index an earlier run wrote. The+ resolve (claude-code, codex) indexes the harness's own skills+ (~/.claude/skills; Codex: ~/.agents/skills, CODEX_HOME/skills)+ and adds a separate per-turn hook that names the few skills+ that fit each prompt (word match; nothing leaves the machine).+ off removes what an earlier run wrote. Thechoice is remembered; GBRAIN_SKILL_LOADING sets it too.--skills-index-only Refresh every skills index recorded for this harness (itsfile, launcher and skill set as recorded) and change@@ -222,6 +228,8 @@ interface SetupFlags {skillsIndexOnly: boolean;workspace?: string;skillLoading?: SkillLoading;+ /** --skill-loading resolve turns the skill-resolver lane on (skill-resolver-setup.ts); off or spring turns it off; unset leaves it as it is. */+ skillResolver?: 'on' | 'off';}const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading']);@@ -245,10 +253,16 @@ function parseFlags(args: string[]): SetupFlags | string {if (args.includes('--instructions') && args.includes('--no-instructions')) return 'pass --instructions or --no-instructions, not both';const workspace = value('--workspace');if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';- const skillLoading = value('--skill-loading');- if (skillLoading !== undefined && !isSkillLoading(skillLoading)) return `unknown --skill-loading '${skillLoading}'; pass off or spring`;+ const flagLoading = value('--skill-loading');+ if (flagLoading !== undefined && flagLoading !== 'resolve' && !isSkillLoading(flagLoading)) return `unknown --skill-loading '${flagLoading}'; pass off, spring or resolve`;const envLoading = process.env[SKILL_LOADING_ENV]?.trim();- if (skillLoading === undefined && envLoading && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;+ if (flagLoading === undefined && envLoading && envLoading !== 'resolve' && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;+ const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex';+ if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code and Codex only (claude-code, codex); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';+ const chosenLoading = flagLoading ?? (envLoading || undefined);+ const skillResolver = !resolverHarness || chosenLoading === undefined ? undefined : chosenLoading === 'resolve' ? 'on' as const : 'off' as const;+ // resolve replaces the spring index: the skills block is decided as off, explicitly, so GBRAIN_SKILL_LOADING=resolve is never read as a block mode.+ const skillLoading = skillResolver === 'on' ? 'off' : flagLoading;return {harness: positionals[0],dryRun: args.includes('--dry-run'),@@ -267,6 +281,7 @@ function parseFlags(args: string[]): SetupFlags | string {skillsIndexOnly: args.includes('--skills-index-only'),workspace,skillLoading: skillLoading as SkillLoading | undefined,+ ...(skillResolver ? { skillResolver } : {}),};}@@ -491,7 +506,8 @@ export async function runSetup(args: string[]): Promise<number> {];const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, { scope, projectDir });const skills = skillsFor('claude-code', flags, launcher, { scope, projectDir }, instructions);- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills });+ const resolver = await resolverFor('claude-code', flags, launcher);+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver });}let notices: Notice[] = [];@@ -502,7 +518,8 @@ export async function runSetup(args: string[]): Promise<number> {for (const s of result.steps) say(out, ` ${s.action.padEnd(8)} ${s.step.padEnd(7)} ${s.detail}`);const instructions = brainFirstFor('claude-code', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, { scope, projectDir });const skills = skillsFor('claude-code', flags, launcher, { scope, projectDir }, instructions);- if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills)) say(out, 'Nothing changed: this install is already wired.');+ const resolver = await resolverFor('claude-code', flags, launcher);+ if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills) && !resolverChanged(resolver)) say(out, 'Nothing changed: this install is already wired.');let verify: { ok: boolean; reason: string; message: string } | null;if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Claude Code session and check /mcp lists gbrain.` };@@ -514,7 +531,7 @@ export async function runSetup(args: string[]): Promise<number> {const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('claude-code', { projectDir }) : null;const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook });+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver });if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('claude-code', turnHook, ['gbrain', 'setup', 'claude-code', ...(scope === 'project' ? ['--scope', 'project'] : [])]), out);return verify.ok || pluginOwner ? code : 1;} catch (e) {@@ -665,7 +682,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon];const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, {});const skills = skillsFor('codex', flags, launcher, {}, instructions);- return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills });+ const resolver = await resolverFor('codex', flags, launcher);+ return finish(out, { harness: 'codex', dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver });}let notices: Notice[] = [];@@ -677,7 +695,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConfor (const n of result.notes) say(out, `note: ${n}`);const instructions = brainFirstFor('codex', flags, { kind: 'mcp', server: flags.name, surface: plan.advertise ?? surface }, {});const skills = skillsFor('codex', flags, launcher, {}, instructions);- if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills)) say(out, 'Nothing changed: this install is already wired.');+ const resolver = await resolverFor('codex', flags, launcher);+ if (!result.changed && !instructionsChanged(instructions) && !instructionsChanged(skills) && !resolverChanged(resolver)) say(out, 'Nothing changed: this install is already wired.');let verify: { ok: boolean; reason: string; message: string };if (pluginOwner) verify = { ok: false, reason: 'plugin_lane', message: `The '${pluginOwner}' plugin serves MCP; start a new Codex session and check /mcp lists gbrain.` };@@ -690,7 +709,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConconst states = ['configured', ...(verify.ok ? ['connection-verified', push === 'native-verified' && result.receipt.trust.owned.UserPromptSubmit ? 'native-verified' : 'native-pending'] : [])];const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('codex') : null;const code = await finish(out, { harness: 'codex', dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent,- steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook });+ steps: result.steps, states, verify, notices, notes: [...notes, ...result.notes], preserved: result.preserved, instructions, skills, turnHook, resolver });if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('codex', turnHook, ['gbrain', 'setup', 'codex']), out);return verify.ok || pluginOwner ? code : 1;} catch (e) {@@ -704,7 +723,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainConasync function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | null, receiptPath: string, brainHome: string, out: Out): Promise<number> {if (!receipt) {say(out, `No gbrain setup receipt at ${receiptPath}; setup owns nothing here, so nothing was removed.`);- return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [] });+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [], resolver: await resolverFor('codex', flags, '') });}if (receipt.gbrain_home !== brainHome) {return refuse(ownerConflict('other_install', `The '${receipt.name}' connection belongs to the gbrain install at ${receipt.gbrain_home}, not ${brainHome}; --remove leaves it alone.`, {@@ -715,8 +734,9 @@ async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | nufor (const n of r.notes) say(out, `note: ${n}`);const instructions = removeBrainFirstFor('codex', {}, flags);const skills = removeSkillsFor('codex', {}, flags);+ const resolver = await resolverFor('codex', flags, '');say(out, 'The brain, its notes and unrelated Codex settings were left as they were.');- return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions, skills });+ return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions, skills, resolver });}function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {@@ -735,7 +755,7 @@ function hostedConnection(url: string, wired: boolean, name: string, harness: Seasync function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null, receiptPath: string, brainHome: string, out: Out): Promise<number> {if (!receipt) {say(out, `No gbrain setup receipt at ${receiptPath}; setup owns nothing here, so nothing was removed.`);- return finish(out, { dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [] });+ return finish(out, { dryRun: flags.dryRun, remove: true, steps: [], states: [], verify: null, notices: [], notes: [], resolver: await resolverFor('claude-code', flags, '') });}if (receipt.gbrain_home !== brainHome) {return refuse(ownerConflict('other_install', `The '${receipt.name}' connection belongs to the gbrain install at ${receipt.gbrain_home}, not ${brainHome}; --remove leaves it alone.`, {@@ -745,8 +765,9 @@ async function runRemove(flags: SetupFlags, receipt: ClaudeSetupReceipt | null,for (const s of r.steps) say(out, ` ${(flags.dryRun ? `would ${s.action}` : s.action).padEnd(14)} ${s.step.padEnd(7)} ${s.detail}`);const instructions = removeBrainFirstFor('claude-code', { scope: receipt.scope, projectDir: receipt.project_dir }, flags);const skills = removeSkillsFor('claude-code', { scope: receipt.scope, projectDir: receipt.project_dir }, flags);+ const resolver = await resolverFor('claude-code', flags, '');say(out, 'The brain, its notes and unrelated Claude Code settings were left as they were.');- return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved, instructions, skills });+ return finish(out, { dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: [], preserved: r.preserved, instructions, skills, resolver });}/** The brain-first block for this run: decided from flags, env and the ledger, then applied (or previewed under --dry-run). */@@ -785,7 +806,30 @@ function removeSkillsFor(harness: BrainFirstHarness, where: { scope?: WiringScopreturn path ? removeSkillsBlock({ harness, path, dryRun: flags.dryRun }) : null;}+/**+ * The skill-resolver lane for this run (claude-code, codex): --skill-loading+ * resolve turns it on, off or spring turns it off, and with no choice a lane+ * that is on is refreshed. Null when there is nothing to do, so an install+ * that never turned it on gets no new output.+ */+async function resolverFor(harness: SetupHarnessId, flags: SetupFlags, launcher: string): Promise<ResolverSetupResult | null> {+ const home = configDir();+ if (flags.skillResolver === 'off' || (flags.remove && flags.skillResolver !== 'on')) return removeSkillResolverSetup({ harness, home, dryRun: flags.dryRun });+ const cfg = readResolverConfig(home);+ if (flags.skillResolver !== 'on' && !(cfg.state === 'ok' && resolverHarnesses(cfg.doc).includes(harness))) return null;+ return syncSkillResolverSetup({ harness, gbrainBin: launcher, gbrainHome: process.env.GBRAIN_HOME?.trim() || undefined, home, dryRun: flags.dryRun });+}++function resolverRefusal(r: ResolverSetupResult): OperationError {+ const { code, message, scanned } = r.error!;+ const rerun = ['gbrain', 'setup', r.harness, '--skill-loading', 'resolve', '--dry-run'];+ return opError(code, message, code === 'skill_resolver_config_unreadable' ? 'Fix or move the config file, then run setup again.' : 'Add a skill to one of the scanned directories (or check they are readable), then run setup again.',+ { docs: `docs/guides/skill-resolver.md#${code}`, ...(scanned.length ? { detail: `scanned: ${scanned.join(', ')}` } : {}),+ fix: { argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the resolver setup would make and names the directories it scans; changes nothing.' } });+}+const instructionsChanged = (o: BrainFirstOutcome | SkillsBlockOutcome | null): boolean => !!o && (o.action === 'write' || o.action === 'remove');+const resolverChanged = (r: ResolverSetupResult | null): boolean => !!r && (!!r.error || r.steps.some((s) => s.action === 'write' || s.action === 'remove'));function describeInstructions(o: BrainFirstOutcome, dryRun: boolean): string {const how = o.decision.value === 'accepted' ? 'opt out with --no-instructions' : 'opt back in with --instructions';@@ -849,18 +893,21 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>// Loud failure: an accepted install whose per-turn hook does not load exits non-zero and names the harness's own check.// A 'print' outcome installed nothing and already names the step that does, so it is reported, not verified.const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;- const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) ? 1 : 0;+ const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;+ const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) || resolver?.error ? 1 : 0;if (out.json) {- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, mcp }, null, 2)}\n`, (t) => process.stdout.write(t));+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, ...(resolver ? { skill_resolver: resolver } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));return code;}if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}${'next' in turnHook && turnHook.next ? `; wire it with: ${turnHook.next}` : ''}`);else if (!off && placed) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);if (skills && skillsOutcomeShown(skills)) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));+ if (resolver) for (const line of describeResolverSetup(resolver, flags.dryRun)) say(out, line);if (check?.ok) say(out, ` verify ${'turn hook'.padEnd(7)} ${check.message}`);if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');+ if (resolver?.error) return refuse(resolverRefusal(resolver), out);if (check && !check.ok) return refuse(turnHookNotLoaded(harness, check, rerun), out);return code;}@@ -872,13 +919,16 @@ async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number>return refuse(opError('invalid_params', `--skills-index-only needs a harness with an instruction file: ${BRAIN_FIRST_HARNESSES.join(', ')}`, 'Pass the harness whose skills index to refresh, e.g. gbrain setup claude-code --skills-index-only.'), out);}const outcomes = refreshSkillsIndexes(harness, { mode: flags.skillLoading, launcher: flags.gbrainBin, dryRun: flags.dryRun });- const code = outcomes.some((o) => o.action === 'preserve') ? 1 : 0;+ const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;+ const code = outcomes.some((o) => o.action === 'preserve') || resolver?.error ? 1 : 0;if (out.json) {- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes }, null, 2)}\n`, (t) => process.stdout.write(t));+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes, ...(resolver ? { skill_resolver: resolver } : {}) }, null, 2)}\n`, (t) => process.stdout.write(t));return code;}- if (outcomes.length === 0) say(out, `No skills index is recorded for ${harness}. Add one with: gbrain setup ${harness} --skill-loading spring`);+ if (outcomes.length === 0 && !resolver) say(out, `No skills index is recorded for ${harness}. Add one with: gbrain setup ${harness} --skill-loading spring`);for (const o of outcomes) say(out, describeSkillsBlockOutcome(o, flags.dryRun));+ if (resolver) for (const line of describeResolverSetup(resolver, flags.dryRun)) say(out, line);+ if (resolver?.error) return refuse(resolverRefusal(resolver), out);return code;}@@ -908,15 +958,16 @@ async function finish(out: Out, doc: {instructions?: BrainFirstOutcome | null;skills?: SkillsBlockOutcome | null;turnHook?: TurnHookVerdict | null;+ resolver?: ResolverSetupResult | null;}): Promise<number> {const harness = doc.harness ?? 'claude-code';const state = doc.states.at(-1) ?? null;- const code = skillsFailed(doc.skills ?? null) ? 1 : 0;+ const code = skillsFailed(doc.skills ?? null) || doc.resolver?.error ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({harness, dry_run: doc.dryRun, remove: doc.remove ?? false,...(doc.target ? { target: doc.target } : {}), ...(doc.consent ? { consent: doc.consent } : {}),- steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, skills: doc.skills ?? null, ...(doc.turnHook ? { turn_hook_check: doc.turnHook } : {}), states: doc.states, state, verify: doc.verify,+ steps: doc.steps, preserved: doc.preserved ?? [], instructions: doc.instructions ?? null, skills: doc.skills ?? null, ...(doc.resolver ? { skill_resolver: doc.resolver } : {}), ...(doc.turnHook ? { turn_hook_check: doc.turnHook } : {}), states: doc.states, state, verify: doc.verify,capability: capabilityRows(harness)[0], capability_table_version: SETUP_CAPABILITY_TABLE_VERSION,notes: doc.notes, notices: doc.notices.map((n) => renderNotice(n, cliRenderContext())),}, null, 2)}\n`, (t) => process.stdout.write(t));@@ -924,6 +975,7 @@ async function finish(out: Out, doc: {}if (doc.instructions) say(out, doc.remove ? describeBrainFirstOutcome(doc.instructions, doc.dryRun) : describeInstructions(doc.instructions, doc.dryRun));if (doc.skills && skillsOutcomeShown(doc.skills)) say(out, describeSkillsBlockOutcome(doc.skills, doc.dryRun));+ if (doc.resolver) for (const line of describeResolverSetup(doc.resolver, doc.dryRun)) say(out, line);if (doc.verify) say(out, `Verify: ${doc.verify.ok ? 'ok' : 'not verified'} (${doc.verify.reason}): ${doc.verify.message}`);if (doc.turnHook?.ok) say(out, `Turn hook: ok (${doc.turnHook.reason}): ${doc.turnHook.message}`);if (state) say(out, `State: ${state} (${doc.states.join(' -> ')}).${state === 'native-verified' ? '' : ' Native push is not claimed until an observed event reaches a fresh session.'}`);@@ -934,6 +986,7 @@ async function finish(out: Out, doc: {+ 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');writeCliNotices(doc.notices.filter((n) => n.code !== 'hosted_option'));if (doc.notices.some((n) => n.code === 'hosted_option')) writeHostedOption('setup', new Set());+ if (doc.resolver?.error) return refuse(resolverRefusal(doc.resolver), out);return code;}diff --git a/src/core/bootstrap/codex-hooks.ts b/src/core/bootstrap/codex-hooks.tsindex 260bfc2785..6056cbcd4c 100644--- a/src/core/bootstrap/codex-hooks.ts+++ b/src/core/bootstrap/codex-hooks.ts@@ -365,6 +365,7 @@ export function removeCodexHooks(opts: { hooksPath?: string; configPath?: stringexport const CODEX_SETUP_LANE_TOKEN = 'GBRAIN_HOOK_LANE=setup';const TURN_RULE_LANE_TOKEN = 'GBRAIN_HOOK_LANE=turn-rule';+const SKILL_RESOLVER_LANE_TOKEN = 'GBRAIN_HOOK_LANE=skill-resolver';export const CODEX_SETUP_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'] as const;export type CodexSetupEvent = (typeof CODEX_SETUP_EVENTS)[number];@@ -426,7 +427,9 @@ export function codexHookCensus(hooksPath: string): CodexHookCensusGroup[] {if (!Array.isArray(groups)) continue;groups.forEach((group, index) => {const commands = (Array.isArray(group?.hooks) ? group.hooks : []).map((h) => h?.command).filter((c): c is string => typeof c === 'string');- const lane = commands.some((c) => c.includes(CODEX_SETUP_LANE_TOKEN)) ? 'setup'+ // The skill-resolver lane (setup/skill-resolver-lane.ts) wires UserPromptSubmit with the context command shape but adds only its skills block: never a context lane.+ const lane = commands.some((c) => c.includes(SKILL_RESOLVER_LANE_TOKEN)) ? 'other'+ : commands.some((c) => c.includes(CODEX_SETUP_LANE_TOKEN)) ? 'setup': commands.some((c) => c.includes(TURN_RULE_LANE_TOKEN)) ? 'turn-rule': commands.some((c) => CONTEXT_LANE_TOKENS.some((t) => c.includes(t))) ? 'bootstrap' : 'other';out.push({ event, index, hash: ownedEntryFingerprint(group), lane, commands });diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.tsindex ad1c6a9974..271b87b6de 100644--- a/src/core/bootstrap/hooks.ts+++ b/src/core/bootstrap/hooks.ts@@ -32,6 +32,7 @@ import { normalizeSeatLabel } from '../context/seat.ts';import { detectExecutionEnvironment } from '../execution-env.ts';import { stdioServeArgv } from '../mcp-registration.ts';import { isHookLauncherPath } from '../setup/hook-launcher.ts';+import { SKILL_RESOLVER_MARKER } from '../setup/skill-resolver-lane.ts';import type { McpSurface } from '../../mcp/surface.ts';import type { HarnessReceipt, HarnessTarget } from './format.ts';import {@@ -468,11 +469,11 @@ function isOurs(entry: unknown, marker: string = GBRAIN_HOOK_MARKER_VALUE): bool);}-/** True when the entry carries the gbrain marker KEY with any OTHER value. */+/** True when the entry carries the gbrain marker KEY with any OTHER value (the skill-resolver lane's never double-fires a context hook, so it never counts). */function isForeignGbrainMarked(entry: unknown, marker: string): boolean {if (typeof entry !== 'object' || entry === null) return false;const v = (entry as Record<string, unknown>)[GBRAIN_HOOK_MARKER_KEY];- return typeof v === 'string' && v !== marker;+ return typeof v === 'string' && v !== marker && v !== SKILL_RESOLVER_MARKER;}/**diff --git a/src/core/bootstrap/plugin-lanes.ts b/src/core/bootstrap/plugin-lanes.tsindex 7daadca4e8..e42711d294 100644--- a/src/core/bootstrap/plugin-lanes.ts+++ b/src/core/bootstrap/plugin-lanes.ts@@ -10,6 +10,7 @@ import { join } from 'node:path';import { codexHookCensus, codexHookGroupRuns } from './codex-hooks.ts';import { classifyHarnessHook } from './hooks.ts';import { isTurnRuleEntry } from '../setup/turn-hook.ts';+import { isSkillResolverEntry } from '../setup/skill-resolver-lane.ts';import { claudeSetupPaths } from '../setup/claude-code.ts';import { codexSetupPaths } from '../setup/codex.ts';import { CLAUDE_HOOK_SUBCOMMAND, claudeUserSettingsPath, codexConfigPath, codexHooksPath, GBRAIN_HOOK_MARKER_KEY } from './host-specs.ts';@@ -221,7 +222,7 @@ export function pluginHookYields(harness: string, subcommand: string, cwd: strinif (!Array.isArray(groups)) continue;for (const g of groups) {const entries = (g as { hooks?: unknown })?.hooks;- if (Array.isArray(entries) && entries.some((e) => typeof (e as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY] === 'string' || classifyHarnessHook(e, event, 'any') || isTurnRuleEntry(e))) return true;+ if (Array.isArray(entries) && entries.some((e) => !isSkillResolverEntry(e) && (typeof (e as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY] === 'string' || classifyHarnessHook(e, event, 'any') || isTurnRuleEntry(e)))) return true;}} catch { /* fail-open */ }}diff --git a/src/core/config.ts b/src/core/config.tsindex aeeea74b96..d90265da8b 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -730,6 +730,11 @@ export function loadConfig(): GBrainConfig | null {const dbUrl = effectiveEnvDatabaseUrl();if (!fileConfig && !dbUrl) return null;+ // GBRA-377: a config.json that holds only file-plane settings (a brainless+ // install's skills.resolver keys) configures no brain. A brain is an engine,+ // a database or a remote endpoint, never the file existing, so such a file+ // must not be read as an implicit Postgres brain.+ if (!dbUrl && fileConfig && !fileConfig.engine && !fileConfig.database_url && !fileConfig.database_path && !fileConfig.remote_mcp) return null;// Infer engine type. A DATABASE_URL-style env var is always a Postgres// connection target and must override a file-backed PGLite enginediff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 8f9bbce2a4..80f078e8ce 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -311,6 +311,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['chat_fallback_chain',// Agent operator wave: is an agent harness wired to this brain (registration read; --only adds the smoke test).'harness_wiring',+ // GBRA-377 PR B: the skill-resolver hook lane's hook, catalog freshness and recent error codes; silent when unconfigured (doctor/checks/skill-resolver.ts).+ 'skill_resolver',// Cat 41: the provider-use decision gbrain setup recorded; declined = no provider request (discovery, probe).'provider_consent','frontmatter_hook',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex fa82eb7d37..1ca4c24750 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -736,6 +736,8 @@ export const CODES = {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_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 <gbrain home>/config.json (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.' } },skill_source_invalid: { class: 'caller', exit: 2, summary: 'The --from-json catalog or --routing file is not valid (not JSON, a malformed entry, over 10,000 skills or 8 MB, or a routing file over 1 MB), so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_invalid', suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects.' },skill_source_unreadable: { class: 'caller', summary: 'A --dir or --routing path does not exist or cannot be read, so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_unreadable', suggestion: 'Pass an existing directory (or file) you can read.' },diff --git a/src/core/setup/claude-code.ts b/src/core/setup/claude-code.tsindex 6dfd094a79..8e7c280eb4 100644--- a/src/core/setup/claude-code.ts+++ b/src/core/setup/claude-code.ts@@ -38,6 +38,7 @@ import {} from '../bootstrap/host-specs.ts';import { stdioServeArgv } from '../mcp-registration.ts';import { isTurnRuleEntry } from './turn-hook.ts';+import { isSkillResolverEntry } from './skill-resolver-lane.ts';import { ensureHookLauncher, hookLauncherPath } from './hook-launcher.ts';import type { McpSurface } from '../../mcp/surface.ts';@@ -210,7 +211,7 @@ function hookCensus(settingsPath: string): HookCensus {if (!Array.isArray(entries)) continue;for (const entry of entries) {const marker = (entry as Record<string, unknown> | null)?.[GBRAIN_HOOK_MARKER_KEY];- if (isTurnRuleEntry(entry)) continue;+ if (isTurnRuleEntry(entry) || isSkillResolverEntry(entry)) continue;if ((typeof marker === 'string' && marker !== GBRAIN_SETUP_MARKER_VALUE) || classifyHarnessHook(entry, event, 'any')) {if ((CLAUDE_HOOK_EVENTS as readonly string[]).includes(event)) otherLane.add(event);continue;diff --git a/src/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.tsnew file mode 100644index 0000000000..441ebddad9--- /dev/null+++ b/src/core/setup/skill-resolver-config.ts@@ -0,0 +1,138 @@+/**+ * skill-resolver-config.ts — the skill resolver's file-plane keys in+ * <config dir>/config.json, read and written engine-free:+ *+ * skills.resolver.enabled true while setup has the lane on for any harness+ * skills.resolver.harnesses the harnesses setup turned it on for+ * 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)+ *+ * A missing file is created with only these keys: no engine, no database, so+ * a brainless install stays brainless (loadConfig decides "a brain is+ * configured" from an engine, a database or a remote endpoint, never from+ * the file existing). A file that exists but cannot be read or parsed is+ * never rewritten: skill_resolver_config_unreadable.+ */+import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { validateSessionTokenBudget } from '../skills/resolver/config.ts';++const CONFIG_CAP_BYTES = 1024 * 1024;++/** A JSON object file, or null when it is missing, unreadable or not an object. */+export function readJsonObjectSafe(path: string): Record<string, unknown> | null {+ try {+ const v = JSON.parse(readFileSync(path, 'utf8')) as unknown;+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;+ } catch { return null; }+}++export type ResolverConfigRead = { state: 'absent'; path: string } | { state: 'ok'; path: string; doc: Record<string, unknown> } | { state: 'unreadable'; path: string; why: string };++export function readResolverConfig(home: string): ResolverConfigRead {+ const path = join(home, 'config.json');+ if (!existsSync(path)) return { state: 'absent', path };+ try {+ if (statSync(path).size > CONFIG_CAP_BYTES) return { state: 'unreadable', path, why: 'it is over 1 MB' };+ const v = JSON.parse(readFileSync(path, 'utf8')) as unknown;+ if (!v || typeof v !== 'object' || Array.isArray(v)) return { state: 'unreadable', path, why: 'it is not a JSON object' };+ return { state: 'ok', path, doc: v as Record<string, unknown> };+ } catch (e) {+ return { state: 'unreadable', path, why: e instanceof SyntaxError ? 'it is not valid JSON' : (e as Error).message };+ }+}++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> : {};+}++/** The harnesses setup has the lane on for (empty when off or unconfigured). */+export function resolverHarnesses(doc: Record<string, unknown> | null): string[] {+ if (!doc) return [];+ const r = resolverSection(doc);+ return r.enabled === true && Array.isArray(r.harnesses) ? r.harnesses.filter((h): h is string => typeof h === 'string') : [];+}++/**+ * Add or drop one harness. Returns what changed (nothing when the keys+ * already say so). Dropping the last harness removes enabled and harnesses,+ * then empty skills.resolver and skills objects, and a config.json left+ * empty. The caller has checked the file is readable.+ */+export function setResolverHarness(read: Exclude<ResolverConfigRead, { state: 'unreadable' }>, harness: string, on: boolean, dryRun: boolean): { changed: boolean; keys: string[]; deletedFile: boolean } {+ const doc = read.state === 'ok' ? structuredClone(read.doc) : {};+ const before = resolverHarnesses(read.state === 'ok' ? read.doc : null);+ const next = on ? [...new Set([...before, harness])].sort() : before.filter((h) => h !== harness);+ const r = resolverSection(doc);+ const changed = on ? !(before.includes(harness) && r.enabled === true) : before.includes(harness) || (next.length === 0 && ('enabled' in r || 'harnesses' in r));+ if (!changed) return { changed: false, keys: [], deletedFile: false };+ if (next.length) Object.assign(r, { enabled: true, harnesses: next });+ else { delete r.enabled; delete r.harnesses; }+ const skills = (doc.skills && typeof doc.skills === 'object' && !Array.isArray(doc.skills) ? doc.skills : {}) as Record<string, unknown>;+ if (Object.keys(r).length) skills.resolver = r; else delete skills.resolver;+ if (Object.keys(skills).length) doc.skills = skills; else delete doc.skills;+ const keys = ['skills.resolver.enabled', 'skills.resolver.harnesses'];+ const deletedFile = Object.keys(doc).length === 0;+ if (!dryRun) {+ if (deletedFile) { try { unlinkSync(read.path); } catch { /* never created */ } }+ else atomicWriteTextFile(read.path, `${JSON.stringify(doc, null, 2)}\n`, { freshMode: 0o600 });+ }+ return { changed: true, keys, deletedFile };+}++export 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;++function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean | number } | { ok: false; error: string } {+ 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' };+ }+ const n = /^\d+$/.test(value) ? Number(value) : NaN;+ if (leaf === 'lane_payload_chars') return Number.isSafeInteger(n) && n >= 500 && n <= 10_000 ? { ok: true, value: n } : { ok: false, error: 'must be a whole number of characters from 500 to 10000 (default 4000)' };+ try { return { ok: true, value: validateSessionTokenBudget(n, `${SKILL_RESOLVER_KEY_PREFIX}session_token_budget`) }; } catch (e) { return { ok: false, error: (e as Error).message }; }+}++/**+ * `gbrain config set|unset|get skills.resolver.<leaf>`, engine-free (before+ * any brain connection, on a brainless install and on a thin client alike):+ * the file plane is the only plane these keys have. Returns false for a+ * key or action this does not own.+ */+export function runSkillResolverConfigKey(args: string[], home: string): boolean {+ const [action, key, ...rest] = args;+ if (!key?.startsWith(SKILL_RESOLVER_KEY_PREFIX) || !['set', 'unset', 'get'].includes(action ?? '')) return false;+ const leaf = key.slice(SKILL_RESOLVER_KEY_PREFIX.length);+ const fail = (msg: string): true => { console.error(`[config] ${msg}`); process.exitCode = 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 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);+ 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]));+ return true;+ }+ if (action === 'unset') {+ if (!(leaf in section)) return fail(`Config key not found: ${key}`);+ delete section[leaf];+ } 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;+ }+ 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;+ 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)`);+ return true;+}diff --git a/src/core/setup/skill-resolver-hook.ts b/src/core/setup/skill-resolver-hook.tsnew file mode 100644index 0000000000..a3498ceffb--- /dev/null+++ b/src/core/setup/skill-resolver-hook.ts@@ -0,0 +1,161 @@+/**+ * skill-resolver-hook.ts — the skill-resolver lane's hook wiring+ * (`GBRAIN_HOOK_LANE=skill-resolver`, runtime in+ * src/core/skills/resolver/hook-lane.ts), written by+ * `gbrain setup <claude-code|codex> --skill-loading resolve`+ * (skill-resolver-setup.ts) and removed by `--skill-loading off` and+ * `setup --remove`.+ *+ * - Claude Code: its own entries in the user settings file, marked+ * `skill-resolver-v1`: UserPromptSubmit (`hook user-prompt`) and+ * SessionStart (`hook session-start`, which only resets a session's+ * dedupe state after a compaction).+ * - Codex: its own UserPromptSubmit group in CODEX_HOME/hooks.json+ * (`hook user-prompt --harness codex`), trusted by its hash in+ * config.toml beside it, like the turn-rule lane.+ *+ * Both run gbrain through the existing hook launcher (hook-launcher.ts); this+ * module writes nothing else into the launcher's directory. Ownership: the+ * marker, else the lane token in the command (Claude Code), the lane token+ * (Codex). Nothing else in either file is touched.+ */+import { mkdirSync } from 'node:fs';+import { dirname } from 'node:path';+import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';+import { codexHookCensus, codexHookTrustHash, codexSetupHookGroup, codexSetupTrustEntry, writeCodexSetupHooks, type CodexHookGroup } from '../bootstrap/codex-hooks.ts';+import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from '../bootstrap/codex-toml.ts';+import { buildClaudeHookCommand, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';+import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, claudeUserSettingsPath, codexConfigPath, codexHooksPath, type ClaudeHookEvent } from '../bootstrap/host-specs.ts';+import { readJsonObjectSafe } from './skill-resolver-config.ts';+import { ensureHookLauncher, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';+import { isSkillResolverCommand, isSkillResolverEntry, SKILL_RESOLVER_LANE, SKILL_RESOLVER_MARKER } from './skill-resolver-lane.ts';++export type ResolverHarness = 'claude-code' | 'codex';+const CLAUDE_EVENTS: ClaudeHookEvent[] = ['UserPromptSubmit', 'SessionStart'];+const TRUST_STATE = 'user_prompt_submit';++export interface ResolverHookPaths { claudeSettings?: string; codexHooks?: string; codexConfig?: string; hookLauncher?: string }+export interface ResolverHookOutcome { action: 'write' | 'keep' | 'remove' | 'skip' | 'refuse'; path: string; detail: string }++const claudePath = (p: ResolverHookPaths) => p.claudeSettings ?? claudeUserSettingsPath();+const codexPaths = (p: ResolverHookPaths) => ({ hooks: p.codexHooks ?? codexHooksPath(), config: p.codexConfig ?? codexConfigPath() });+const laneEnv = (home: string | undefined) => ({ ...(home ? { GBRAIN_HOME: home } : {}), GBRAIN_HOOK_LANE: SKILL_RESOLVER_LANE });++/** Every entry of this lane in a Claude Code settings file, by event. */+function claudeOurs(path: string): Array<{ event: string; entry: Record<string, unknown> }> {+ const hooks = readJsonObjectSafe(path)?.hooks;+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return [];+ return Object.entries(hooks as Record<string, unknown>).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : [])+ .flatMap((g) => (Array.isArray((g as { hooks?: unknown })?.hooks) ? (g as { hooks: unknown[] }).hooks : []))+ .filter(isSkillResolverEntry).map((entry) => ({ event, entry: entry as Record<string, unknown> })));+}++function codexOurs(p: { hooks: string }) {+ return codexHookCensus(p.hooks).filter((g) => g.event === 'UserPromptSubmit' && g.commands.some(isSkillResolverCommand));+}++export function codexResolverGroup(bin: string, home: string | undefined, launcher: string): CodexHookGroup {+ return codexSetupHookGroup(bin, 'UserPromptSubmit', home ? { GBRAIN_HOME: home } : {}, SKILL_RESOLVER_LANE, launcher);+}++/** The commands this install's lane runs (what the hook entries would hold). */+export function skillResolverCommands(harness: ResolverHarness, bin: string, home: string | undefined, launcher: string): string[] {+ if (harness === 'codex') return codexResolverGroup(bin, home, launcher).hooks.map((h) => h.command);+ return CLAUDE_EVENTS.map((e) => buildClaudeHookCommand(bin, e, laneEnv(home), launcher));+}++/** Whether this lane's hook is present: absent, wired (and, on Codex, trusted) or untrusted. */+export function inspectSkillResolverHook(harness: ResolverHarness, paths: ResolverHookPaths = {}): { state: 'absent' | 'wired' | 'untrusted'; path: string; commands: string[] } {+ try {+ if (harness === 'codex') {+ const p = codexPaths(paths);+ const ours = codexOurs(p);+ if (ours.length === 0) return { state: 'absent', path: p.hooks, commands: [] };+ const g = ours[0]!;+ const table = readCodexTomlTable(p.config, ['hooks', 'state', `${p.hooks}:${TRUST_STATE}:${g.index}:0`]) as { trusted_hash?: unknown; enabled?: unknown } | undefined;+ const trusted = table?.enabled !== false && table?.trusted_hash === codexHookTrustHash(TRUST_STATE, g.commands[0]!, 15);+ return { state: trusted ? 'wired' : 'untrusted', path: p.hooks, commands: g.commands };+ }+ const path = claudePath(paths);+ const ours = claudeOurs(path);+ return { state: ours.some((o) => o.event === 'UserPromptSubmit') ? 'wired' : 'absent', path, commands: ours.map((o) => String(o.entry.command)) };+ } catch {+ return { state: 'absent', path: harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths), commands: [] };+ }+}++/** Install or refresh the lane's hook. Throws on a file it cannot write safely. */+export function syncSkillResolverHook(opts: { harness: ResolverHarness; gbrainBin: string; gbrainHome?: string; paths?: ResolverHookPaths; dryRun?: boolean }): ResolverHookOutcome {+ const paths = opts.paths ?? {};+ const launcher = paths.hookLauncher ?? hookLauncherPath();+ const launcherFresh = hookLauncherState(launcher).state === 'current';+ if (!opts.dryRun) ensureHookLauncher(launcher);+ const out = opts.harness === 'codex' ? syncCodex(opts.gbrainBin, opts.gbrainHome, launcher, codexPaths(paths), !!opts.dryRun)+ : syncClaude(opts.gbrainBin, opts.gbrainHome, launcher, claudePath(paths), !!opts.dryRun);+ return out.action === 'keep' && !launcherFresh ? { ...out, action: 'write', detail: `${out.detail}; hook launcher ${launcher}` } : out;+}++function syncClaude(bin: string, home: string | undefined, launcher: string, path: string, dryRun: boolean): ResolverHookOutcome {+ const want = CLAUDE_EVENTS.map((e) => hookEntryHash({ type: 'command', command: buildClaudeHookCommand(bin, e, laneEnv(home), launcher), timeout: CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[e] })!);+ const ours = claudeOurs(path);+ const detail = `skill-resolver lane hooks (UserPromptSubmit, SessionStart) in ${path}`;+ const have = ours.map((o) => hookEntryHash(o.entry));+ if (have.length === want.length && want.every((h) => have.includes(h))) return { action: 'keep', path, detail };+ if (dryRun) return { action: 'write', path, detail };+ mkdirSync(dirname(path), { recursive: true });+ writeClaudeHooksAt(path, { gbrainBin: bin, hookLauncher: launcher, env: { ...laneEnv(home), GBRAIN_SEAT: '' }, events: CLAUDE_EVENTS, marker: SKILL_RESOLVER_MARKER,+ ownedEntryHashes: new Set([...want, ...have.filter((h): h is string => !!h)]), freshMode: 0o600 });+ return { action: 'write', path, detail };+}++const trustPath = (key: string) => ['hooks', 'state', key];++function dropOurTrust(config: string, hooks: string, ours: ReturnType<typeof codexOurs>): void {+ const commands = ours.flatMap((g) => g.commands);+ for (const g of ours) {+ const key = `${hooks}:${TRUST_STATE}:${g.index}:0`;+ const table = readCodexTomlTable(config, trustPath(key)) as { trusted_hash?: unknown } | undefined;+ if (table && commands.some((c) => codexHookTrustHash(TRUST_STATE, c, 15) === table.trusted_hash)) removeCodexTomlTable(config, trustPath(key));+ }+}++function syncCodex(bin: string, home: string | undefined, launcher: string, p: { hooks: string; config: string }, dryRun: boolean): ResolverHookOutcome {+ const group = codexResolverGroup(bin, home, launcher);+ const hash = ownedEntryFingerprint(group);+ const ours = codexOurs(p);+ const detail = `skill-resolver lane hook (UserPromptSubmit) in ${p.hooks}, trusted in ${p.config}`;+ const current = ours.length === 1 && ours[0]!.hash === hash;+ const entry = codexSetupTrustEntry(p.hooks, 'UserPromptSubmit', current ? ours[0]!.index : 0, group);+ if (current && (readCodexTomlTable(p.config, trustPath(entry.key)) as { trusted_hash?: unknown } | undefined)?.trusted_hash === entry.trusted_hash) return { action: 'keep', path: p.hooks, detail };+ if (dryRun) return { action: 'write', path: p.hooks, detail };+ mkdirSync(dirname(p.hooks), { recursive: true, mode: 0o700 });+ dropOurTrust(p.config, p.hooks, ours);+ const w = writeCodexSetupHooks(p.hooks, { want: { UserPromptSubmit: group }, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });+ const index = w.indexes.UserPromptSubmit;+ if (index === undefined) return { action: 'refuse', path: p.hooks, detail: `${p.hooks} did not take the skill-resolver hook` };+ const trust = codexSetupTrustEntry(p.hooks, 'UserPromptSubmit', index, group);+ const existing = readCodexTomlTable(p.config, trustPath(trust.key)) as { trusted_hash?: unknown } | undefined;+ if (existing === undefined) appendCodexTomlTable(p.config, trustPath(trust.key), { trusted_hash: trust.trusted_hash }, 'gbrain setup (skill-resolver): trusts the skill-resolver lane hook; owned by its hash');+ else if (existing.trusted_hash !== trust.trusted_hash) return { action: 'refuse', path: p.hooks, detail: `${p.config} already has a different [hooks.state."${trust.key}"]; trust gbrain's skill-resolver hook in Codex's /hooks` };+ return { action: 'write', path: p.hooks, detail };+}++/** Remove the lane's hook (and, on Codex, its trust entry). Throws on a file it cannot write safely. */+export function removeSkillResolverHook(opts: { harness: ResolverHarness; paths?: ResolverHookPaths; dryRun?: boolean }): ResolverHookOutcome {+ const paths = opts.paths ?? {};+ if (opts.harness === 'codex') {+ const p = codexPaths(paths);+ const ours = codexOurs(p);+ if (ours.length === 0) return { action: 'skip', path: p.hooks, detail: `no skill-resolver hook in ${p.hooks}` };+ if (!opts.dryRun) {+ dropOurTrust(p.config, p.hooks, ours);+ writeCodexSetupHooks(p.hooks, { want: {}, owned: new Set(ours.map((g) => g.hash)), preserve: new Set() });+ }+ return { action: 'remove', path: p.hooks, detail: `skill-resolver lane hook from ${p.hooks} and its trust entry from ${p.config}` };+ }+ const path = claudePath(paths);+ const ours = claudeOurs(path);+ if (ours.length === 0) return { action: 'skip', path, detail: `no skill-resolver hooks in ${path}` };+ if (!opts.dryRun) removeClaudeHooksAt(path, SKILL_RESOLVER_MARKER, { ownedEntryHashes: new Set(ours.map((o) => hookEntryHash(o.entry)).filter((h): h is string => !!h)) });+ return { action: 'remove', path, detail: `skill-resolver lane hooks from ${path}` };+}diff --git a/src/core/setup/skill-resolver-lane.ts b/src/core/setup/skill-resolver-lane.tsnew file mode 100644index 0000000000..a4339c2f6d--- /dev/null+++ b/src/core/setup/skill-resolver-lane.ts@@ -0,0 +1,22 @@+/**+ * Identity of the skill-resolver hook lane (`GBRAIN_HOOK_LANE=skill-resolver`,+ * src/core/skills/resolver/hook-lane.ts), as a leaf every other lane can+ * import: its entries never count as a turn-rule, setup, bootstrap or plugin+ * wiring of an event (the resolver lane only adds the skills block, never the+ * per-turn rule or the read-context block), and those lanes never yield to it.+ */+export const SKILL_RESOLVER_LANE = 'skill-resolver';+export const SKILL_RESOLVER_MARKER = 'skill-resolver-v1';+export const SKILL_RESOLVER_LANE_TOKEN = 'GBRAIN_HOOK_LANE=skill-resolver';++/** A hook command that runs this lane (any carrier, any event). */+export function isSkillResolverCommand(command: unknown): boolean {+ return typeof command === 'string' && /(?:^|[\s'])GBRAIN_HOOK_LANE=skill-resolver(?=[\s']|$)/.test(command) && /\shook\s/.test(command);+}++/** A Claude Code hook entry that is this lane's: marked, or (marker dropped on a rewrite) its command. */+export function isSkillResolverEntry(entry: unknown): boolean {+ if (!entry || typeof entry !== 'object') return false;+ const e = entry as Record<string, unknown>;+ return e._gbrain === SKILL_RESOLVER_MARKER || isSkillResolverCommand(e.command);+}diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.tsnew file mode 100644index 0000000000..eebfe227c6--- /dev/null+++ b/src/core/setup/skill-resolver-setup.ts@@ -0,0 +1,146 @@+/**+ * skill-resolver-setup.ts — `gbrain setup <claude-code|codex> --skill-loading+ * 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+ * (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+ * a fresh catalog, the keys and the hook in place changes nothing. It ends+ * with a sample block and an "on; N skills; fresh" status line.+ *+ * Off: remove the hook, the keys, this harness's catalogs (user and project)+ * and, when no harness is left on, the session state and the lane log.+ * Returns null when there is nothing of the resolver's for this harness, so+ * an install that never turned it on gets no new output.+ *+ * Default setup (no --skill-loading resolve) never writes a catalog, and+ * nothing here writes into the hook launcher's directory beyond the launcher+ * setup already writes.+ */+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 { 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 { readResolverConfig, resolverHarnesses, 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 }+export interface ResolverSetupError { code: 'skill_resolver_setup_incomplete' | 'skill_resolver_config_unreadable'; message: string; scanned: string[] }+export interface ResolverSetupResult {+ harness: ResolverHarness;+ mode: 'on' | 'off';+ steps: ResolverStep[];+ status?: { catalog: string; skills: number; fresh: boolean; line: string };+ sample?: string;+ error?: ResolverSetupError;+}++export const userCatalog = (harness: ResolverHarness) => `${harness}-user`;+const isHarnessCatalog = (harness: ResolverHarness, name: string) => name === userCatalog(harness) || name.startsWith(`${harness}-project-`);++/** The user-level skill directories a harness loads natively, whether or not they exist. */+export function harnessSkillDirs(harness: ResolverHarness): string[] {+ if (harness === 'claude-code') return [claudeUserSkillsDir()];+ return [join(process.env.HOME?.trim() || '', '.agents', 'skills'), join(dirname(codexConfigPath()), 'skills')];+}++function incomplete(scanned: string[] | null, why: string, sideEffects: string): ResolverSetupError {+ return { code: 'skill_resolver_setup_incomplete', scanned: scanned ?? [],+ message: `The skill resolver was not turned on: ${why}${scanned ? ` (scanned ${scanned.join(', ')})` : ''}. ${sideEffects}` };+}++/** Turn the lane on for one harness (or preview it). */+export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; gbrainBin: string; gbrainHome?: string; home: string; dryRun: boolean; paths?: ResolverHookPaths }): Promise<ResolverSetupResult> {+ const { harness, home, dryRun } = opts;+ const out: ResolverSetupResult = { harness, mode: 'on', steps: [] };+ const cfg = readResolverConfig(home);+ if (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));+ 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);+ if (dirs.length === 0) return { ...out, error: incomplete(harnessSkillDirs(harness), 'no user-level skill directory exists', 'Nothing was written.') };++ 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) {+ 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.`) };+ }+ 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}` });++ 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}` });+ const hook = syncSkillResolverHook({ harness, gbrainBin: opts.gbrainBin, gbrainHome: opts.gbrainHome, paths: opts.paths, dryRun });+ if (hook.action === 'refuse') return { ...out, error: incomplete(dirs, hook.detail, 'The catalog and the config keys were written; re-run after fixing that.') };+ out.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'}` } };+}++/** Whether anything of the resolver's exists for this harness (keys, hook or catalogs). */+export function skillResolverPresent(harness: ResolverHarness, home: string, paths?: ResolverHookPaths): boolean {+ const cfg = readResolverConfig(home);+ if (cfg.state === 'unreadable') return true;+ return resolverHarnesses(cfg.state === 'ok' ? cfg.doc : null).includes(harness) || inspectSkillResolverHook(harness, paths).state !== 'absent'+ || listCatalogs(home).some((n) => isHarnessCatalog(harness, n));+}++/** Turn the lane off for one harness (or preview it); null when nothing of it exists. */+export async function removeSkillResolverSetup(opts: { harness: ResolverHarness; home: string; dryRun: boolean; paths?: ResolverHookPaths }): Promise<ResolverSetupResult | null> {+ const { harness, home, dryRun } = opts;+ if (!skillResolverPresent(harness, home, opts.paths)) return null;+ const out: ResolverSetupResult = { harness, mode: 'off', steps: [] };+ const cfg = readResolverConfig(home);+ if (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.` } };+ const hook = removeSkillResolverHook({ harness, paths: opts.paths, dryRun });+ if (hook.action === 'remove') out.steps.push({ step: 'hook', action: 'remove', detail: hook.detail });+ const keys = setResolverHarness(cfg, harness, false, dryRun);+ const left = resolverHarnesses(cfg.state === 'ok' ? cfg.doc : null).filter((h) => h !== harness);+ if (keys.changed) out.steps.push({ step: 'config', action: 'remove', detail: `${left.length ? `${harness} from skills.resolver.harnesses` : 'skills.resolver.enabled and skills.resolver.harnesses'} in ${cfg.path}${keys.deletedFile ? ' (the file held nothing else, so it was removed)' : ''}` });+ for (const name of listCatalogs(home).filter((n) => isHarnessCatalog(harness, n))) {+ if (!dryRun) await removeSkillIndex(name, { home });+ out.steps.push({ step: 'catalog', action: 'remove', detail: join(skillIndexRoot(home), name) });+ }+ if (left.length === 0) {+ for (const p of [sessionsDir(home), logsDir(home)]) {+ if (!existsSync(p)) continue;+ if (!dryRun) rmSync(p, { recursive: true, force: true });+ out.steps.push({ step: 'state', action: 'remove', detail: p });+ }+ }+ return out;+}++/** One human line per step, matching setup's step lines. */+export function describeResolverSetup(r: ResolverSetupResult, dryRun: boolean): string[] {+ const lines = r.steps.map((s) => ` ${(dryRun && s.action !== 'keep' && s.action !== 'skip' ? `would ${s.action}` : s.action).padEnd(8)} ${'resolver'.padEnd(7)} ${s.step}: ${s.detail}`);+ if (r.sample) lines.push('Sample skill-resolver block:', ...r.sample.split('\n').map((l) => ` ${l}`));+ if (r.status) lines.push(r.status.line);+ return lines;+}diff --git a/src/core/setup/turn-hook-check.ts b/src/core/setup/turn-hook-check.tsindex 6347b3c4b0..772b0cc476 100644--- a/src/core/setup/turn-hook-check.ts+++ b/src/core/setup/turn-hook-check.ts@@ -26,6 +26,7 @@ import { enabledPluginLanes } from '../bootstrap/plugin-lanes.ts';import { brainFirstTarget, openclawConfigPath, parseJson5ish } from './brain-first.ts';import { inspectHermesTurnHook } from './hermes-turn-hook.ts';import { OPENCLAW_TURN_PLUGIN_ID, openclawTurnPluginDir } from './openclaw-turn-plugin.ts';+import { isSkillResolverEntry } from './skill-resolver-lane.ts';import { isOtherGbrainEntry, isTurnRuleEntry, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnHookPaths } from './turn-hook.ts';export const TURN_HOOK_NATIVE_INSPECT: Record<string, string> = {@@ -62,7 +63,7 @@ function claudeEntries(path: string): Array<Record<string, unknown>> {}const isGbrainPromptEntry = (e: Record<string, unknown>) =>- isTurnRuleEntry(e) || typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, 'UserPromptSubmit', 'any');+ !isSkillResolverEntry(e) && (isTurnRuleEntry(e) || typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string' || !!classifyHarnessHook(e, 'UserPromptSubmit', 'any'));/** Files only, no process run. `projectDir`: a project-scope Claude Code install's directory; `managedDir`: Claude Code's managed-settings directory (default: the system one). */export function inspectTurnHook(harness: string, opts: { projectDir?: string; managedDir?: string } = {}): TurnHookState {diff --git a/src/core/setup/turn-hook.ts b/src/core/setup/turn-hook.tsindex 648fd2f00a..e43b211c3a 100644--- a/src/core/setup/turn-hook.ts+++ b/src/core/setup/turn-hook.ts@@ -39,6 +39,7 @@ import { appendCodexTomlTable, readCodexTomlTable, removeCodexTomlTable } from 'import { buildClaudeHookCommand, classifyHarnessHook, hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../bootstrap/hooks.ts';import { CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS, GBRAIN_HOOK_MARKER_KEY, claudeManagedSettingsPaths, claudeUserSettingsPath, codexConfigPath, codexHooksPath } from '../bootstrap/host-specs.ts';import { ensureHookLauncher, hookLauncherPath, hookLauncherState } from './hook-launcher.ts';+import { isSkillResolverEntry } from './skill-resolver-lane.ts';export const TURN_RULE_LANE = 'turn-rule';export const TURN_RULE_MARKER = 'turn-rule-v1';@@ -106,7 +107,7 @@ function claudePromptEntries(path: string): Array<Record<string, unknown>> {/** An entry another gbrain lane owns (setup, workspace bootstrap, bootstrap harness). A repo's committed settings.json counts only a command that parses as gbrain's hook, never a bare marker. */export function isOtherGbrainEntry(e: Record<string, unknown>, committed = false): boolean {- if (isTurnRuleEntry(e)) return false;+ if (isTurnRuleEntry(e) || isSkillResolverEntry(e)) return false;return (!committed && typeof e[GBRAIN_HOOK_MARKER_KEY] === 'string') || !!classifyHarnessHook(e, EVENT, 'any');}diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsnew file mode 100644index 0000000000..6a98413848--- /dev/null+++ b/src/core/skills/resolver/hook-lane.ts@@ -0,0 +1,315 @@+/**+ * The skill-resolver hook lane (`GBRAIN_HOOK_LANE=skill-resolver`): its own+ * hook entry in Claude Code (UserPromptSubmit, plus SessionStart for the+ * compaction reset) and its own hooks.json group in Codex (UserPromptSubmit),+ * written by `gbrain setup <claude-code|codex> --skill-loading resolve`+ * (src/core/setup/skill-resolver-hook.ts). It never shares output with the+ * turn-rule, setup or plugin lanes: it prints only the <relevant_skills> block.+ *+ * It runs the resolver in this process (never over serve's IPC), so it works+ * with serve down and with no brain, and it always fails open: every path+ * exits 0, and a path that cannot deliver a block prints nothing.+ *+ * Deadline (50 ms from lane entry): the main thread does only async I/O (the+ * config, stdin, the carriers, the commit) and every synchronous step (index+ * and session reads, ranking, rendering) runs in a worker thread+ * (hook-worker.ts) that checks the deadline inside each stage. At the+ * deadline the main thread prints nothing and exits the process at once,+ * abandoning the worker, and commits no dedupe state: a commit starts only+ * after the block was written, on the main thread, before the deadline.+ *+ * One owner per event: like the harness, plugin and turn-rule lanes, it parses+ * the carriers the harness merges (Claude Code: managed settings, the+ * workspace's settings.local.json and settings.json, the user settings;+ * Codex: CODEX_HOME/hooks.json) and runs only when the first skill-resolver+ * entry there names its own GBRAIN_HOME, so two wirings never deliver two+ * blocks. (Identical commands are deduplicated by the harness itself.)+ *+ * Catalogs: <harness>-user (built by setup) and, for Claude Code, a second+ * catalog for the project's .claude/skills, keyed by a hash of the project+ * root, built out of the turn by a detached `gbrain skills index build` on+ * first sight and merged at rank time (names only: scope project). A stale+ * 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.+ *+ * 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).+ *+ * Lane log: <home>/skill-index/logs/lane.jsonl, one line per turn that got+ * past the on/off check (outcome, error code, duration; never turn text),+ * capped at 256 KB; doctor's skill_resolver check reads it.+ */+import { spawn } from 'node:child_process';+import { createHash } from 'node:crypto';+import { appendFile, mkdir, readFile, realpath, stat, truncate, unlink, writeFile } from 'node:fs/promises';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { Worker } from 'node:worker_threads';+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 { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';+import { commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';+import type { TurnOutput } from './resolve.ts';++export const LANE_DEADLINE_MS = 50;+export const LANE_STDIN_CAP_BYTES = 256 * 1024;+export const LANE_PAYLOAD_CHARS_DEFAULT = 4000;+export const LANE_PAYLOAD_CHARS_MIN = 500;+export const LANE_PAYLOAD_CHARS_MAX = 10_000;+export const LANE_LOG_FILE = 'lane.jsonl';+const LANE_LOG_CAP_BYTES = 256 * 1024;+const CONFIG_CAP_BYTES = 1024 * 1024;+const SPAWN_INTERVAL_MS = 60_000;+/** Time kept back from the worker's own deadline for delivery and the commit. */+const COMMIT_RESERVE_MS = 10;+/**+ * The worker's entry. A compiled binary bundles src/ under a virtual root+ * (/$bunfs/root/, ~BUN on Windows) and carries hook-worker.ts as a second+ * entrypoint at its src-relative path (every release build passes it); the+ * bundle's own import.meta.url is the binary, so the path is taken from there.+ */+const WORKER_SRC_PATH = 'core/skills/resolver/hook-worker.ts';+const workerEntry = (): string | URL => (/[\\/](\$bunfs|~BUN)[\\/]/.test(import.meta.url) ? Bun.main.replace(/[^\\/]*$/, '') + WORKER_SRC_PATH : new URL('./hook-worker.ts', import.meta.url));++export type LaneHarness = 'claude-code' | 'codex';+export const userCatalogName = (harness: LaneHarness) => `${harness}-user`;+export const projectCatalogPrefix = (harness: LaneHarness) => `${harness}-project-`;++/** The GBRAIN_HOME a lane command pins ('' for none). */+function commandHome(command: string): string {+ const words = shellWords(command) ?? [];+ return (words.find(w => w.startsWith('GBRAIN_HOME='))?.slice('GBRAIN_HOME='.length) ?? '').trim();+}++async function readJsonFile(path: string, cap = CONFIG_CAP_BYTES): Promise<unknown> {+ if ((await stat(path)).size > cap) throw new Error('too large');+ return JSON.parse(await readFile(path, 'utf8'));+}++/**+ * The GBRAIN_HOME of the skill-resolver wiring that owns this event, or+ * undefined when no carrier holds one (a manual run). Async reads only;+ * an unreadable carrier is skipped.+ */+export async function skillResolverOwner(harness: LaneHarness, event: 'user-prompt' | 'session-start', cwd: string, managedDir?: string): Promise<string | undefined> {+ const eventKey = event === 'user-prompt' ? 'UserPromptSubmit' : 'SessionStart';+ const carriers = harness === 'codex' ? [codexHooksPath()]+ : [...claudeManagedSettingsPaths(managedDir), join(cwd, '.claude', 'settings.local.json'), join(cwd, '.claude', 'settings.json'), claudeUserSettingsPath()];+ for (const path of carriers) {+ let doc: unknown;+ try { doc = await readJsonFile(path); } catch { continue; }+ const groups = (doc as { hooks?: Record<string, unknown> } | null)?.hooks?.[eventKey];+ if (!Array.isArray(groups)) continue;+ for (const g of groups) {+ const entries = (g as { hooks?: unknown })?.hooks;+ if (!Array.isArray(entries)) continue;+ const hit = entries.find(e => (harness === 'codex' ? isSkillResolverCommand((e as { command?: unknown })?.command) : isSkillResolverEntry(e)) && typeof (e as { command?: unknown }).command === 'string');+ if (hit) return commandHome((hit as { command: string }).command);+ }+ }+ return undefined;+}++export interface LaneSettings { state: 'absent' | 'unreadable' | 'invalid' | 'ok'; enabled: boolean; harnesses: string[]; payloadChars: number; autoRebuild: boolean }++/** 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' };+ let cfg: unknown;+ try { cfg = await readJsonFile(join(home, 'config.json')); } catch (e) {+ return { ...base, state: (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'absent' : 'unreadable' };+ }+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) return { ...base, state: 'unreadable' };+ const r = (cfg as { skills?: { resolver?: Record<string, unknown> } }).skills?.resolver;+ if (!r || typeof r !== 'object') return base;+ const chars = r.lane_payload_chars;+ const validChars = chars === undefined || (Number.isInteger(chars) && (chars as number) >= LANE_PAYLOAD_CHARS_MIN && (chars as number) <= LANE_PAYLOAD_CHARS_MAX);+ return {+ state: validChars ? 'ok' : 'invalid',+ enabled: r.enabled === true,+ harnesses: 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,+ };+}++export interface LaneLogLine { at: string; harness: string; event: string; outcome: string; code?: string; ms: number; catalogs?: string[]; dropped_chars?: number }++async function appendLaneLog(home: string, line: LaneLogLine): Promise<void> {+ try {+ const dir = logsDir(home);+ await mkdir(dir, { recursive: true, mode: 0o700 });+ const p = join(dir, LANE_LOG_FILE);+ try { if ((await stat(p)).size > LANE_LOG_CAP_BYTES) await truncate(p, 0); } catch { /* new */ }+ await appendFile(p, `${JSON.stringify(line)}\n`, { mode: 0o600 });+ } catch { /* logging never fails a turn */ }+}++async function readStdinBounded(stream: NodeJS.ReadableStream & { isTTY?: boolean }, cap: number): Promise<string | null> {+ if (stream.isTTY) return null;+ const chunks: Buffer[] = [];+ let n = 0;+ for await (const c of stream as AsyncIterable<Buffer | string>) {+ const b = typeof c === 'string' ? Buffer.from(c) : c;+ n += b.length;+ if (n > cap) return null;+ chunks.push(b);+ }+ return Buffer.concat(chunks).toString('utf8');+}++function selfArgv(args: string[]): string[] {+ const exec = process.execPath;+ return /[/\\]gbrain(\.exe)?$/.test(exec) ? [exec, ...args] : [exec, process.argv[1]!, ...args];+}++function spawnDetached(argv: string[]): void {+ const child = spawn(argv[0]!, argv.slice(1), { detached: true, stdio: 'ignore', env: process.env });+ child.on('error', () => { /* best effort */ });+ child.unref();+}++/** Start a detached build at most once a minute per catalog (stamp under logs/). */+async function scheduleBuild(home: string, catalog: string, args: string[], spawnFn: (argv: string[]) => void): Promise<boolean> {+ const stamp = join(logsDir(home), `spawn-${assertCatalogName(catalog)}.stamp`);+ try { if (Date.now() - (await stat(stamp)).mtimeMs < SPAWN_INTERVAL_MS) return false; } catch { /* none */ }+ try {+ await mkdir(logsDir(home), { recursive: true, mode: 0o700 });+ await writeFile(stamp, '', { mode: 0o600 });+ spawnFn(selfArgv(args));+ return true;+ } catch { return false; }+}++export interface LaneIo {+ stdin?: NodeJS.ReadableStream & { isTTY?: boolean };+ /** Resolves once the text was handed to stdout. */+ write?: (s: string) => Promise<void>;+ exit?: (code: number) => void;+ env?: NodeJS.ProcessEnv;+ cwd?: string;+ deadlineMs?: number;+ spawn?: (argv: string[]) => void;+ managedDir?: string;+}++const writeStdout = (s: string) => new Promise<void>((resolve, reject) => { process.stdout.write(s, (e) => (e ? reject(e) : resolve())); });++interface Turn { outcome: string; code?: string; catalogs?: string[]; dropped_chars?: number }++/** Run one lane event. Always resolves 0; at the deadline it exits the process itself. */+export async function runSkillResolverLane(event: string, harness: LaneHarness, io: LaneIo = {}): Promise<number> {+ const t0 = performance.now();+ if (event !== 'user-prompt' && event !== 'session-start') return 0;+ if (harness === 'codex' && event !== 'user-prompt') return 0;+ const env = io.env ?? process.env;+ let home: string;+ try { home = resolverHome(env); } catch { return 0; }+ const deadlineMs = io.deadlineMs ?? (Number(env.GBRAIN_TEST_SKILL_LANE_DEADLINE_MS) || LANE_DEADLINE_MS);+ const elapsed = () => performance.now() - t0;+ const ctl = { expired: false, worker: null as Worker | null, logged: false };+ const log = (t: Turn) => appendLaneLog(home, { at: new Date().toISOString(), harness, event, outcome: t.outcome, ...(t.code ? { code: t.code } : {}), ms: Math.round(elapsed() * 10) / 10, ...(t.catalogs ? { catalogs: t.catalogs } : {}), ...(t.dropped_chars ? { dropped_chars: t.dropped_chars } : {}) });++ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<'deadline'>((resolve) => { timer = setTimeout(() => resolve('deadline'), deadlineMs); });+ const work = laneTurn(event, harness, home, env, io, ctl, elapsed, deadlineMs).catch((): Turn => ({ outcome: 'error', code: 'skill_resolver_internal' }));+ const result = await Promise.race([work, deadline]);+ if (result === 'deadline') {+ ctl.expired = true;+ void ctl.worker?.terminate();+ if (ctl.logged) await Promise.race([log({ outcome: 'timeout', code: 'skill_resolve_timeout' }), new Promise(r => setTimeout(r, 5))]);+ (io.exit ?? ((c: number) => process.exit(c)))(0);+ return 0;+ }+ clearTimeout(timer);+ void ctl.worker?.terminate();+ if (result.outcome !== 'off' && result.outcome !== 'yield') await log(result);+ return 0;+}++async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarness, home: string, env: NodeJS.ProcessEnv, io: LaneIo, ctl: { expired: boolean; worker: Worker | null; logged: boolean }, elapsed: () => number, deadlineMs: number): Promise<Turn> {+ const settings = await readLaneSettings(home, env);+ if (settings.state === 'absent') return { outcome: 'off' };+ if (settings.state === 'unreadable') { ctl.logged = true; return { outcome: 'error', code: 'skill_resolver_config_unreadable' }; }+ if (!settings.enabled || !settings.harnesses.includes(harness)) return { outcome: 'off' };+ ctl.logged = true;+ if (settings.state === 'invalid') 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>;+ try { j = JSON.parse(raw ?? '') as Record<string, unknown>; } catch { return { outcome: 'error', code: 'skill_resolve_no_input' }; }+ if (!j || typeof j !== 'object') return { outcome: 'error', code: 'skill_resolve_no_input' };+ const cwd = io.cwd ?? env.GBRAIN_HOOK_CWD ?? (typeof j.cwd === 'string' ? j.cwd : process.cwd());+ const owner = await skillResolverOwner(harness, event, cwd, io.managedDir);+ if (owner !== undefined && owner !== (env.GBRAIN_HOME ?? '').trim()) return { outcome: 'yield' };+ const sessionId = typeof j.session_id === 'string' && /^[\x21-\x7e]{1,256}$/.test(j.session_id) ? j.session_id : undefined;++ if (event === 'session-start') {+ if (j.source !== 'compact' || !sessionId) return { outcome: 'off' };+ await Promise.all(['on', 'shadow'].map(scope => unlink(join(home, 'skill-index', 'sessions', `${sessionKey(scope as 'on' | 'shadow', harness, sessionId)}.json`)).catch(() => {})));+ return { outcome: 'reset' };+ }++ const prompt = typeof j.prompt === 'string' ? j.prompt : '';+ if (!prompt.trim() || /^\s*<(task-notification|teammate-message)[\s>]/.test(prompt)) return { outcome: 'empty' };+ const spawnFn = io.spawn ?? spawnDetached;+ const catalogs = [userCatalogName(harness)];+ if (harness === 'claude-code') {+ const project = await projectCatalog(env.CLAUDE_PROJECT_DIR || cwd, home);+ if (project?.built) catalogs.push(project.name);+ else if (project && settings.autoRebuild) await scheduleBuild(home, project.name, ['skills', 'index', 'build', '--catalog', project.name, '--dir', project.dir, '--scope', 'project', '--harness', harness], spawnFn);+ }++ const posted = await new Promise<{ output?: TurnOutput; pending?: { key: string; delta: TurnDelta } | null; error?: { code: string } }>((resolve) => {+ const worker = new Worker(workerEntry(), {+ workerData: { input: { message: prompt, harness, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS), stall: env.GBRAIN_TEST_SKILL_LANE_STALL },+ });+ ctl.worker = worker;+ worker.unref();+ worker.once('message', resolve);+ worker.once('error', () => resolve({ error: { code: 'skill_resolver_internal' } }));+ });+ if (posted.error || !posted.output) return { outcome: 'error', code: posted.error?.code ?? 'skill_resolver_internal', catalogs };+ const out = posted.output;+ if (out.meta.index_stale && settings.autoRebuild) await scheduleStaleRebuilds(home, catalogs, spawnFn);+ if (out.error) return { outcome: 'error', code: out.error.code, catalogs };+ if (ctl.expired) return { outcome: 'timeout', code: 'skill_resolve_timeout', catalogs };++ const outcome = out.block ? 'delivered' : out.budget_exhausted ? 'budget_exhausted' : out.no_skill ? 'no_skill' : 'empty';+ if (out.block) {+ const payload = JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: out.block } });+ if (payload.length > settings.payloadChars) return { outcome: 'payload_dropped', catalogs, dropped_chars: payload.length };+ await (io.write ?? writeStdout)(`${payload}\n`);+ }+ if (posted.pending && !ctl.expired) await commitSessionAsync(home, posted.pending.key, posted.pending.delta);+ return { outcome, catalogs };+}++/** The project's .claude/skills catalog: name keyed by the real project root, and whether it is built. Null when there is none (or it is the user's own dir). */+async function projectCatalog(root: string, home: string): Promise<{ name: string; dir: string; built: boolean } | null> {+ try {+ const real = await realpath(root);+ if (real === await realpath(homedir()).catch(() => homedir())) return null;+ const dir = join(real, '.claude', 'skills');+ if (!(await stat(dir)).isDirectory()) return null;+ const name = `${projectCatalogPrefix('claude-code')}${createHash('sha256').update(real).digest('hex').slice(0, 16)}`;+ let built = true;+ try { await stat(catalogFile(home, name, 'receipt.json')); } catch { built = false; }+ return { name, dir, built };+ } catch { return null; }+}++/** Rebuild each catalog the turn marked stale (stale.stamp) from its receipt's recorded command; an adapter-owned (stdin) catalog has none and is skipped. */+async function scheduleStaleRebuilds(home: string, catalogs: string[], spawnFn: (argv: string[]) => void): Promise<void> {+ for (const name of catalogs) {+ try {+ await stat(catalogFile(home, name, 'stale.stamp'));+ const receipt = await readJsonFile(catalogFile(home, name, 'receipt.json')) as { build?: { rebuild_argv?: unknown } };+ const argv = receipt.build?.rebuild_argv;+ if (!Array.isArray(argv) || argv[0] !== 'gbrain' || argv.some(a => typeof a !== 'string')) continue;+ await scheduleBuild(home, name, (argv as string[]).slice(1), spawnFn);+ } catch { /* not stale, or no receipt */ }+ }+}diff --git a/src/core/skills/resolver/hook-worker.ts b/src/core/skills/resolver/hook-worker.tsnew file mode 100644index 0000000000..84e7cbbabd--- /dev/null+++ b/src/core/skills/resolver/hook-worker.ts@@ -0,0 +1,28 @@+/**+ * The hook lane's worker thread (hook-lane.ts): every synchronous step of a+ * turn (reading the index and session state, ranking, rendering) runs here,+ * so the lane's main thread keeps an event loop whose deadline timer can+ * always fire. It posts the prepared turn and its pending commit; it never+ * commits: the main thread does, after delivery and before the deadline.+ *+ * GBRAIN_TEST_SKILL_LANE_STALL (tests only) forces a slow stage: block+ * (synchronous 10 s busy loop), hang (never answers), late (answers after+ * 300 ms). GBRAIN_TEST_SKILL_LANE_DEADLINE_MS (tests only, hook-lane.ts)+ * widens the lane's deadline so a loaded test machine can assert delivery.+ */+import { parentPort, workerData } from 'node:worker_threads';+import { resolveSkills } from './resolve.ts';++const { input, home, catalogs, deadlineMs, stall } = workerData as { input: unknown; home: string; catalogs: string[]; deadlineMs: number; stall?: string };++if (stall === 'block') { const end = Date.now() + 10_000; while (Date.now() < end) { /* forced synchronous stall */ } }+if (stall === 'hang') await new Promise(() => {});+if (stall === 'late') await new Promise(r => setTimeout(r, 300));++try {+ const r = await resolveSkills(input, { home, catalogs, deadlineMs, failOpen: true });+ parentPort!.postMessage({ output: r.output, pending: r.pending ?? null });+} catch (e) {+ const code = (e as { code?: unknown }).code;+ parentPort!.postMessage({ error: { code: typeof code === 'string' ? code : 'skill_resolver_internal' } });+}diff --git a/src/core/skills/resolver/lock.ts b/src/core/skills/resolver/lock.tsindex 0fb0d49b61..dda11d1e05 100644--- a/src/core/skills/resolver/lock.ts+++ b/src/core/skills/resolver/lock.ts@@ -9,6 +9,7 @@* caller's token, so a stale owner cannot act on its successor's lease.*/import { closeSync, fsyncSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from 'node:fs';+import { open as openAsync, readFile as readFileAsync, unlink as unlinkAsync } from 'node:fs/promises';import { randomBytes } from 'node:crypto';import { hostname } from 'node:os';import { ResolverError } from './errors.ts';@@ -96,6 +97,28 @@ export function renewLease(lease: Lease, leaseMs: number, now: () => number = Dareturn holdsLease(lease);}+/**+ * One attempt with async I/O only, for a caller whose event loop owns a+ * deadline (the hook lane): an expired or unparsable lease counts as held+ * here (the sync acquireLease reclaims it), so this never replaces a file.+ */+export async function tryAcquireLeaseAsync(path: string, opts: LeaseOpts): Promise<Lease | null> {+ const rec = makeRecord(opts);+ let fh;+ try { fh = await openAsync(path, 'wx', 0o600); } catch (e) { if ((e as NodeJS.ErrnoException).code === 'EEXIST') return null; throw e; }+ try { await fh.writeFile(JSON.stringify(rec)); await fh.sync(); } finally { await fh.close(); }+ return { path, token: rec.token, record: rec };+}++export async function releaseLeaseAsync(lease: Lease): Promise<boolean> {+ try {+ const cur = JSON.parse(await readFileAsync(lease.path, 'utf8')) as LeaseRecord;+ if (cur?.token !== lease.token) return false;+ await unlinkAsync(lease.path);+ return true;+ } catch { return false; }+}+export function releaseLease(lease: Lease): boolean {if (!holdsLease(lease)) return false;try { unlinkSync(lease.path); return true; } catch { return false; }diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex 43c648292e..e8cc156925 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -30,7 +30,7 @@ import { ensureDir, writeFileDurable } from './fsutil.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';-import { commitSession, freshState, loadSession, sessionKey, type SessionState } from './session.ts';+import { commitSession, freshState, loadSession, sessionKey, type SessionState, type TurnDelta } from './session.ts';export const SCHEMA_VERSION = 1;export const MESSAGE_CAP_BYTES = 8192;@@ -112,6 +112,8 @@ export interface ResolveResult {failOpen?: boolean;/** Commit this turn's session state; call only after the block was delivered. */commit(): Promise<boolean>;+ /** What commit() would apply, for a caller that commits on another thread (the hook lane): null when there is no session to commit. */+ pending?: { key: string; delta: TurnDelta } | null;}const sha = (s: string) => createHash('sha256').update(s).digest('hex');@@ -275,10 +277,11 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:};const finish = (out: TurnOutput, delta: { tokens: number; suggested: string[]; resuggested: string[] }, explain?: Explain): ResolveResult => {out.meta.timing_ms = round4(performance.now() - t0);- const commit = async () => (key ? commitSession(home, key, { ...delta, reset: input.reset_session }) : false);- if (!input.shadow) return { output: out, ...(explain ? { explain } : {}), commit };+ const pending = key ? { key, delta: { ...delta, reset: input.reset_session } } : null;+ const commit = async () => (pending ? commitSession(home, pending.key, pending.delta) : false);+ if (!input.shadow) return { output: out, ...(explain ? { explain } : {}), commit, pending };const quiet: TurnOutput = { ...out, suggestions: [], block: '', block_tokens: 0, deduped: [], shadow: true };- return { output: quiet, shadowOutput: { ...out, shadow: true }, ...(explain ? { explain } : {}), commit };+ return { output: quiet, shadowOutput: { ...out, shadow: true }, ...(explain ? { explain } : {}), commit, pending };};if (isAcknowledgement(input.message)) return finish({ ...base, no_skill: true, no_skill_reason: 'ack' }, { tokens: 0, suggested: [], resuggested: [] });diff --git a/src/core/skills/resolver/session.ts b/src/core/skills/resolver/session.tsindex 9d4edbec7c..4a53a13d8a 100644--- a/src/core/skills/resolver/session.ts+++ b/src/core/skills/resolver/session.ts@@ -14,9 +14,11 @@*/import { createHash } from 'node:crypto';import { readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';+import { mkdir, open, readdir, readFile, rename, stat, unlink } from 'node:fs/promises';+import { randomBytes } from 'node:crypto';import { join } from 'node:path';import { ensureDir, writeFileDurable } from './fsutil.ts';-import { acquireLease, releaseLease } from './lock.ts';+import { acquireLease, releaseLease, releaseLeaseAsync, tryAcquireLeaseAsync } from './lock.ts';import { sessionsDir } from './paths.ts';export const MAX_SESSION_FILES = 10_000;@@ -70,20 +72,66 @@ export async function commitSession(home: string, key: string, delta: TurnDelta)let lease;try { lease = await acquireLease(`${p}.lock`, { purpose: 'session-commit', leaseMs: 2000, retries: 3, waitMs: 5 }); } catch { return false; }try {- const s = delta.reset ? freshState() : loadSession(home, key);- s.turn += 1;- s.spent += delta.tokens;- for (const id of delta.resuggested) s.again[id] = 1;- for (const id of delta.suggested) if (id in s.last || Object.keys(s.last).length < MAX_SESSION_IDS) s.last[id] = s.turn;- writeFileDurable(p, JSON.stringify(s));+ writeFileDurable(p, JSON.stringify(applyDelta(delta.reset ? freshState() : loadSession(home, key), delta)));return true;} finally {releaseLease(lease);}}+function applyDelta(s: SessionState, delta: TurnDelta): SessionState {+ s.turn += 1;+ s.spent += delta.tokens;+ for (const id of delta.resuggested) s.again[id] = 1;+ for (const id of delta.suggested) if (id in s.last || Object.keys(s.last).length < MAX_SESSION_IDS) s.last[id] = s.turn;+ return s;+}++/**+ * commitSession with async I/O only (no sync file call), for the hook lane,+ * whose event loop owns its deadline. Same file, lease and rules; a busy+ * lease is retried a few times over at most ~15 ms, then the commit is+ * skipped (a skipped commit only means a repeat).+ */+export async function commitSessionAsync(home: string, key: string, delta: TurnDelta): Promise<boolean> {+ const dir = sessionsDir(home);+ const p = statePath(home, key);+ try {+ await mkdir(dir, { recursive: true, mode: 0o700 });+ let exists = true;+ try { await stat(p); } catch { exists = false; }+ if (!exists && (await readdir(dir)).length >= MAX_SESSION_FILES) return false;+ let lease = null;+ for (let attempt = 0; attempt < 4 && !lease; attempt++) {+ lease = await tryAcquireLeaseAsync(`${p}.lock`, { purpose: 'session-commit', leaseMs: 2000 });+ if (!lease && attempt < 3) await new Promise(r => setTimeout(r, 2 ** attempt * 2));+ }+ if (!lease) return false;+ try {+ let s = freshState();+ if (!delta.reset) {+ try {+ if ((await stat(p)).size <= STATE_CAP_BYTES) {+ const raw = JSON.parse(await readFile(p, 'utf8')) as SessionState;+ if (raw?.v === 1 && typeof raw.turn === 'number' && typeof raw.spent === 'number' && raw.last && typeof raw.last === 'object') s = { v: 1, turn: raw.turn, spent: raw.spent, last: raw.last, again: raw.again && typeof raw.again === 'object' ? raw.again : {} };+ }+ } catch { /* none or unreadable: fresh */ }+ }+ const tmp = join(dir, `.${key}.json.tmp-${randomBytes(6).toString('hex')}`);+ const fh = await open(tmp, 'wx', 0o600);+ try { await fh.writeFile(JSON.stringify(applyDelta(s, delta))); await fh.sync(); } finally { await fh.close(); }+ try { await rename(tmp, p); } catch (e) { await unlink(tmp).catch(() => {}); throw e; }+ return true;+ } finally {+ await releaseLeaseAsync(lease);+ }+ } catch {+ return false;+ }+}+export async function resetSession(home: string, key: string): Promise<void> {- try { unlinkSync(statePath(home, key)); } catch { /* none */ }+ try { await unlink(statePath(home, key)); } catch { /* none */ }}/** Delete session files idle for 7 days, examining at most GC_WORK_BOUND files per run. */diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsnew file mode 100644index 0000000000..885a49e4ee--- /dev/null+++ b/test/skill-resolver-hook-lane.test.ts@@ -0,0 +1,263 @@+/**+ * GBRA-377 PR B: the skill-resolver hook lane (`GBRAIN_HOOK_LANE=skill-resolver`,+ * src/core/skills/resolver/hook-lane.ts) as the harness runs it: each test+ * wires the lane with `gbrain setup <claude-code|codex> --skill-loading+ * resolve` against a temp HOME, then runs the exact command setup wrote.+ *+ * Protects: the block names each skill with the harness's own load line+ * (Codex adds the SKILL.md path); dedupe and the compaction reset; the 50 ms+ * deadline, measured from outside the process, for a blocking, hung and late+ * worker (exit 0, no output, no dedupe commit); a brainless install stays+ * brainless; an unreadable config fails open with its code; a block over the+ * payload budget is dropped whole and counted; one owner per event; the+ * project catalog is built out of the turn and merged at rank time; with the+ * lane off it prints and writes nothing.+ */+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { LANE_DEADLINE_MS, projectCatalogPrefix } from '../src/core/skills/resolver/hook-lane.ts';++setDefaultTimeout(60_000);+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const CLAUDE_LOAD = 'To use one, load it with the Skill tool (by its id) before acting.';+const CODEX_LOAD = 'To use one, open the SKILL.md at its path and follow it.';+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { root: string; home: string; project: string; bin: string; env: Record<string, string | undefined> }+function box(): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-skill-lane-'));+ roots.push(root);+ const home = join(root, 'home'), project = join(root, 'project');+ mkdirSync(home, { recursive: true });+ mkdirSync(project, { recursive: true });+ mkdirSync(join(root, 'bin'));+ const bin = join(root, 'bin', 'gbrain');+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ return { root, home, project, bin, env: {+ HOME: home, GBRAIN_HOME: home, PATH: '/usr/bin:/bin', CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,+ CLAUDE_PROJECT_DIR: undefined, GBRAIN_HOOKS: undefined, GBRAIN_HOOK_LANE: undefined, GBRAIN_SKILLS_NO_AUTOREBUILD: undefined,+ GBRAIN_TEST_SKILL_LANE_STALL: undefined, GBRAIN_TEST_SKILL_LANE_DEADLINE_MS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ } };+}++function skill(dir: string, name: string, description: string): void {+ mkdirSync(join(dir, name), { recursive: true });+ writeFileSync(join(dir, name, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\nSteps for ${name}.\n`);+}+const claudeSkills = (b: Box) => join(b.home, '.claude', 'skills');+const codexSkills = (b: Box) => join(b.home, '.agents', 'skills');+function seedSkills(dir: string): void {+ skill(dir, 'deploy-widget', 'Deploy the widget service to staging or production.');+ skill(dir, 'write-changelog', 'Write a changelog entry for a release.');+ skill(dir, 'triage-bug', 'Triage a bug report: reproduce it and find the owner.');+}++async function setup(b: Box, harness: string, extra: string[] = []) {+ const r = await runCli(['setup', harness, '--instructions-only', '--skill-loading', 'resolve', '--gbrain-bin', b.bin, ...extra], { env: b.env, cwd: b.project });+ expect(r.exitCode, r.stderr + r.stdout).toBe(0);+ return r;+}+const readJson = (p: string) => JSON.parse(readFileSync(p, 'utf8'));+/** The lane command setup wrote for this harness and event. */+function wired(b: Box, harness: 'claude-code' | 'codex', event: 'UserPromptSubmit' | 'SessionStart' = 'UserPromptSubmit'): string {+ const doc = readJson(harness === 'codex' ? join(b.home, '.codex', 'hooks.json') : join(b.home, '.claude', 'settings.json'));+ const cmds = (doc.hooks?.[event] ?? []).flatMap((g: any) => g.hooks).map((h: any) => h.command as string).filter((c: string) => c.includes('GBRAIN_HOOK_LANE=skill-resolver'));+ expect(cmds).toHaveLength(1);+ return cmds[0];+}++interface Run { stdout: string; stderr: string; exitCode: number; wallMs: number }+/** Run a hook command the way the harness does: sh -c, the event JSON on stdin. Wall time is measured outside the process. */+async function hook(b: Box, command: string, payload: Record<string, unknown>, env: Record<string, string | undefined> = {}): Promise<Run> {+ const merged: Record<string, string> = {};+ for (const [k, v] of Object.entries({ ...process.env, ...b.env, GBRAIN_SKIP_STARTUP_HOOKS: '1', ...env })) if (v !== undefined) merged[k] = v;+ const t0 = performance.now();+ const proc = Bun.spawn(['sh', '-c', command], { env: merged, cwd: b.project, stdin: new TextEncoder().encode(JSON.stringify({ cwd: b.project, ...payload })), stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { stdout, stderr, exitCode, wallMs: performance.now() - t0 };+}+const WIDE = { GBRAIN_TEST_SKILL_LANE_DEADLINE_MS: '10000' };+const laneLog = (b: Box): any[] => {+ const p = join(b.home, '.gbrain', 'skill-index', 'logs', 'lane.jsonl');+ return existsSync(p) ? readFileSync(p, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)) : [];+};+const sessions = (b: Box) => { const d = join(b.home, '.gbrain', 'skill-index', 'sessions'); return existsSync(d) ? readdirSync(d) : []; };+const contextOf = (r: Run) => JSON.parse(r.stdout).hookSpecificOutput.additionalContext as string;++describe('skill-resolver lane: delivery per harness', () => {+ test('claude-code: the wired command names each skill and gives the Skill tool load line; a repeat is deduped', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const first = await hook(b, cmd, { prompt: 'please deploy the widget to staging', session_id: 'sess-a' }, WIDE);+ expect(first.exitCode).toBe(0);+ const block = contextOf(first);+ expect(JSON.parse(first.stdout).hookSpecificOutput.hookEventName).toBe('UserPromptSubmit');+ expect(block).toContain('<relevant_skills>');+ expect(block).toContain('id: "deploy-widget"');+ expect(block).toContain(CLAUDE_LOAD);+ expect(block).not.toContain('path: ');+ expect(sessions(b)).toHaveLength(1);+ const again = await hook(b, cmd, { prompt: 'please deploy the widget to staging', session_id: 'sess-a' }, WIDE);+ expect(again.exitCode).toBe(0);+ expect(again.stdout).toBe('');+ expect(laneLog(b).map((l) => l.outcome)).toEqual(['delivered', 'empty']);+ });++ test('codex: the wired command passes --harness codex; the block carries each SKILL.md path and the Codex load line', async () => {+ const b = box();+ seedSkills(codexSkills(b));+ await setup(b, 'codex');+ const cmd = wired(b, 'codex');+ expect(cmd).toContain('hook user-prompt --harness codex');+ const r = await hook(b, cmd, { prompt: 'write the changelog for this release', session_id: 'sess-c', hook_event_name: 'UserPromptSubmit' }, WIDE);+ expect(r.exitCode).toBe(0);+ const block = contextOf(r);+ expect(block).toContain('id: "write-changelog"');+ expect(block).toContain(`path: ${JSON.stringify(join(codexSkills(b), 'write-changelog', 'SKILL.md'))}`);+ expect(block).toContain(CODEX_LOAD);+ expect(block).not.toContain(CLAUDE_LOAD);+ });++ test('claude-code SessionStart after a compaction resets the session, so the skill is offered again', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const turn = { prompt: 'triage this bug report', session_id: 'sess-r' };+ expect(contextOf(await hook(b, cmd, turn, WIDE))).toContain('triage-bug');+ expect((await hook(b, cmd, turn, WIDE)).stdout).toBe('');+ const start = await hook(b, wired(b, 'claude-code', 'SessionStart'), { source: 'startup', session_id: 'sess-r' }, WIDE);+ expect(start.stdout).toBe('');+ expect((await hook(b, cmd, turn, WIDE)).stdout).toBe('');+ const reset = await hook(b, wired(b, 'claude-code', 'SessionStart'), { source: 'compact', session_id: 'sess-r' }, WIDE);+ expect(reset.exitCode).toBe(0);+ expect(reset.stdout).toBe('');+ expect(contextOf(await hook(b, cmd, turn, WIDE))).toContain('triage-bug');+ });+});++describe('skill-resolver lane: deadline, measured outside the process', () => {+ for (const stall of ['block', 'hang', 'late'] as const) {+ test(`${stall}: exits 0 at the deadline with no output and no dedupe commit`, async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const baseline = await hook(b, cmd, { prompt: 'hello there', session_id: 'warm' }, WIDE);+ const r = await hook(b, cmd, { prompt: 'please deploy the widget to staging', session_id: 'sess-t' }, { GBRAIN_TEST_SKILL_LANE_STALL: stall });+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toBe('');+ expect(sessions(b).length).toBe(sessions(b).length);+ const last = laneLog(b).at(-1);+ expect(last).toMatchObject({ outcome: 'timeout', code: 'skill_resolve_timeout' });+ expect(last.ms).toBeGreaterThanOrEqual(LANE_DEADLINE_MS - 1);+ expect(last.ms).toBeLessThan(LANE_DEADLINE_MS + 250);+ // A blocking worker would hold the process 10 s and a hung one forever; the+ // process ends within the deadline plus the same startup cost as a normal turn.+ expect(r.wallMs).toBeLessThan(baseline.wallMs + 1500);+ expect(sessions(b).some((s) => readFileSync(join(b.home, '.gbrain', 'skill-index', 'sessions', s), 'utf8').includes('deploy-widget'))).toBe(false);+ });+ }+});++describe('skill-resolver lane: fail open', () => {+ test('lane off (no config): prints nothing and writes nothing', async () => {+ const b = box();+ const cmd = `env GBRAIN_HOOK_LANE=skill-resolver '${b.bin}' hook user-prompt`;+ const r = await hook(b, cmd, { prompt: 'deploy the widget', session_id: 's' });+ expect(r).toMatchObject({ exitCode: 0, stdout: '', stderr: '' });+ expect(existsSync(join(b.home, '.gbrain'))).toBe(false);+ });++ test('a brainless install stays brainless and the lane needs no brain or serve', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ expect(Object.keys(readJson(join(b.home, '.gbrain', 'config.json')))).toEqual(['skills']);+ expect(readdirSync(join(b.home, '.gbrain')).filter((n) => /pglite|brain/.test(n))).toEqual([]);+ const r = await hook(b, wired(b, 'claude-code'), { prompt: 'deploy the widget', session_id: 's' }, WIDE);+ expect(contextOf(r)).toContain('deploy-widget');+ const status = await runCli(['doctor', '--json'], { env: b.env, cwd: b.project });+ expect(`${status.stdout}${status.stderr}`).not.toMatch(/database_url|ECONNREFUSED/);+ });++ test('an unreadable config prints nothing, exits 0 and logs skill_resolver_config_unreadable', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ writeFileSync(join(b.home, '.gbrain', 'config.json'), '{ not json');+ const r = await hook(b, wired(b, 'claude-code'), { prompt: 'deploy the widget', session_id: 's' }, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'error', code: 'skill_resolver_config_unreadable' });+ });++ test('a block over the payload budget is dropped whole and counted', async () => {+ const b = box();+ const long = (w: string) => `Deploy the widget ${w}: ${'deploy widget release steps and checks '.repeat(5)}`;+ for (const n of ['deploy-widget-a', 'deploy-widget-b', 'deploy-widget-c']) skill(claudeSkills(b), n, long(n));+ await setup(b, 'claude-code');+ const set = await runCli(['config', 'set', 'skills.resolver.lane_payload_chars', '500'], { env: b.env, cwd: b.project });+ expect(set.exitCode, set.stderr).toBe(0);+ const r = await hook(b, wired(b, 'claude-code'), { prompt: 'deploy the widget please', session_id: 's' }, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ const last = laneLog(b).at(-1);+ expect(last.outcome).toBe('payload_dropped');+ expect(last.dropped_chars).toBeGreaterThan(500);+ expect(sessions(b)).toEqual([]);+ });++ test('one owner per event: a lane whose GBRAIN_HOME is not the first wiring yields', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const other = join(b.root, 'other-home');+ mkdirSync(join(b.project, '.claude'), { recursive: true });+ writeFileSync(join(b.project, '.claude', 'settings.local.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: cmd.replace(`GBRAIN_HOME=${b.home}`, `GBRAIN_HOME=${other}`), _gbrain: 'skill-resolver-v1' }] }] } }));+ const r = await hook(b, cmd, { prompt: 'deploy the widget', session_id: 's' }, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ expect(laneLog(b)).toEqual([]);+ });+});++describe('skill-resolver lane: project catalog', () => {+ test("claude-code: the project's .claude/skills is built out of the turn, keyed by the root, then merged by name", async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ skill(join(b.project, '.claude', 'skills'), 'rotate-fixtures', 'Rotate the fixture files for the nightly widget run.');+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ const turn = { prompt: 'rotate the fixture files', session_id: 'sess-p' };+ const first = await hook(b, cmd, turn, WIDE);+ expect(first.exitCode).toBe(0);+ const root = join(b.home, '.gbrain', 'skill-index');+ let built: string | undefined;+ for (let i = 0; i < 100 && !built; i++) {+ built = readdirSync(root).find((n) => n.startsWith(projectCatalogPrefix('claude-code')) && existsSync(join(root, n, 'receipt.json')));+ if (!built) await Bun.sleep(100);+ }+ expect(built).toMatch(/^claude-code-project-[0-9a-f]{16}$/);+ const r = await hook(b, cmd, { prompt: 'rotate the fixture files', session_id: 'sess-p2' }, WIDE);+ const block = contextOf(r);+ expect(block).toContain('- id: "rotate-fixtures" name: "rotate-fixtures"');+ expect(block).not.toContain('Rotate the fixture files for the nightly');+ expect(laneLog(b).at(-1).catalogs).toEqual(['claude-code-user', built]);+ });++ test('GBRAIN_SKILLS_NO_AUTOREBUILD=1 never starts a build', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ skill(join(b.project, '.claude', 'skills'), 'rotate-fixtures', 'Rotate the fixture files.');+ await setup(b, 'claude-code');+ await hook(b, wired(b, 'claude-code'), { prompt: 'rotate the fixture files', session_id: 's' }, { ...WIDE, GBRAIN_SKILLS_NO_AUTOREBUILD: '1' });+ await Bun.sleep(1500);+ expect(readdirSync(join(b.home, '.gbrain', 'skill-index')).filter((n) => n.startsWith('claude-code-project-'))).toEqual([]);+ });+});