Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Skill resolver: a match-strength floor, longer exclude lists, named skills past the budget

garrytan223678057f85
diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.md
index acd219343d..3e1f026b2f 100644
--- a/docs/guides/skill-resolver.md
+++ b/docs/guides/skill-resolver.md
@@ -120,8 +120,9 @@ binary built without it delivers nothing and logs `skill_resolver_internal`.
The JSON Schemas are checked in under `docs/schemas/`:
- `skill-resolver.v1.turn-input.json`: `{message, previous_user_message?,
- session_id?, harness?, top_k (1-8, default 5), exclude?, shadow?,
- expected_catalog_hash?, reset_session?}` for `--input-json -` or the library.
+ session_id?, harness?, top_k (1-8, default 5), exclude? (up to 1,024 ids),
+ min_match_strength?, shadow?, expected_catalog_hash?, reset_session?}` for
+ `--input-json -` or the library.
- `skill-resolver.v1.turn-output.json`: the `--json` result. Everything outside
`meta` is byte-identical for the same index, input and session state.
- `skill-resolver.v1.build-input.json`: the `--from-json` catalog,
@@ -136,9 +137,12 @@ Within v1, changes are additive only.
(`"no_match"`). There is no score threshold: a weak match is still
suggested, and each suggestion's `match_strength` says how it matched
(`named` in the turn, else the first of `name`, `triggers`, `routing`,
-`description`, `body`) so an adapter can set its own floor, for example
-dropping body-only matches. A skill named in the turn (`$name`, `@name`, a leading `/name`,
-"the name skill", or its full id) ranks first.
+`description`, `body`). `min_match_strength` (`--min-match`) sets a floor:
+weaker matches are dropped before the cut to `top_k`, so `description` drops
+body-only matches and the stronger ones still fill the block. A skill named in
+the turn (`$name`, `@name`, a leading `/name`, "the name skill", or its full
+id) ranks first. When the message matches no catalog word (a follow-up such
+as "do it again"), `previous_user_message` (`--previous`) is ranked instead.
### Exit codes and fail-open
@@ -165,7 +169,9 @@ With `--session <id>` the resolver remembers which skills it suggested:
in `config.json` (default 2,000 tokens; 0 silences the resolver, otherwise
100-50,000). k drops to 3 once half is spent and to 1 at 80%; after half,
only a turn whose top result matched on name, triggers or routing spends
- any. When it is spent, `budget_exhausted` is true and the block is empty;
+ any. When it is spent, `budget_exhausted` is true and the block is empty,
+ except for a skill the turn names, which still gets its line (and its
+ tokens still count);
- state is committed only after the block was delivered: the CLI commits
after writing stdout, the library through `result.commit()`;
- `--reset-session` (`reset_session: true`) on the first turn after a
@@ -254,11 +260,15 @@ source as the CLI:
The CLI JSON contract stays the primary interface.
```ts
-const r = await resolveSkills({ message, session_id, harness: 'codex' }, { catalogs: ['codex-user'], failOpen: true });
-inject(r.output.suggestions.filter(s => s.match_strength !== 'body').length ? r.output.block : '');
+const r = await resolveSkills({ message, session_id, harness: 'codex', min_match_strength: 'description' }, { catalogs: ['codex-user'], failOpen: true });
+inject(r.output.block);
await r.commit();
```
+`RESOLVER_FEATURES` lists what this build supports beyond the first v1
+release (for example `min_match_strength`), so an adapter can check before
+it sends a field an older gbrain would refuse.
+
On an event loop that must not block, commit with async I/O instead:
`if (r.pending) await commitSessionAsync(home, r.pending.key, r.pending.delta)`
(same file, lease and rules as `commit()`).
@@ -280,8 +290,8 @@ is rebuilt by its adapter.
### skill_catalog_mismatch
`expected_catalog_hash` (`--expect-catalog`) differs from the index: the catalog
-was built from another skill list. Nothing was suggested or committed. Rebuild
-from the current list.
+was built from another skill list. Nothing was suggested or committed; the
+output's `catalog_hash` is the index's own hash. Rebuild from the current list.
### skill_index_locked
diff --git a/docs/schemas/skill-resolver.v1.turn-input.json b/docs/schemas/skill-resolver.v1.turn-input.json
index 05c2bda191..a016ebbdb0 100644
--- a/docs/schemas/skill-resolver.v1.turn-input.json
+++ b/docs/schemas/skill-resolver.v1.turn-input.json
@@ -15,7 +15,7 @@
},
"previous_user_message": {
"type": "string",
- "description": "The user's previous message. Accepted for adapters; v1 ranks the current message only."
+ "description": "The user's previous message. Ranked only when the current message matches no catalog word (a short follow-up such as \"do it again\"); a skill named only there is not treated as named."
},
"session_id": {
"type": "string",
@@ -42,7 +42,7 @@
},
"exclude": {
"type": "array",
- "maxItems": 64,
+ "maxItems": 1024,
"items": {
"type": "string",
"maxLength": 256
@@ -59,6 +59,17 @@
"pattern": "^[0-9a-f]{64}$",
"description": "Refuse with skill_catalog_mismatch unless the catalog hash matches."
},
+ "min_match_strength": {
+ "enum": [
+ "named",
+ "name",
+ "triggers",
+ "routing",
+ "description",
+ "body"
+ ],
+ "description": "The weakest match_strength to suggest (strongest first: named, name, triggers, routing, description, body). Weaker matches are dropped before the cut to top_k. Omit it to keep every match."
+ },
"reset_session": {
"type": "boolean",
"default": false,
diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.ts
index 9d2c1a06b7..20441c14e9 100644
--- a/src/commands/skill-resolver.ts
+++ b/src/commands/skill-resolver.ts
@@ -46,7 +46,7 @@ Guide: docs/guides/skill-resolver.md
`;
const HELP_RESOLVE = `Usage: gbrain skills resolve [--catalog <name>]... (--text <t> [--previous <t>] | --input-json -)
- [--session <id>] [--harness <h>] [--exclude a,b] [--top-k n] [--shadow [--shadow-log <file>]]
+ [--session <id>] [--harness <h>] [--exclude a,b] [--top-k n] [--min-match <strength>] [--shadow [--shadow-log <file>]]
[--expect-catalog <hash>] [--reset-session] [--names-only] [--load-hint <text>]
[--explain-target <id>] [--fail-open] [--json]
@@ -61,6 +61,8 @@ and no brain connection is needed.
--harness <h> picks the load line: openclaw, claude-code, codex, hermes, qm, pi or cursor
--top-k <n> at most n suggestions (1-8, default 5)
--exclude <ids> comma-separated skill ids to leave out
+ --min-match <s> the weakest match to suggest: named, name, triggers, routing,
+ description or body (default: every match)
--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
@@ -195,7 +197,7 @@ async function runIndex(args: string[]): Promise<void> {
}
async function runResolve(args: string[]): Promise<void> {
- const p = parseFlags(args, ['--catalog', '--text', '--previous', '--input-json', '--session', '--harness', '--exclude', '--top-k', '--shadow-log', '--explain-target', '--expect-catalog', '--load-hint'],
+ const p = parseFlags(args, ['--catalog', '--text', '--previous', '--input-json', '--session', '--harness', '--exclude', '--top-k', '--min-match', '--shadow-log', '--explain-target', '--expect-catalog', '--load-hint'],
['--shadow', '--json', '--fail-open', '--reset-session', '--names-only'], HELP_RESOLVE);
if (p.positionals.length) usage(`Unexpected argument "${p.positionals[0]}".`, 'Pass the message with --text "<message>" or turn JSON with --input-json -.');
const json = p.bools.has('--json');
@@ -220,6 +222,7 @@ async function runResolve(args: string[]): Promise<void> {
const exclude = one(p, '--exclude'); if (exclude !== undefined) input.exclude = exclude.split(',').map(s => s.trim()).filter(Boolean);
const topK = one(p, '--top-k');
if (topK !== undefined) { if (!/^\d+$/.test(topK)) throw new ResolverError('skill_resolve_invalid_input', '--top-k takes an integer from 1 to 8.', { suggestion: 'Example: --top-k 3' }); input.top_k = Number(topK); }
+ const minMatch = one(p, '--min-match'); if (minMatch !== undefined) input.min_match_strength = minMatch;
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/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index faf21bc240..fd5954571a 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -124,7 +124,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],
- 'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--names-only', '--out', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--top-k'],
+ 'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--min-match', '--names-only', '--out', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--top-k'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
diff --git a/src/core/skills/resolver/index.ts b/src/core/skills/resolver/index.ts
index a49c0a88c3..6c1decd3d0 100644
--- a/src/core/skills/resolver/index.ts
+++ b/src/core/skills/resolver/index.ts
@@ -11,7 +11,7 @@
* docs/schemas/skill-resolver.v1.*.json.
*/
export { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, sessionStatus, type BuildInput, type BuildReceipt, type CatalogStatus } from './build.ts';
-export { resolveSkills, normalizeTurnInput, errorTurnOutput, SCHEMA_VERSION, type Explain, type MatchStrength, type ResolveOptions, type ResolveResult, type Suggestion, type TurnInput, type TurnOutput } from './resolve.ts';
+export { resolveSkills, normalizeTurnInput, errorTurnOutput, SCHEMA_VERSION, EXCLUDE_MAX, MATCH_STRENGTHS, type Explain, type MatchStrength, type ResolveOptions, type ResolveResult, type Suggestion, type TurnInput, type TurnOutput } from './resolve.ts';
export { commitSessionAsync, type TurnDelta } from './session.ts';
export { VERSION as GBRAIN_VERSION } from '../../../version.ts';
export { ResolverError, type ResolverErrorCode } from './errors.ts';
@@ -20,6 +20,16 @@ export { resolverHome } from './paths.ts';
import { resolverHome } from './paths.ts';
import { resetSession, sessionKey } from './session.ts';
+/**
+ * What this build of the resolver supports beyond the first v1 release, so
+ * an adapter can check before it sends a field: min_match_strength in the
+ * turn input, exclude up to EXCLUDE_MAX ids, the index's catalog_hash on
+ * skill_catalog_mismatch, a named skill's line past a spent budget,
+ * previous_user_message as the fallback ranking text, and the pi and cursor
+ * harnesses.
+ */
+export const RESOLVER_FEATURES: readonly string[] = ['min_match_strength', 'exclude_1024', 'mismatch_catalog_hash', 'named_past_budget', 'previous_user_message', 'harness_pi', 'harness_cursor'];
+
/** Drop a session's dedupe and budget state (what a compaction does). */
export async function resetSkillSession(sessionId: string, opts: { home?: string; harness?: string; shadow?: boolean } = {}): Promise<void> {
await resetSession(opts.home ?? resolverHome(), sessionKey(opts.shadow ? 'shadow' : 'on', opts.harness, sessionId));
diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.ts
index aac2240fd2..2dd68491ae 100644
--- a/src/core/skills/resolver/resolve.ts
+++ b/src/core/skills/resolver/resolve.ts
@@ -16,7 +16,12 @@
* it ranks first with a name, trigger or routing match at least 10 turns
* later, or whenever the turn names it explicitly;
* - when nothing new is in the top k the block is empty; when no new line
- * fits what is left of the budget, budget_exhausted is true.
+ * fits what is left of the budget, budget_exhausted is true, but a skill
+ * the turn names explicitly still gets its line (its tokens still count).
+ *
+ * min_match_strength drops weaker matches before the cut to k, so a floor
+ * never shrinks the block below what the stronger matches fill. A message
+ * that matches no catalog word falls back to previous_user_message.
*/
import { appendFileSync, existsSync, readFileSync, statSync, truncateSync } from 'node:fs';
import { createHash } from 'node:crypto';
@@ -37,7 +42,7 @@ export const SCHEMA_VERSION = 1;
export const MESSAGE_CAP_BYTES = 8192;
export const TOP_K_DEFAULT = 5;
export const TOP_K_MAX = 8;
-export const EXCLUDE_MAX = 64;
+export const EXCLUDE_MAX = 1024;
export const RESUGGEST_AFTER_TURNS = 10;
export const STAT_CHECK_INTERVAL_MS = 60_000;
/** Stat calls one turn may spend on the freshness sweep; a larger catalog is swept over several turns. */
@@ -53,11 +58,14 @@ export interface TurnInput {
shadow?: boolean;
expected_catalog_hash?: string;
reset_session?: boolean;
+ min_match_strength?: MatchStrength;
}
/** 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';
const STRENGTH_FIELDS = ['name', 'triggers', 'routing', 'description', 'body'] as const;
+/** Strongest first. */
+export const MATCH_STRENGTHS: readonly MatchStrength[] = ['named', ...STRENGTH_FIELDS];
export interface Suggestion { id: string; name: string; score: number; summary: string; reason: string; match_strength: MatchStrength; path?: string; catalog: string }
export interface TurnError { code: string; message: string; fix: { suggestion: string; command?: string } }
export interface TurnOutput {
@@ -135,7 +143,7 @@ function capUtf8(s: string, max: number): string {
export function normalizeTurnInput(raw: unknown): Required<Pick<TurnInput, 'message' | 'top_k' | 'exclude' | 'shadow' | 'reset_session'>> & TurnInput {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw invalid('The turn input must be a JSON object.', 'Send {"message": "..."} (see docs/schemas/skill-resolver.v1.turn-input.json).');
const o = raw as Record<string, unknown>;
- const known = new Set(['message', 'previous_user_message', 'session_id', 'harness', 'top_k', 'exclude', 'shadow', 'expected_catalog_hash', 'reset_session']);
+ const known = new Set(['message', 'previous_user_message', 'session_id', 'harness', 'top_k', 'exclude', 'shadow', 'expected_catalog_hash', 'reset_session', 'min_match_strength']);
const extra = Object.keys(o).find(k => !known.has(k));
if (extra) throw invalid(`Unknown turn input field "${extra}".`, 'Use only the fields in docs/schemas/skill-resolver.v1.turn-input.json.');
if (typeof o.message !== 'string') throw invalid('message is required and must be a string.', 'Send the user message as "message".');
@@ -146,6 +154,7 @@ export function normalizeTurnInput(raw: unknown): Required<Pick<TurnInput, 'mess
if (o.exclude !== undefined && (!Array.isArray(o.exclude) || o.exclude.length > EXCLUDE_MAX || o.exclude.some(x => typeof x !== 'string' || x.length > 256))) throw invalid(`exclude must be at most ${EXCLUDE_MAX} skill ids.`, 'Pass the ids already loaded this turn.');
if (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.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),
@@ -157,6 +166,7 @@ export function normalizeTurnInput(raw: unknown): Required<Pick<TurnInput, 'mess
shadow: o.shadow === true,
reset_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 } : {}),
};
}
@@ -215,7 +225,8 @@ function emptyOutput(input: { shadow?: boolean }, extra: Partial<TurnOutput>): T
/** The turn output for a runtime error: no suggestions, block "", `error` set. */
export function errorTurnOutput(err: ResolverError, opts: { shadow?: boolean; catalog?: string | null } = {}): TurnOutput {
- return emptyOutput({ shadow: opts.shadow }, { error: err.toJSON(), catalog: opts.catalog ?? null });
+ const hash = err.code === 'skill_catalog_mismatch' && typeof err.context.catalog_hash === 'string' ? err.context.catalog_hash : null;
+ return emptyOutput({ shadow: opts.shadow }, { error: err.toJSON(), catalog: opts.catalog ?? null, catalog_hash: hash });
}
function logUnexpected(home: string, e: unknown): void {
@@ -265,7 +276,7 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:
const variant = loaded.map(l => l.receipt.ranker.variant).join('+');
if (input.expected_catalog_hash !== undefined && input.expected_catalog_hash !== catalogHash) {
throw new ResolverError('skill_catalog_mismatch', `The catalog "${catalog}" was built from a different skill list than the caller expects (expected ${input.expected_catalog_hash.slice(0, 12)}, index has ${catalogHash.slice(0, 12)}).`,
- { suggestion: 'Rebuild the catalog from the current skill list (an adapter passes its new snapshot to gbrain skills index build --from-json -), then retry.' }, { catalog });
+ { suggestion: 'Rebuild the catalog from the current skill list (an adapter passes its new snapshot to gbrain skills index build --from-json -), then retry.' }, { catalog, catalog_hash: catalogHash });
}
const oldest = Math.min(...loaded.map(l => Date.parse(l.receipt.build.built_at)));
const meta = { timing_ms: 0, index_age_s: Number.isFinite(oldest) ? Math.max(0, Math.floor((now - oldest) / 1000)) : null, index_stale: loaded.some(l => l.stale !== null) };
@@ -290,36 +301,43 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:
if (isAcknowledgement(input.message)) return finish({ ...base, no_skill: true, no_skill_reason: 'ack' }, { tokens: 0, suggested: [], resuggested: [] });
- const ranks: RankResult[] = loaded.map(l => { const r = rankIndex(l.ix, input.message, check); check(); return r; });
+ const rankText = (text: string): RankResult[] => loaded.map(l => { const r = rankIndex(l.ix, text, check); check(); return r; });
+ let ranks = rankText(input.message);
+ if (ranks.every(r => r.idfSum === 0) && input.previous_user_message?.trim()) ranks = rankText(input.previous_user_message);
if (ranks.every(r => r.idfSum === 0)) return finish({ ...base, no_skill: true, no_skill_reason: 'no_match' }, { tokens: 0, suggested: [], resuggested: [] });
interface Cand { c: number; doc: number; score: number; id: string; explicit: boolean }
const metaOf = (c: number, doc: number) => loaded[c]!.ix.meta(doc);
- const explicitIds = new Set<string>();
- const ordered: Cand[] = [];
+ const strengthOf = (x: Cand): MatchStrength => {
+ if (x.explicit) return 'named';
+ const fields = ranks[x.c]!.matchedFields(x.doc).fields;
+ return STRENGTH_FIELDS.find(f => fields[f]?.length) ?? 'body';
+ };
+ const excluded = new Set(input.exclude);
+ const floor = MATCH_STRENGTHS.indexOf(input.min_match_strength ?? 'body');
+ const window: Cand[] = [];
const seen = new Set<string>();
+ const admit = (x: Cand) => {
+ seen.add(x.id);
+ if (window.length < kEff && !excluded.has(x.id) && MATCH_STRENGTHS.indexOf(strengthOf(x)) <= floor) window.push(x);
+ };
loaded.forEach((_, c) => {
for (const r of ranks[c]!.ranked) {
if (!ranks[c]!.nameHits.has(r.doc)) continue;
const m = metaOf(c, r.doc);
- if (!seen.has(m.id) && mentionsSkill(input.message, m.id, m.name)) { seen.add(m.id); explicitIds.add(m.id); ordered.push({ c, doc: r.doc, score: r.score, id: m.id, explicit: true }); }
+ if (!seen.has(m.id) && mentionsSkill(input.message, m.id, m.name)) admit({ c, doc: r.doc, score: r.score, id: m.id, explicit: true });
}
});
const longest = Math.max(...ranks.map(r => r.ranked.length));
- const want = TOP_K_MAX + EXCLUDE_MAX + 8;
- for (let i = 0; i < longest && ordered.length < want + explicitIds.size; i++) {
+ for (let i = 0; i < longest && window.length < kEff; i++) {
loaded.forEach((_, c) => {
const r = ranks[c]!.ranked[i];
if (!r) return;
const m = metaOf(c, r.doc);
- if (seen.has(m.id)) return;
- seen.add(m.id);
- ordered.push({ c, doc: r.doc, score: r.score, id: m.id, explicit: false });
+ if (!seen.has(m.id)) admit({ c, doc: r.doc, score: r.score, id: m.id, explicit: false });
});
+ check();
}
- check();
- const excluded = new Set(input.exclude);
- const window = ordered.filter(x => !excluded.has(x.id)).slice(0, kEff);
const strong = (x: Cand) => x.explicit || ranks[x.c]!.matchedFields(x.doc).strong;
const picked: Cand[] = [];
const resuggested: string[] = [];
@@ -342,14 +360,16 @@ async function resolveInner(input: ReturnType<typeof normalizeTurnInput>, opts:
const m = metaOf(x.c, x.doc);
return { id: m.id, name: m.name, summary: m.summary, ...(m.path ? { path: m.path } : {}), namesOnly: Boolean(opts.namesOnly) || loaded[x.c]!.receipt.catalog.hints === 'names_only' };
});
- const r = renderBlock(lines, { harness: input.harness, loadHint: opts.loadHint, cap: Math.min(BLOCK_TOKEN_CAP, remaining) });
- const kept = picked.slice(0, r.kept);
+ let r = renderBlock(lines, { harness: input.harness, loadHint: opts.loadHint, cap: Math.min(BLOCK_TOKEN_CAP, remaining) });
const exhausted = budget === 0 || remaining === 0 || (picked.length > 0 && r.kept === 0 && remaining < BLOCK_TOKEN_CAP);
+ const named = picked.filter(x => x.explicit).length;
+ if (budget > 0 && r.kept === 0 && named > 0) r = renderBlock(lines.slice(0, named), { harness: input.harness, loadHint: opts.loadHint, cap: BLOCK_TOKEN_CAP });
+ const kept = picked.slice(0, r.kept);
const suggestions: Suggestion[] = kept.map(x => {
const m = metaOf(x.c, x.doc);
const namesOnly = lines.find(l => l.id === m.id)!.namesOnly;
const fields = ranks[x.c]!.matchedFields(x.doc).fields;
- const match_strength: MatchStrength = x.explicit ? 'named' : STRENGTH_FIELDS.find(f => fields[f]?.length) ?? 'body';
+ const match_strength = strengthOf(x);
return { id: m.id, name: m.name, score: round4(x.score), summary: namesOnly ? '' : m.summary, reason: x.explicit ? `named in the turn; ${reasonText(fields)}` : reasonText(fields), match_strength, ...(m.path ? { path: m.path } : {}), catalog: loaded[x.c]!.name };
});
const out: TurnOutput = { ...base, budget_exhausted: exhausted, suggestions, block: r.block, block_tokens: r.tokens, deduped };
diff --git a/test/skill-resolver-cli.test.ts b/test/skill-resolver-cli.test.ts
index e588bce08e..3574f64ce8 100644
--- a/test/skill-resolver-cli.test.ts
+++ b/test/skill-resolver-cli.test.ts
@@ -100,6 +100,7 @@ describe('gbrain skills (CLI)', () => {
[['skills', 'resolve'], undefined, 'skill_resolve_no_input'],
[['skills', 'resolve', '--catalog', '../config', '--text', 'x'], undefined, 'skill_catalog_unknown'],
[['skills', 'resolve', '--text', 'x', '--top-k', '9'], undefined, 'skill_resolve_invalid_input'],
+ [['skills', 'resolve', '--text', 'x', '--min-match', 'weak'], undefined, 'skill_resolve_invalid_input'],
[['skills', 'index', 'build', '--catalog', 'c', '--from-json', '-'], '{"skills": 1}', 'skill_source_invalid'],
[['skills', 'index', 'frobnicate'], undefined, 'Unknown subcommand'],
];
diff --git a/test/skill-resolver-contract.test.ts b/test/skill-resolver-contract.test.ts
index 1122d70190..ce05e2411d 100644
--- a/test/skill-resolver-contract.test.ts
+++ b/test/skill-resolver-contract.test.ts
@@ -32,9 +32,9 @@ const SKILLS = [
];
describe('turn input', () => {
- const good = [{ message: 'deploy' }, { message: '', top_k: 8, exclude: [], shadow: false, reset_session: true }, { message: 'x', session_id: 'a'.repeat(256), harness: 'codex', expected_catalog_hash: 'a'.repeat(64), previous_user_message: 'y' }];
+ const good = [{ message: 'deploy' }, { message: '', top_k: 8, exclude: [], shadow: false, reset_session: true }, { message: 'x', session_id: 'a'.repeat(256), harness: 'codex', expected_catalog_hash: 'a'.repeat(64), previous_user_message: 'y' }, { message: 'x', exclude: Array(1024).fill('a'), min_match_strength: 'description', harness: 'pi' }];
const bad = [{}, { message: 1 }, { message: 'x', top_k: 0 }, { message: 'x', top_k: 9 }, { message: 'x', top_k: 2.5 }, { message: 'x', extra: true }, { message: 'x', harness: 'vim' },
- { message: 'x', session_id: '' }, { message: 'x', session_id: 'a b' }, { message: 'x', exclude: Array(65).fill('a') }, { message: 'x', exclude: [1] }, { message: 'x', expected_catalog_hash: 'ABC' }, { message: 'x', shadow: 'yes' }];
+ { message: 'x', session_id: '' }, { message: 'x', session_id: 'a b' }, { message: 'x', exclude: Array(1025).fill('a') }, { message: 'x', min_match_strength: 'weak' }, { message: 'x', exclude: [1] }, { message: 'x', expected_catalog_hash: 'ABC' }, { message: 'x', shadow: 'yes' }];
test('the schema and the resolver accept and refuse the same inputs', () => {
for (const g of good) { expect(validate(INPUT, g)).toEqual([]); expect(() => normalizeTurnInput(g)).not.toThrow(); }
for (const b of bad) {
diff --git a/test/skill-resolver.test.ts b/test/skill-resolver.test.ts
index 10e613c67b..5358871d84 100644
--- a/test/skill-resolver.test.ts
+++ b/test/skill-resolver.test.ts
@@ -28,7 +28,7 @@ import { estimateTokens } from '../src/core/skills/resolver/block.ts';
import { acquireLease, holdsLease, releaseLease, tryAcquireLease } from '../src/core/skills/resolver/lock.ts';
import { commitSession, commitSessionAsync, gcSessions, loadSession, sessionKey } from '../src/core/skills/resolver/session.ts';
import { catalogFile } from '../src/core/skills/resolver/paths.ts';
-import { STAT_CHECK_SLICE } from '../src/core/skills/resolver/resolve.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';
const scratch: string[] = [];
@@ -99,6 +99,45 @@ describe('turn rules', () => {
expect(named.output.suggestions[0]).toMatchObject({ id: 'x:delta', match_strength: 'named' });
});
+ test('min_match_strength drops weaker matches before the cut to top_k, and only kept suggestions are committed', async () => {
+ const home = tmp();
+ await jsonCatalog(home, 'c', [
+ ...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 });
+ 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 });
+ 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 });
+ expect([strict.output.suggestions, strict.output.block, strict.output.no_skill]).toEqual([[], '', false]);
+ const named = await resolveSkills({ message: 'use the desc-3 skill', min_match_strength: 'named' }, { home });
+ expect(named.output.suggestions.map(s => s.id)).toEqual(['x:desc-3']);
+ });
+
+ test('previous_user_message is ranked only when the current message matches nothing', async () => {
+ const home = tmp();
+ await jsonCatalog(home, 'c', BASIC);
+ const follow = await resolveSkills({ message: 'do it again', previous_user_message: 'write the weekly status reports' }, { home });
+ expect(follow.output.suggestions[0]!.id).toBe('gbrain:reports');
+ const own = await resolveSkills({ message: 'deploy the service', previous_user_message: 'write the weekly status reports' }, { home });
+ expect(own.output.suggestions[0]!.id).toBe('gbrain:deploy');
+ expect(own.output.suggestions.map(s => s.id)).not.toContain('gbrain:reports');
+ const none = await resolveSkills({ message: 'do it again', previous_user_message: 'zzqx' }, { home });
+ expect([none.output.no_skill, none.output.no_skill_reason]).toEqual([true, 'no_match']);
+ });
+
+ test('exclude takes up to EXCLUDE_MAX ids and still fills top_k from what is left', async () => {
+ const home = tmp();
+ 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 });
+ expect(r.output.suggestions).toHaveLength(3);
+ for (const s of r.output.suggestions) expect(exclude).not.toContain(s.id);
+ });
+
test('ack and no_match are the only no_skill results; short imperatives and CJK turns are ranked', async () => {
const home = tmp();
await jsonCatalog(home, 'c', [...BASIC, { id: 'x:minutes', name: 'minutes', description: '会议纪要 整理' }]);
@@ -176,7 +215,7 @@ describe('turn rules', () => {
const r = await resolveSkills({ message: 'meeting notes email reports', top_k: 2, exclude: ['gbrain:meeting-notes'] }, { home });
expect(r.output.suggestions.length).toBe(2);
expect(r.output.suggestions.map(s => s.id)).not.toContain('gbrain:meeting-notes');
- for (const bad of [{}, { message: 1 }, { message: 'x', top_k: 9 }, { message: 'x', top_k: 0 }, { message: 'x', extra: 1 }, { message: 'x', exclude: new Array(65).fill('a') },
+ for (const bad of [{}, { message: 1 }, { message: 'x', top_k: 9 }, { message: 'x', top_k: 0 }, { message: 'x', extra: 1 }, { message: 'x', exclude: new Array(EXCLUDE_MAX + 1).fill('a') }, { message: 'x', min_match_strength: 'weak' },
{ message: 'x', session_id: 'has space' }, { message: 'x', session_id: 'é' }, { message: 'x', session_id: 'a'.repeat(257) }, { message: 'x', harness: 'vim' }, { message: 'x', expected_catalog_hash: 'abc' }]) {
expect(await codeOf(resolveSkills(bad as TurnInput, { home }))).toBe('skill_resolve_invalid_input');
}
@@ -262,6 +301,21 @@ describe('sessions', () => {
expect(loadSession(home, key).turn).toBe(1);
});
+ test('a skill the turn names still gets its line after the budget is spent; its tokens count', async () => {
+ const home = tmp();
+ await jsonCatalog(home, 'c', BASIC);
+ const key = sessionKey('on', 'claude-code', 'n');
+ await commitSession(home, key, { tokens: 2000, suggested: [], resuggested: [], reset: false });
+ const r = await resolveSkills({ message: 'run the deploy skill and write the reports', session_id: 'n', harness: 'claude-code' }, { home });
+ expect(r.output.budget_exhausted).toBe(true);
+ expect(r.output.suggestions.map(s => [s.id, s.match_strength])).toEqual([['gbrain:deploy', 'named']]);
+ expect(r.output.block).toContain('id: "gbrain:deploy"');
+ await r.commit();
+ expect(loadSession(home, key).spent).toBe(2000 + r.output.block_tokens);
+ const silent = await resolveSkills({ message: 'run the deploy skill' }, { home, sessionTokenBudget: 0 });
+ expect(silent.output.block).toBe('');
+ });
+
test('a budget of 0 silences the resolver; out-of-range budgets refuse', async () => {
const home = tmp();
await jsonCatalog(home, 'c', BASIC);
@@ -741,6 +795,7 @@ describe('freshness and errors', () => {
expect(ok.output.catalog_hash).toBe(rec.catalog.catalog_hash);
const bad = await resolveSkills({ message: 'deploy', session_id: 'h', expected_catalog_hash: 'f'.repeat(64) }, { home, failOpen: true });
expect([bad.output.error!.code, bad.output.block, bad.failOpen]).toEqual(['skill_catalog_mismatch', '', true]);
+ expect(bad.output.catalog_hash).toBe(rec.catalog.catalog_hash);
expect(await bad.commit()).toBe(false);
expect(sessionStatus('h', { home }).turn).toBe(0);
});