Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Skill resolver: stop suggesting a skill when none fits (GST-2704) (#9356)
Garry Tan5b4cbe816b1d
diff --git a/behavior-changes.d/skill_resolver_gate_default_gst2704.md b/behavior-changes.d/skill_resolver_gate_default_gst2704.mdnew file mode 100644index 0000000000..2be804bf03--- /dev/null+++ b/behavior-changes.d/skill_resolver_gate_default_gst2704.md@@ -0,0 +1 @@+The skill resolver now stays quiet when no skill fits. Before, it showed a skills block on almost every message, including ones that need no skill, because some skill always shared a word with the message. It now leaves the block out when its best match is weak (skills.resolver.top_gate, default 0.6), and a skill you name in the message is still suggested. On a 351-skill public test catalog this cut blocks on no-skill requests from 100% to 11.5% and kept the right skill in the block for 174 of 228 requests that needed one, against 176 before. To tune it, run gbrain config set skills.resolver.top_gate <number>; set it to 0 to get the old behavior back. OpenClaw and Pi pick up the setting on the next gbrain setup <harness> --skill-loading resolve.diff --git a/changelog.d/capy-skill-resolver-no-skill-gate-gst2704.md b/changelog.d/capy-skill-resolver-no-skill-gate-gst2704.mdnew file mode 100644index 0000000000..2df978ff1f--- /dev/null+++ b/changelog.d/capy-skill-resolver-no-skill-gate-gst2704.md@@ -0,0 +1,7 @@+**The skill resolver now leaves its skills block out when no skill fits the message, instead of showing one on every turn.**++### Fixed+- `gbrain skills resolve`, the hook lane, and the OpenClaw and Pi plugins apply `top_gate` by default (0.6): a block whose best skill only matches weakly is left out (`block_reason: weak_top_match`), and a skill named in the message still gets through. On harness-evals' public set P with its 351-skill catalog, blocks on requests that need no skill drop from 61 of 61 to 7 of 61, and the acceptable skill stays in the block for 174 of 228 skill requests (176 before). `skills.resolver.top_gate 0` restores the old behavior.+- `gbrain skills resolve` and the OpenClaw and Pi plugins now read `skills.resolver.top_gate` (and `per_harness.<harness>.top_gate`); before, only the hook lane did. `--top-gate` still wins on the command line.++<!-- behavior-change: skill_resolver_gate_default_gst2704 -->diff --git a/docs/architecture/key-files/skills-continued.md b/docs/architecture/key-files/skills-continued.mdindex 8db093949e..010844264b 100644--- a/docs/architecture/key-files/skills-continued.md+++ b/docs/architecture/key-files/skills-continued.md@@ -12,7 +12,7 @@ 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, the off-by-default `top_gate` (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/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).@@ -25,8 +25,8 @@ Contract schemas: `docs/schemas/skill-resolver.v1.*.json`. Every module under- `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 or unset off), `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 (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), `EXCLUDE_MAX` (1,024) and `MATCH_STRENGTHS` (`named`, then the field strengths from `name` to `body`), exported from the library.+- `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).diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex a39e9e3694..b5338b42b2 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -137,8 +137,8 @@ The lane always exits 0 and prints nothing when it cannot deliver:deadline the process prints nothing, exits and commits no session state.- **Turn settings:** `skills.resolver.top_k` (1-8, default 5),`skills.resolver.min_match` (the weakest `match_strength` to suggest;- default every match), `skills.resolver.top_gate` (off unless set; see- [the gate](#top_gate-an-experimental-gate-off-by-default)) and+ default every match), `skills.resolver.top_gate` (0.6 unless set, 0 turns it off; see+ [the gate](#top_gate-the-no-skill-gate-on-by-default)) and`skills.resolver.pinned` (skill ids the harness always loads itself, neversuggested). `skills.resolver.per_harness.<harness>.top_k`, `.min_match`and `.top_gate` override one harness; what it leaves out falls back to the@@ -204,7 +204,7 @@ gateway's Node process instead:`~/.gbrain/lib/<sha256>.mjs`.2. It writes the plugin to `<openclaw state dir>/gbrain/gbrain-skill-resolver`and its state to `~/.gbrain/openclaw-skill-resolver.json` (mode 0600: per- agent the mode, catalog, top_k, floor, pinned block and rollout knobs).+ agent the mode, catalog, top_k, floor, top_gate when set, pinned block and rollout knobs).3. It runs `openclaw plugins install --link`, `plugins enable` and`config set ...hooks.allowConversationAccess true`, then`plugins inspect` and one self-test turn under Node. Anything short of a@@ -248,9 +248,9 @@ on its next turn, so no OpenClaw command runs and the gateway does not reload:- `--skill-loading off`: uninstalls the plugin and removes its files andstate. Pins stay in config.json.-`skills.resolver.per_harness.openclaw.{top_k,min_match}` overrides the-defaults (3 and `description`); the global `skills.resolver.top_k` and-`min_match` apply when it is unset, and `skills.resolver.pinned` lists skills+`skills.resolver.per_harness.openclaw.{top_k,min_match,top_gate}` overrides the+defaults (3, `description` and the resolver's gate); the global `skills.resolver.top_k`,+`min_match` and `top_gate` apply when it is unset, and `skills.resolver.pinned` lists skillsOpenClaw already loads, which are never suggested. The plugin reads these theway every lane does, so a bad value makes setup refuse with`skill_resolver_config_invalid` and write nothing; a change takes effect at@@ -388,8 +388,8 @@ Within v1, changes are additive only.`no_skill` is true only for an acknowledgement from a small multilingual list(`no_skill_reason: "ack"`) or when no word of the turn is in the catalog-(`"no_match"`). There is no score threshold: a weak match is still-suggested, and each suggestion's `match_strength` says how it matched+(`"no_match"`). The ranker has no score threshold of its own; `top_gate`+(below) empties the block when the best match is weak. Each suggestion's `match_strength` says how it matched(`named` in the turn, else the first of `name`, `triggers`, `routing`,`description`, `body`). `min_match_strength` (`--min-match`) filterscandidates: weaker matches are dropped before the cut to `top_k` and the@@ -402,30 +402,45 @@ 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.-### top_gate: an experimental gate, off by default+### top_gate: the no-skill gate, on by default`top_gate` (`--top-gate`, `skills.resolver.top_gate`) empties the blockwhen the best skill the block would show (after `exclude`, pinned skills,`min_match_strength`, session dedupe and pacing) has a score that, divided by its catalog's maximumidf, `ln(1 + (n - 0.5) / 1.5)` for a catalog of `n` skills, is below the-threshold (0 to 100; unset or 0 is off). With merged catalogs it takes the+threshold (0 to 100). With merged catalogs it takes thehighest of those candidates. A skill named in the turn bypasses it. Thedivision keeps the number comparable across catalog sizes; it does not undomessage length, so long messages still score higher.-It stays off by default because no threshold has yet shown that it removes-suggestions on no-skill turns without hiding many right ones. Two offline-measurements disagree:+The default is 0.6; `0` turns the gate off. Without it, a large catalog+almost always has some skill that shares a word with the message, so every+turn got a block, including turns that need no skill. On harness-evals'+public set P (289 labelled requests, the 351-skill public catalog, Codex+index, top 5), each request ranked once with no session:-| Source | Turns | Gate fitted on | False suggestions on no-skill turns | hit@5 on skill turns, gated (ungated) |-|---|---|---|---|---|-| [gbrain-evals `2026-11-07-skill-ranker-offline`](https://github.com/garrytan/gbrain-evals/tree/main/docs/benchmarks/2026-11-07-skill-ranker-offline), gate probe | 320 test and gate-stress turns (terse skill requests, long no-skill messages), 250 / 750 / 1,500 skills | dev and stress-dev, at threshold 1.33 | 0.19 / 0.17 / 0.19 | 0.26 / 0.27 / 0.28 (0.515 / 0.555 / 0.611) |-| harness-evals set P dev half, HARN-52 (descriptive) | 146 turns, one 349-skill catalog | the same rows it is scored on, as a raw score of 4.16 (top_gate 0.76 on that catalog) | 0.03 | 0.71 (0.78) |--The first is a held-out score on turns written to break length-based gates;-the second is fitted and scored on the same rows. Treat `top_gate` as a-setting to measure, not one to turn on: the threshold that fits one catalog-and one kind of turn is not known to fit another.+| Gate | No-skill requests that get a block | Skill requests whose acceptable skill is in the block |+|---|---|---|+| off (before) | 61 of 61 (100%) | 176 of 228 (77.2%) |+| 0.5 | 14 of 61 (23.0%) | 175 of 228 (76.8%) |+| **0.6 (default)** | **7 of 61 (11.5%)** | **174 of 228 (76.3%)** |+| 0.7 | 3 of 61 (4.9%) | 166 of 228 (72.8%) |++0.6 is the lowest setting that keeps the no-skill rate at or under 25% on+the set's dev half (5 of 31, against 8 of 31 at 0.55); on the held-out test+half it gives 2 of 30 no-skill blocks and loses 1 of 113 skill requests.+A threshold that fits one catalog and one kind of turn is not known to fit+another. The [gbrain-evals gate probe](https://github.com/garrytan/gbrain-evals/tree/main/docs/benchmarks/2026-11-07-skill-ranker-offline),+on turns written to break length-based gates (terse skill requests, long+no-skill messages), found no threshold that removed false suggestions there+without hiding many right ones. In ordinary use, one-word requests that match only a skill's body, and catalogs+where many skills share the request's words, score lower and are the first+to lose their block. Set `skills.resolver.top_gate` (or+`per_harness.<harness>.top_gate`) to tune it, or to `0` to turn it off.+`gbrain skills resolve` reads only those two keys, and only when neither+`--top-gate` nor the input's `top_gate` is given. A bad value there exits 1+with `skill_resolver_config_invalid`; under `--fail-open` it prints a warning+on stderr and keeps the default.An empty block carries `block_reason`: `ack`, `no_match`, `filtered` (everymatch was excluded or below `min_match_strength`), `weak_top_match` (the bestdiff --git a/docs/schemas/skill-resolver.v1.turn-input.json b/docs/schemas/skill-resolver.v1.turn-input.jsonindex 7767667083..ac6c534668 100644--- a/docs/schemas/skill-resolver.v1.turn-input.json+++ b/docs/schemas/skill-resolver.v1.turn-input.json@@ -74,7 +74,7 @@"type": "number","minimum": 0,"maximum": 100,- "description": "Empty the block (block_reason weak_top_match) when the best skill the block would show (after exclude, min_match_strength, session dedupe and pacing) has a score that, divided by its catalog's maximum idf, ln(1 + (n - 0.5) / 1.5) for n skills, is below this; with merged catalogs, the highest of those candidates. A skill named in the turn bypasses it. Omit it or pass 0 to keep the gate off (the default)."+ "description": "Empty the block (block_reason weak_top_match) when the best skill the block would show (after exclude, min_match_strength, session dedupe and pacing) has a score that, divided by its catalog's maximum idf, ln(1 + (n - 0.5) / 1.5) for n skills, is below this; with merged catalogs, the highest of those candidates. A skill named in the turn bypasses it. Omit it for the default gate of 0.6; pass 0 to turn the gate off."},"reset_session": {"type": "boolean",diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 46f05d7d32..1700216aea 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -383,7 +383,7 @@ test/serve-http-github-webhook.test.ts handler wiring (source pin) 1 source-surftest/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 source-surface-helpertest/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 source-surface-helpertest/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync-test/setup-pi-skill-extension.test.ts (file-level) 6 readFileSync+test/setup-pi-skill-extension.test.ts (file-level) 7 readFileSynctest/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSynctest/shared-skills-catalog.test.ts (file-level) 22 readFileSynctest/shared-skills-export.serial.test.ts (file-level) 15 readFileSyncdiff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.tsindex f6747b5b21..17a17128e3 100644--- a/src/commands/skill-resolver.ts+++ b/src/commands/skill-resolver.ts@@ -24,7 +24,8 @@ import {ResolverError, HARNESSES, errorTurnOutput, GBRAIN_VERSION, type BuildInput, type TurnInput,} from '../core/skills/resolver/index.ts';import { validCatalogName } from '../core/skills/resolver/paths.ts';-import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';+import { readResolverConfig, resolverHarnesses, resolverSection } from '../core/setup/skill-resolver-config.ts';+import { configuredTopGate } from '../core/skills/resolver/config.ts';import { catalogSkillIds, pinProblem, PINS_MAX, readPins, renderPinnedBlock, writePins } from '../core/setup/skill-pins.ts';import { refreshOpenclawPins } from '../core/setup/openclaw-skill-plugin.ts';import { PI_SKILL_CATALOG, refreshPiPins } from '../core/setup/pi-skill-extension.ts';@@ -78,8 +79,8 @@ and no brain connection is needed.stronger matches still fill the block, so it never empties it--top-gate <x> empty the block when the best skill it would show (after--exclude, --min-match and session dedupe) scores below x over its catalog's- maximum word weight (0-100; default off); a skill named in the- turn bypasses it+ maximum word weight (0-100; default skills.resolver.top_gate, else 0.6;+ 0 turns it off); a skill named in the turn bypasses it--shadow compute the block without injecting it (block "" on stdout);--shadow-log <file> appends what would have been injected--expect-catalog <h> refuse with skill_catalog_mismatch unless the catalog hash is h@@ -261,6 +262,17 @@ async function runResolve(args: string[]): Promise<void> {const minMatch = one(p, '--min-match'); if (minMatch !== undefined) input.min_match_strength = minMatch;const topGate = one(p, '--top-gate');if (topGate !== undefined) { if (!/^\d+(\.\d+)?$/.test(topGate)) throw new ResolverError('skill_resolve_invalid_input', '--top-gate takes a number from 0 to 100.', { suggestion: 'Example: --top-gate 1.5' }); input.top_gate = Number(topGate); }+ if (input.top_gate === undefined) {+ const read = readResolverConfig(resolverHome());+ const section = read.state === 'ok' ? resolverSection(read.doc) : {};+ try {+ const configured = configuredTopGate(section, typeof input.harness === 'string' ? input.harness : '');+ if (configured !== undefined) input.top_gate = configured;+ } catch (err) {+ if (!failOpen) throw err;+ console.error(`gbrain skills resolve: ${(err as Error).message}; using the default top_gate.`);+ }+ }if (p.bools.has('--shadow')) input.shadow = true;if (p.bools.has('--reset-session')) input.reset_session = true;const expect = one(p, '--expect-catalog'); if (expect !== undefined) input.expected_catalog_hash = expect;diff --git a/src/core/setup/openclaw-skill-plugin-code.ts b/src/core/setup/openclaw-skill-plugin-code.tsindex 89da7abed7..60332ed73f 100644--- a/src/core/setup/openclaw-skill-plugin-code.ts+++ b/src/core/setup/openclaw-skill-plugin-code.ts@@ -310,7 +310,7 @@ async function resolveTurn(event, ctx, opts) {const w = ensureWorker(s);if (!w) return finish({ outcome: 'error', code: 'skill_resolver_worker_unavailable' });const reset = resetNext.delete(sessionKey);- const input = { message: text, session_id: sessionKey, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, exclude: [...(Array.isArray(a.pinned_ids) ? a.pinned_ids : []), ...(Array.isArray(a.exclude_ids) ? a.exclude_ids : [])].slice(0, 1024), shadow: arm !== 'live', ...(reset ? { reset_session: true } : {}) };+ const input = { message: text, session_id: sessionKey, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, exclude: [...(Array.isArray(a.pinned_ids) ? a.pinned_ids : []), ...(Array.isArray(a.exclude_ids) ? a.exclude_ids : [])].slice(0, 1024), shadow: arm !== 'live', ...(typeof a.top_gate === 'number' ? { top_gate: a.top_gate } : {}), ...(reset ? { reset_session: true } : {}) };const reply = await ask(w, { type: 'resolve', input, catalog: a.catalog, deadlineMs: DEADLINE_MS - 5, floor: a.min_match || null, dirs: a.skill_dirs || [] });if (reply.late) {if (reset) resetNext.add(sessionKey);@@ -399,7 +399,7 @@ export default {if (warm.code) { dropWorker(); return { ok: false, code: warm.code }; }const a = s.agents[agentId];const t0 = Date.now();- const reply = await ask(w, { type: 'resolve', input: { message, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, shadow: true }, catalog: a.catalog, deadlineMs: DEADLINE_MS - 5, floor: a.min_match || null, dirs: [] });+ const reply = await ask(w, { type: 'resolve', input: { message, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, shadow: true, ...(typeof a.top_gate === 'number' ? { top_gate: a.top_gate } : {}) }, catalog: a.catalog, deadlineMs: DEADLINE_MS - 5, floor: a.min_match || null, dirs: [] });dropWorker();if (reply.late) return { ok: false, code: 'skill_resolve_timeout', ms: Date.now() - t0 };if (reply.code && !reply.block) return { ok: false, code: reply.code, ms: Date.now() - t0 };diff --git a/src/core/setup/openclaw-skill-plugin.ts b/src/core/setup/openclaw-skill-plugin.tsindex 119297cbed..49a33a99fb 100644--- a/src/core/setup/openclaw-skill-plugin.ts+++ b/src/core/setup/openclaw-skill-plugin.ts@@ -60,6 +60,8 @@ export interface OpenclawSkillAgentState {skill_dirs: string[];top_k: number;min_match: string;+ /** skills.resolver.top_gate when set (0 turns the gate off); unset leaves the resolver's default. */+ top_gate?: number;/** skills.resolver.pinned: skills OpenClaw loads itself, so they are never suggested. */exclude_ids: string[];live_fraction: number;@@ -235,11 +237,11 @@ export interface OpenclawSkillSyncOptions {}/** The lane's own turn settings for openclaw (per_harness, then the global keys), else the OpenClaw defaults. Throws skill_resolver_config_invalid on a bad value, as every lane does. */-function openclawLaneConfig(home: string): { top_k: number; min_match: string; exclude_ids: string[] } {+function openclawLaneConfig(home: string): { top_k: number; min_match: string; top_gate?: number; exclude_ids: string[] } {const read = readResolverConfig(home);const section = read.state === 'ok' ? (read.doc.skills as { resolver?: Record<string, unknown> } | undefined)?.resolver ?? {} : {};const s = laneTurnSettings(section, 'openclaw');- return { top_k: s.top_k ?? OPENCLAW_TOP_K_DEFAULT, min_match: s.min_match_strength ?? OPENCLAW_FLOOR_DEFAULT, exclude_ids: s.exclude ?? [] };+ return { top_k: s.top_k ?? OPENCLAW_TOP_K_DEFAULT, min_match: s.min_match_strength ?? OPENCLAW_FLOOR_DEFAULT, ...(s.top_gate !== undefined ? { top_gate: s.top_gate } : {}), exclude_ids: s.exclude ?? [] };}/** Turn the plugin on (live or shadow) for some agents, or refresh what is on. Never throws for an expected failure. */@@ -300,7 +302,7 @@ export async function syncOpenclawSkillPlugin(opts: OpenclawSkillSyncOptions): Pconst pins = dryRun ? { block: '', ids: [], unknown: [] as string[] } : pinnedBlockFor(home, catalog, 'openclaw');agents[id] = {mode: opts.mode ?? before?.mode ?? 'live', catalog, skill_dirs: dirs,- top_k: lane.top_k, min_match: lane.min_match, exclude_ids: [...new Set([...lane.exclude_ids, ...hidden])],+ top_k: lane.top_k, min_match: lane.min_match, ...(lane.top_gate !== undefined ? { top_gate: lane.top_gate } : {}), exclude_ids: [...new Set([...lane.exclude_ids, ...hidden])],live_fraction: tune.live_fraction ?? before?.live_fraction ?? 1, pins_route: tune.pins_route ?? before?.pins_route ?? 'system',pinned_block: pins.block, pinned_ids: pins.ids, owner_sender_ids: tune.owner_sender_ids ?? before?.owner_sender_ids ?? [],};diff --git a/src/core/setup/pi-skill-extension-code.ts b/src/core/setup/pi-skill-extension-code.tsindex 9077c36d20..86b3866044 100644--- a/src/core/setup/pi-skill-extension-code.ts+++ b/src/core/setup/pi-skill-extension-code.ts@@ -196,7 +196,7 @@ async function beforeAgentStart(event, ctx) {const hidden = hiddenFrom(event, s);const exclude = [...(Array.isArray(s.pinned_ids) ? s.pinned_ids : []), ...(Array.isArray(s.exclude_ids) ? s.exclude_ids : []), ...hidden].slice(0, 1024);const deadline = warm ? DEADLINE_MS : COLD_DEADLINE_MS;- const input = { message: text, session_id: key, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, exclude, ...(reset ? { reset_session: true } : {}) };+ const input = { message: text, session_id: key, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, exclude, ...(typeof s.top_gate === 'number' ? { top_gate: s.top_gate } : {}), ...(reset ? { reset_session: true } : {}) };const reply = await ask(w, { type: 'resolve', input, catalog: s.catalog, deadlineMs: deadline - 5, floor: s.min_match || null, dirs: s.skill_dirs || [] }, deadline);if (reply.late) {if (reset) resetNext.add(key);@@ -235,7 +235,7 @@ export async function selfTest(message) {});if (warmed.code) { dropWorker(); return { ok: false, code: warmed.code }; }const t0 = Date.now();- const reply = await ask(w, { type: 'resolve', input: { message, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, shadow: true }, catalog: s.catalog, deadlineMs: 1000, floor: s.min_match || null, dirs: [] }, 2000);+ const reply = await ask(w, { type: 'resolve', input: { message, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, shadow: true, ...(typeof s.top_gate === 'number' ? { top_gate: s.top_gate } : {}) }, catalog: s.catalog, deadlineMs: 1000, floor: s.min_match || null, dirs: [] }, 2000);dropWorker();if (reply.late) return { ok: false, code: 'skill_resolve_timeout', ms: Date.now() - t0 };if (reply.code && !reply.block) return { ok: false, code: reply.code, ms: Date.now() - t0 };diff --git a/src/core/setup/pi-skill-extension.ts b/src/core/setup/pi-skill-extension.tsindex 2011afca22..02b9cd047d 100644--- a/src/core/setup/pi-skill-extension.ts+++ b/src/core/setup/pi-skill-extension.ts@@ -47,7 +47,7 @@ export const PI_NO_EXTENSIONS_NOTE = 'Pi started with extensions off (pi --no-exexport interface PiSkillState {v: 1; gbrain_version: string; library_sha256: string; mode: 'live'; catalog: string; skill_dirs: string[];- top_k: number; min_match: string; exclude_ids: string[]; pinned_block: string; pinned_ids: string[]; catalog_ids: string[];+ top_k: number; min_match: string; top_gate?: number; exclude_ids: string[]; pinned_block: string; pinned_ids: string[]; catalog_ids: string[];}export interface PiSkillStep { step: 'catalog' | 'library' | 'state' | 'extension' | 'self-test' | 'verify'; action: 'write' | 'keep' | 'remove' | 'skip' | 'run'; detail: string }export interface PiSkillResult {@@ -121,12 +121,12 @@ export async function syncPiSkillExtension(opts: PiSkillSyncOptions): Promise<Piif (!opts.gbrainBin.startsWith('/')) return fail('skill_resolver_setup_incomplete', 'No absolute gbrain binary was found for the extension (Pi may start with no PATH that has gbrain); pass --gbrain-bin. Nothing was written.');const dirs = piSkillDirs();if (dirs.length === 0) return fail('skill_resolver_setup_incomplete', `No Pi skill directory exists (looked for ${join(piAgentDir(), 'skills')} and ${join(home0(), '.agents', 'skills')}). Add a skill to one of them, then run setup again. Nothing was written.`);- let lane: { top_k: number; min_match: string; exclude_ids: string[] };+ let lane: { top_k: number; min_match: string; top_gate?: number; exclude_ids: string[] };try {const read = readResolverConfig(home);const section = read.state === 'ok' ? (read.doc.skills as { resolver?: Record<string, unknown> } | undefined)?.resolver ?? {} : {};const s = laneTurnSettings(section, 'pi');- lane = { top_k: s.top_k ?? TOP_K_DEFAULT, min_match: s.min_match_strength ?? FLOOR_DEFAULT, exclude_ids: s.exclude ?? [] };+ lane = { top_k: s.top_k ?? TOP_K_DEFAULT, min_match: s.min_match_strength ?? FLOOR_DEFAULT, ...(s.top_gate !== undefined ? { top_gate: s.top_gate } : {}), exclude_ids: s.exclude ?? [] };} catch (e) {if (e instanceof ResolverError && e.code === 'skill_resolver_config_invalid') return fail('skill_resolver_config_invalid', `${e.message} Nothing was written.`);throw e;@@ -165,7 +165,7 @@ export async function syncPiSkillExtension(opts: PiSkillSyncOptions): Promise<Pi}out.steps.push({ step: 'library', action: lib.wrote ? 'write' : 'keep', detail: lib.path });const state: PiSkillState = { v: 1, gbrain_version: VERSION, library_sha256: lib.sha256, mode: 'live', catalog, skill_dirs: dirs, top_k: lane.top_k, min_match: lane.min_match,- exclude_ids: lane.exclude_ids, pinned_block: pins.block, pinned_ids: pins.ids, catalog_ids: ids.slice(0, CATALOG_IDS_MAX) };+ ...(lane.top_gate !== undefined ? { top_gate: lane.top_gate } : {}), exclude_ids: lane.exclude_ids, pinned_block: pins.block, pinned_ids: pins.ids, catalog_ids: ids.slice(0, CATALOG_IDS_MAX) };const stateText = `${JSON.stringify(state, null, 2)}\n`;const stateChanged = (() => { try { return readFileSync(piSkillStatePath(home), 'utf8') !== stateText; } catch { return true; } })();if (stateChanged) { mkdirSync(home, { recursive: true }); atomicWriteTextFile(piSkillStatePath(home), stateText, { freshMode: 0o600 }); }diff --git a/src/core/skills/resolver/config.ts b/src/core/skills/resolver/config.tsindex db9fd8b177..20d8783fd9 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.top_gate empty the block when the best skill it would- * show scores below this over its catalog's maxIdf (0..100; default off)+ * show scores below this over its catalog's maxIdf (0..100, 0 is off;+ * default TOP_GATE_DEFAULT)* skills.resolver.per_harness.<harness>.{top_k,min_match,top_gate} overrides* 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@@ -36,7 +37,7 @@ import { readFileSync, statSync } from 'node:fs';import { join, resolve } from 'node:path';import { HARNESSES } from './block.ts';import { ResolverError } from './errors.ts';-import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, TOP_GATE_MAX, TOP_K_MAX } from './limits.ts';+import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, TOP_GATE_DEFAULT, TOP_GATE_MAX, TOP_K_MAX } from './limits.ts';export const DEFAULT_SESSION_TOKEN_BUDGET = 2000;export const MIN_SESSION_TOKEN_BUDGET = 100;@@ -94,7 +95,7 @@ export function validateMinMatch(v: unknown, key: string): MatchStrength {export function validateTopGate(v: unknown, key: string): number {if (typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= TOP_GATE_MAX) return v;- throw configInvalid(key, `must be a number from 0 to ${TOP_GATE_MAX} (0 or unset: off)`);+ throw configInvalid(key, `must be a number from 0 to ${TOP_GATE_MAX} (0: off; unset: ${TOP_GATE_DEFAULT})`);}export function validateSkillDirs(v: unknown, key: string): string[] {@@ -115,6 +116,15 @@ export function validatePinned(v: unknown, key: string): string[] {throw configInvalid(key, `must be a list of at most ${EXCLUDE_MAX} skill ids`);}+/** The top_gate configured for `harness` (its per_harness key, else the global one), or undefined when neither is set. Reads and validates only those two keys, so a bad value elsewhere in the section never affects it. Throws skill_resolver_config_invalid on a bad top_gate. */+export function configuredTopGate(section: Record<string, unknown>, harness: string): number | undefined {+ const per = section.per_harness;+ const mine = harness && per && typeof per === 'object' && !Array.isArray(per) ? (per as Record<string, unknown>)[harness] : undefined;+ const own = mine && typeof mine === 'object' && !Array.isArray(mine) ? (mine as Record<string, unknown>).top_gate : undefined;+ if (own !== undefined) return validateTopGate(own, `skills.resolver.per_harness.${harness}.top_gate`);+ return section.top_gate === undefined ? undefined : validateTopGate(section.top_gate, 'skills.resolver.top_gate');+}+/** The turn settings the lane uses for `harness`: its per_harness keys, else the global ones. Throws skill_resolver_config_invalid on a bad value anywhere in the section. */export function laneTurnSettings(section: Record<string, unknown>, harness: string): LaneTurnSettings {const p = 'skills.resolver.';diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.tsindex 03b16bd666..db27bd0144 100644--- a/src/core/skills/resolver/hook-lane.ts+++ b/src/core/skills/resolver/hook-lane.ts@@ -64,8 +64,8 @@** Turn settings: skills.resolver.top_k, min_match, top_gate, pinned (sent as* exclude) and per_harness.<harness>.{top_k,min_match,top_gate} (config.ts- * laneTurnSettings); unset, a turn is top_k 5 with every match, no gate and- * nothing excluded.+ * laneTurnSettings); unset, a turn is top_k 5 with every match, the resolver's+ * default top_gate (TOP_GATE_DEFAULT; 0 turns it off) and nothing excluded.** Payload: the lane's own budget (skills.resolver.lane_payload_chars, default* 4000 characters of hook JSON, Hermes's included); a block that does not fitdiff --git a/src/core/skills/resolver/limits.ts b/src/core/skills/resolver/limits.tsindex 7e53200e00..25d06d4ded 100644--- a/src/core/skills/resolver/limits.ts+++ b/src/core/skills/resolver/limits.ts@@ -6,8 +6,13 @@export const TOP_K_DEFAULT = 5;export const TOP_K_MAX = 8;export const EXCLUDE_MAX = 1024;-/** top_gate's upper bound; 0 (or unset) turns the gate off. */+/** top_gate's upper bound; 0 turns the gate off. */export const TOP_GATE_MAX = 100;+/**+ * The gate a turn gets when it sets no top_gate: chosen on harness-evals+ * set P's dev half and checked on its held-out half (docs/guides/skill-resolver.md#top_gate-the-no-skill-gate-on-by-default).+ */+export const TOP_GATE_DEFAULT = 0.6;/** The strongest way a suggestion matched the turn: named in it, then by field. A body-only match is the weakest. */export type MatchStrength = 'named' | 'name' | 'triggers' | 'routing' | 'description' | 'body';diff --git a/src/core/skills/resolver/rank.ts b/src/core/skills/resolver/rank.tsindex bf62f13a39..23bbac71af 100644--- a/src/core/skills/resolver/rank.ts+++ b/src/core/skills/resolver/rank.ts@@ -7,8 +7,10 @@* matched terms, ties broken by name then id, so a ranking equals the* prototype's on the same records.*- * There is no score threshold. A turn gets no skill only when it is a known- * acknowledgement (ack) or none of its terms is in the index (no_match).+ * The ranker has no score threshold: no_skill is set only for a known+ * acknowledgement (ack) or when none of the turn's terms is in the index+ * (no_match). resolve.ts's top_gate, on by default, empties a block whose+ * best skill scores below it over maxIdf.*/import { FIELDS, type IndexReader } from './index-format.ts';import { lexTerms } from './tokenize.ts';diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.tsindex 5aa265eb20..de6621c64d 100644--- a/src/core/skills/resolver/resolve.ts+++ b/src/core/skills/resolver/resolve.ts@@ -21,8 +21,8 @@** min_match_strength drops weaker matches before the cut to k, so a floor* never shrinks the block below what the stronger matches fill: it filters- * candidates and does not gate the block. top_gate (off unless set) does:- * when the best skill the block would show (after exclude,+ * candidates and does not gate the block. top_gate (TOP_GATE_DEFAULT unless+ * set; 0 turns it off) does: when the best skill the block would show (after exclude,* min_match_strength, session dedupe and pacing) scores below it over its* catalog's maxIdf, the block is empty (block_reason weak_top_match), unless* the turn names a skill. A message that matches no catalog word falls back to@@ -39,7 +39,7 @@ import { readResolverSettings, type ResolverSettings, validateSessionTokenBudgetimport { ResolverError } from './errors.ts';import { appendDailyLogSync, RESOLVER_LOG } from './daily-log.ts';import { ensureDir, writeFileAtomic } from './fsutil.ts';-import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, STRENGTH_FIELDS, TOP_GATE_MAX, TOP_K_DEFAULT, TOP_K_MAX } from './limits.ts';+import { EXCLUDE_MAX, MATCH_STRENGTHS, type MatchStrength, STRENGTH_FIELDS, TOP_GATE_DEFAULT, TOP_GATE_MAX, TOP_K_DEFAULT, TOP_K_MAX } from './limits.ts';import { IndexReader, RANKER_ID, RANKER_VERSION } from './index-format.ts';import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';import { isAcknowledgement, maxIdf, mentionsSkill, rankIndex, reasonText, type RankResult } from './rank.ts';@@ -159,7 +159,7 @@ export function normalizeTurnInput(raw: unknown): Required<Pick<TurnInput, 'messif (o.shadow !== undefined && typeof o.shadow !== 'boolean') throw invalid('shadow must be a boolean.', 'Pass true or false.');if (o.reset_session !== undefined && typeof o.reset_session !== 'boolean') throw invalid('reset_session must be a boolean.', 'Pass true on the first turn after a compaction.');if (o.min_match_strength !== undefined && !(MATCH_STRENGTHS as readonly unknown[]).includes(o.min_match_strength)) throw invalid(`min_match_strength must be one of ${MATCH_STRENGTHS.join(', ')}.`, 'Omit it to keep every match, or pass description to drop body-only matches.');- if (o.top_gate !== undefined && (typeof o.top_gate !== 'number' || !Number.isFinite(o.top_gate) || o.top_gate < 0 || o.top_gate > TOP_GATE_MAX)) throw invalid(`top_gate must be a number from 0 to ${TOP_GATE_MAX}.`, 'Omit it (or pass 0) to keep the gate off.');+ if (o.top_gate !== undefined && (typeof o.top_gate !== 'number' || !Number.isFinite(o.top_gate) || o.top_gate < 0 || o.top_gate > TOP_GATE_MAX)) throw invalid(`top_gate must be a number from 0 to ${TOP_GATE_MAX}.`, 'Omit it for the default gate, or pass 0 to turn the gate off.');if (o.expected_catalog_hash !== undefined && (typeof o.expected_catalog_hash !== 'string' || !/^[0-9a-f]{64}$/.test(o.expected_catalog_hash))) throw invalid('expected_catalog_hash must be a sha256 hex string.', 'Pass the catalog_hash from the build receipt.');return {message: capUtf8(o.message, MESSAGE_CAP_BYTES),@@ -172,7 +172,7 @@ export function normalizeTurnInput(raw: unknown): Required<Pick<TurnInput, 'messreset_session: o.reset_session === true,...(o.expected_catalog_hash !== undefined ? { expected_catalog_hash: o.expected_catalog_hash as string } : {}),...(o.min_match_strength !== undefined ? { min_match_strength: o.min_match_strength as MatchStrength } : {}),- ...(o.top_gate ? { top_gate: o.top_gate as number } : {}),+ ...(o.top_gate === undefined ? { top_gate: TOP_GATE_DEFAULT } : o.top_gate ? { top_gate: o.top_gate as number } : {}),};}diff --git a/test/openclaw-skill-plugin.test.ts b/test/openclaw-skill-plugin.test.tsindex ed654af29d..2c311e65f6 100644--- a/test/openclaw-skill-plugin.test.ts+++ b/test/openclaw-skill-plugin.test.ts@@ -196,6 +196,31 @@ describe.skipIf(!NODE)('gbrain setup openclaw --skill-loading', () => {expect(out[0].appendContext).not.toContain('email-triage');});+ test('skills.resolver.top_gate reaches the plugin: a gate of 100 empties the block, and a gate of 0 (the opt-out) is kept and shows a weak match the default gate hides', async () => {+ const b = box();+ mkdirSync(gbrainHome(b), { recursive: true });+ writeFileSync(join(gbrainHome(b), 'config.json'), JSON.stringify({ skills: { resolver: { per_harness: { openclaw: { top_gate: 100 } } } } }));+ expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(readState(b).agents.main).toMatchObject({ top_gate: 100 });+ const out = drive(b, [['turn', { text: 'deploy the service to production', id: 'g1' }]]);+ expect(out[0]?.appendContext ?? '').not.toContain('deploy-service');++ const off = box();+ mkdirSync(gbrainHome(off), { recursive: true });+ writeFileSync(join(gbrainHome(off), 'config.json'), JSON.stringify({ skills: { resolver: { top_gate: 0 } } }));+ expect((await setup(off, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(readState(off).agents.main).toMatchObject({ top_gate: 0 });+ const weak = 'what runs in production today';+ const shown = drive(off, [['turn', { text: weak, id: 'g2' }]]);+ expect(shown[0]?.appendContext ?? '').toContain('deploy-service');++ const dflt = box();+ expect((await setup(dflt, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(readState(dflt).agents.main.top_gate).toBeUndefined();+ const gated = drive(dflt, [['turn', { text: weak, id: 'g3' }]]);+ expect(gated[0]?.appendContext ?? '').not.toContain('deploy-service');+ });+test('--dry-run writes nothing', async () => {const b = box();const r = await setup(b, ['--skill-loading', 'resolve', '--dry-run']);diff --git a/test/setup-pi-skill-extension.test.ts b/test/setup-pi-skill-extension.test.tsindex c4f97afbc9..62587fcd95 100644--- a/test/setup-pi-skill-extension.test.ts+++ b/test/setup-pi-skill-extension.test.ts@@ -121,6 +121,24 @@ describe.skipIf(!NODE)('gbrain setup pi --skill-loading', () => {expect(again.resolver.steps.find((s: any) => s.step === 'extension')).toMatchObject({ action: 'keep' });});+ test('skills.resolver.top_gate reaches the extension: a gate of 100 leaves the suggestion out, and a gate of 0 (the opt-out) is kept', async () => {+ const b = box();+ mkdirSync(gbrainHome(b), { recursive: true });+ writeFileSync(join(gbrainHome(b), 'config.json'), JSON.stringify({ skills: { resolver: { per_harness: { pi: { top_gate: 100 } } } } }));+ expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(readState(b)).toMatchObject({ top_gate: 100 });+ const out = drive(b, [['start', {}], ['run', { prompt: 'deploy the service to production', skills: [{ name: 'deploy-service', disableModelInvocation: false }] }], ['flush', {}]]);+ expect(JSON.stringify(out[2])).not.toContain('deploy-service');++ const off = box();+ mkdirSync(gbrainHome(off), { recursive: true });+ writeFileSync(join(gbrainHome(off), 'config.json'), JSON.stringify({ skills: { resolver: { top_gate: 0 } } }));+ expect((await setup(off, ['--skill-loading', 'resolve'])).exitCode).toBe(0);+ expect(readState(off)).toMatchObject({ top_gate: 0 });+ const shown = drive(off, [['start', {}], ['run', { prompt: 'deploy the service to production', skills: [{ name: 'deploy-service', disableModelInvocation: false }] }], ['flush', {}]]);+ expect(JSON.stringify(shown[2])).toContain('deploy-service');+ });+test('the extension: one hidden message with paths, pins as a system section every run, nothing on custom runs, never a pinned or hidden skill, dedupe until session_compact', async () => {const b = box();expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);diff --git a/test/skill-resolver-catalogs.test.ts b/test/skill-resolver-catalogs.test.tsindex cbd23c9020..717f4f9a6a 100644--- a/test/skill-resolver-catalogs.test.ts+++ b/test/skill-resolver-catalogs.test.ts@@ -66,7 +66,7 @@ describe('OpenClaw skills list --json', () => {expect(rec.catalog.skill_count).toBe(2);expect(rec.catalog.source).toMatchObject({ kind: 'json', dirs: [root] });expect(rec.build.rebuild_argv).toEqual(['gbrain', 'skills', 'index', 'build', '--catalog', 'oc', '--dir', root, '--from-json', file, '--harness', 'openclaw']);- const t = await resolveSkills({ message: 'zebrafinch rollout' }, { home, catalogs: ['oc'] });+ const t = await resolveSkills({ message: 'zebrafinch rollout', top_gate: 0 }, { home, catalogs: ['oc'] });expect(t.output.suggestions.map((s) => [s.id, s.path])).toEqual([['deploy-widget', path]]);expect((await resolveSkills({ message: 'not listed skill' }, { home, catalogs: ['oc'] })).output.suggestions.map((s) => s.id)).not.toContain('not-listed');expect((await catalogStatus('oc', { home })).fresh).toBe(true);diff --git a/test/skill-resolver-cli.test.ts b/test/skill-resolver-cli.test.tsindex 269c2c3e0e..185ec4e7a8 100644--- a/test/skill-resolver-cli.test.ts+++ b/test/skill-resolver-cli.test.ts@@ -127,13 +127,53 @@ describe('gbrain skills (CLI)', () => {expect(cli(h, ['skills', 'index', 'build', '--catalog', 'c', '--from-json', '-'], SKILLS).code).toBe(0);writeFileSync(join(gb, 'config.json'), JSON.stringify({ remote_mcp: { issuer_url: 'https://brain.example.invalid', mcp_url: 'https://brain.example.invalid/mcp' } }));const log = join(h, 'shadow.jsonl');- const r = cli(h, ['skills', 'resolve', '--text', 'deploy', '--shadow', '--shadow-log', log, '--session', 'x']);+ const r = cli(h, ['skills', 'resolve', '--text', 'deploy', '--top-gate', '0', '--shadow', '--shadow-log', log, '--session', 'x']);expect([r.code, r.out]).toEqual([0, '']);const rec = JSON.parse(readFileSync(log, 'utf8').trim());expect(rec.shadow).toBe(true);expect(rec.block).toContain('gbrain:deploy');}, 60_000);+ test('with no --top-gate, a request that only matches skill bodies weakly gets no block (exit 0, weak_top_match) on a brainless, repo-less home; skills.resolver.top_gate and per_harness override the default, and --top-gate overrides both', () => {+ const h = tmp();+ const skills = JSON.stringify([+ { id: 'x:dinner-split', name: 'dinner-split', description: 'Split a restaurant bill between friends' },+ { id: 'x:deploy', name: 'deploy', description: 'Deploy the service to staging and production', body: 'Run each step in order. Ask the person who owns the service before production.' },+ ]);+ expect(cli(h, ['skills', 'index', 'build', '--catalog', 'c', '--from-json', '-'], skills).code).toBe(0);+ const quiet = cli(h, ['skills', 'resolve', '--text', 'how much does each person owe', '--harness', 'codex', '--json']);+ const doc = JSON.parse(quiet.out);+ expect(validate(loadSchema('skill-resolver.v1.turn-output'), doc)).toEqual([]);+ expect([quiet.code, doc.block, doc.block_reason]).toEqual([0, '', 'weak_top_match']);+ expect(cli(h, ['skills', 'resolve', '--text', 'how much does each person owe']).out).toBe('');+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'split the restaurant bill', '--json']).out).block).toContain('x:dinner-split');+ writeFileSync(join(h, '.gbrain', 'config.json'), JSON.stringify({ skills: { resolver: { per_harness: { codex: { top_gate: 0 } } } } }));+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'how much does each person owe', '--harness', 'codex', '--json']).out).block).toContain('x:deploy');+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'how much does each person owe', '--json']).out).block_reason).toBe('weak_top_match');+ writeFileSync(join(h, '.gbrain', 'config.json'), JSON.stringify({ skills: { resolver: { top_gate: 0 } } }));+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'how much does each person owe', '--json']).out).block).toContain('x:deploy');+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'how much does each person owe', '--top-gate', '100', '--json']).out).block_reason).toBe('weak_top_match');+ }, 60_000);++ test('skills resolve reads only the top_gate keys from config: an invalid unrelated skills.resolver key changes nothing, and an invalid top_gate exits 1, or under --fail-open keeps the default and says so on stderr', () => {+ const h = tmp();+ expect(cli(h, ['skills', 'index', 'build', '--catalog', 'c', '--from-json', '-'], SKILLS).code).toBe(0);+ const cfg = join(h, '.gbrain', 'config.json');+ writeFileSync(cfg, JSON.stringify({ skills: { resolver: { top_k: 99, pinned: 'oops', min_match: 'loud', per_harness: { nosuch: {}, codex: { top_k: 'x' } } } } }));+ for (const extra of [[], ['--top-k', '3'], ['--harness', 'codex'], ['--fail-open']]) {+ const r = cli(h, ['skills', 'resolve', '--text', 'deploy the service to production', '--json', ...extra]);+ const doc = JSON.parse(r.out);+ expect({ extra, code: r.code, error: doc.error ?? null, deploy: doc.block.includes('gbrain:deploy'), warned: r.err.includes('top_gate') }).toEqual({ extra, code: 0, error: null, deploy: true, warned: false });+ }+ writeFileSync(cfg, JSON.stringify({ skills: { resolver: { top_k: 99, top_gate: 100 } } }));+ expect(JSON.parse(cli(h, ['skills', 'resolve', '--text', 'deploy the service to production', '--json']).out).block_reason).toBe('weak_top_match');+ writeFileSync(cfg, JSON.stringify({ skills: { resolver: { top_gate: 'high' } } }));+ const strict = cli(h, ['skills', 'resolve', '--text', 'deploy the service to production', '--json']);+ expect([strict.code, JSON.parse(strict.out).error?.code ?? JSON.parse(strict.out).error]).toEqual([1, 'skill_resolver_config_invalid']);+ const open = cli(h, ['skills', 'resolve', '--text', 'deploy the service to production', '--json', '--fail-open']);+ expect([open.code, JSON.parse(open.out).block.includes('gbrain:deploy'), open.err.includes('skills.resolver.top_gate')]).toEqual([0, true, true]);+ }, 60_000);+test('--top-gate empties the block with block_reason weak_top_match, and the output validates', () => {const h = tmp();expect(cli(h, ['skills', 'index', 'build', '--catalog', 'c', '--from-json', '-'], SKILLS).code).toBe(0);diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.tsindex 8048a63f67..6148682882 100644--- a/test/skill-resolver-hook-lane.test.ts+++ b/test/skill-resolver-hook-lane.test.ts@@ -227,6 +227,7 @@ describe('skill-resolver lane: turn settings from config', () => {await setup(b, 'claude-code');await setup(b, 'codex');const claude = wired(b, 'claude-code'), codex = wired(b, 'codex');+ expect((await config(b, 'set', 'skills.resolver.top_gate', '0')).exitCode).toBe(0);const ids = (r: Run) => [...contextOf(r).matchAll(/id: "([^"]+)"/g)].map((m) => m[1]);const ask = (cmd: string, s: string) => hook(b, cmd, { prompt: 'deploy the widget service', session_id: s, hook_event_name: 'UserPromptSubmit' }, WIDE);expect(ids(await ask(claude, 'd1')).length).toBeGreaterThanOrEqual(3);@@ -397,6 +398,7 @@ describe('skill-resolver lane: fail open', () => {await setup(b, 'claude-code');const set = await runCli(['config', 'set', 'skills.resolver.lane_payload_chars', '500'], { env: b.env, cwd: b.project });expect(set.exitCode, set.stderr).toBe(0);+ expect((await runCli(['config', 'set', 'skills.resolver.top_gate', '0'], { env: b.env, cwd: b.project })).exitCode).toBe(0);const r = await hook(b, wired(b, 'claude-code'), { prompt: 'deploy the widget please', session_id: 's' }, WIDE);expect(r).toMatchObject({ exitCode: 0, stdout: '' });const last = laneLog(b).at(-1);diff --git a/test/skill-resolver-reproduction.test.ts b/test/skill-resolver-reproduction.test.tsindex 866dc47e3c..0fbfa2d4c3 100644--- a/test/skill-resolver-reproduction.test.ts+++ b/test/skill-resolver-reproduction.test.ts@@ -45,7 +45,7 @@ const G = JSON.parse(gunzipSync(readFileSync(join(import.meta.dir, 'fixtures/skiasync function topFive(home: string, catalog: string, turns: { id: string; text: string }[]): Promise<Record<string, string[]>> {const out: Record<string, string[]> = {};for (const t of turns) {- const r = await resolveSkills({ message: t.text, top_k: 5 }, { home, catalogs: [catalog], sessionTokenBudget: 50_000 });+ const r = await resolveSkills({ message: t.text, top_k: 5, top_gate: 0 }, { home, catalogs: [catalog], sessionTokenBudget: 50_000 });out[t.id] = r.output.suggestions.map(s => s.id);}return out;diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.tsindex 1081333be3..73b6fa113f 100644--- a/test/skill-resolver.test.ts+++ b/test/skill-resolver.test.ts@@ -31,6 +31,7 @@ import { catalogFile } from '../src/core/skills/resolver/paths.ts';import { appendDailyLog, appendDailyLogSync, DAILY_LOG_DAY_CAP_BYTES, dailyLogFile, LANE_LOG, readRecentDailyLog, RESOLVER_LOG } from '../src/core/skills/resolver/daily-log.ts';import { EXCLUDE_MAX, STAT_CHECK_SLICE } from '../src/core/skills/resolver/resolve.ts';import { RACY_MTIME_MS } from '../src/core/skills/resolver/build.ts';+import { TOP_GATE_DEFAULT } from '../src/core/skills/resolver/limits.ts';const scratch: string[] = [];afterAll(() => { for (const d of scratch) rmSync(d, { recursive: true, force: true }); });@@ -93,7 +94,7 @@ describe('turn rules', () => {{ id: 'x:delta', name: 'delta', description: 'Other work', body: 'Step one: check the zorvek dashboard.' },{ id: 'x:zorvek', name: 'zorvek', description: 'Other work' },]);- const r = await resolveSkills({ message: 'zorvek', top_k: 8 }, { home });+ const r = await resolveSkills({ message: 'zorvek', top_k: 8, top_gate: 0 }, { home });const by = Object.fromEntries(r.output.suggestions.map(s => [s.id, s.match_strength]));expect(by).toEqual({ 'x:zorvek': 'name', 'x:beta': 'triggers', 'x:gamma': 'routing', 'x:alpha': 'description', 'x:delta': 'body' });const named = await resolveSkills({ message: 'use the delta skill for zorvek' }, { home });@@ -106,9 +107,9 @@ describe('turn rules', () => {...Array.from({ length: 6 }, (_, i) => ({ id: `x:desc-${i}`, name: `desc-${i}`, description: `Rotate the zorvek keys, part ${i}`, triggers: ['unrelated chore'] })),{ id: 'x:route', name: 'route', description: 'Other work', routing: ['zorvek'] },]);- const all = await resolveSkills({ message: 'rotate the zorvek keys', top_k: 2 }, { home });+ const all = await resolveSkills({ message: 'rotate the zorvek keys', top_k: 2, top_gate: 0 }, { home });expect(all.output.suggestions.map(s => s.match_strength)).toEqual(['description', 'description']);- const floored = await resolveSkills({ message: 'rotate the zorvek keys', top_k: 2, min_match_strength: 'routing', session_id: 'f' }, { home });+ const floored = await resolveSkills({ message: 'rotate the zorvek keys', top_k: 2, min_match_strength: 'routing', session_id: 'f', top_gate: 0 }, { home });expect(floored.output.suggestions.map(s => [s.id, s.match_strength])).toEqual([['x:route', 'routing']]);expect(floored.pending!.delta.suggested).toEqual(['x:route']);const strict = await resolveSkills({ message: 'rotate the zorvek keys', min_match_strength: 'name' }, { home });@@ -117,7 +118,7 @@ describe('turn rules', () => {expect(named.output.suggestions.map(s => s.id)).toEqual(['x:desc-3']);});- test('top_gate empties the block when the best skill scores below it over its catalog maxIdf; off by default and at 0, a named skill bypasses it, nothing gated is committed', async () => {+ test('top_gate empties the block when the best skill scores below it over its catalog maxIdf; off at 0, a named skill bypasses it, nothing gated is committed', async () => {const home = tmp();await jsonCatalog(home, 'c', BASIC);const open = await resolveSkills({ message: 'team status', session_id: 'g' }, { home });@@ -132,6 +133,24 @@ describe('turn rules', () => {expect(named.output.suggestions[0]).toMatchObject({ id: 'gbrain:deploy', match_strength: 'named' });});+ test('the gate is on by default: a turn whose best skill only matches weakly gets no block (weak_top_match), top_gate 0 turns it off, a named skill still bypasses it', async () => {+ const home = tmp();+ await jsonCatalog(home, 'c', [+ { id: 'x:dinner-split', name: 'dinner-split', description: 'Split a restaurant bill between friends' },+ { id: 'x:release-notes', name: 'release-notes', description: 'Write release notes for a software version', body: 'Collect the merged changes. Each person on the team reviews the draft before it ships.' },+ { id: 'x:deploy', name: 'deploy', description: 'Deploy the service to staging and production', body: 'Run each step in order. Ask the person who owns the service before production.' },+ ]);+ const weak = 'how much does each person owe';+ const off = await resolveSkills({ message: weak, top_gate: 0 }, { home });+ expect(off.output.suggestions.length).toBeGreaterThan(0);+ expect(off.output.suggestions[0]!.score / maxIdf(3)).toBeLessThan(TOP_GATE_DEFAULT);+ const gated = await resolveSkills({ message: weak, session_id: 'd' }, { home });+ expect([gated.output.block, gated.output.suggestions, gated.output.block_reason, gated.output.no_skill]).toEqual(['', [], 'weak_top_match', false]);+ expect(gated.pending!.delta.suggested).toEqual([]);+ expect((await resolveSkills({ message: 'split the restaurant bill' }, { home })).output.suggestions[0]!.id).toBe('x:dinner-split');+ expect((await resolveSkills({ message: 'how much does each person owe with the deploy skill' }, { home })).output.suggestions[0]).toMatchObject({ id: 'x:deploy', match_strength: 'named' });+ });+test('top_gate reads the best skill the block would show: an excluded top skill does not open it, and an empty window stays filtered', async () => {const home = tmp();await jsonCatalog(home, 'c', BASIC);@@ -197,7 +216,7 @@ describe('turn rules', () => {const skills = Array.from({ length: 1100 }, (_, i) => ({ id: `x:s${i}`, name: `s${i}`, description: `Rotate the zorvek keys step ${i}` }));await jsonCatalog(home, 'c', skills);const exclude = skills.slice(0, EXCLUDE_MAX).map(s => s.id);- const r = await resolveSkills({ message: 'rotate zorvek keys', exclude, top_k: 3 }, { home });+ const r = await resolveSkills({ message: 'rotate zorvek keys', exclude, top_k: 3, top_gate: 0 }, { home });expect(r.output.suggestions).toHaveLength(3);for (const s of r.output.suggestions) expect(exclude).not.toContain(s.id);});@@ -220,10 +239,10 @@ describe('turn rules', () => {expect(cjk.output.suggestions[0]!.id).toBe('x:minutes');});- test('a weak match is still suggested: there is no score threshold', async () => {+ test('with the gate off (top_gate 0), a weak match is still suggested: the ranker itself has no score threshold', async () => {const home = tmp();await jsonCatalog(home, 'c', BASIC);- const r = await resolveSkills({ message: 'something about a team offsite and nothing else' }, { home });+ const r = await resolveSkills({ message: 'something about a team offsite and nothing else', top_gate: 0 }, { home });expect(r.output.no_skill).toBe(false);expect(r.output.suggestions.map(s => s.id)).toEqual(['gbrain:reports']);expect(r.output.suggestions[0]!.reason).toBe('description: team');@@ -330,7 +349,7 @@ describe('sessions', () => {for (let t = 1; t <= 50; t++) {const s = strong.indexOf(t);const message = s >= 0 ? `can you ${targets[s]!.name} this` : `${pool[t % 12]} ${pool[(t + 5) % 12]}`;- const r = await resolveSkills({ message, session_id: 'fifty' }, { home });+ const r = await resolveSkills({ message, session_id: 'fifty', top_gate: 0 }, { home });perTurn.push({ turn: t, n: r.output.suggestions.length, tokens: r.output.block_tokens });expect(await r.commit()).toBe(true);}@@ -550,12 +569,12 @@ describe('block', () => {await buildSkillIndex({ catalog: 'c', dirs: [root] }, { home });const lines: Record<string, string> = { 'claude-code': 'Skill tool', 'codex': 'open the SKILL.md at its path', 'hermes': 'skill_view(name)', 'openclaw': 'skills_read({name}) using its name', 'qm': 'action read', 'pi': 'read the SKILL.md at its path', 'cursor': 'read the SKILL.md at its path' };for (const [h, needle] of Object.entries(lines)) {- const r = await resolveSkills({ message: 'deploy acme-example-secret-words', harness: h }, { home });+ const r = await resolveSkills({ message: 'deploy acme-example-secret-words', harness: h, top_gate: 0 }, { home });expect(r.output.block).toContain(needle);expect(r.output.block).not.toContain('acme-example-secret-words');expect(r.output.block.includes(JSON.stringify(p))).toBe(['codex', 'openclaw', 'pi', 'cursor'].includes(h));}- const custom = await resolveSkills({ message: 'deploy' }, { home, loadHint: 'Load it with my_loader <now>' });+ const custom = await resolveSkills({ message: 'deploy', top_gate: 0 }, { home, loadHint: 'Load it with my_loader <now>' });expect(custom.output.block).toContain('Load it with my_loader now');expect(custom.output.suggestions[0]!.path).toBe(p);});@@ -625,7 +644,7 @@ describe('block', () => {skillDir(root, `${plugin}/skills/deploy`, { name: 'deploy', description: `Deploy with ${plugin}` });}await buildSkillIndex({ catalog: 'c', dirs: [root] }, { home });- const r = await resolveSkills({ message: 'deploy', harness: 'hermes' }, { home });+ const r = await resolveSkills({ message: 'deploy', harness: 'hermes', top_gate: 0 }, { home });expect(r.output.suggestions.map(s => [s.id, s.name]).sort()).toEqual([['alpha-example:deploy', 'deploy'], ['beta-example:deploy', 'deploy']]);expect(r.output.block).toContain('id: "alpha-example:deploy"');expect(r.output.block).toContain('id: "beta-example:deploy"');@@ -685,7 +704,7 @@ describe('catalog sources and bounds', () => {expect(Buffer.byteLength(snap)).toBeLessThan(2 * 1024 * 1024);expect((JSON.parse(snap) as { body: string }[])[0]!.body.length).toBeLessThanOrEqual(4096);expect((await catalogStatus('full', { home })).fresh).toBe(true);- expect((await resolveSkills({ message: 'zebrafinch' }, { home, catalogs: ['full'] })).output.suggestions[0]?.id).toBe('s7');+ expect((await resolveSkills({ message: 'zebrafinch', top_gate: 0 }, { home, catalogs: ['full'] })).output.suggestions[0]?.id).toBe('s7');});test('a JSON catalog over 8 MB stays fresh when a 4 KB cut ends on whitespace or a body opens with two frontmatter blocks', async () => {