Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
16.3 KB
Raw Blame

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-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, top_gate (default TOP_GATE_DEFAULT 0.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 over maxIdf(n) of its catalog, highest across catalogs, below the threshold empties the block as weak_top_match; an explicit mention bypasses it), 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), maxIdf(n) (the BM25 idf of a term in one of n skills, the top_gate divisor), 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, 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. A pass may take a GcBound (files, until): the hook lane passes LANE_GC_FILES (64) and its deadline less GC_RESERVE_MS and awaits sessionGcSettled() 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 open IndexReader and the settings, re-stats receipt.json, index.bin and config.json once per turn and reloads only what changed; turns run resolve.ts runTurn, so output, pending, commit() and errors equal resolveSkills apart from meta.timing_ms (test/skill-resolver-runtime.test.ts).
  • src/core/skills/resolver/build-thread.ts — buildSkillIndexOffThread: buildSkillIndex in a node:worker_threads Worker whose entry is the module's own URL (in the Node bundle, the bundle), run by a top-level guard keyed on BUILD_THREAD_MARKER in workerData; no worker file ships; a ResolverError comes 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 by estimateTokens.
  • 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) and auto_rebuild / GBRAIN_SKILLS_NO_AUTOREBUILD=1, read straight from config.json; the lane's turn settings top_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) and per_harness.<harness>.{top_k,min_match,top_gate} (falling back to the global keys) through laneTurnSettings and the validators validateTopK, validateMinMatch, validateTopGate and validatePinned; per_harness.<claude-code|codex>.dirs (at most SKILL_DIRS_MAX absolute paths, no ..) through configuredSkillDirs, read by setup; configuredTopGate reads and validates only the top_gate keys for gbrain skills resolve (a bad value anywhere in the section is skill_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 no top_gate), EXCLUDE_MAX (1,024) and MATCH_STRENGTHS (named, then the field strengths from name to body), exported from the library.
  • src/core/skills/resolver/daily-log.ts — the lane and resolver logs under skill-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 under skill-index/, the fixed file names.
  • 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/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 only worker_threads; in a compiled binary the worker path comes from the binary's import.meta.url. Null when the worker cannot start (the lane then reports skill_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.ts and sources.ts import it.
  • 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, then one bounded session GC pass awaited before exit, 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 UserPromptSubmit and SessionStart groups, each trusted in config.toml (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), the user catalog's extra directories from per_harness.<harness>.dirs (missing ones skipped, kept in rebuild_argv; an invalid value stops setup before any write), and the build-then-write order (≥1 skill or skill_resolver_setup_incomplete). Pinned by test/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 separate gbrain-skill-resolver OpenClaw plugin. Builds one openclaw-<agent> catalog per agent, writes the content-addressed library (~/.gbrain/lib/<sha256>.mjs), the 0600 state file openclaw-skill-resolver.json (per agent: mode, catalog, top_k 3, floor description, live_fraction, pins route, pinned block, the skills.resolver.pinned exclude list, owner senders; read through core's laneTurnSettings), the generated loader and worker (Node worker thread, 50 ms deadline, resolve then commit/discard, library uid/mode/sha checks, stuck-worker restart, daily skill-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 is skill_resolver_plugin_not_installed (exit 3). Pinned by test/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|list in src/commands/skill-resolver.ts.
  • src/commands/doctor/checks/skill-resolver-openclaw.ts — the OpenClaw part of doctor skill_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 — 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.
  • scripts/build-skill-resolver-bundle.ts — builds and Node-smoke-tests gbrain-skill-resolver.mjs and writes its .sha256; the release job skill-resolver-bundle attaches both and checks the sum before publishing.