Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver lane: Hermes IO, Codex project catalog, plugins catalog, doctor and per_harness fixes; HARN-52 freshness, budget and receipt fixes
garrytan95bf880a0b6e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 7b5721a088..99d4fefaf3 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 src/core/skills/resolver/hook-worker.ts+ - run: bun build --compile --no-compile-autoload-bunfig --define GBRAIN_BUILD_COMMIT='"${{ github.sha }}"' --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/dbg-tmp.ts b/dbg-tmp.tsdeleted file mode 100644index ab836bffc7..0000000000--- a/dbg-tmp.ts+++ /dev/null@@ -1,18 +0,0 @@-import { PGLiteEngine } from './src/core/pglite-engine.ts';-import { operations } from './src/core/operations.ts';-import { generateTemporalEdgesWorld, currentEmployers } from '/home/user/.capy/work/src/gbrain-evals-p0/eval/generators/temporal-edges-gen.ts';-const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();-const ctx: any = { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' };-const op = (n: string) => operations.find(o => o.name === n)!;-const w = generateTemporalEdgesWorld({ seed: 3, phrasing: process.argv[2] });-for (const p of w.pages) { const s = await engine.readPageSnapshot(p.slug, { sourceId: 'default' }); await op('put_page').handler(ctx, { slug: p.slug, content: p.content, ...(s ? { expected_revision: s.revision } : {}) }); }-let shown = 0; const styles: Record<string, number> = {};-for (const p of w.people) {- const cur = currentEmployers(p);- const live = (await op('get_links').handler(ctx, { slug: p.slug, link_type: 'works_at' }) as any[]).map(r => r.to_slug);- const wrong = live.filter(s => !cur.includes(s)); if (!wrong.length) continue;- styles[p.style] = (styles[p.style] ?? 0) + 1;- if (shown++ < 2) { console.log('WRONG', p.style, wrong, JSON.stringify(p.stints.map(s => [s.company.slice(10), s.from, s.until]))); console.log(w.pages.find(x => x.slug === p.slug)!.content);- for (const r of await op('get_links').handler(ctx, { slug: p.slug, status: 'all', link_type: 'works_at' }) as any[]) console.log(' ', r.to_slug, r.status, JSON.stringify(r.stints)); }-}-console.log(styles);diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex a438979a3d..23c49003fa 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -46,12 +46,12 @@ Contract schemas: `docs/schemas/skill-resolver.v1.*.json`. Every module under`skill-catalog.ts` import, static or dynamic (`test/skill-resolver-module-graph.test.ts`).- `src/core/skills/resolver/index.ts` — the library entry (`gbrain/skill-resolver` export, and the entry of the Node bundle `gbrain-skill-resolver.mjs`). Re-exports build, status, remove, resolve, `openCatalog`, `buildSkillIndexOffThread`, `ResolverError`, `resolverHome`; `resetSkillSession` deletes one session's state; `gcSkillSessions` runs one bounded async GC pass; `RESOLVER_FEATURES` names what an adapter may rely on.-- `src/core/skills/resolver/resolve.ts` — one turn: `normalizeTurnInput` (the turn-input schema, unknown fields refused, message capped at 8 KB), catalog loading through a `TurnSource` (`openCatalogIndex`: receipt and ranker identity, index size; then per turn the gbrain version and, for `dir` and `claude_plugins` catalogs, the sliced stat freshness check: at most `STAT_CHECK_SLICE` entries per turn, a full sweep at most once per `STAT_CHECK_INTERVAL_MS`, cursor in `stat-check`; `stale.stamp` is written without fsync, only when absent and only for a catalog with `rebuild_argv`, never an adapter-owned stdin one), ack and no_match, explicit mentions first, merged-catalog interleave, the `min_match_strength` floor before the cut to k, `previous_user_message` as the no-match fallback, the session rules (k 5/3/1 at 50%/80% of the budget, strong-match pacing, no-repeat, one re-suggestion after 10 turns, a named skill past a spent budget), the block, `explain`, `failOpen`, `deadlineMs`. Returns `commit()`; session state changes only through it. Pinned by `test/skill-resolver.test.ts` and `test/skill-resolver-contract.test.ts`.+- `src/core/skills/resolver/resolve.ts` — one turn: `normalizeTurnInput` (the turn-input schema, unknown fields refused, message capped at 8 KB), catalog loading through a `TurnSource` (`openCatalogIndex`: receipt and ranker identity, index size; then per turn the gbrain version and, for `dir` and `claude_plugins` catalogs, the sliced stat freshness check: at most `STAT_CHECK_SLICE` entries per turn, a full sweep at most once per `STAT_CHECK_INTERVAL_MS`, cursor in `stat-check`; `stale.stamp` is written without fsync, only when absent and only for a catalog with `rebuild_argv`, never an adapter-owned stdin one), ack and no_match, explicit mentions first, merged-catalog interleave, the `min_match_strength` floor before the cut to k, `previous_user_message` as the no-match fallback, the session rules (k 5/3/1 at 50%/80% of the budget, strong-match pacing, no-repeat, one re-suggestion after 10 turns, a named skill past a spent budget, `budget_exhausted` kept on ack and no-match turns), the block and its `block_reason`, `explain`, `failOpen`, `deadlineMs`. Returns `commit()`; session state changes only through it. Pinned by `test/skill-resolver.test.ts` and `test/skill-resolver-contract.test.ts`.- `src/core/skills/resolver/rank.ts` — the A5 BM25F ranker over an `IndexReader` (scores summed in the prototype's order, ranked by score over summed idf, ties by name then id), the multilingual acknowledgement list, `mentionsSkill` (a `/name` counts only as a leading slash command) and `reasonText`. `test/skill-resolver-reproduction.test.ts` pins top-5 equality with the Step 1 prototype.- `src/core/skills/resolver/tokenize.ts` — `splitWords` (shared with `scoreSkillMatch` in `skill-catalog.ts`) and `lexTerms`, the frozen Step 1 term rule (stopwords, light stemming); CJK runs become overlapping bigrams. Vectors: `test/fixtures/skill-resolver/tokenizer-vectors.json`.- `src/core/skills/resolver/index-format.ts` — `index.bin` (magic `GBSKIDX1`, JSON header, field-length averages, per-skill lengths, sorted term dictionary, flat postings with per-field tf, per-skill meta), byte-identical for identical records; `VARIANT_PARAMS` (D and T constants), `fieldText`, `summaryOf` (the description cut at 120 characters), `IndexReader` (lazy postings and meta reads).- `src/core/skills/resolver/build.ts` — `buildSkillIndex` under the catalog lease (variant choice: T at a 25% trigger-or-routing share, kept down to 20%; publication only while the lease is held and the directory exists, receipt written last), `catalogStatus` (content tier: re-reads the source and re-hashes the index), `removeSkillIndex` (rename then delete, so a concurrent build fails `skill_index_removed`), `listCatalogs`, `sessionStatus`, `dirFingerprintSlice`, `catalogHash`.-- `src/core/skills/resolver/sources.ts` — the four sources: `--dir` (real paths only, symlinks out of the root skipped, breadth-first, first id wins, plugin namespace from `.claude-plugin/plugin.json`, stat fingerprint), `--bundled` (dynamic import of `src/core/skills/bundled.ts`, never the operations table), `--from-json` (`JSON_INPUT_CAP_BYTES` 64 MB, 10,000 entries, bodies trimmed to 4 KB, a snapshot over `JSON_SOURCE_CAP_BYTES` kept trimmed; an adapter list or OpenClaw's `skills list --json` as is, name as id; with `--dir`, `mergeSkillFolders` takes bodies, paths and triggers by name) and `--claude-plugins` (`readClaudePluginSources`: enabled user-scope plugins from `installed_plugins.json` and `settings.json`, as `<plugin>:<skill>`); `applyRouting`; bounds (`MAX_SKILLS`, `MAX_DIRS_VISITED`, `MAX_DEPTH`).+- `src/core/skills/resolver/sources.ts` — the four sources: `--dir` (real paths only, symlinks out of the root skipped, breadth-first, dot-entries and `node_modules` never read, a per-directory `listingKey` so a harness writing its own dot-files leaves the index fresh, first id wins, plugin namespace from `.claude-plugin/plugin.json`, stat fingerprint), `--bundled` (dynamic import of `src/core/skills/bundled.ts`, never the operations table), `--from-json` (`JSON_INPUT_CAP_BYTES` 64 MB, 10,000 entries, bodies trimmed to 4 KB, a snapshot over `JSON_SOURCE_CAP_BYTES` kept trimmed; an adapter list or OpenClaw's `skills list --json` as is, name as id; with `--dir`, `mergeSkillFolders` takes bodies, paths and triggers by name) and `--claude-plugins` (`readClaudePluginSources`: enabled user-scope plugins from `installed_plugins.json` and `settings.json`, as `<plugin>:<skill>`); `applyRouting`; bounds (`MAX_SKILLS`, `MAX_DIRS_VISITED`, `MAX_DEPTH`).- `src/core/skills/resolver/frontmatter.ts` — bounded SKILL.md reader (64 KB file, 4 KB body): name, description, `when_to_use`, triggers, `disable-model-invocation`.- `src/core/skills/resolver/routing.ts` — one RESOLVER-style routing file's table and compact-list rows, skipping the generated skills block.- `src/core/skills/resolver/session.ts` — session state (`sessions/<sha256(scope, harness, id)>.json`: ids and counters only), `commitSession` under a short lease, file and id caps, 7-day GC with a per-run work bound; every commit (sync or async) then starts an async GC pass after it settles, at most once per `GC_INTERVAL_MS` (10 min) per home by the mtime of `logs/session-gc.stamp`, so new sessions keep deduping past `MAX_SESSION_FILES`.@@ -64,9 +64,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 the daily lane log (`daily-log.ts`: `skill-index/logs/lane-<date>.jsonl`, kept 14 days). 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/core/skills/resolver/hook-lane.ts` + `hook-worker.ts` + `hook-input.ts` — the hook lane (`GBRAIN_HOOK_LANE=skill-resolver`, dispatched first in `src/commands/hook.ts` after the `GBRAIN_HOOKS=0` check; `--harness claude-code|codex|hermes`): per-harness wire shapes in `LANE_IO` (Claude Code and Codex: top-level `prompt` in, `hookSpecificOutput.additionalContext` out; Hermes `pre_llm_call`: `extra.user_message` in through `readJsonFields`, the streaming reader over `Bun.stdin` that keeps only the named string paths and skips any history size unbuffered, `{"context"}` out; Hermes has no owner carrier and no compaction event), 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 catalogs (each only once its receipt exists, else outcome `no_catalog`: `<harness>-user`, `claude-code-plugins`, then the project catalog: `claude-code-project-<root hash>` over `.claude/skills`, or `codex-project-<dir-list hash>` over each `.agents/skills` from the `.git` root down to cwd, root first, without `~/.agents/skills`; built by a detached `skills index build`, stamp-limited to once a minute) and the daily lane log (`daily-log.ts`: `skill-index/logs/lane-<date>.jsonl`, kept 14 days). 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 (`inspectSkillResolverHook`: absent, wired, untrusted, or outdated when UserPromptSubmit lacks its SessionStart entry; sync rewrites it), the file-plane keys (`skills.resolver.*`, engine-free in `gbrain config`; an unreadable file is never rewritten; a non-object `per_harness` entry reads as unset and set/unset replace it), 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 (an `outdated` hook warns with `gbrain setup <harness> --skill-loading resolve`), 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`, `skills resolve` and `skills library` 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.- `src/commands/skill-resolver-library.ts` — the one Node-bundle builder (Bun.build of the library entry, written atomically, sha256 returned) behind `gbrain skills library` (default `GBRAIN_HOME/.gbrain/lib/gbrain-skill-resolver.mjs`) and the release script; a compiled binary has no source and refuses with `skill_source_unreadable`. Pinned by `test/skill-resolver-packaging.test.ts`.diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex d3525dac02..d4f7b5ac67 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -49,7 +49,9 @@ One catalog per skill set. Names are 1-64 characters of `a-z`, `0-9`, `_` and- `--dir` is repeatable; earlier directories win duplicate ids (the loser islisted in the receipt as `duplicate_id`). Symlinks that leave the root,skills with `disable-model-invocation: true` and JSON entries with- `eligible: false` are never indexed.+ `eligible: false` are never indexed. Dot-entries (harness-owned state such+ as Codex's `.system/` or Hermes's `.usage.json`) and `node_modules` are+ never read, so a harness writing them does not make the index stale.- `--routing <file>` adds the rows of one RESOLVER-style routing table tothe skills they name.- `--scope project` marks a cloned repository's skills: their blocks show ids@@ -92,6 +94,16 @@ per-turn hook that puts the block in front of the model on every prompt:`--dry-run` lists every write, and re-running changes nothing. A bare`gbrain setup <harness>` refreshes a lane that is on.+**Hermes** runs the same lane as a `pre_llm_call` shell hook:+`GBRAIN_HOOK_LANE=skill-resolver gbrain hook user-prompt --harness hermes`.+Setup does not wire it yet, so build `hermes-user` yourself+(`gbrain skills index build --catalog hermes-user --dir ~/.hermes/skills+--harness hermes`) and add `hermes` to `skills.resolver.harnesses`. The lane+reads `extra.user_message`, `session_id` and `cwd` from the hook's stdin and+answers `{"context": "<block>"}`. Hermes sends the whole conversation history+on every turn, so the lane streams stdin and keeps only those three strings+(each capped at 8 KB): a history of any size is read, never refused.+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 idsand gives the harness's own load line; Codex lines also carry the SKILL.md path.@@ -104,32 +116,46 @@ The lane always exits 0 and prints nothing when it cannot deliver:default every match) and `skills.resolver.pinned` (skill ids the harnessalways loads itself, never suggested). `skills.resolver.per_harness.<harness>.top_k`and `.min_match` override one harness; what it leaves out falls back to the- global key. Set them with `gbrain config set`; a bad value makes the lane+ global key, and an entry that is not an object counts as unset. Set them with `gbrain config set`; a bad value makes the lanelog `skill_resolver_config_invalid` and deliver nothing.- **Payload:** at most `skills.resolver.lane_payload_chars` characters of hookoutput (default 4000, 500 to 10,000); a larger block is dropped whole andcounted as `payload_dropped`.- **One owner:** when several settings files wire the lane, only the firstentry 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.+- **Catalogs:** a turn searches the user catalog, Claude Code's+ `claude-code-plugins` (setup builds it from enabled plugins) and the project+ catalog, each only once it is built. With none built the turn prints nothing+ and logs `no_catalog`.+- **Project skills:** Claude Code's `.claude/skills` in the project gets its+ own catalog, `claude-code-project-<hash of the root>`. Codex's gets+ `codex-project-<hash of the dirs>`, over every `.agents/skills` from the+ project root (the nearest folder above the working directory that holds a+ `.git`, else the working directory) down to the working directory, root+ first, the way Codex 0.165 loads them; your own `~/.agents/skills` stays in+ `codex-user`. Each is 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` (Claude Code, and Codex0.165 and later) resets the session, so skills can be offered again. A Codexinstall from before gets the SessionStart group on its next setup run.+ Hermes has no compaction event yet.Each turn appends one line (outcome, error code, duration, catalogs; neverturn text) to `skill-index/logs/lane-<UTC date>.jsonl`, one file per day,kept 14 days and capped at 2 MB a day. `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.+the recent error codes; it says nothing while the resolver is off. A hook from+before the compaction reset (UserPromptSubmit without SessionStart) shows as+`outdated` and warns with its fix, `gbrain setup codex --skill-loading+resolve` (or `claude-code`).Compiled binaries carry the lane's worker as a second entrypoint(`bun build --compile src/cli.ts src/core/skills/resolver/hook-worker.ts`); abinary built without it delivers nothing and logs `skill_resolver_internal`.+The release and `bun run build` also pass `--define GBRAIN_BUILD_COMMIT=<sha>`,+so a compiled binary's build receipts record `gbrain_commit`.## The contract (schema_version 1)@@ -160,6 +186,13 @@ the turn (`$name`, `@name`, a leading `/name`, "the name skill", or its fullid) ranks first. When the message matches no catalog word (a follow-up suchas "do it again"), `previous_user_message` (`--previous`) is ranked instead.+An empty block carries `block_reason`: `ack`, `no_match`, `filtered` (every+match was excluded or below `min_match_strength`), `deduped` (every match was+already suggested in the session), `paced` (past half the budget and the top+match is not on a name, trigger or routing row), `budget_exhausted`, `shadow`+(the live output of a `--shadow` turn) or `error`. It is null when the block+has a suggestion.+### Exit codes and fail-open| Result | Exit | stdout |@@ -185,7 +218,8 @@ With `--session <id>` the resolver remembers which skills it suggested:in `config.json` (default 2,000 tokens; 0 silences the resolver, otherwise100-50,000). k drops to 3 once half is spent and to 1 at 80%; after half,only a turn whose top result matched on name, triggers or routing spends- any. When it is spent, `budget_exhausted` is true and the block is empty,+ any. When it is spent, `budget_exhausted` is true on every turn (an+ acknowledgement included) and the block is empty,except for a skill the turn names, which still gets its line (and itstokens still count);- state is committed only after the block was delivered: the CLI commitsdiff --git a/docs/schemas/skill-resolver.v1.turn-output.json b/docs/schemas/skill-resolver.v1.turn-output.jsonindex a0b243b302..7f61adb783 100644--- a/docs/schemas/skill-resolver.v1.turn-output.json+++ b/docs/schemas/skill-resolver.v1.turn-output.json@@ -187,6 +187,10 @@"budget_exhausted": {"type": "boolean"},+ "block_reason": {+ "description": "Why the block is empty; null when it has a suggestion.",+ "enum": ["ack", "no_match", "filtered", "deduped", "paced", "budget_exhausted", "shadow", "error", null]+ },"suggestions": {"type": "array","maxItems": 8,diff --git a/package.json b/package.jsonindex 3088554ea2..30bf64293c 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 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": "bun build --compile --no-compile-autoload-bunfig --define GBRAIN_BUILD_COMMIT=\\\"$(git rev-parse HEAD)\\\" --outfile bin/gbrain src/cli.ts src/core/skills/resolver/hook-worker.ts",+ "build:all": "bun build --compile --no-compile-autoload-bunfig --define GBRAIN_BUILD_COMMIT=\\\"$(git rev-parse HEAD)\\\" --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 --define GBRAIN_BUILD_COMMIT=\\\"$(git rev-parse HEAD)\\\" --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/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 0eedc23ab2..03cec28150 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -385,6 +385,7 @@ test/shared-skills-setup.test.ts packaged default skills 2 readFileSynctest/shared-skills-setup.test.ts shared-skills migration recovery (#5569, #5476, A-NEW-4) 4 readFileSynctest/shared-skills-setup.test.ts staged skill migration 7 readFileSynctest/shared-skills-writer-boundary.test.ts (file-level) 7 readFileSync+test/skill-resolver-hook-lane.test.ts skill-resolver lane: codex project catalog 2 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: compiled binaries 1 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: delivery per harness 4 readFileSynctest/skill-resolver-hook-lane.test.ts skill-resolver lane: fail open 6 readFileSyncdiff --git a/src/cli.ts b/src/cli.tsindex 228fda56b7..d431130361 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -53,7 +53,8 @@ async function runSkillResolverLaneFastPath(): Promise<void> {if (process.env.GBRAIN_HOOKS === '0') return;(await import('./core/session-cwd.ts')).captureHookSessionCwd();const h = rest.indexOf('--harness');- await (await import('./core/skills/resolver/hook-lane.ts')).runSkillResolverLane(event, h >= 0 && rest[h + 1] === 'codex' ? 'codex' : 'claude-code');+ const harness = h >= 0 ? rest[h + 1] : undefined;+ await (await import('./core/skills/resolver/hook-lane.ts')).runSkillResolverLane(event, harness === 'codex' || harness === 'hermes' ? harness : 'claude-code');}async function runFastPath(path: 'help' | 'version' | 'skill-resolver-lane'): Promise<void> {diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.tsindex 77f9d49373..f966ee3b0a 100644--- a/src/commands/doctor/checks/skill-resolver.ts+++ b/src/commands/doctor/checks/skill-resolver.ts@@ -2,7 +2,8 @@* `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+ * hook (wired, untrusted in Codex, outdated when it predates the SessionStart+ * compaction reset, 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.@@ -17,18 +18,18 @@ 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, readRecentDailyLog } from '../../../core/skills/resolver/daily-log.ts';-import { projectCatalogPrefix, userCatalogName, type LaneHarness } from '../../../core/skills/resolver/hook-lane.ts';+import { CLAUDE_PLUGINS_CATALOG, projectCatalogPrefix, userCatalogName } 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';+import { inspectSkillResolverHook, type ResolverHarness, type ResolverHookState } from '../../../core/setup/skill-resolver-hook.ts';const name = 'skill_resolver';-const HARNESSES: LaneHarness[] = ['claude-code', 'codex'];+const HARNESSES: ResolverHarness[] = ['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 SkillResolverHarnessView { harness: ResolverHarness; on: boolean; hook: ResolverHookState; catalogs: SkillResolverCatalogView[] }export interface SkillResolverView {config: 'ok' | 'absent' | 'unreadable';harnesses: SkillResolverHarnessView[];@@ -53,6 +54,9 @@ function recentLane(home: string): SkillResolverView['recent'] | null {return { turns, outcomes, errors };}+/** A catalog a turn can rank with no project: the user catalog, and for Claude Code the plugins catalog. */+const isTurnCatalog = (harness: ResolverHarness, n: string) => n === userCatalogName(harness) || (harness === 'claude-code' && n === CLAUDE_PLUGINS_CATALOG);+/** 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);@@ -62,7 +66,7 @@ export async function skillResolverView(home = configDir()): Promise<SkillResolvconst harnesses: SkillResolverHarnessView[] = [];for (const harness of HARNESSES) {const hook = inspectSkillResolverHook(harness).state;- const mine = catalogs.filter((n) => n === userCatalogName(harness) || n.startsWith(projectCatalogPrefix(harness)));+ const mine = catalogs.filter((n) => isTurnCatalog(harness, n) || n.startsWith(projectCatalogPrefix(harness)));if (!on.includes(harness) && hook === 'absent' && mine.length === 0) continue;const views: SkillResolverCatalogView[] = [];for (const name of mine) {@@ -81,7 +85,7 @@ const setupArgv = (harness: string) => ['gbrain', 'setup', harness, '--skill-loaexport 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 user = h.catalogs.find((c) => c.name === userCatalogName(h.harness)) ?? h.catalogs.find((c) => isTurnCatalog(h.harness, c.name));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}`;});@@ -98,10 +102,11 @@ export function skillResolverCheck(v: SkillResolverView | null): Check | null {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))));+ const broken = v.harnesses.find((h) => h.on && (h.hook !== 'wired' || !h.catalogs.some((c) => isTurnCatalog(h.harness, c.name))));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, status: 'warn', message: `${describeSkillResolver(v)} ${broken.harness}: the resolver is on but ${what}, so no skills block is added.`, details,+ const what = broken.hook === 'outdated' ? `its hook has no SessionStart entry (installed before the compaction reset), so skills offered before a compaction are not offered again; ${setupArgv(broken.harness).join(' ')} adds it`+ : `${broken.hook === 'untrusted' ? 'its Codex hook is not trusted' : broken.hook === 'absent' ? 'its hook entry is missing' : 'its user catalog is missing'}, so no skills block is added`;+ return { name, status: 'warn', message: `${describeSkillResolver(v)} ${broken.harness}: the resolver is on but ${what}.`, 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.` } };}diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex faba95996d..b6b602305c 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -305,7 +305,10 @@ 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;- if (process.env.GBRAIN_HOOK_LANE === 'skill-resolver') return (await import('../core/skills/resolver/hook-lane.ts')).runSkillResolverLane(event, io.harness === 'codex' ? 'codex' : 'claude-code', io.cwd ? { cwd: io.cwd } : {});+ if (process.env.GBRAIN_HOOK_LANE === 'skill-resolver') {+ const laneHarness = harnessIdx >= 0 && args[harnessIdx + 1] === 'hermes' ? 'hermes' : io.harness === 'codex' ? 'codex' : 'claude-code';+ return (await import('../core/skills/resolver/hook-lane.ts')).runSkillResolverLane(event, laneHarness, 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/core/setup/skill-resolver-config.ts b/src/core/setup/skill-resolver-config.tsindex 25a83af3aa..19391b7569 100644--- a/src/core/setup/skill-resolver-config.ts+++ b/src/core/setup/skill-resolver-config.ts@@ -23,6 +23,7 @@ import { setCliExitVerdict } from '../cli-force-exit.ts';import { laneTurnSettings, validateMinMatch, validatePinned, validateSessionTokenBudget, validateTopK } from '../skills/resolver/config.ts';const CONFIG_CAP_BYTES = 1024 * 1024;+const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);/** A JSON object file, or null when it is missing, unreadable or not an object. */export function readJsonObjectSafe(path: string): Record<string, unknown> | null {@@ -111,8 +112,10 @@ function parseLeafValue(leaf: string, value: string): { ok: true; value: boolean/*** `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.+ * the file plane is the only plane these keys have. A per_harness entry that+ * is not an object (a hand-edited null, list or scalar) reads as unset, and+ * set or unset replaces it with {}. Returns false for a key or action this+ * does not own.*/export function runSkillResolverConfigKey(args: string[], home: string): boolean {const [action, key, ...rest] = args;@@ -127,7 +130,9 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanconst doc = read.state === 'ok' ? structuredClone(read.doc) : {};const section = resolverSection(doc);const perHarness = (section.per_harness && typeof section.per_harness === 'object' && !Array.isArray(section.per_harness) ? section.per_harness : {}) as Record<string, Record<string, unknown>>;- const holder: Record<string, unknown> = nested ? (Object.hasOwn(perHarness, nested[1]!) ? perHarness[nested[1]!]! : (perHarness[nested[1]!] = {})) : section;+ const stored: unknown = nested && Object.hasOwn(perHarness, nested[1]!) ? perHarness[nested[1]!] : undefined;+ const replaced = !!nested && stored !== undefined && !isPlainObject(stored);+ const holder: Record<string, unknown> = !nested ? section : isPlainObject(stored) ? stored : (perHarness[nested[1]!] = {});const field = nested ? nested[2]! : leaf;if (action === 'get') {if (holder[field] === undefined) return fail(`Config key not found: ${key}`);@@ -135,7 +140,7 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanreturn true;}if (action === 'unset') {- if (!(field in holder)) return fail(`Config key not found: ${key}`);+ if (!(field in holder) && !replaced) return fail(`Config key not found: ${key}`);delete holder[field];} else {const value = rest.find((a) => !a.startsWith('-'));@@ -145,7 +150,7 @@ export function runSkillResolverConfigKey(args: string[], home: string): booleanholder[field] = parsed.value;}if (nested) {- for (const [h, o] of Object.entries(perHarness)) if (Object.keys(o).length === 0) delete perHarness[h];+ for (const [h, o] of Object.entries(perHarness)) if (isPlainObject(o) && Object.keys(o).length === 0) delete perHarness[h];if (Object.keys(perHarness).length) section.per_harness = perHarness; else delete section.per_harness;try { laneTurnSettings(section, nested[1]!); } catch (e) { return fail(`${(e as Error).message} Nothing was written.`); }}diff --git a/src/core/setup/skill-resolver-hook.ts b/src/core/setup/skill-resolver-hook.tsindex 9a499f4d71..56bfb85489 100644--- a/src/core/setup/skill-resolver-hook.ts+++ b/src/core/setup/skill-resolver-hook.ts@@ -71,18 +71,26 @@ export function skillResolverCommands(harness: ResolverHarness, bin: string, homreturn 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[] } {+/**+ * Whether this lane's hook is present: absent, wired (and, on Codex,+ * trusted), untrusted, or outdated (the UserPromptSubmit hook without the+ * SessionStart compaction reset, an install from before it; setup adds it).+ */+export type ResolverHookState = 'absent' | 'wired' | 'untrusted' | 'outdated';+export function inspectSkillResolverHook(harness: ResolverHarness, paths: ResolverHookPaths = {}): { state: ResolverHookState; path: string; commands: string[] } {try {if (harness === 'codex') {const p = codexPaths(paths);const ours = codexOurs(p);+ const commands = ours.flatMap((g) => g.commands);if (!ours.some((g) => g.event === 'UserPromptSubmit')) return { state: 'absent', path: p.hooks, commands: [] };- return { state: ours.every((g) => codexTrusted(p, g)) ? 'wired' : 'untrusted', path: p.hooks, commands: ours.flatMap((g) => g.commands) };+ if (!ours.some((g) => g.event === 'SessionStart')) return { state: 'outdated', path: p.hooks, commands };+ return { state: ours.every((g) => codexTrusted(p, g)) ? 'wired' : 'untrusted', path: p.hooks, 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)) };+ const has = (event: string) => ours.some((o) => o.event === event);+ return { state: !has('UserPromptSubmit') ? 'absent' : has('SessionStart') ? 'wired' : 'outdated', path, commands: ours.map((o) => String(o.entry.command)) };} catch {return { state: 'absent', path: harness === 'codex' ? codexPaths(paths).hooks : claudePath(paths), commands: [] };}diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.tsindex d04668d4f0..a63e13bd81 100644--- a/src/core/setup/skill-resolver-setup.ts+++ b/src/core/setup/skill-resolver-setup.ts@@ -26,7 +26,7 @@ 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 { CLAUDE_PLUGINS_CATALOG, logsDir, sessionsDir, skillIndexRoot } from '../skills/resolver/paths.ts';import { resolveSkills } from '../skills/resolver/resolve.ts';import { claudePluginRoots, readDirSources } from '../skills/resolver/sources.ts';import { readResolverConfig, resolverHarnesses, setResolverHarness } from './skill-resolver-config.ts';@@ -44,7 +44,6 @@ export interface ResolverSetupResult {}export const userCatalog = (harness: ResolverHarness) => `${harness}-user`;-export const CLAUDE_PLUGINS_CATALOG = 'claude-code-plugins';const isHarnessCatalog = (harness: ResolverHarness, name: string) => name === userCatalog(harness) || name === `${harness}-plugins` || name.startsWith(`${harness}-project-`);/** The Claude Code config directory whose plugins the plugin catalog indexes. */diff --git a/src/core/skills/resolver/build.ts b/src/core/skills/resolver/build.tsindex 54cddfa9b7..d971bd9906 100644--- a/src/core/skills/resolver/build.ts+++ b/src/core/skills/resolver/build.ts@@ -69,7 +69,11 @@ export interface BuildReceipt {build: { args: string[]; rebuild_argv: string[] | null; ms: number; built_at: string; generation: number };}+/** Set by `bun build --define` in the release and `bun run build` compiles, where no .git sits beside the source. */+declare const GBRAIN_BUILD_COMMIT: string | undefined;+function gbrainCommit(): string | null {+ if (typeof GBRAIN_BUILD_COMMIT === 'string' && /^[0-9a-f]{40}$/.test(GBRAIN_BUILD_COMMIT)) return GBRAIN_BUILD_COMMIT;try {let d = dirname(new URL(import.meta.url).pathname);for (let i = 0; i < 6; i++, d = dirname(d)) {diff --git a/src/core/skills/resolver/catalog-files.ts b/src/core/skills/resolver/catalog-files.tsindex eda2e0c775..63aab59c24 100644--- a/src/core/skills/resolver/catalog-files.ts+++ b/src/core/skills/resolver/catalog-files.ts@@ -5,7 +5,8 @@* frontmatter, no YAML), so the hook lane's worker loads only what a turn* needs; build.ts and sources.ts take these from here.*/-import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { existsSync, readdirSync, readFileSync, statSync, type Dirent } from 'node:fs';import { join } from 'node:path';import { readBounded } from './fsutil.ts';import { catalogFile, skillIndexRoot, validCatalogName } from './paths.ts';@@ -29,10 +30,24 @@ export function listCatalogs(home: string): string[] {} catch { return []; }}-/** Recheck a directory fingerprint by stat only (the turn-path freshness tier). */+/** Entries a skills scan never reads: dot-entries (harness-owned state such as Codex's .system/ or Hermes's .usage.json, and .git) and node_modules. */+export const skippedEntry = (name: string) => name.startsWith('.') || name === 'node_modules';++/** A hash of the directory entries that can change a catalog: subdirectories, symlinks and SKILL.md, never a skipped entry. */+export function listingKey(entries: readonly Dirent[]): string {+ const names = entries.filter(e => !skippedEntry(e.name) && (e.isDirectory() || e.isSymbolicLink() || e.name === 'SKILL.md')).map(e => e.name).sort();+ return createHash('sha256').update(names.join('\0')).digest('hex').slice(0, 16);+}++/**+ * Recheck a directory fingerprint by stat only (the turn-path freshness+ * tier). A directory whose mtime moved is re-listed, and counts as changed+ * only when its listing key did (a fingerprint from before the key existed+ * counts any mtime move).+ */export function fingerprintChanged(fp: DirFingerprint, routing?: [string, number, number]): boolean {try {- for (const [d, m] of fp.dirs) if (statSync(d).mtimeMs !== m) return true;+ for (const [d, m, key] of fp.dirs) if (statSync(d).mtimeMs !== m && (key === undefined || listingKey(readdirSync(d, { withFileTypes: true })) !== key)) return true;for (const [f, size, m] of fp.files) { const st = statSync(f); if (st.size !== size || st.mtimeMs !== m) return true; }if (routing) { const st = statSync(routing[0]); if (st.size !== routing[1] || st.mtimeMs !== routing[2]) return true; }return false;diff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.tsindex 263f740e13..1defacb2f4 100644--- a/src/core/skills/resolver/config.ts+++ b/src/core/skills/resolver/config.ts@@ -18,7 +18,8 @@* skills.resolver.min_match the weakest match_strength to suggest* (default: every match)* skills.resolver.per_harness.<harness>.{top_k,min_match} overrides- * for one harness; a key it leaves out falls back to the global one+ * for one harness; a key it leaves out falls back to the global one, and+ * an entry that is not an object (a hand-edited null) counts as unset* skills.resolver.pinned skill ids the harness always loads itself,* never suggested (at most 1,024)*/@@ -99,7 +100,8 @@ export function laneTurnSettings(section: Record<string, unknown>, harness: strifor (const [h, o] of Object.entries(per as Record<string, unknown>)) {const key = `${p}per_harness.${h}`;if (!(HARNESSES as readonly string[]).includes(h)) throw configInvalid(key, `names no harness (one of ${HARNESSES.join(', ')})`);- if (!o || typeof o !== 'object' || Array.isArray(o) || Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match')) throw configInvalid(key, 'may hold only top_k and min_match');+ if (!o || typeof o !== 'object' || Array.isArray(o)) continue;+ if (Object.keys(o).some(k => k !== 'top_k' && k !== 'min_match')) throw configInvalid(key, 'may hold only top_k and min_match');const r = o as Record<string, unknown>;const parsed: LaneTurnSettings = {...(r.top_k !== undefined ? { top_k: validateTopK(r.top_k, `${key}.top_k`) } : {}),diff --git a/src/core/skills/resolver/hook-input.ts b/src/core/skills/resolver/hook-input.tsnew file mode 100644index 0000000000..d72381340a--- /dev/null+++ b/src/core/skills/resolver/hook-input.ts@@ -0,0 +1,218 @@+/**+ * A bounded streaming reader for hook JSON whose size the harness decides+ * (Hermes's pre_llm_call sends the whole extra.conversation_history every+ * turn): it walks the stream's bytes as they arrive, keeps only the string+ * values at the named dotted paths (each capped at `cap` characters) and+ * discards everything else without buffering it, so a payload of any size+ * yields its fields and is never refused. The objects on the way to a path+ * are parsed strictly; any other array, object or string is skipped by a+ * byte scan for brackets and native indexOf jumps between quotes and+ * backslashes (nesting and string ends checked, scalars not), and only kept+ * strings are decoded, so a 5 MB history costs about as much as JSON.parse+ * of it. Leaf module: no I/O of its own.+ */++/** The turn input's message cap (resolve.ts MESSAGE_CAP_BYTES); resolve.ts is not loaded on the lane's main thread. */+export const HOOK_FIELD_CAP = 8192;+const KEY_CAP_BYTES = 256;++type Mode = 'value' | 'key' | 'key-or-end' | 'colon' | 'after' | 'done';+type Num = 'sign' | 'zero' | 'int' | 'dot' | 'frac' | 'e' | 'esign' | 'exp';+/** A string being read: kept ones gather their raw JSON bytes (escapes included) up to `room`. */+interface Str { key: boolean; path: string | null; keep: boolean; raw: Buffer[]; room: number; over: boolean; esc: boolean }+/** A discarded array or object being skipped: its open brackets and string state. */+interface Skip { open: number[]; inStr: boolean; esc: boolean }++const QUOTE = 0x22, BACKSLASH = 0x5c, OPEN_OBJECT = 0x7b, CLOSE_OBJECT = 0x7d, OPEN_ARRAY = 0x5b, CLOSE_ARRAY = 0x5d;++/**+ * Skip a discarded array or object through `t` from `i`, in locals so the+ * byte loops stay tight: the index just past its closing bracket, -1 when+ * the chunk ran out first (state kept in `s`), -2 when malformed.+ */+function skipScan(t: Uint8Array, i: number, s: Skip): number {+ const open = s.open, n = t.length;+ let inStr = s.inStr, esc = s.esc, nb = -1;+ while (i < n) {+ if (esc) { esc = false; i++; continue; }+ if (inStr) {+ if (nb < i) { nb = t.indexOf(BACKSLASH, i); if (nb < 0) nb = n; }+ const q = t.indexOf(QUOTE, i);+ i = Math.min(q < 0 ? n : q, nb);+ if (i === n) break;+ if (t[i++] === BACKSLASH) esc = true; else inStr = false;+ continue;+ }+ let c = 0;+ for (; i < n; i++) { c = t[i]!; if (c === QUOTE || c === OPEN_OBJECT || c === CLOSE_OBJECT || c === OPEN_ARRAY || c === CLOSE_ARRAY) break; }+ if (i === n) break;+ i++;+ if (c === QUOTE) inStr = true;+ else if (c === OPEN_OBJECT || c === OPEN_ARRAY) open.push(c);+ else if (open.pop() !== (c === CLOSE_OBJECT ? OPEN_OBJECT : OPEN_ARRAY)) return -2;+ else if (open.length === 0) return i;+ }+ s.inStr = inStr;+ s.esc = esc;+ return -1;+}++/** The first quote or backslash in `t` from `i`, else t.length. */+function stringStop(t: Uint8Array, i: number): number {+ for (; i < t.length; i++) { const c = t[i]!; if (c === QUOTE || c === BACKSLASH) return i; }+ return i;+}++const NUMBER_END = new Set<Num>(['zero', 'int', 'frac', 'exp']);+const isSpace = (c: number) => c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09;+const isDigit = (c: number) => c >= 0x30 && c <= 0x39;++/** The next number state after byte `c`: a state, undefined where the number may end before `c`, null where it is malformed. */+function numberStep(n: Num, c: number): Num | null | undefined {+ const digit = isDigit(c);+ const exp = c === 0x65 || c === 0x45;+ switch (n) {+ case 'sign': return c === 0x30 ? 'zero' : digit ? 'int' : null;+ case 'zero': return c === 0x2e ? 'dot' : exp ? 'e' : undefined;+ case 'int': return digit ? 'int' : c === 0x2e ? 'dot' : exp ? 'e' : undefined;+ case 'dot': return digit ? 'frac' : null;+ case 'frac': return digit ? 'frac' : exp ? 'e' : undefined;+ case 'e': return digit ? 'exp' : c === 0x2b || c === 0x2d ? 'esign' : null;+ case 'esign': return digit ? 'exp' : null;+ case 'exp': return digit ? 'exp' : undefined;+ }+}++/** A kept string's value: its raw JSON decoded and unescaped (a cut-off trailing escape dropped first); undefined when it is not valid JSON. */+function decodeKept(s: Str): string | undefined {+ let raw = Buffer.concat(s.raw).toString('utf8');+ if (s.over) {+ const m = /(\\+)(u[0-9a-fA-F]{0,3})?$/.exec(raw);+ if (m && m[1]!.length % 2 === 1) raw = raw.slice(0, m.index + m[1]!.length - 1);+ }+ try { return JSON.parse(`"${raw}"`) as string; } catch { return undefined; }+}++/**+ * The string values at `paths` (dotted object keys from the root, e.g.+ * 'extra.user_message') of the JSON object on `stream`, keyed by path; a+ * path holding no string is left out and a repeated key keeps its last+ * value, as JSON.parse does. Null for a TTY, malformed JSON or a document+ * that is not an object. The stream is always read to its end.+ */+export async function readJsonFields(stream: AsyncIterable<Uint8Array | string> & { isTTY?: boolean }, paths: readonly string[], cap: number): Promise<Record<string, string> | null> {+ if (stream.isTTY) return null;+ const wanted = new Set(paths);+ const prefixes = new Set(paths.flatMap(p => p.split('.').slice(0, -1).map((_, i, a) => a.slice(0, i + 1).join('.'))));+ const out: Record<string, string> = {};+ const stack: string[] = [];+ let mode = 'value' as Mode;+ let keyPath: string | null = null;+ let str: Str | null = null;+ let skip: Skip | null = null;+ let literal = '';+ let num: Num | null = null;++ const endValue = () => { mode = stack.length ? 'after' : 'done'; };+ const endString = (s: Str): boolean => {+ str = null;+ const value = s.keep ? decodeKept(s) : '';+ if (value === undefined) return false;+ if (s.key) {+ const parent = stack.at(-1)!;+ const p = parent ? `${parent}.${value}` : value;+ keyPath = s.keep && !s.over && (wanted.has(p) || prefixes.has(p)) ? p : null;+ mode = 'colon';+ return true;+ }+ if (s.keep) out[s.path!] = value.slice(0, cap);+ endValue();+ return true;+ };++ const feed = (t: Uint8Array): boolean => {+ const gather = (s: Str, from: number, to: number) => {+ if (!s.keep || to <= from) return;+ const n = Math.min(to - from, s.room);+ if (n > 0) { s.raw.push(Buffer.from(t.subarray(from, from + n))); s.room -= n; }+ if (n < to - from) s.over = true;+ };+ let i = 0;+ while (i < t.length) {+ if (skip) {+ const end = skipScan(t, i, skip);+ if (end === -1) return true;+ if (end === -2) return false;+ skip = null;+ i = end;+ endValue();+ continue;+ }+ if (str) {+ if (str.esc) { str.esc = false; gather(str, i, i + 1); i++; continue; }+ const stop = stringStop(t, i);+ gather(str, i, stop);+ if (stop >= t.length) return true;+ i = stop + 1;+ if (t[stop] === BACKSLASH) { gather(str, stop, i); str.esc = true; continue; }+ if (!endString(str)) return false;+ continue;+ }+ const c = t[i]!;+ if (literal) {+ if (c !== literal.charCodeAt(0)) return false;+ literal = literal.slice(1);+ i++;+ if (!literal) endValue();+ continue;+ }+ if (num !== null) {+ const step = numberStep(num, c);+ if (step === null) return false;+ if (step !== undefined) { num = step; i++; continue; }+ if (!NUMBER_END.has(num)) return false;+ num = null;+ endValue();+ continue;+ }+ i++;+ if (isSpace(c)) continue;+ if (mode === 'done') return false;+ if (mode === 'colon') { if (c !== 0x3a) return false; mode = 'value'; continue; }+ if (mode === 'after') {+ if (c === 0x2c) { mode = 'key'; continue; }+ if (c !== CLOSE_OBJECT) return false;+ stack.pop();+ endValue();+ continue;+ }+ if (mode === 'key' || mode === 'key-or-end') {+ if (c === CLOSE_OBJECT && mode === 'key-or-end') { stack.pop(); endValue(); continue; }+ if (c !== QUOTE) return false;+ str = { key: true, path: null, keep: true, raw: [], room: KEY_CAP_BYTES, over: false, esc: false };+ continue;+ }+ const root = stack.length === 0;+ if (root && c !== OPEN_OBJECT) return false;+ const path = root ? '' : keyPath;+ if (c === OPEN_OBJECT && path !== null) { stack.push(path); mode = 'key-or-end'; }+ else if (c === OPEN_OBJECT || c === OPEN_ARRAY) skip = { open: [c], inStr: false, esc: false };+ else if (c === QUOTE) { const keep = path !== null && wanted.has(path); str = { key: false, path, keep, raw: [], room: keep ? cap * 6 + 12 : 0, over: false, esc: false }; }+ else if (c === 0x74) literal = 'rue';+ else if (c === 0x66) literal = 'alse';+ else if (c === 0x6e) literal = 'ull';+ else if (c === 0x2d) num = 'sign';+ else if (isDigit(c)) num = c === 0x30 ? 'zero' : 'int';+ else return false;+ }+ return true;+ };++ let bad = false;+ try {+ for await (const chunk of stream) {+ if (!bad) bad = !feed(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);+ }+ } catch { return null; }+ return bad || mode !== 'done' || str || skip || literal || num !== null ? null : out;+}diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsindex 1181aead65..9e9c99f764 100644--- a/src/core/skills/resolver/hook-lane.ts+++ b/src/core/skills/resolver/hook-lane.ts@@ -3,9 +3,19 @@* hook entry in Claude Code and its own hooks.json groups in Codex, each* UserPromptSubmit plus SessionStart for the compaction reset,* written by `gbrain setup <claude-code|codex> --skill-loading resolve`- * (src/core/setup/skill-resolver-hook.ts). It never shares output with the+ * (src/core/setup/skill-resolver-hook.ts), and Hermes's pre_llm_call shell+ * hook (`hook user-prompt --harness hermes`). It never shares output with the* turn-rule, setup or plugin lanes: it prints only the <relevant_skills> block.*+ * Wire shapes (LANE_IO): Claude Code and Codex send the prompt, session_id+ * and cwd at the top level (read whole, up to LANE_STDIN_CAP_BYTES) and take+ * hookSpecificOutput.additionalContext; Hermes sends extra.user_message,+ * session_id and maybe cwd beside the whole extra.conversation_history, read+ * by the bounded streaming reader (hook-input.ts) over Bun's native stdin+ * stream (about 4x faster than process.stdin on a multi-MB payload) so no+ * history size is refused, and takes {"context": block}. Hermes has no+ * compaction event.+ ** 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.@@ -27,22 +37,30 @@* Codex: CODEX_HOME/hooks.json) and runs only when the first skill-resolver* 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.)+ * are deduplicated by the harness itself.) Hermes has no carrier read yet,+ * so its lane always runs under its own GBRAIN_HOME.*- * 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.+ * Catalogs, each searched only once its receipt exists (none: outcome+ * no_catalog, no output): <harness>-user (built by setup), for Claude Code+ * claude-code-plugins (built by setup from enabled plugins), then a project+ * catalog built out of the turn by a detached `gbrain skills index build` on+ * first sight and merged at rank time (names only: scope project). Claude+ * Code's covers the project's .claude/skills, keyed by a hash of the real+ * project root; Codex's covers every existing .agents/skills from the project+ * root (the nearest ancestor of cwd holding a .git entry, else cwd) down to+ * cwd, root first, as Codex 0.165 loads them (codex-rs host_roots.rs), keyed+ * by a hash of that real dir list and leaving out the user's own+ * ~/.agents/skills. 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.** Turn settings: skills.resolver.top_k, min_match, pinned (sent as exclude)* and per_harness.<harness>.{top_k,min_match} (config.ts laneTurnSettings);* unset, a turn is top_k 5 with every match and nothing excluded.** Payload: the lane's own budget (skills.resolver.lane_payload_chars, default- * 4000 characters of hook JSON); a block that does not fit is dropped whole- * and counted (outcome payload_dropped in the lane log).+ * 4000 characters of hook JSON, Hermes's included); 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-<UTC day>.jsonl (daily-log.ts, kept* 14 days), one line per turn that got past the on/off check (outcome, error@@ -53,7 +71,7 @@ import { createHash } from 'node:crypto';import { unlinkSync } from 'node:fs';import { mkdir, readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';import { homedir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import type { Worker } from 'node:worker_threads';import { spawn } from '../../spawn.ts';import { claudeManagedSettingsPaths, claudeUserSettingsPath, codexHooksPath } from '../../bootstrap/host-specs.ts';@@ -61,7 +79,8 @@ import { shellWords } from '../../setup/hook-launcher.ts';import { isSkillResolverCommand, isSkillResolverEntry } from '../../setup/skill-resolver-lane.ts';import { laneTurnSettings, type LaneTurnSettings } from './config.ts';import { appendDailyLog, LANE_LOG } from './daily-log.ts';-import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';+import { HOOK_FIELD_CAP, readJsonFields } from './hook-input.ts';+import { assertCatalogName, catalogFile, CLAUDE_PLUGINS_CATALOG, logsDir, resolverHome } from './paths.ts';import { type CommitHold, commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';import type { TurnOutput } from './resolve.ts';import type { LaneWorkerTurn } from './hook-worker.ts';@@ -80,7 +99,8 @@ 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;-export type LaneHarness = 'claude-code' | 'codex';+export type LaneHarness = 'claude-code' | 'codex' | 'hermes';+export { CLAUDE_PLUGINS_CATALOG };export const userCatalogName = (harness: LaneHarness) => `${harness}-user`;export const projectCatalogPrefix = (harness: LaneHarness) => `${harness}-project-`;@@ -102,6 +122,7 @@ async function readJsonFile(path: string, cap = CONFIG_CAP_BYTES): Promise<unkno* 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> {+ if (harness === 'hermes') return 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()];@@ -174,6 +195,37 @@ async function readStdinBounded(stream: NodeJS.ReadableStream & { isTTY?: booleareturn Buffer.concat(chunks).toString('utf8');}+type LaneStdin = NodeJS.ReadableStream & { isTTY?: boolean };+/** One hook event's fields as the harness sent them, not yet checked. */+interface HookEvent { prompt: string; sessionId?: unknown; cwd?: unknown; source?: unknown }+/** `stdin` is the injected stream, else undefined for the process's own. */+interface HarnessIo { read: (stdin: LaneStdin | undefined) => Promise<HookEvent | null>; render: (block: string) => string }++const HOOK_SPECIFIC_IO: HarnessIo = {+ read: async (stdin) => {+ let j: unknown;+ try { j = JSON.parse(await readStdinBounded(stdin ?? process.stdin, LANE_STDIN_CAP_BYTES) ?? ''); } catch { return null; }+ if (!j || typeof j !== 'object') return null;+ const o = j as Record<string, unknown>;+ return { prompt: typeof o.prompt === 'string' ? o.prompt : '', sessionId: o.session_id, cwd: o.cwd, source: o.source };+ },+ render: (block) => JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: block } }),+};++/** Each lane harness's stdin and stdout shapes. */+const LANE_IO: Record<LaneHarness, HarnessIo> = {+ 'claude-code': HOOK_SPECIFIC_IO,+ codex: HOOK_SPECIFIC_IO,+ hermes: {+ read: async (stdin) => {+ const source = stdin ?? (process.stdin.isTTY ? process.stdin : Bun.stdin.stream());+ const f = await readJsonFields(source, ['session_id', 'cwd', 'extra.user_message'], HOOK_FIELD_CAP);+ return f && { prompt: f['extra.user_message'] ?? '', sessionId: f.session_id, cwd: f.cwd };+ },+ render: (block) => JSON.stringify({ context: block }),+ },+};+function selfArgv(args: string[]): string[] {const exec = process.execPath;return /[/\\]gbrain(\.exe)?$/.test(exec) ? [exec, ...args] : [exec, process.argv[1]!, ...args];@@ -216,7 +268,7 @@ interface Turn { outcome: string; code?: string; catalogs?: string[]; dropped_ch/** 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 (event !== 'user-prompt' && (event !== 'session-start' || harness === 'hermes')) return 0;const env = io.env ?? process.env;let home: string;try { home = resolverHome(env); } catch { return 0; }@@ -258,30 +310,31 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarlet turnSettings: LaneTurnSettings;try { turnSettings = laneTurnSettings(settings.section, harness); } catch { return { outcome: 'error', code: 'skill_resolver_config_invalid' }; }- const raw = await readStdinBounded(io.stdin ?? process.stdin, LANE_STDIN_CAP_BYTES);- let j: Record<string, unknown>;- 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 hookEvent = await LANE_IO[harness].read(io.stdin);+ if (!hookEvent) return { outcome: 'error', code: 'skill_resolve_no_input' };+ const cwd = io.cwd ?? env.GBRAIN_HOOK_CWD ?? (typeof hookEvent.cwd === 'string' ? hookEvent.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;+ const sessionId = typeof hookEvent.sessionId === 'string' && /^[\x21-\x7e]{1,256}$/.test(hookEvent.sessionId) ? hookEvent.sessionId : undefined;if (event === 'session-start') {- if (j.source !== 'compact' || !sessionId) return { outcome: 'off' };+ if (hookEvent.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 : '';+ const prompt = hookEvent.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 [userBuilt, pluginsBuilt, project] = await Promise.all([+ isBuilt(home, userCatalogName(harness)),+ harness === 'claude-code' && isBuilt(home, CLAUDE_PLUGINS_CATALOG),+ harness === 'hermes' ? null : projectCatalog(harness, harness === 'claude-code' ? env.CLAUDE_PROJECT_DIR || cwd : cwd, home),+ ]);+ const catalogs = [...(userBuilt ? [userCatalogName(harness)] : []), ...(pluginsBuilt ? [CLAUDE_PLUGINS_CATALOG] : [])];+ if (project?.built) catalogs.push(project.name);+ else if (project && settings.autoRebuild) await scheduleBuild(home, project.name, ['skills', 'index', 'build', '--catalog', project.name, ...project.dirs.flatMap(d => ['--dir', d]), '--scope', 'project', '--harness', harness], spawnFn);+ if (catalogs.length === 0) return { outcome: 'no_catalog' };const worker = ctl.worker;if (!worker || laneWorkerFailed()) return { outcome: 'error', code: 'skill_resolver_internal', catalogs };@@ -299,7 +352,7 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarconst 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 } });+ const payload = LANE_IO[harness].render(out.block);if (payload.length > settings.payloadChars) return { outcome: 'payload_dropped', catalogs, dropped_chars: payload.length };await (io.write ?? writeStdout)(`${payload}\n`);}@@ -309,17 +362,40 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarreturn { 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> {+const isBuilt = (home: string, name: string) => stat(catalogFile(home, name, 'receipt.json')).then(() => true, () => false);+const isDir = (path: string) => stat(path).then(s => s.isDirectory(), () => false);++/**+ * Codex's repo skill dirs: each existing <dir>/.agents/skills from the+ * project root (the nearest ancestor of `cwd` holding a .git entry, else+ * `cwd`) down to `cwd`, root first, as real paths, without the user's own+ * ~/.agents/skills (the user catalog has it).+ */+async function codexProjectSkillDirs(cwd: string, home: string): Promise<string[]> {+ const chain = [cwd];+ for (let d = cwd; dirname(d) !== d;) chain.push(d = dirname(d));+ const marked = await Promise.all(chain.map(d => stat(join(d, '.git')).then(() => true, () => false)));+ const root = marked.indexOf(true);+ const below = chain.slice(0, root < 0 ? 1 : root + 1).reverse();+ const [user, ...found] = await Promise.all([realpath(join(home, '.agents', 'skills')).catch(() => null),+ ...below.map(async d => (await isDir(join(d, '.agents', 'skills')) ? realpath(join(d, '.agents', 'skills')) : null))]);+ return [...new Set(found.filter((p): p is string => p !== null && p !== user))];+}++/**+ * The project catalog for `root`: Claude Code's .claude/skills, named by the+ * real root; Codex's .agents/skills dirs, named by their real list. Null when+ * there is none (or it is the user's own dir).+ */+async function projectCatalog(harness: 'claude-code' | 'codex', root: string, home: string): Promise<{ name: string; dirs: 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 };+ const user = await realpath(homedir()).catch(() => homedir());+ const claudeDir = join(real, '.claude', 'skills');+ const dirs = harness === 'codex' ? await codexProjectSkillDirs(real, user) : real !== user && await isDir(claudeDir) ? [claudeDir] : [];+ if (dirs.length === 0) return null;+ const name = `${projectCatalogPrefix(harness)}${createHash('sha256').update(harness === 'codex' ? dirs.join('\0') : real).digest('hex').slice(0, 16)}`;+ return { name, dirs, built: await isBuilt(home, name) };} catch { return null; }}diff --git a/src/core/skills/resolver/index.ts b/src/core/skills/resolver/index.tsindex 90c12e3d9e..84c9953650 100644--- a/src/core/skills/resolver/index.ts+++ b/src/core/skills/resolver/index.ts@@ -28,10 +28,14 @@ import { gcSessionsAsync, resetSession, sessionKey } from './session.ts';* turn input, exclude up to EXCLUDE_MAX ids, the index's catalog_hash on* skill_catalog_mismatch, a named skill's line past a spent budget,* previous_user_message as the fallback ranking text, the pi and cursor- * harnesses, the warm handle (openCatalog), the worker-thread build- * (buildSkillIndexOffThread) and gcSkillSessions.+ * harnesses, OpenClaw's skills list --json as a catalog, --from-json with+ * --dir bodies, Claude Code plugin catalogs, the warm handle (openCatalog),+ * the worker-thread build (buildSkillIndexOffThread), gcSkillSessions, the+ * hook lane for Hermes (`hook user-prompt --harness hermes`, answering+ * {"context"}) and the lane's Codex project catalog (codex-project-<hash>,+ * the .agents/skills dirs from the project root to cwd).*/-export const RESOLVER_FEATURES: readonly string[] = ['min_match_strength', 'exclude_1024', 'mismatch_catalog_hash', 'named_past_budget', 'previous_user_message', 'harness_pi', 'harness_cursor', 'openclaw_skills_list', 'from_json_with_dirs', 'claude_plugins', 'open_catalog', 'build_off_thread', 'gc_sessions'];+export const RESOLVER_FEATURES: readonly string[] = ['min_match_strength', 'exclude_1024', 'mismatch_catalog_hash', 'named_past_budget', 'previous_user_message', 'harness_pi', 'harness_cursor', 'openclaw_skills_list', 'from_json_with_dirs', 'claude_plugins', 'open_catalog', 'build_off_thread', 'gc_sessions', 'harness_hermes_lane', 'codex_project_catalog'];/** One bounded pass (at most 1,000 files, async I/O) deleting session files idle for 7 days; returns how many it deleted. Commits already run one at most every 10 minutes. */export async function gcSkillSessions(opts: { home?: string; now?: number } = {}): Promise<number> {diff --git a/src/core/skills/resolver/paths.ts b/src/core/skills/resolver/paths.tsindex 085b855488..c3f65e05d6 100644--- a/src/core/skills/resolver/paths.ts+++ b/src/core/skills/resolver/paths.ts@@ -21,6 +21,8 @@ import { isAbsolute, join, resolve, sep } from 'node:path';import { ResolverError } from './errors.ts';export const CATALOG_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;+/** The catalog setup claude-code builds from Claude Code's enabled plugins. */+export const CLAUDE_PLUGINS_CATALOG = 'claude-code-plugins';const RESERVED = new Set(['sessions', 'logs']);/** The gbrain config directory (configDir() in src/core/config.ts). */diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex 7cfe0de3a8..89371d0297 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -63,6 +63,8 @@ export interface TurnInput {export interface Suggestion { id: string; name: string; score: number; summary: string; reason: string; match_strength: MatchStrength; path?: string; catalog: string }export interface TurnError { code: string; message: string; fix: { suggestion: string; command?: string } }+/** Why a block is empty; null when it has a suggestion. */+export type BlockReason = 'ack' | 'no_match' | 'filtered' | 'deduped' | 'paced' | 'budget_exhausted' | 'shadow' | 'error';export interface TurnOutput {schema_version: 1;gbrain_version: string;@@ -73,6 +75,7 @@ export interface TurnOutput {no_skill: boolean;no_skill_reason: 'ack' | 'no_match' | null;budget_exhausted: boolean;+ block_reason: BlockReason | null;suggestions: Suggestion[];block: string;block_tokens: number;@@ -244,7 +247,7 @@ function emptyOutput(input: { shadow?: boolean }, extra: Partial<TurnOutput>): Treturn {schema_version: 1, gbrain_version: VERSION, catalog: null, catalog_hash: null, index_hash: null,ranker: { id: RANKER_ID, version: RANKER_VERSION, variant: null, k: 0 },- no_skill: false, no_skill_reason: null, budget_exhausted: false, suggestions: [], block: '', block_tokens: 0, tokenizer: BLOCK_TOKENIZER,+ no_skill: false, no_skill_reason: null, budget_exhausted: false, block_reason: extra.error ? 'error' : null, suggestions: [], block: '', block_tokens: 0, tokenizer: BLOCK_TOKENIZER,deduped: [], shadow: Boolean(input.shadow), meta: { timing_ms: 0, index_age_s: null, index_stale: false }, ...extra,};}@@ -317,23 +320,23 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:const kEff = spentFrac < 0.5 ? input.top_k : spentFrac < 0.8 ? Math.min(input.top_k, 3) : 1;const base: TurnOutput = {...emptyOutput(input, {}), catalog, catalog_hash: catalogHash, index_hash: indexHash,- ranker: { id: RANKER_ID, version: RANKER_VERSION, variant, k: kEff }, meta,+ ranker: { id: RANKER_ID, version: RANKER_VERSION, variant, k: kEff }, meta, budget_exhausted: budget === 0 || state.spent >= budget,};const finish = (out: TurnOutput, delta: { tokens: number; suggested: string[]; resuggested: string[] }, explain?: Explain): ResolveResult => {out.meta.timing_ms = round4(performance.now() - t0);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 };+ const quiet: TurnOutput = { ...out, block_reason: 'shadow', suggestions: [], block: '', block_tokens: 0, deduped: [], shadow: true };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: [] });+ if (isAcknowledgement(input.message)) return finish({ ...base, no_skill: true, no_skill_reason: 'ack', block_reason: 'ack' }, { tokens: 0, suggested: [], resuggested: [] });const rankText = (text: string): RankResult[] => loaded.map(l => { const r = rankIndex(l.ix, text, check); check(); return r; });let ranks = rankText(input.message);if (ranks.every(r => r.idfSum === 0) && input.previous_user_message?.trim()) ranks = rankText(input.previous_user_message);- if (ranks.every(r => r.idfSum === 0)) return finish({ ...base, no_skill: true, no_skill_reason: 'no_match' }, { tokens: 0, suggested: [], resuggested: [] });+ if (ranks.every(r => r.idfSum === 0)) return finish({ ...base, no_skill: true, no_skill_reason: 'no_match', block_reason: 'no_match' }, { tokens: 0, suggested: [], resuggested: [] });interface Cand { c: number; doc: number; score: number; id: string; explicit: boolean }const metaOf = (c: number, doc: number) => loaded[c]!.ix.meta(doc);@@ -401,7 +404,8 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:const match_strength = strengthOf(x);return { id: m.id, name: m.name, score: round4(x.score), summary: namesOnly ? '' : m.summary, reason: x.explicit ? `named in the turn; ${reasonText(fields)}` : reasonText(fields), match_strength, ...(m.path ? { path: m.path } : {}), catalog: loaded[x.c]!.name };});- const out: TurnOutput = { ...base, budget_exhausted: exhausted, suggestions, block: r.block, block_tokens: r.tokens, deduped };+ const blockReason: BlockReason | null = suggestions.length ? null : exhausted ? 'budget_exhausted' : paced ? 'paced' : window.length ? 'deduped' : 'filtered';+ const out: TurnOutput = { ...base, budget_exhausted: exhausted, block_reason: blockReason, suggestions, block: r.block, block_tokens: r.tokens, deduped };let explain: Explain | undefined;if (opts.explainTarget !== undefined) {const target = opts.explainTarget;diff --git a/src/core/skills/resolver/sources.ts b/src/core/skills/resolver/sources.tsindex 239833b64a..5d74f120ac 100644--- a/src/core/skills/resolver/sources.ts+++ b/src/core/skills/resolver/sources.ts@@ -34,6 +34,7 @@ import { ResolverError } from './errors.ts';import { readBounded, readHead } from './fsutil.ts';import { boundBody, cleanText, parseSkillDoc, SKILL_FILE_CAP_BYTES } from './frontmatter.ts';import { parseRoutingTable } from './routing.ts';+import { listingKey, skippedEntry } from './catalog-files.ts';export { fingerprintChanged } from './catalog-files.ts';export const MAX_SKILLS = 10_000;@@ -65,7 +66,7 @@ export interface SkillRecord {export type SkipReason = 'duplicate_id' | 'not_model_invocable' | 'ineligible' | 'symlink_outside_root' | 'unreadable' | 'invalid_entry';export interface SkippedSkill { reason: SkipReason; id?: string; path?: string; kept?: string }-export interface DirFingerprint { dirs: [string, number][]; files: [string, number, number][] }+export interface DirFingerprint { dirs: [string, number, string?][]; files: [string, number, number][] }export interface SourceRead {kind: 'dir' | 'bundled' | 'json' | 'claude_plugins';@@ -135,11 +136,12 @@ export function readDirSources(dirs: readonly string[], rootNamespaces: readonlyif (++visited > MAX_DIRS_VISITED) throw tooLarge(`more than ${MAX_DIRS_VISITED} directories under the --dir roots`);let entries: string[];try {- fp.dirs.push([dir, statSync(dir).mtimeMs]);- entries = readdirSync(dir).sort();+ const mtime = statSync(dir).mtimeMs;+ const listed = readdirSync(dir, { withFileTypes: true });+ fp.dirs.push([dir, mtime, listingKey(listed)]);+ entries = listed.map(e => e.name).filter(n => !skippedEntry(n)).sort();} catch { skipped.push({ reason: 'unreadable', path: dir }); continue; }for (const name of entries) {- if (name === 'node_modules' || name === '.git') continue;const full = join(dir, name);let real = full;let st;diff --git a/test/setup-skill-resolver.test.ts b/test/setup-skill-resolver.test.tsindex 40c0e3b4b4..92af383da4 100644--- a/test/setup-skill-resolver.test.ts+++ b/test/setup-skill-resolver.test.ts@@ -12,7 +12,9 @@* 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.+ * resolver is configured, and warns on an install that predates the+ * SessionStart compaction entry; a hand-edited per_harness entry that is not+ * an object reads as unset and is replaced on set or unset.*/import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -22,6 +24,7 @@ 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';+import { laneTurnSettings } from '../src/core/skills/resolver/config.ts';setDefaultTimeout(60_000);const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');@@ -256,3 +259,61 @@ describe('doctor', () => {expect(unreadable).toMatchObject({ status: 'warn', details: { code: 'skill_resolver_config_unreadable' } });});});++describe('doctor: an install from before the SessionStart entry', () => {+ for (const harness of ['claude-code', 'codex'] as H[]) {+ test(`${harness}: only the UserPromptSubmit hook warns as outdated with the setup fix, and setup repairs it`, async () => {+ const b = box();+ skill(HARNESS[harness].skills(b), 'deploy-widget', 'Deploy the widget service.');+ expect((await setup(b, harness, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ const doctor = async () => JSON.parse((await runCli(['doctor', '--only', 'skill_resolver', '--json'], { env: b.env, cwd: b.project })).stdout).checks.find((c: any) => c.name === 'skill_resolver');+ expect((await doctor()).status).toBe('ok');+ const file = HARNESS[harness].hookFile(b);+ const doc = JSON.parse(read(file)!);+ doc.hooks.SessionStart = doc.hooks.SessionStart.filter((g: any) => !JSON.stringify(g).includes('skill-resolver'));+ if (doc.hooks.SessionStart.length === 0) delete doc.hooks.SessionStart;+ writeFileSync(file, JSON.stringify(doc));+ const outdated = await doctor();+ expect(outdated.status).toBe('warn');+ expect(outdated.details.harnesses[0]).toMatchObject({ harness, hook: 'outdated' });+ expect(outdated.message).toContain('SessionStart');+ expect(outdated.message).toContain(`gbrain setup ${harness} --skill-loading resolve`);+ expect(outdated.fix.argv).toEqual(['gbrain', 'setup', harness, '--skill-loading', 'resolve']);+ const repair = await setup(b, harness, ['--skill-loading', 'resolve', '--json']);+ expect(repair.exitCode, repair.stderr).toBe(0);+ expect(repair.doc.skill_resolver.steps.find((s: any) => s.step === 'hook').action).toBe('write');+ expect(await doctor()).toMatchObject({ status: 'ok', details: { harnesses: [{ harness, hook: 'wired' }] } });+ });+ }+});++describe('per_harness entries that are not objects', () => {+ for (const bad of [null, [1], 'fast', 3]) {+ test(`config get, set and unset treat per_harness.codex = ${JSON.stringify(bad)} as unset and replace it`, async () => {+ const b = box();+ const run = (...args: string[]) => runCli(['config', ...args], { env: b.env, cwd: b.project });+ const seed = () => { mkdirSync(gb(b), { recursive: true }); writeFileSync(configPath(b), JSON.stringify({ skills: { resolver: { top_k: 3, per_harness: { codex: bad } } } })); };+ seed();+ const get = await run('get', 'skills.resolver.per_harness.codex.top_k');+ expect(get.exitCode).not.toBe(0);+ expect(get.stderr).toContain('Config key not found');+ expect(get.stderr).not.toContain('TypeError');+ const set = await run('set', 'skills.resolver.per_harness.codex.top_k', '2');+ expect(set.exitCode, set.stderr).toBe(0);+ expect(JSON.parse(read(configPath(b))!).skills.resolver.per_harness).toEqual({ codex: { top_k: 2 } });+ seed();+ const unset = await run('unset', 'skills.resolver.per_harness.codex.top_k');+ expect(unset.exitCode, unset.stderr).toBe(0);+ expect(JSON.parse(read(configPath(b))!).skills.resolver).toEqual({ top_k: 3 });+ const inherited = await run('set', 'skills.resolver.per_harness.constructor.top_k', '2');+ expect(inherited.exitCode).not.toBe(0);+ expect(inherited.stderr).toContain('names no harness');+ });++ test(`laneTurnSettings falls back to the global keys for per_harness.codex = ${JSON.stringify(bad)}`, () => {+ const section = { top_k: 3, min_match: 'description', per_harness: { codex: bad, 'claude-code': { top_k: 1 } } };+ expect(laneTurnSettings(section, 'codex')).toEqual({ top_k: 3, min_match_strength: 'description' });+ expect(laneTurnSettings(section, 'claude-code')).toEqual({ top_k: 1, min_match_strength: 'description' });+ });+ }+});diff --git a/test/skill-resolver-catalogs.test.ts b/test/skill-resolver-catalogs.test.tsindex 164684d87c..d555dc4866 100644--- a/test/skill-resolver-catalogs.test.ts+++ b/test/skill-resolver-catalogs.test.ts@@ -15,7 +15,7 @@* missing plugin indexes, or setup leaves the plugin catalog behind.*/import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { runCli } from './helpers/cli-spawn.ts';@@ -192,3 +192,44 @@ describe('setup claude-code --skill-loading resolve with plugins', () => {expect(on.stdout).toContain('skill resolver: on; 2 skills; fresh');});});++describe('harness-owned entries in a skills root (HARN-52)', () => {+ const built = async (prefix: string) => {+ const home = tmp();+ const root = tmp(prefix);+ skill(root, 'deploy', 'deploy', 'Deploy a service to production');+ await buildSkillIndex({ catalog: 'h', dirs: [root], harness: 'codex' }, { home });+ return { home, root };+ };+ const stale = async (home: string) => (await resolveSkills({ message: 'deploy a service' }, { home, catalogs: ['h'] })).output.meta.index_stale;++ test('Codex creating .system/ with its own skills leaves the index fresh, and dot-directories are never indexed', async () => {+ const { home, root } = await built('skres-codex-root-');+ skill(join(root, '.system'), 'skill-creator', 'skill-creator', 'Create a new skill');+ expect(await stale(home)).toBe(false);+ expect((await catalogStatus('h', { home })).fresh).toBe(true);+ const ids = (await resolveSkills({ message: 'create a new skill' }, { home, catalogs: ['h'] })).output.suggestions.map((s) => s.id);+ expect(ids).not.toContain('skill-creator');+ });++ test('Hermes rewriting a dot-file in the root (write and rename) leaves the index fresh', async () => {+ const { home, root } = await built('skres-hermes-root-');+ writeFileSync(join(root, '.usage.json.tmp'), '{"deploy":1}');+ renameSync(join(root, '.usage.json.tmp'), join(root, '.usage.json'));+ writeFileSync(join(root, '.hub'), 'x');+ expect(await stale(home)).toBe(false);+ writeFileSync(join(root, '.usage.json.tmp'), '{"deploy":2}');+ renameSync(join(root, '.usage.json.tmp'), join(root, '.usage.json'));+ expect(await stale(home)).toBe(false);+ expect((await catalogStatus('h', { home })).fresh).toBe(true);+ });++ test('a new skill folder or an edited SKILL.md still makes the index stale', async () => {+ const a = await built('skres-new-skill-');+ skill(a.root, 'notes', 'notes', 'Take meeting notes');+ expect(await stale(a.home)).toBe(true);+ const b = await built('skres-edit-skill-');+ writeFileSync(join(b.root, 'deploy', 'SKILL.md'), '---\nname: deploy\ndescription: Deploy a service to staging first\n---\nSteps.\n');+ expect(await stale(b.home)).toBe(true);+ });+});diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsindex d44b9a492f..d501480123 100644--- a/test/skill-resolver-hook-lane.test.ts+++ b/test/skill-resolver-hook-lane.test.ts@@ -10,15 +10,21 @@* 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.+ * project catalog (Claude Code's .claude/skills, Codex's .agents/skills from the+ * project root down to cwd) is built out of the turn and merged at rank time;+ * a built claude-code-plugins catalog is searched; no built catalog ends the+ * turn as no_catalog; Hermes reads extra.user_message from a stream of any size+ * and answers {"context"}; 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 { Readable } from 'node:stream';import { runCli } from './helpers/cli-spawn.ts';-import { LANE_DEADLINE_MS, projectCatalogPrefix, WORKER_SRC_PATH } from '../src/core/skills/resolver/hook-lane.ts';+import { CLAUDE_PLUGINS_CATALOG, LANE_DEADLINE_MS, projectCatalogPrefix, WORKER_SRC_PATH } from '../src/core/skills/resolver/hook-lane.ts';+import { HOOK_FIELD_CAP, readJsonFields } from '../src/core/skills/resolver/hook-input.ts';+import { MESSAGE_CAP_BYTES } from '../src/core/skills/resolver/resolve.ts';import { dailyLogFile, LANE_LOG } from '../src/core/skills/resolver/daily-log.ts';setDefaultTimeout(60_000);@@ -74,11 +80,12 @@ function wired(b: Box, harness: 'claude-code' | 'codex', event: 'UserPromptSubmiinterface 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> {+async function hook(b: Box, command: string, payload: Record<string, unknown> | string, env: Record<string, string | undefined> = {}, cwd = b.project): 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 stdin = new TextEncoder().encode(typeof payload === 'string' ? payload : JSON.stringify({ cwd, ...payload }));+ const proc = Bun.spawn(['sh', '-c', command], { env: merged, cwd, stdin, 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 };}@@ -419,3 +426,192 @@ describe('skill-resolver lane: project catalog', () => {expect(readdirSync(join(b.home, '.gbrain', 'skill-index')).filter((n) => n.startsWith('claude-code-project-'))).toEqual([]);});});++const catalogRoot = (b: Box) => join(b.home, '.gbrain', 'skill-index');+async function waitForCatalog(b: Box, prefix: string): Promise<string | undefined> {+ for (let i = 0; i < 100; i++) {+ const built = readdirSync(catalogRoot(b)).find((n) => n.startsWith(prefix) && existsSync(join(catalogRoot(b), n, 'receipt.json')));+ if (built) return built;+ await Bun.sleep(100);+ }+ return undefined;+}+const spawnStamps = (b: Box) => { const d = join(catalogRoot(b), 'logs'); return existsSync(d) ? readdirSync(d).filter((n) => n.startsWith('spawn-')) : []; };+async function buildCatalog(b: Box, catalog: string, dir: string, harness: string) {+ const r = await runCli(['skills', 'index', 'build', '--catalog', catalog, '--dir', dir, '--harness', harness], { env: b.env, cwd: b.project });+ expect(r.exitCode, r.stderr).toBe(0);+}++describe('skill-resolver lane: codex project catalog', () => {+ test("a repo's .agents/skills at the root and in a subdir get one catalog over both, root first, keyed by the dir list", async () => {+ const b = box();+ seedSkills(codexSkills(b));+ mkdirSync(join(b.project, '.git'));+ const sub = join(b.project, 'packages', 'widget');+ skill(join(b.project, '.agents', 'skills'), 'rotate-fixtures', 'Rotate the fixture files for the nightly widget run.');+ skill(join(sub, '.agents', 'skills'), 'bump-widget-schema', 'Bump the widget schema version.');+ await setup(b, 'codex');+ const cmd = wired(b, 'codex');+ const turn = { prompt: 'rotate the fixture files and bump the widget schema', hook_event_name: 'UserPromptSubmit' };+ expect((await hook(b, cmd, { ...turn, session_id: 'cp1' }, WIDE, sub)).exitCode).toBe(0);+ const built = await waitForCatalog(b, projectCatalogPrefix('codex'));+ expect(built).toMatch(/^codex-project-[0-9a-f]{16}$/);+ const receipt = readJson(join(catalogRoot(b), built!, 'receipt.json'));+ expect(receipt.catalog).toMatchObject({ source: { dirs: [join(b.project, '.agents', 'skills'), join(sub, '.agents', 'skills')] }, scope: 'project', harness: 'codex' });+ const block = contextOf(await hook(b, cmd, { ...turn, session_id: 'cp2' }, WIDE, sub));+ expect(block).toContain('id: "rotate-fixtures"');+ expect(block).toContain('id: "bump-widget-schema"');+ expect(block).toContain(CODEX_LOAD);+ expect(laneLog(b).at(-1).catalogs).toEqual(['codex-user', built]);+ });++ test('no .agents/skills below the project root, or only the home directory\'s own, means no project catalog', async () => {+ const b = box();+ seedSkills(codexSkills(b));+ mkdirSync(join(b.project, '.git'));+ await setup(b, 'codex');+ const cmd = wired(b, 'codex');+ const turn = { prompt: 'write the changelog for this release', hook_event_name: 'UserPromptSubmit' };+ expect(contextOf(await hook(b, cmd, { ...turn, session_id: 'cn1' }, WIDE))).toContain('write-changelog');+ mkdirSync(join(b.home, '.git'));+ const fromHome = await hook(b, cmd, { ...turn, session_id: 'cn2' }, WIDE, b.home);+ expect(contextOf(fromHome)).toContain('write-changelog');+ expect(laneLog(b).map((l) => l.catalogs)).toEqual([['codex-user'], ['codex-user']]);+ expect(spawnStamps(b)).toEqual([]);+ });+});++describe('skill-resolver lane: built catalogs only', () => {+ test('claude-code: a built claude-code-plugins catalog is searched, between the user and the project catalog', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ expect(CLAUDE_PLUGINS_CATALOG).toBe('claude-code-plugins');+ const plugins = join(b.root, 'plugin-fixtures');+ skill(plugins, 'audit-widget-licenses', 'Audit the widget dependency licenses.');+ await buildCatalog(b, CLAUDE_PLUGINS_CATALOG, plugins, 'claude-code');+ const r = await hook(b, wired(b, 'claude-code'), { prompt: 'audit the widget licenses', session_id: 'pl1' }, WIDE);+ expect(contextOf(r)).toContain('id: "audit-widget-licenses"');+ expect(laneLog(b).at(-1).catalogs).toEqual(['claude-code-user', CLAUDE_PLUGINS_CATALOG]);+ });++ test('claude-code with only plugin skills: the plugins catalog alone delivers', async () => {+ const b = box();+ seedSkills(claudeSkills(b));+ await setup(b, 'claude-code');+ rmSync(join(catalogRoot(b), 'claude-code-user'), { recursive: true });+ const plugins = join(b.root, 'plugin-fixtures');+ skill(plugins, 'audit-widget-licenses', 'Audit the widget dependency licenses.');+ await buildCatalog(b, CLAUDE_PLUGINS_CATALOG, plugins, 'claude-code');+ const r = await hook(b, wired(b, 'claude-code'), { prompt: 'audit the widget licenses', session_id: 'pl2' }, WIDE);+ expect(contextOf(r)).toContain('id: "audit-widget-licenses"');+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'delivered', catalogs: [CLAUDE_PLUGINS_CATALOG] });+ });++ for (const harness of ['claude-code', 'codex'] as const) {+ test(`${harness}: no built catalog ends the turn with no output and outcome no_catalog, never skill_index_missing`, async () => {+ const b = box();+ seedSkills(harness === 'codex' ? codexSkills(b) : claudeSkills(b));+ await setup(b, harness);+ rmSync(join(catalogRoot(b), `${harness}-user`), { recursive: true });+ const r = await hook(b, wired(b, harness), { prompt: 'please deploy the widget to staging', session_id: 'nc', hook_event_name: 'UserPromptSubmit' }, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ const last = laneLog(b).at(-1);+ expect(last.outcome).toBe('no_catalog');+ expect(last.code).toBeUndefined();+ });+ }+});++describe('skill-resolver lane: hermes', () => {+ const HERMES_LOAD = 'To use one, load it with skill_view(name) using its id before acting.';+ const hermesCmd = (b: Box) => `env GBRAIN_HOOK_LANE=skill-resolver GBRAIN_HOME='${b.home}' '${b.bin}' hook user-prompt --harness hermes`;+ async function hermesBox(extra: Record<string, unknown> = {}): Promise<Box> {+ const b = box();+ const dir = join(b.home, '.hermes', 'skills');+ seedSkills(dir);+ await buildCatalog(b, 'hermes-user', dir, 'hermes');+ writeFileSync(join(b.home, '.gbrain', 'config.json'), JSON.stringify({ skills: { resolver: { enabled: true, harnesses: ['hermes'], ...extra } } }));+ return b;+ }+ const history = (bytes: number) => {+ const turns: unknown[] = [];+ const item = { role: 'user', content: 'An earlier turn with "quotes", a \\ backslash, \u00e9t\u00e9 and \ud83d\ude80, plus a decoy.', user_message: 'decoy: rotate the fixtures' };+ const size = JSON.stringify(item).length + 1;+ for (let n = 0; n * size < bytes; n++) turns.push(item);+ return turns;+ };++ test('a pre_llm_call turn reads extra.user_message and answers {"context": block}; a repeat in the session is deduped', async () => {+ const b = await hermesBox();+ const turn = { session_id: 'h1', extra: { user_message: 'please deploy the widget to staging', conversation_history: [] } };+ const r = await hook(b, hermesCmd(b), turn, WIDE);+ expect(r.exitCode).toBe(0);+ const out = JSON.parse(r.stdout);+ expect(Object.keys(out)).toEqual(['context']);+ expect(out.context).toContain('id: "deploy-widget"');+ expect(out.context).toContain(HERMES_LOAD);+ expect((await hook(b, hermesCmd(b), turn, WIDE)).stdout).toBe('');+ expect(laneLog(b).map((l) => [l.harness, l.outcome])).toEqual([['hermes', 'delivered'], ['hermes', 'empty']]);+ });++ test('a 5 MB conversation_history before and after user_message is read, never refused, and still delivers within a turn budget', async () => {+ const b = await hermesBox();+ const small = await hook(b, hermesCmd(b), { session_id: 'h2a', extra: { user_message: 'please deploy the widget to staging' } }, WIDE);+ expect(JSON.parse(small.stdout).context).toContain('id: "deploy-widget"');+ const turn = { session_id: 'h2', extra: { conversation_history: history(2.5e6), user_message: 'please deploy the widget to staging', later_history: history(2.5e6) } };+ expect(JSON.stringify(turn).length).toBeGreaterThan(5e6);+ const r = await hook(b, hermesCmd(b), turn, WIDE);+ expect(r.exitCode).toBe(0);+ expect(JSON.parse(r.stdout).context).toContain('id: "deploy-widget"');+ const [base, big] = laneLog(b).slice(-2);+ expect(big).toMatchObject({ outcome: 'delivered' });+ // Reading 5 MB adds less than one lane deadline to a small turn; a buffering or quadratic reader would not.+ expect(big.ms - base.ms).toBeLessThan(LANE_DEADLINE_MS);+ });++ test('malformed Hermes JSON fails open: exit 0, no stdout, skill_resolve_no_input', async () => {+ const b = await hermesBox();+ for (const raw of ['{"session_id": "h3", "extra": {"user_message": "deploy the widget"', '{"extra": {"user_message": "deploy the widget"}} trailing', '[1, 2]', '']) {+ const r = await hook(b, hermesCmd(b), raw, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'error', code: 'skill_resolve_no_input' });+ }+ });++ test('skills.resolver.lane_payload_chars caps the Hermes JSON too', async () => {+ const b = await hermesBox({ lane_payload_chars: 500 });+ const r = await hook(b, hermesCmd(b), { session_id: 'h4', extra: { user_message: 'deploy the widget, write the changelog and triage the bug' } }, WIDE);+ expect(r).toMatchObject({ exitCode: 0, stdout: '' });+ expect(laneLog(b).at(-1).outcome).toBe('payload_dropped');+ });+});++describe('readJsonFields: the bounded streaming hook reader', () => {+ const chunks = (text: string, size: number) => { const bytes = Buffer.from(text); return Readable.from(Array.from({ length: Math.ceil(bytes.length / size) }, (_, i) => bytes.subarray(i * size, (i + 1) * size))); };+ const PATHS = ['session_id', 'cwd', 'extra.user_message'];++ test('keeps only the string values at the paths, decoding escapes across any chunk boundary; nested decoys do not match', async () => {+ const doc = { cwd: '/w/acme-example', extra: { conversation_history: [{ user_message: 'decoy', extra: { user_message: 'decoy' } }], user_message: 'say "hi" \\ \u00e9 \ud83d\ude80\n', n: -1.5e3, ok: [true, false, null] }, session_id: 's-1', user_message: 'top-level decoy' };+ const text = JSON.stringify(doc);+ for (const size of [1, 3, 7, 64 * 1024]) {+ expect(await readJsonFields(chunks(text, size), PATHS, HOOK_FIELD_CAP)).toEqual({ cwd: '/w/acme-example', 'extra.user_message': doc.extra.user_message, session_id: 's-1' });+ }+ });++ test('caps each kept value and refuses no payload size', async () => {+ expect(HOOK_FIELD_CAP).toBe(MESSAGE_CAP_BYTES);+ const text = JSON.stringify({ extra: { conversation_history: 'x'.repeat(6e6), user_message: 'y'.repeat(20_000) } });+ const got = await readJsonFields(chunks(text, 64 * 1024), PATHS, 100);+ expect(got).toEqual({ 'extra.user_message': 'y'.repeat(100) });+ const escaped = `{"session_id":"a${'\\u00e9'.repeat(200)}"}`;+ expect(await readJsonFields(chunks(escaped, 5), PATHS, 100)).toEqual({ session_id: `a${'\u00e9'.repeat(99)}` });+ });++ test('null for malformed JSON (a kept string fully checked, discarded ones for nesting and ends), a non-object document; a non-string value is skipped', async () => {+ for (const bad of ['', '{', '{"a":}', '{"a":1,}', '{"session_id":"\\x"}', '{"cwd":"\\u12"}', '{"extra":{"user_message":"line\nbreak"}}', '{"a":01}', '{"a":tru}', '{} {}', '"x"', '[]', '{"a":[{"b":"x"]}', '{"a":"open}']) {+ expect(await readJsonFields(chunks(bad, 2), PATHS, 100)).toBeNull();+ }+ expect(await readJsonFields(chunks('{"session_id": 7, "extra": {"user_message": ["x"]}}', 4), PATHS, 100)).toEqual({});+ });+});diff --git a/test/skill-resolver-packaging.test.ts b/test/skill-resolver-packaging.test.tsindex ff8e59ad25..1357a4d350 100644--- a/test/skill-resolver-packaging.test.ts+++ b/test/skill-resolver-packaging.test.ts@@ -94,4 +94,18 @@ describe('skill resolver packaging', () => {expect(check).toBeGreaterThan(0);expect(check).toBeLessThan(wf.indexOf('uses: softprops/action-gh-release'));});+ test('a compiled build records its commit in the build receipt: GBRAIN_BUILD_COMMIT is defined at compile time (HARN-52)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'skres-commit-'));+ try {+ const sha = 'a'.repeat(40);+ const built = Bun.spawnSync(['bun', 'build', '--target=bun', '--outfile', join(dir, 'lib.js'), '--define', `GBRAIN_BUILD_COMMIT="${sha}"`, join(ROOT, 'src/core/skills/resolver/index.ts')], { stderr: 'pipe' });+ expect(built.exitCode, built.stderr.toString()).toBe(0);+ const run = Bun.spawnSync(['bun', '-e', `const m = await import(${JSON.stringify(join(dir, 'lib.js'))}); const r = await m.buildSkillIndex({ catalog: 'c', fromJson: '[{"id":"a","name":"a"}]', fromJsonStdin: true }, { home: ${JSON.stringify(dir)} }); console.log(r.gbrain_commit);`], { cwd: dir, stderr: 'pipe' });+ expect(run.stdout.toString().trim(), run.stderr.toString()).toBe(sha);+ const pkg = await Bun.file(join(ROOT, 'package.json')).json() as { scripts: Record<string, string> };+ for (const s of ['build', 'build:all']) for (const cmd of pkg.scripts[s]!.split('&&')) expect(cmd).toContain('--define GBRAIN_BUILD_COMMIT=');+ const release = readFileSync(join(ROOT, '.github/workflows/release.yml'), 'utf8');+ for (const line of release.split('\n').filter(l => l.includes('bun build --compile'))) expect(line).toContain("--define GBRAIN_BUILD_COMMIT='\"${{ github.sha }}\"'");+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });});diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.tsindex 04b996d9e6..fb6b33f0bb 100644--- a/test/skill-resolver.test.ts+++ b/test/skill-resolver.test.ts@@ -302,6 +302,35 @@ describe('sessions', () => {expect(loadSession(home, key).turn).toBe(1);});+ test('a spent budget stays spent on an acknowledgement or a no-match turn (HARN-52)', async () => {+ const home = tmp();+ await jsonCatalog(home, 'c', BASIC);+ await commitSession(home, sessionKey('on', 'claude-code', 'a'), { tokens: 2000, suggested: [], resuggested: [], reset: false });+ for (const message of ['ok thanks', 'zzqxv']) {+ const r = await resolveSkills({ message, session_id: 'a', harness: 'claude-code' }, { home });+ expect([r.output.no_skill, r.output.budget_exhausted, r.output.block_reason]).toEqual([true, true, message === 'zzqxv' ? 'no_match' : 'ack']);+ }+ expect((await resolveSkills({ message: 'ok thanks', session_id: 'fresh', harness: 'claude-code' }, { home })).output.budget_exhausted).toBe(false);+ });++ test('block_reason says why a block is empty: deduped, paced, budget_exhausted, filtered, shadow', async () => {+ const home = tmp();+ await jsonCatalog(home, 'c', BASIC);+ const first = await resolveSkills({ message: 'deploy', session_id: 'd' }, { home, sessionTokenBudget: 50_000 });+ expect(first.output.block_reason).toBeNull();+ await first.commit();+ const again = await resolveSkills({ message: 'deploy', session_id: 'd' }, { home, sessionTokenBudget: 50_000 });+ expect([again.output.block, again.output.block_reason]).toEqual(['', 'deduped']);+ await commitSession(home, sessionKey('on', undefined, 'p'), { tokens: 1000, suggested: [], resuggested: [], reset: false });+ const paced = await resolveSkills({ message: 'team status', session_id: 'p' }, { home });+ expect([paced.output.block, paced.output.block_reason]).toEqual(['', 'paced']);+ await commitSession(home, sessionKey('on', undefined, 'p'), { tokens: 1000, suggested: [], resuggested: [], reset: false });+ expect((await resolveSkills({ message: 'team status', session_id: 'p' }, { home })).output.block_reason).toBe('budget_exhausted');+ expect((await resolveSkills({ message: 'deploy', exclude: ['gbrain:deploy'], min_match_strength: 'name' }, { home })).output.block_reason).toBe('filtered');+ const shadow = await resolveSkills({ message: 'deploy', shadow: true }, { home });+ expect([shadow.output.block_reason, shadow.shadowOutput?.block_reason]).toEqual(['shadow', null]);+ });+test('a skill the turn names still gets its line after the budget is spent; its tokens count', async () => {const home = tmp();await jsonCatalog(home, 'c', BASIC);