Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Key files: Skills (continued)
Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Skill resolver
The engine-free skill resolver behind gbrain skills index and
gbrain skills resolve. Guide: docs/guides/skill-resolver.md.
Contract schemas: docs/schemas/skill-resolver.v1.*.json. Every module under
src/core/skills/resolver/ is a leaf: no engine, operations table, provider or
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-resolverexport, and the entry of the Node bundlegbrain-skill-resolver.mjs). Re-exports build, status, remove, resolve,openCatalog,buildSkillIndexOffThread,ResolverError,resolverHome;resetSkillSessiondeletes one session's state;gcSkillSessionsruns one bounded async GC pass;RESOLVER_FEATURESnames 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 aTurnSource(openCatalogIndex: receipt and ranker identity, index size; then per turn the gbrain version and, fordirandclaude_pluginscatalogs, the sliced stat freshness check: at mostSTAT_CHECK_SLICEentries per turn, a full sweep at most once perSTAT_CHECK_INTERVAL_MS, cursor instat-check;stale.stampis written without fsync, only when absent and only for a catalog withrebuild_argv, never an adapter-owned stdin one), ack and no_match, explicit mentions first, merged-catalog interleave, themin_match_strengthfloor before the cut to k,top_gate(defaultTOP_GATE_DEFAULT0.6 when the turn sets none, 0 off; over the skills the block would deliver, after exclude,min_match_strength, session dedupe and pacing: the best score overmaxIdf(n)of its catalog, highest across catalogs, below the threshold empties the block asweak_top_match; an explicit mention bypasses it),previous_user_messageas 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_exhaustedkept on ack and no-match turns), the block and itsblock_reason,explain,failOpen,deadlineMs. Returnscommit(); session state changes only through it. Pinned bytest/skill-resolver.test.tsandtest/skill-resolver-contract.test.ts.src/core/skills/resolver/rank.ts— the A5 BM25F ranker over anIndexReader(scores summed in the prototype's order, ranked by score over summed idf, ties by name then id),maxIdf(n)(the BM25 idf of a term in one ofnskills, thetop_gatedivisor), the multilingual acknowledgement list,mentionsSkill(a/namecounts only as a leading slash command) andreasonText.test/skill-resolver-reproduction.test.tspins top-5 equality with the Step 1 prototype.src/core/skills/resolver/tokenize.ts—splitWords(shared withscoreSkillMatchinskill-catalog.ts) andlexTerms, 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(magicGBSKIDX1, 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—buildSkillIndexunder 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 failsskill_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, dot-entries andnode_modulesnever read, a per-directorylistingKeyso 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 ofsrc/core/skills/bundled.ts, never the operations table),--from-json(JSON_INPUT_CAP_BYTES64 MB, 10,000 entries, bodies trimmed to 4 KB, a snapshot overJSON_SOURCE_CAP_BYTESkept trimmed; an adapter list or OpenClaw'sskills list --jsonas is, name as id; with--dir,mergeSkillFolderstakes bodies, paths and triggers by name) and--claude-plugins(readClaudePluginSources: enabled user-scope plugins frominstalled_plugins.jsonandsettings.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),commitSessionunder 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 perGC_INTERVAL_MS(10 min) per home by the mtime oflogs/session-gc.stamp, so new sessions keep deduping pastMAX_SESSION_FILES. A pass may take aGcBound(files,until): the hook lane passesLANE_GC_FILES(64) and its deadline lessGC_RESERVE_MSand awaitssessionGcSettled()before exit; the stamp is written only when a pass finishes, so a pass its deadline cut retries on the next turn.src/core/skills/resolver/handle.ts—openCatalog(catalogs, opts), the warm handle for long-lived hosts: keeps each catalog's receipt and openIndexReaderand the settings, re-statsreceipt.json,index.binandconfig.jsononce per turn and reloads only what changed; turns runresolve.tsrunTurn, so output,pending,commit()and errors equalresolveSkillsapart frommeta.timing_ms(test/skill-resolver-runtime.test.ts).src/core/skills/resolver/build-thread.ts—buildSkillIndexOffThread:buildSkillIndexin anode:worker_threadsWorker whose entry is the module's own URL (in the Node bundle, the bundle), run by a top-level guard keyed onBUILD_THREAD_MARKERinworkerData; no worker file ships; aResolverErrorcomes back with its code, message, fix and context. The hook lane never reaches it (test/skill-resolver-module-graph.test.ts).src/core/skills/resolver/block.ts— the<relevant_skills>block: header, one JSON-quoted line per suggestion (id, name, path for codex, openclaw, pi and cursor, summary unless names-only), one load line per harness or--load-hint, cut at whole lines to 400 tokens byestimateTokens.src/core/skills/resolver/lock.ts— ownership leases (O_EXCL create, random token, expiry; reclaimed only after expiry; release and renewal check the token).src/core/skills/resolver/config.ts—skills.resolver.session_token_budget(0 or 100-50,000, default 2,000) andauto_rebuild/GBRAIN_SKILLS_NO_AUTOREBUILD=1, read straight fromconfig.json; the lane's turn settingstop_k(1-8, default 5),min_match,top_gate(0-TOP_GATE_MAX, 0 off, unset the resolver's default),pinned(sent to resolve as exclude) andper_harness.<harness>.{top_k,min_match,top_gate}(falling back to the global keys) throughlaneTurnSettingsand the validatorsvalidateTopK,validateMinMatch,validateTopGateandvalidatePinned;per_harness.<claude-code|codex>.dirs(at mostSKILL_DIRS_MAXabsolute paths, no..) throughconfiguredSkillDirs, read by setup;configuredTopGatereads and validates only thetop_gatekeys forgbrain skills resolve(a bad value anywhere in the section isskill_resolver_config_invalid).src/core/skills/resolver/limits.ts— the shared limits and names:TOP_K_DEFAULT(5),TOP_K_MAX(8),TOP_GATE_MAX(100),TOP_GATE_DEFAULT(0.6, the gate a turn gets when it sets notop_gate),EXCLUDE_MAX(1,024) andMATCH_STRENGTHS(named, then the field strengths fromnametobody), exported from the library.src/core/skills/resolver/daily-log.ts— the lane and resolver logs underskill-index/logs/: one file per UTC day (lane-<day>.jsonl,resolver-<day>.log), kept 14 days, capped at 2 MB a day; the first write of a day deletes older files and the undated legacy file. Never turn text.src/core/skills/resolver/paths.ts—resolverHome(GBRAIN_HOME convention), catalog-name rule and confinement underskill-index/, the fixed file names.src/core/skills/resolver/errors.ts—ResolverErrorcodes (rows insrc/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 byskill-catalog.ts,bundled.tsand the bundled source.src/core/skills/resolver/lane-worker.ts— starts the hook lane's worker thread (hook-worker.ts) once per process; the CLI's lane fast path (src/cli.ts) calls it before loading the lane so the worker starts beside the CLI, and the lane takes that worker. Imports onlyworker_threads; in a compiled binary the worker path comes from the binary'simport.meta.url. Null when the worker cannot start (the lane then reportsskill_resolver_internal).src/core/skills/resolver/catalog-files.ts— the catalog files the turn path reads: a catalog's receipt, the list of built catalogs and the sliced stat freshness check (listingKey, which also hashes each symlink's target) over a directory catalog's fingerprint. No source parser, so the hook worker loads only what a turn needs;build.tsandsources.tsimport it.src/core/skills/resolver/hook-lane.ts+hook-worker.ts+hook-input.ts— the hook lane (GBRAIN_HOOK_LANE=skill-resolver, dispatched first insrc/commands/hook.tsafter theGBRAIN_HOOKS=0check;--harness claude-code|codex|hermes): per-harness wire shapes inLANE_IO(Claude Code and Codex: top-levelpromptin,hookSpecificOutput.additionalContextout; Hermespre_llm_call:extra.user_messagein throughreadJsonFields, the streaming reader overBun.stdinthat 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.tsbeside it; compiled binary: the second build entrypoint atWORKER_SRC_PATH, so everybun build --compilethat 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, then one bounded session GC pass awaited before exit, the payload budget (skills.resolver.lane_payload_chars, dropped whole aspayload_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 outcomeno_catalog:<harness>-user,claude-code-plugins, then the project catalog:claude-code-project-<root hash>over.claude/skills, orcodex-project-<dir-list hash>over each.agents/skillsfrom the.gitroot down to cwd, root first, without~/.agents/skills; built by a detachedskills 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 bytest/skill-resolver-hook-lane.test.ts.src/core/setup/skill-resolver-{lane,hook,config,setup}.ts—setup <claude-code|codex> --skill-loading resolve|offand--remove: the lane identity leaf (markerskill-resolver-v1, which every other lane's ownership and yield test excludes), the Claude Code entries and the Codex UserPromptSubmit and SessionStart groups, each trusted inconfig.toml(inspectSkillResolverHook: absent, wired, untrusted, or outdated when UserPromptSubmit lacks its SessionStart entry; sync rewrites it), the file-plane keys (skills.resolver.*, engine-free ingbrain config; an unreadable file is never rewritten; a non-objectper_harnessentry reads as unset and set/unset replace it), the user catalog's extra directories fromper_harness.<harness>.dirs(missing ones skipped, kept inrebuild_argv; an invalid value stops setup before any write), and the build-then-write order (≥1 skill orskill_resolver_setup_incomplete). Pinned bytest/setup-skill-resolver.test.ts.src/core/setup/openclaw-skill-plugin.ts+openclaw-skill-plugin-code.ts—setup openclaw --skill-loading resolve|shadow|off: the separategbrain-skill-resolverOpenClaw plugin. Builds oneopenclaw-<agent>catalog per agent, writes the content-addressed library (~/.gbrain/lib/<sha256>.mjs), the 0600 state fileopenclaw-skill-resolver.json(per agent: mode, catalog, top_k 3, floordescription, live_fraction, pins route, pinned block, theskills.resolver.pinnedexclude list, owner senders; read through core'slaneTurnSettings), the generated loader and worker (Node worker thread, 50 ms deadline, resolve then commit/discard, library uid/mode/sha checks, stuck-worker restart, dailyskill-index/logs/openclaw-<date>.jsonl), and runs the openclaw CLI only to install, enable, allow and inspect; a mode or pin change rewrites only the state. A partial install isskill_resolver_plugin_not_installed(exit 3). Pinned bytest/openclaw-skill-plugin.test.ts.src/core/setup/skill-pins.ts— operator pins (skills.resolver.pins.<catalog>in config.json, 64 per catalog, 100-character lines, 600-token block, unknown names left out);gbrain skills pin add|remove|listinsrc/commands/skill-resolver.ts.src/commands/doctor/checks/skill-resolver-openclaw.ts— the OpenClaw part of doctorskill_resolver: plugin registration, library hash, per-agent catalog freshness and pins, and 24 hours of plugin logs (outcomes, error codes, reads of suggested skills, the deadline-miss rate; warns above 5% over at least 20 turns).src/commands/doctor/checks/skill-resolver.ts— doctorskill_resolver(emitted by theharness_wiringentry, whose details carry the same view): hook state (anoutdatedhook warns withgbrain 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.tsdispatches;src/cli/command-route.tsroutes onlyskills index,skills resolveandskills libraryhere, so plaingbrain skillsstayslist_skills). Exit 0, 1 (runtime error), 0 with--fail-open, 2 (usage); commits a session turn only after stdout is written. Pinned bytest/skill-resolver-cli.test.tsandtest/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.ymlon 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) behindgbrain skills library(defaultGBRAIN_HOME/.gbrain/lib/gbrain-skill-resolver.mjs) and the release script; a compiled binary has no source and refuses withskill_source_unreadable. Pinned bytest/skill-resolver-packaging.test.ts.scripts/build-skill-resolver-bundle.ts— builds and Node-smoke-testsgbrain-skill-resolver.mjsand writes its.sha256; the release jobskill-resolver-bundleattaches both and checks the sum before publishing.