Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
skill resolver lane: compiled worker entry, owner rule, doctor check, tests, docs
garrytanb1c75c86db4a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dee5aab801..e9d6fa205e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ identifiers and attribution are available in the pre-removal Git revision### Added- `gbrain skills index build|status|remove` and `gbrain skills resolve`: an engine-free skill resolver that ranks a harness's skill catalog against one user turn and prints a short `<relevant_skills>` block (at most 5 suggestions, at most 400 tokens), so an agent with hundreds of skills sees the few that fit. Off by default; nothing changes until you build a catalog and call it. Works with no brain, on thin clients and while `gbrain serve` holds the PGLite lock. Word matching only (the BM25F ranker frozen by the Step 1 offline eval); nothing leaves the machine. Sessions never repeat a suggestion and share a 2,000-token budget (`skills.resolver.session_token_budget`). JSON contract in `docs/schemas/skill-resolver.v1.*.json`; library as `gbrain/skill-resolver` and, for Node, the `gbrain-skill-resolver.mjs` release asset. Guide: `docs/guides/skill-resolver.md`.+- `gbrain setup claude-code|codex --skill-loading resolve`: a per-turn hook lane (`GBRAIN_HOOK_LANE=skill-resolver`) that adds the resolver's block to every prompt, with the harness's own load line. Setup builds the user catalog first and writes the `skills.resolver.*` keys and the hook only when it found at least one skill (`skill_resolver_setup_incomplete` otherwise); `--skill-loading off` and `setup --remove` undo all of it. The lane runs in the hook process with no brain and no serve, exits within 50 ms with nothing printed when it cannot deliver, drops a block over `skills.resolver.lane_payload_chars` whole, and lets exactly one wiring deliver. Claude Code project skills get their own catalog, built in the background. `gbrain doctor` reports it as `skill_resolver`. Off by default; with it off, hook output and setup's files are unchanged. A `config.json` that holds only file-plane settings no longer reads as a Postgres brain. Release binaries are now built with the lane's worker as a second entrypoint.## [0.60.611.0] - 2026-11-08diff --git a/docs/architecture/key-files/skill-resolver.md b/docs/architecture/key-files/skill-resolver.mdindex db9932fe19..34e833e04d 100644--- a/docs/architecture/key-files/skill-resolver.md+++ b/docs/architecture/key-files/skill-resolver.md@@ -23,6 +23,9 @@ Contract schemas: `docs/schemas/skill-resolver.v1.*.json`. Every module under- `src/core/skills/resolver/errors.ts` — `ResolverError` codes (rows in `src/core/error-registry.ts`), `USAGE_CODES` (exit 2).- `src/core/skills/resolver/fsutil.ts` — temp-file, fsync and rename writes; bounded reads.- `src/core/skill-description.ts` — `oneLineDescription` (frontmatter description, block scalars folded, else the first body paragraph), shared by `skill-catalog.ts`, `bundled.ts` and the bundled source.+- `src/core/skills/resolver/hook-lane.ts` + `hook-worker.ts` — the hook lane (`GBRAIN_HOOK_LANE=skill-resolver`, dispatched first in `src/commands/hook.ts` after the `GBRAIN_HOOKS=0` check): async config/stdin/carrier reads on the main thread, ranking in a worker (source: `hook-worker.ts` beside it; compiled binary: the second build entrypoint at `WORKER_SRC_PATH`, so every `bun build --compile` that ships a binary lists it), a 50 ms deadline that exits the process with no output and no commit, the commit (`commitSessionAsync`) on the main thread after delivery, the payload budget (`skills.resolver.lane_payload_chars`, dropped whole as `payload_dropped`), the one-owner rule (first carrier entry whose home has the lane on), the SessionStart compaction reset, the Claude Code project catalog (`claude-code-project-<root hash>`, built by a detached `skills index build`, stamp-limited to once a minute) and `skill-index/logs/lane.jsonl`. Test seams: `GBRAIN_TEST_SKILL_LANE_STALL`, `GBRAIN_TEST_SKILL_LANE_DEADLINE_MS`. Pinned by `test/skill-resolver-hook-lane.test.ts`.+- `src/core/setup/skill-resolver-{lane,hook,config,setup}.ts` — `setup <claude-code|codex> --skill-loading resolve|off` and `--remove`: the lane identity leaf (marker `skill-resolver-v1`, which every other lane's ownership and yield test excludes), the Claude Code entries and the Codex group plus its `config.toml` trust, the file-plane keys (`skills.resolver.*`, engine-free in `gbrain config`; an unreadable file is never rewritten), and the build-then-write order (≥1 skill or `skill_resolver_setup_incomplete`). Pinned by `test/setup-skill-resolver.test.ts`.+- `src/commands/doctor/checks/skill-resolver.ts` — doctor `skill_resolver` (emitted by the `harness_wiring` entry, whose details carry the same view): hook state, each catalog's content-tier freshness, recent lane outcomes and error codes; silent when nothing of the resolver exists.- `src/commands/skill-resolver.ts` — the CLI (`src/cli/commands/skill-resolver.ts` dispatches; `src/cli/command-route.ts` routes only `skills index` and `skills resolve` here, so plain `gbrain skills` stays `list_skills`). Exit 0, 1 (runtime error), 0 with `--fail-open`, 2 (usage); commits a session turn only after stdout is written. Pinned by `test/skill-resolver-cli.test.ts` and `test/skill-resolver-guide.test.ts`.- `scripts/bench-skill-resolver.ts` — the latency bars (cold turn p95: 10 ms at 1,000 skills, 40 ms at 7,500), enforced by `.github/workflows/skill-resolver-bench.yml` on a 2-vCPU runner.- `scripts/build-skill-resolver-bundle.ts` — builds and Node-smoke-tests `gbrain-skill-resolver.mjs`; the release job `skill-resolver-bundle` attaches it.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 72b68395bd..95ab8ae765 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4616,6 +4616,16 @@ More: [docs/guides/skill-resolver.md#skill_resolve_timeout](../../docs/guides/skMore: [docs/guides/skill-resolver.md#skill_resolver_config_invalid](../../docs/guides/skill-resolver.md#skill_resolver_config_invalid)+### skill_resolver_config_unreadable++<a id="skill_resolver_config_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| 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). | The request itself was wrong or no longer matches the brain; nothing was changed. | Fix or move <gbrain home>/config.json (it must be a JSON object), then run gbrain doctor --only skill_resolver. Run: gbrain doctor --only skill_resolver --json | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_config_unreadable](../../docs/guides/skill-resolver.md#skill_resolver_config_unreadable)+### skill_resolver_internal<a id="skill_resolver_internal"></a>@@ -4626,6 +4636,16 @@ More: [docs/guides/skill-resolver.md#skill_resolver_config_invalid](../../docs/gMore: [docs/guides/skill-resolver.md#skill_resolver_internal](../../docs/guides/skill-resolver.md#skill_resolver_internal)+### skill_resolver_setup_incomplete++<a id="skill_resolver_setup_incomplete"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| 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. | The request itself was wrong or no longer matches the brain; nothing was changed. | Add a skill to one of the scanned directories (the message names them), then run setup again. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_setup_incomplete](../../docs/guides/skill-resolver.md#skill_resolver_setup_incomplete)+### skill_retention_capacity<a id="skill_retention_capacity"></a>diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex be5f4e0925..85d112c029 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -215,7 +215,7 @@ gbrain. MCP `get_skill` is unchanged.| | ||---|---|-| Select | `--skill-loading off\|spring` on `gbrain setup <harness>`, `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness`; or `GBRAIN_SKILL_LOADING`. Flag, then env, then the recorded choice, then `off`. |+| Select | `--skill-loading off\|spring` on `gbrain setup <harness>` (`resolve` on `setup claude-code\|codex` turns on the per-turn skill resolver instead: [skill-resolver guide](skill-resolver.md#hook-lane-claude-code-and-codex)), `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness`; or `GBRAIN_SKILL_LOADING`. Flag, then env, then the recorded choice, then `off`. || Default | `off`: no index is written, and `off` removes one an earlier run wrote. || Which skills | Host installs (`setup`, `bootstrap harness`) list all bundled skills; hosted and thin-client connections leave out the host-maintenance ones. || Opt out | `--skill-loading off`; `--no-instructions` removes both blocks; `--remove` takes both out and deletes a file only gbrain created once nothing else is in it. On Codex, `--skill-loading off`, `--no-instructions` and `GBRAIN_SKILL_LOADING=off` also strip an index gbrain recorded in the other global instruction file of the same `CODEX_HOME` (`AGENTS.md` or `AGENTS.override.md`) and print it as a second skills line (`paired` in `--json`, in `--dry-run` too), so the index cannot return when the override file goes. |diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex 5a05daea45..2d89e8abb7 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -8,7 +8,9 @@ five suggestions, at most 400 tokens) for the harness to put in front of themodel.- **Off by default.** Nothing changes until you build a catalog and wire a- harness to call `gbrain skills resolve`. Setup writes nothing for it.+ harness to call `gbrain skills resolve`, or turn on the hook lane with+ `gbrain setup <claude-code|codex> --skill-loading resolve`. Setup writes+ nothing for it otherwise.- **Local and deterministic.** Word matching (BM25F) over the catalog's names,descriptions, triggers, routing rows and the first 4 KB of each body. Nonetwork, no model, no clock, no randomness on the turn path.@@ -61,6 +63,57 @@ drops below 20%. The constants were frozen on the Step 1 offline eval(gbrain-evals `docs/benchmarks/2026-11-07-skill-ranker-offline`) and arerecorded in the receipt.+## Hook lane: Claude Code and Codex++`gbrain setup claude-code --skill-loading resolve` (or `codex`) turns on a+per-turn hook that puts the block in front of the model on every prompt:++1. It builds the user catalog `claude-code-user` from `~/.claude/skills`+ (Codex: `codex-user` from `~/.agents/skills` and `$CODEX_HOME/skills`).+ With no skill found it stops with `skill_resolver_setup_incomplete` and+ writes nothing else.+2. It sets `skills.resolver.enabled` and `skills.resolver.harnesses` in+ `~/.gbrain/config.json`. A brainless install stays brainless: the file+ holds no engine, so nothing reads it as a brain.+3. It adds the lane's own hook: Claude Code gets UserPromptSubmit and+ SessionStart entries marked `skill-resolver-v1` in `~/.claude/settings.json`;+ Codex gets a UserPromptSubmit group in `hooks.json` (`--harness codex`),+ trusted in `config.toml`. Both run through the existing hook launcher.+4. It prints a sample block and `skill resolver: on; N skills; fresh`.++`--dry-run` lists every write, and re-running changes nothing. A bare+`gbrain setup <harness>` refreshes a lane that is on.++The lane runs the resolver in the hook process (never through `gbrain serve`),+so it works with serve down and with no brain. Each block names the skill ids+and gives the harness's own load line; Codex lines also carry the SKILL.md path.+The lane always exits 0 and prints nothing when it cannot deliver:++- **Deadline:** 50 ms from lane start. Ranking runs in a worker thread; at the+ deadline the process prints nothing, exits and commits no session state.+- **Payload:** at most `skills.resolver.lane_payload_chars` characters of hook+ output (default 4000, 500 to 10,000); a larger block is dropped whole and+ counted as `payload_dropped`.+- **One owner:** when several settings files wire the lane, only the first+ entry whose home has the lane on delivers.+- **Project skills (Claude Code):** a project's `.claude/skills` gets its own+ catalog, `claude-code-project-<hash of the root>`, built in the background+ the first time the project is seen and merged by name only. Stale catalogs+ rebuild the same way, at most once a minute;+ `skills.resolver.auto_rebuild false` or `GBRAIN_SKILLS_NO_AUTOREBUILD=1`+ stops both.+- **Compaction:** a SessionStart with `source: compact` resets the session, so+ skills can be offered again.++Each turn appends one line (outcome, error code, duration; never turn text)+to `skill-index/logs/lane.jsonl`. `gbrain doctor` (`skill_resolver`, and+`harness_wiring`'s details) reports the hook, each catalog's freshness and+the recent error codes; it says nothing while the resolver is off.++Compiled binaries carry the lane's worker as a second entrypoint+(`bun build --compile src/cli.ts src/core/skills/resolver/hook-worker.ts`); a+binary built without it delivers nothing and logs `skill_resolver_internal`.+## The contract (schema_version 1)The JSON Schemas are checked in under `docs/schemas/`:@@ -163,7 +216,10 @@ escaped.## Turning it offStop calling `gbrain skills resolve` from the harness, or set-`skills.resolver.session_token_budget` to 0. `gbrain skills index remove --catalog <name>`+`skills.resolver.session_token_budget` to 0. For the hook lane,+`gbrain setup <harness> --skill-loading off` (or `setup --remove`) removes the+hook, the config keys, that harness's catalogs and, once no harness is left,+the session state and the lane log. `gbrain skills index remove --catalog <name>`deletes a catalog; deleting `skill-index/` removes everything.## Latency@@ -241,6 +297,21 @@ The `--from-json` catalog or routing file is malformed or over its size bound`skills.resolver.session_token_budget` is not 0 or 100-50,000, or GBRAIN_HOMEis not an absolute path.+### skill_resolver_config_unreadable++`~/.gbrain/config.json` exists but is not a JSON object gbrain can read (or is+over 1 MB). Setup refuses and writes nothing, the hook lane prints nothing,+and `gbrain config set skills.resolver.*` refuses; gbrain never rewrites the+file. Fix or move it, then run `gbrain setup <harness> --skill-loading resolve`.++### skill_resolver_setup_incomplete++`gbrain setup <harness> --skill-loading resolve` found no model-invocable+skill in the directories it scanned (named in the message), the catalog build+failed, or no absolute gbrain binary was found for the hook. Nothing was+written (an empty catalog is removed). Add a skill there, or pass+`--gbrain-bin`, and run setup again; `--dry-run` shows what it would scan.+### skill_resolver_internalAn unexpected failure; a scrubbed trace was written todiff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 0d04d433db..3e500a6856 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -25,6 +25,7 @@* process is gone.*/import type { SkillsIndexState, SkillsIndexView } from '../../../core/setup/skills-block.ts';+import type { SkillResolverView } from './skill-resolver.ts';import { existsSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, isAbsolute, join } from 'node:path';@@ -602,12 +603,15 @@ export function withHookLaunchers(check: Check, problem: HookLauncherProblem | nreturn { name: NAME, status: 'warn', message, details: { ...details, code: 'hook_session_cwd', hook_launcher_reason: problem.reason }, fix };}-/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block, its per-turn hook and the hook launcher. */-export async function harnessWiringCheck(opts: { smoke: boolean }): Promise<Check> {+/** Registration read (full run) or registration read + smoke (`--only harness_wiring`), plus the brain-first block, its per-turn hook, the hook launcher and the skill-resolver lane (when configured). */+export async function harnessWiringCheck(opts: { smoke: boolean; skillResolver?: SkillResolverView | null }): Promise<Check> {const regs = readHarnessRegistrations();const { skillsIndexViews } = await import('../../../core/setup/skills-block.ts');const views = instructionBlockViews(regs);- return withSkillsIndex(withHookLaunchers(withSurfaceNote(withTurnHooks(withInstructionBlocks(await registrationCheck(opts, regs), views), views, turnHookViews(views)), regs), hookLauncherProblems(views)), skillsIndexViews());+ const check = withSkillsIndex(withHookLaunchers(withSurfaceNote(withTurnHooks(withInstructionBlocks(await registrationCheck(opts, regs), views), views, turnHookViews(views)), regs), hookLauncherProblems(views)), skillsIndexViews());+ if (!opts.skillResolver) return check;+ const { describeSkillResolver } = await import('./skill-resolver.ts');+ return { ...check, message: `${check.message} ${describeSkillResolver(opts.skillResolver)}`, details: { ...(check.details ?? {}), skill_resolver: opts.skillResolver } };}/**@@ -668,21 +672,25 @@ 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;+ const { skillResolverCheck, skillResolverView } = await import('./skill-resolver.ts');+ let skillResolver: SkillResolverView | null = null;+ let resolverError: unknown = null;try {- resolver = await skillResolverView();+ skillResolver = await skillResolverView();} catch (e) {- checks.push(checkError('skill_resolver', 'read the skill resolver state', e));+ resolverError = 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);+ checks.push(await harnessWiringCheck({ smoke: !!ctx.only?.has('harness_wiring'), skillResolver }));} catch (e) {checks.push(checkError('harness_wiring', 'read the harness registrations', e));}- const own = skillResolverCheck(resolver);- if (own) checks.push(own);+ if (resolverError) {+ checks.push(checkError('skill_resolver', 'read the skill resolver state', resolverError));+ } else {+ const resolverCheck = skillResolverCheck(skillResolver);+ if (resolverCheck) checks.push(resolverCheck);+ }return checks;}diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.tsindex cfbbaafe45..7707dc7ed9 100644--- a/src/commands/doctor/checks/skill-resolver.ts+++ b/src/commands/doctor/checks/skill-resolver.ts@@ -21,7 +21,7 @@ import { LANE_LOG_FILE, projectCatalogPrefix, userCatalogName, type LaneHarnessimport { readResolverConfig, resolverHarnesses } from '../../../core/setup/skill-resolver-config.ts';import { inspectSkillResolverHook } from '../../../core/setup/skill-resolver-hook.ts';-const NAME = 'skill_resolver';+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;@@ -99,17 +99,17 @@ 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',+ return { 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),+ return { 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 };+ return { name, status: 'ok', message: describeSkillResolver(v), details };}diff --git a/src/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.tsindex 441ebddad9..7ca525abe3 100644--- a/src/core/setup/skill-resolver-config.ts+++ b/src/core/setup/skill-resolver-config.ts@@ -17,6 +17,7 @@import { existsSync, readFileSync, statSync, unlinkSync } from 'node:fs';import { join } from 'node:path';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { setCliExitVerdict } from '../cli-force-exit.ts';import { validateSessionTokenBudget } from '../skills/resolver/config.ts';const CONFIG_CAP_BYTES = 1024 * 1024;@@ -107,7 +108,7 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanconst [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; };+ const fail = (msg: string): true => { console.error(`[config] ${msg}`); setCliExitVerdict(1); return true; };if (leaf === 'harnesses') return fail(`${key} is written by gbrain setup <claude-code|codex> --skill-loading resolve (and removed by --skill-loading off); nothing was written.`);if (!(SKILL_RESOLVER_CONFIG_LEAVES as readonly string[]).includes(leaf)) return fail(`Unknown config key "${key}". skills.resolver keys: ${SKILL_RESOLVER_CONFIG_LEAVES.join(', ')}. Nothing was written.`);const read = readResolverConfig(home);@@ -132,7 +133,8 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanconst 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 });+ if (Object.keys(doc).length === 0) unlinkSync(read.path);+ else atomicWriteTextFile(read.path, `${JSON.stringify(doc, null, 2)}\n`, { freshMode: 0o600 });console.log(action === 'set' ? `Set ${key} = ${JSON.stringify(section[leaf])} (file plane: ${read.path})` : `Unset ${key} (file plane)`);return true;}diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsindex 6a98413848..01872bc612 100644--- a/src/core/skills/resolver/hook-lane.ts+++ b/src/core/skills/resolver/hook-lane.ts@@ -22,8 +22,9 @@* 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.)+ * entry there whose home has the lane on names its own GBRAIN_HOME, so two+ * wirings of different homes 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@@ -70,7 +71,7 @@ const COMMIT_RESERVE_MS = 10;* 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';+export 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';@@ -89,9 +90,10 @@ async function readJsonFile(path: string, cap = CONFIG_CAP_BYTES): Promise<unkno}/**- * 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.+ * The GBRAIN_HOME of the skill-resolver wiring that owns this event: the+ * first lane entry, in carrier order, whose home has the lane on for this+ * harness. Undefined when none does (a manual run, or every wiring off).+ * Async reads only; an unreadable carrier or home 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';@@ -105,8 +107,15 @@ export async function skillResolverOwner(harness: LaneHarness, event: 'user-promfor (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);+ for (const e of entries) {+ const command = (e as { command?: unknown } | null)?.command;+ if (typeof command !== 'string' || !(harness === 'codex' ? isSkillResolverCommand(command) : isSkillResolverEntry(e))) continue;+ const home = commandHome(command);+ try {+ const s = await readLaneSettings(resolverHome(home ? { GBRAIN_HOME: home } : {}), {});+ if (s.enabled && s.harnesses.includes(harness)) return home;+ } catch { /* a home gbrain cannot use owns nothing */ }+ }}}return undefined;diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex dbe187e7ad..cf9278ea29 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -225,6 +225,10 @@"category": "ops","name": "harness_wiring"},+ {+ "category": "ops",+ "name": "skill_resolver"+ },{"category": "meta","name": "agent_contract"diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.tsnew file mode 100644index 0000000000..a28df84ecf--- /dev/null+++ b/test/setup-skill-resolver.test.ts@@ -0,0 +1,256 @@+/**+ * GBRA-377 PR B: `gbrain setup <claude-code|codex> --skill-loading resolve`+ * (src/core/setup/skill-resolver-setup.ts) and the skills.resolver.* config+ * keys (src/core/setup/skill-resolver-config.ts).+ *+ * Protects: setup builds the user catalog and writes the keys and the hook+ * only after a build with at least one skill (else+ * skill_resolver_setup_incomplete and nothing written); it is idempotent;+ * --dry-run lists every write and writes nothing; --skill-loading off and+ * setup --remove undo every write; nothing new lands in the hook-launcher+ * directory; a plain setup writes no catalog and no key; an unreadable config+ * refuses with skill_resolver_config_unreadable; a brainless install stays+ * brainless (no engine inferred from the file) and a later init, a thin client+ * and removal keep the keys' engine boundary; doctor stays silent until the+ * resolver is configured.+ */+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 { withEnv } from './helpers/with-env.ts';+import { loadConfig } from '../src/core/config.ts';+import { SKILL_RESOLVER_MARKER } from '../src/core/setup/skill-resolver-lane.ts';++setDefaultTimeout(60_000);+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+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-resolver-setup-'));+ 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,+ GBRAIN_SKILL_LOADING: undefined, GBRAIN_HOOK_LANE: undefined, GBRAIN_AGENT_INSTRUCTIONS: 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.\n`);+}+const HARNESS = {+ 'claude-code': { skills: (b: Box) => join(b.home, '.claude', 'skills'), hookFile: (b: Box) => join(b.home, '.claude', 'settings.json') },+ 'codex': { skills: (b: Box) => join(b.home, '.agents', 'skills'), hookFile: (b: Box) => join(b.home, '.codex', 'hooks.json') },+} as const;+type H = keyof typeof HARNESS;++async function setup(b: Box, harness: string, extra: string[]) {+ const r = await runCli(['setup', harness, '--instructions-only', '--gbrain-bin', b.bin, ...extra], { env: b.env, cwd: b.project });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc };+}+const gb = (b: Box) => join(b.home, '.gbrain');+const configPath = (b: Box) => join(gb(b), 'config.json');+const read = (p: string) => (existsSync(p) ? readFileSync(p, 'utf8') : null);+const catalogs = (b: Box) => (existsSync(join(gb(b), 'skill-index')) ? readdirSync(join(gb(b), 'skill-index')).filter((n) => !n.startsWith('.') && n !== 'logs' && n !== 'sessions') : []);+/** Every file under the box (relative path -> content), for before/after comparisons. */+function tree(dir: string, base = dir, out: Record<string, string> = {}): Record<string, string> {+ if (!existsSync(dir)) return out;+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ const p = join(dir, e.name);+ if (e.isDirectory()) tree(p, base, out); else out[p.slice(base.length + 1)] = readFileSync(p, 'utf8');+ }+ return out;+}++for (const harness of ['claude-code', 'codex'] as H[]) {+ describe(`setup ${harness} --skill-loading resolve`, () => {+ test('no skill directory: refuses with skill_resolver_setup_incomplete, names the scanned dirs, writes nothing of the resolver', async () => {+ const b = box();+ const r = await setup(b, harness, ['--skill-loading', 'resolve', '--json']);+ expect(r.exitCode).not.toBe(0);+ expect(`${r.stdout}${r.stderr}`).toContain('skill_resolver_setup_incomplete');+ expect(`${r.stdout}${r.stderr}`).toContain(HARNESS[harness].skills(b));+ expect(read(configPath(b))).toBeNull();+ expect(catalogs(b)).toEqual([]);+ expect(read(HARNESS[harness].hookFile(b)) ?? '').not.toContain('GBRAIN_HOOK_LANE=skill-resolver');+ });++ test('an empty skill directory: refuses and leaves no catalog behind', async () => {+ const b = box();+ mkdirSync(HARNESS[harness].skills(b), { recursive: true });+ const r = await setup(b, harness, ['--skill-loading', 'resolve', '--json']);+ expect(`${r.stdout}${r.stderr}`).toContain('skill_resolver_setup_incomplete');+ expect(read(configPath(b))).toBeNull();+ expect(catalogs(b)).toEqual([]);+ });++ test('on, idempotent, dry-run lists every write, then off and --remove undo all of it', async () => {+ const b = box();+ skill(HARNESS[harness].skills(b), 'deploy-widget', 'Deploy the widget service.');+ const plain = await setup(b, harness, []);+ expect(plain.exitCode).toBe(0);+ const before = { ...tree(b.home) };+ expect(catalogs(b)).toEqual([]);+ expect(read(configPath(b))).toBeNull();++ const dry = await setup(b, harness, ['--skill-loading', 'resolve', '--dry-run']);+ expect(dry.exitCode).toBe(0);+ for (const step of ['resolver catalog:', 'resolver config:', 'resolver hook:']) expect(dry.stdout).toContain(`would write resolver ${step.split(' ')[1]}`);+ expect(tree(b.home)).toEqual(before);++ const on = await setup(b, harness, ['--skill-loading', 'resolve']);+ expect(on.exitCode, on.stderr).toBe(0);+ expect(on.stdout).toContain('<relevant_skills>');+ expect(on.stdout).toMatch(/skill resolver: on; 1 skills; fresh/);+ expect(JSON.parse(read(configPath(b))!)).toEqual({ skills: { resolver: { enabled: true, harnesses: [harness] } } });+ expect(catalogs(b)).toEqual([`${harness}-user`]);+ const hooks = read(HARNESS[harness].hookFile(b))!;+ expect(hooks.split('GBRAIN_HOOK_LANE=skill-resolver').length - 1).toBe(harness === 'codex' ? 1 : 2);+ if (harness === 'claude-code') expect(hooks).toContain(SKILL_RESOLVER_MARKER);+ else expect(read(join(b.home, '.codex', 'config.toml'))).toContain('skill-resolver');+ const launcherDir = join(gb(b), 'hook-launcher');+ const launcherFiles = readdirSync(launcherDir).sort();++ const resolverFiles = () => Object.fromEntries([configPath(b), HARNESS[harness].hookFile(b), join(b.home, '.codex', 'config.toml'), join(gb(b), 'skill-index', `${harness}-user`, 'receipt.json')].map((p) => [p, read(p)]));+ const onFiles = resolverFiles();+ const again = await setup(b, harness, ['--skill-loading', 'resolve', '--json']);+ expect(again.exitCode).toBe(0);+ expect(again.doc.skill_resolver.steps.map((s: any) => s.action)).toEqual(['keep', 'keep', 'keep']);+ const refresh = await setup(b, harness, ['--json']);+ expect(refresh.exitCode).toBe(0);+ expect(refresh.doc.skill_resolver.steps.every((s: any) => s.action === 'keep')).toBe(true);+ expect(resolverFiles()).toEqual(onFiles);+ expect(readdirSync(launcherDir).sort()).toEqual(launcherFiles);++ const off = await setup(b, harness, ['--skill-loading', 'off']);+ expect(off.exitCode).toBe(0);+ expect(read(configPath(b))).toBeNull();+ expect(catalogs(b)).toEqual([]);+ const rel = (p: string) => p.slice(b.home.length + 1);+ expect(read(HARNESS[harness].hookFile(b))).toBe(before[rel(HARNESS[harness].hookFile(b))]!);+ if (harness === 'codex') expect(read(join(b.home, '.codex', 'config.toml'))).toBe(before[rel(join(b.home, '.codex', 'config.toml'))]!);+ expect(existsSync(join(gb(b), 'skill-index', 'sessions'))).toBe(false);++ expect((await setup(b, harness, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ const removed = await runCli(['setup', harness, '--remove', '--gbrain-bin', b.bin], { env: b.env, cwd: b.project });+ expect(removed.exitCode, removed.stderr).toBe(0);+ expect(read(configPath(b))).toBeNull();+ expect(catalogs(b)).toEqual([]);+ expect(read(HARNESS[harness].hookFile(b))).toBe(before[rel(HARNESS[harness].hookFile(b))]!);+ });+ });+}++describe('setup --skill-loading resolve: refusals and other keys', () => {+ test('another harness refuses resolve', async () => {+ const b = box();+ const r = await setup(b, 'opencode', ['--skill-loading', 'resolve']);+ expect(r.exitCode).not.toBe(0);+ expect(read(configPath(b))).toBeNull();+ });++ test('an unreadable config: refuses with skill_resolver_config_unreadable and leaves the file as it was', async () => {+ const b = box();+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ mkdirSync(gb(b), { recursive: true });+ writeFileSync(configPath(b), '{ broken');+ const r = await setup(b, 'claude-code', ['--skill-loading', 'resolve', '--json']);+ expect(r.exitCode).not.toBe(0);+ expect(`${r.stdout}${r.stderr}`).toContain('skill_resolver_config_unreadable');+ expect(read(configPath(b))).toBe('{ broken');+ expect(catalogs(b)).toEqual([]);+ });++ test('other config keys survive on and off', async () => {+ const b = box();+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ mkdirSync(gb(b), { recursive: true });+ writeFileSync(configPath(b), JSON.stringify({ self_upgrade: { channel: 'alpha' } }));+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(JSON.parse(read(configPath(b))!)).toEqual({ self_upgrade: { channel: 'alpha' }, skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } });+ expect((await setup(b, 'claude-code', ['--skill-loading', 'off'])).exitCode).toBe(0);+ expect(JSON.parse(read(configPath(b))!)).toEqual({ self_upgrade: { channel: 'alpha' } });+ });++ test('config set|get|unset skills.resolver.* run without a brain; harnesses belongs to setup', async () => {+ const b = box();+ const run = (...args: string[]) => runCli(['config', ...args], { env: b.env, cwd: b.project });+ expect((await run('set', 'skills.resolver.lane_payload_chars', '600')).exitCode).toBe(0);+ expect((await run('get', 'skills.resolver.lane_payload_chars')).stdout.trim()).toBe('600');+ expect((await run('set', 'skills.resolver.lane_payload_chars', '20')).exitCode).not.toBe(0);+ expect((await run('set', 'skills.resolver.harnesses', 'codex')).exitCode).not.toBe(0);+ expect((await run('unset', 'skills.resolver.lane_payload_chars')).exitCode).toBe(0);+ expect(read(configPath(b))).toBeNull();+ });+});++describe('the engine boundary with resolver-only settings', () => {+ test('resolver keys alone configure no brain; an engine, a database or a remote endpoint does', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-resolver-boundary-'));+ roots.push(dir);+ const write = (doc: unknown) => { mkdirSync(join(dir, '.gbrain'), { recursive: true }); writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(doc)); };+ const load = () => withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => loadConfig());+ write({ skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } });+ expect(await load()).toBeNull();+ write({ engine: 'pglite', database_path: join(dir, '.gbrain', 'brain.pglite'), skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } });+ expect((await load())?.engine).toBe('pglite');+ write({ remote_mcp: { issuer_url: 'https://brain.example.invalid', mcp_url: 'https://brain.example.invalid/mcp', oauth_client_id: 'client-a' }, skills: { resolver: { enabled: true } } });+ expect((await load())?.remote_mcp).toBeTruthy();+ });++ test('after a brainless resolver setup, init creates the brain and keeps the keys; removal leaves the brain', async () => {+ const b = box();+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ const init = await runCli(['init', '--pglite', '--no-embedding', '--json'], { env: b.env, cwd: b.project, timeoutMs: 120_000 });+ expect(init.exitCode, init.stderr).toBe(0);+ const cfg = JSON.parse(read(configPath(b))!);+ expect(cfg.engine).toBe('pglite');+ expect(cfg.skills).toEqual({ resolver: { enabled: true, harnesses: ['claude-code'] } });+ const stats = await runCli(['stats', '--json'], { env: b.env, cwd: b.project, timeoutMs: 120_000 });+ expect(stats.exitCode, stats.stderr).toBe(0);+ expect((await setup(b, 'claude-code', ['--skill-loading', 'off'])).exitCode).toBe(0);+ const left = JSON.parse(read(configPath(b))!);+ expect(left.engine).toBe('pglite');+ expect(left.skills).toBeUndefined();+ }, 240_000);+});++describe('doctor', () => {+ test('silent when the resolver is not configured; reports the lane once it is on', async () => {+ const b = box();+ const doctor = async (only = ['--only', 'skill_resolver']) => JSON.parse((await runCli(['doctor', ...only, '--json'], { env: b.env, cwd: b.project })).stdout);+ const unconfigured = await doctor(['--only', 'harness_wiring']);+ expect(unconfigured.checks.some((c: any) => c.name === 'harness_wiring')).toBe(true);+ expect(unconfigured.checks.find((c: any) => c.name === 'skill_resolver')).toBeUndefined();+ expect(JSON.stringify(unconfigured.checks.find((c: any) => c.name === 'harness_wiring'))).not.toContain('skill_resolver');+ skill(HARNESS['claude-code'].skills(b), 'deploy-widget', 'Deploy the widget service.');+ expect((await setup(b, 'claude-code', ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ const on = (await doctor()).checks.find((c: any) => c.name === 'skill_resolver');+ expect(on).toMatchObject({ status: 'ok', details: { config: 'ok', harnesses: [{ harness: 'claude-code', on: true, hook: 'wired', catalogs: [{ name: 'claude-code-user', fresh: true, skills: 1 }] }] } });+ skill(HARNESS['claude-code'].skills(b), 'write-changelog', 'Write a changelog entry.');+ const stale = (await doctor()).checks.find((c: any) => c.name === 'skill_resolver');+ expect(stale.details.harnesses[0].catalogs[0]).toMatchObject({ fresh: false, stale_reason: 'source_changed' });+ const settings = JSON.parse(read(HARNESS['claude-code'].hookFile(b))!);+ for (const ev of Object.keys(settings.hooks)) settings.hooks[ev] = settings.hooks[ev].filter((g: any) => !JSON.stringify(g).includes('skill-resolver'));+ writeFileSync(HARNESS['claude-code'].hookFile(b), JSON.stringify(settings));+ const broken = (await doctor()).checks.find((c: any) => c.name === 'skill_resolver');+ expect(broken.status).toBe('warn');+ expect(broken.fix.argv).toEqual(['gbrain', 'setup', 'claude-code', '--skill-loading', 'resolve']);+ writeFileSync(configPath(b), '{ broken');+ const unreadable = (await doctor()).checks.find((c: any) => c.name === 'skill_resolver');+ expect(unreadable).toMatchObject({ status: 'warn', details: { code: 'skill_resolver_config_unreadable' } });+ });+});diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsindex 885a49e4ee..5fd4ba63bd 100644--- a/test/skill-resolver-hook-lane.test.ts+++ b/test/skill-resolver-hook-lane.test.ts@@ -18,7 +18,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSynimport { 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';+import { LANE_DEADLINE_MS, projectCatalogPrefix, WORKER_SRC_PATH } from '../src/core/skills/resolver/hook-lane.ts';setDefaultTimeout(60_000);const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');@@ -154,7 +154,6 @@ describe('skill-resolver lane: deadline, measured outside the process', () => {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);@@ -184,8 +183,6 @@ describe('skill-resolver lane: fail open', () => {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 () => {@@ -212,19 +209,55 @@ describe('skill-resolver lane: fail open', () => {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 () => {+ test('one owner per event: user scope, workspace and plugin wired at once give exactly one block and one dedupe commit', async () => {const b = box();seedSkills(claudeSkills(b));await setup(b, 'claude-code');- const cmd = wired(b, 'claude-code');+ const user = wired(b, 'claude-code');+ // A second home with the lane on, wired in the workspace's settings.local.json (earlier in carrier order).const other = join(b.root, 'other-home');+ mkdirSync(join(other, '.gbrain'), { recursive: true });+ writeFileSync(join(other, '.gbrain', 'config.json'), JSON.stringify({ skills: { resolver: { enabled: true, harnesses: ['claude-code'] } } }));+ const build = await runCli(['skills', 'index', 'build', '--catalog', 'claude-code-user', '--dir', claudeSkills(b), '--harness', 'claude-code'], { env: { ...b.env, GBRAIN_HOME: other }, cwd: b.project });+ expect(build.exitCode, build.stderr).toBe(0);+ const workspace = user.replace(`GBRAIN_HOME=${b.home}`, `GBRAIN_HOME=${other}`);+ expect(workspace).not.toBe(user);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: '' });+ writeFileSync(join(b.project, '.claude', 'settings.local.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: workspace, _gbrain: 'skill-resolver-v1' }] }] } }));+ const plugin = `env GBRAIN_HOOK_LANE=plugin GBRAIN_HOME=${b.home} '${b.bin}' hook user-prompt`;+ const turn = { prompt: 'please deploy the widget to staging', session_id: 'sess-o' };+ const runs = await Promise.all([user, workspace, plugin].map((c) => hook(b, c, turn, WIDE)));+ expect(runs.map((r) => r.exitCode)).toEqual([0, 0, 0]);+ expect(runs.filter((r) => r.stdout.includes('<relevant_skills>')).length).toBe(1);+ expect(runs[1]!.stdout).toContain('<relevant_skills>');+ const commits = [b.home, other].flatMap((h) => { const d = join(h, '.gbrain', 'skill-index', 'sessions'); return existsSync(d) ? readdirSync(d) : []; });+ expect(commits).toHaveLength(1);expect(laneLog(b)).toEqual([]);});++ test('a wiring whose home has the lane off owns nothing', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ const cmd = wired(b, 'claude-code');+ 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=${join(b.root, 'off-home')}`), _gbrain: 'skill-resolver-v1' }] }] } }));+ expect(contextOf(await hook(b, cmd, { prompt: 'deploy the widget', session_id: 's' }, WIDE))).toContain('deploy-widget');+ });+});++describe('skill-resolver lane: compiled binaries', () => {+ // A compiled binary bundles src/ into one entry; a worker it starts must be a second+ // entrypoint (bun build --compile src/cli.ts <worker>), found at its src-relative path.+ test('every shipped binary build carries the worker entry at the path the lane starts', () => {+ const root = join(import.meta.dir, '..');+ expect(existsSync(join(root, 'src', WORKER_SRC_PATH))).toBe(true);+ const pkg = readJson(join(root, 'package.json')) as { scripts: Record<string, string> };+ const release = readFileSync(join(root, '.github', 'workflows', 'release.yml'), 'utf8');+ const builds = [pkg.scripts.build!, ...pkg.scripts['build:all']!.split('&&'), ...release.split('\n').filter((l) => l.includes('bun build --compile'))];+ expect(builds.length).toBe(4);+ for (const b of builds) expect(b).toContain(`src/cli.ts src/${WORKER_SRC_PATH}`);+ });});describe('skill-resolver lane: project catalog', () => {