Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(skills): list_skills query ranks the host catalog by lexical overlap (#6471)

garrytan932c031b7131
diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.md
index 0bddb964e1..7d41635e5c 100644
--- a/docs/architecture/key-files/skills.md
+++ b/docs/architecture/key-files/skills.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/skill-brain-first.ts` — pure analyzer. `analyzeSkillBrainFirst(skillPath, content): SkillBrainFirstResult` walks the compliance ladder for every SKILL.md: (1) absent external-lookup pattern → `no_external`; (2) `brain_first: exempt` frontmatter → `exempt_frontmatter`; (3) canonical `> **Convention:** see [conventions/brain-first.md](../...)` callout → `compliant_callout`; (4) explicit `## Phase 1: Brain` heading → `compliant_phase`; (5) first `gbrain search`/`query`/`get_page` reference precedes first external pattern in the BODY (frontmatter stripped) → `compliant_position`; (6) else `missing_brain_first` warn. External pattern set: word-boundary regex over `web_search`, `web_fetch`, `exa`, `perplexity`, `happenstance`, `crustdata`, `captain_api`, `firecrawl`. Position scan is BODY-ONLY so a `tools: [web_search]` frontmatter declaration doesn't false-flag the skill. The 40-name `FORMERLY_HARDCODED_EXEMPT` list is preserved so doctor can emit a "this used to be auto-exempt, declare `brain_first: exempt` if still appropriate" hint. Consumed by 3 surfaces: doctor check, skillify-check item 12, dry-fix MISSING_RULE_PATTERNS.
-- `src/core/skill-catalog.ts` — legacy host-repo fallback for MCP `list_skills` / `get_skill`. Canonical schema-version-2 discovery uses [shared brain skills](shared-skills.md); version 1 also uses the canonical compatibility layer when that catalog is active. This module serves the remaining host-catalog fallback, not canonical revision discovery. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `resolveSkillTools` shares list/detail semantics: declared `tools:` narrow the caller's effective inventory via `crossReferenceTools`; valid mapping frontmatter that omits `tools` inherits `availableBrainTools(ctx)` without granting new permissions. Explicit `tools: []` stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates through `disabledOpsForPublishGates` before building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes. `opAllowedForBoundClient` also applies the same operation grants, slug-bound write fences, and degraded-projection policy as dispatch. Pure catalog calls without resolved gates conservatively hide gated operations from remote callers. The list's `tools` remains the declared list (empty when omitted), while `usable_tools` carries the effective inventory. Pinned by `test/skill-catalog-optional-tools.test.ts`. `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). The legacy catalog entrypoints in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade) are: `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
+- `src/core/skill-catalog.ts` — legacy host-repo fallback for MCP `list_skills` / `get_skill`. Canonical schema-version-2 discovery uses [shared brain skills](shared-skills.md); version 1 also uses the canonical compatibility layer when that catalog is active. This module serves the remaining host-catalog fallback, not canonical revision discovery. `buildSkillCatalog(ctx, dir, source, { section, query, limit, gateDisabled })` builds the catalog after the publish gate and confinement; with `query` (#6471) it ranks the section-filtered entries by `scoreSkillMatch` (lexical token overlap: trigger tokens ×2, a whole trigger phrase inside the query ×4, name tokens ×3, description tokens ×1; no model call), drops zero-score entries, breaks ties by name, caps at `limit` (default 10, max 100) and sets `match: { score, matched_on }` per entry; without `query` the output is byte-identical to the unranked build. The `list_skills` op refuses `query` with `invalid_params` on the schema-version-2 and active shared-catalog routes before any catalog read (`ops/skills-catalog.ts`); `query` is advertised on the full MCP surface only (`fullSurfaceOnly`) so the starter list keeps its size budget. Pinned by `test/list-skills-query-6471.test.ts`. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `resolveSkillTools` shares list/detail semantics: declared `tools:` narrow the caller's effective inventory via `crossReferenceTools`; valid mapping frontmatter that omits `tools` inherits `availableBrainTools(ctx)` without granting new permissions. Explicit `tools: []` stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates through `disabledOpsForPublishGates` before building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes. `opAllowedForBoundClient` also applies the same operation grants, slug-bound write fences, and degraded-projection policy as dispatch. Pure catalog calls without resolved gates conservatively hide gated operations from remote callers. The list's `tools` remains the declared list (empty when omitted), while `usable_tools` carries the effective inventory. Pinned by `test/skill-catalog-optional-tools.test.ts`. `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). The legacy catalog entrypoints in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade) are: `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
- `src/core/skill-fix-gates.ts` — shared safety primitives for `dry-fix.ts`. `getWorkingTreeStatus(file)` 3-state (`'clean' | 'dirty' | 'not_a_repo'`); `isInsideCodeFence(content, offset)`; `findAfterH1Paragraph(content)` (canonical insertion offset for the auto-inserted Convention callout). Both REPLACE expanders (DRY violations) and the INSERT expander (MISSING_RULE_PATTERNS) consume from here so the install-path refusal and dirty-tree gates apply uniformly. `src/core/dry-fix.ts` re-exports them.
diff --git a/docs/guides/skill-reference.md b/docs/guides/skill-reference.md
index 17472b15d0..da283ac149 100644
--- a/docs/guides/skill-reference.md
+++ b/docs/guides/skill-reference.md
@@ -19,6 +19,18 @@ Preconditions and trigger routing limited to what the skill covers.
**Skillify loop:** skillify (the markdown orchestration), skillpack-check
(agent-readable health report).
+**Finding the right skill for a task over MCP:** `list_skills` takes an optional
+`query` (full MCP surface, host catalog) and returns the skills whose name,
+triggers or description share words with it, best first, with
+`match.matched_on` saying which of the three matched; skills that share no
+words are left out, and `limit` (default 10) caps the list. It is a word-overlap
+ranking, not a model call, so it is free and instant, and the same call
+without `query` returns the whole catalog exactly as before. On a brain that
+serves a shared catalog (`schema_version: 2`, or shared skills activated)
+`query` is refused with `invalid_params` instead of being ignored; narrow with
+`section` there. **Say to your agent:** *"Which of my brain's skills should I
+use to prepare for this meeting?"*
+
**Brain-resident skillpacks + advisor:** A brain repo can carry its
own publishable skillpack (`brain_resident: true` in `skillpack.json` + `schema_pack`);
`gbrain skillpack init-brain-pack` scaffolds one with a 5-section machine-parseable README.
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index d95fe813f3..61d1c42eb5 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -252,10 +252,11 @@ List the skills this agent's brain publishes. A skill is a named prose instructi
| Parameter | Type | Guidance |
| --- | --- | --- |
| `schema_version` | number | Request 2 for the canonical source-qualified sealed catalog; omitted preserves version 1. |
-| `limit` | number | Version 2 page size, 1-100. |
+| `limit` | number | Version 2 page size, 1-100; with `query`, how many ranked skills to return (default 10). |
| `cursor` | string | Version 2 opaque snapshot cursor. |
| `source_id` | string | Narrow version 2 enumeration to one permitted source. |
| `section` | string | Optional: only skills whose routing section matches this exactly. |
+| `query` | string | Full surface, version 1 host catalog only: the task in plain words. Skills are ranked by word overlap over their name, triggers and description (a whole trigger phrase inside the query counts most, then name words, then description words); skills matching nothing are dropped, ties break by name, `limit` caps the list, and each kept entry carries `match: { score, matched_on: trigger \| name \| description }`. Without `query` the catalog is unchanged (name order, every skill, no `match`). On a shared catalog (`schema_version: 2`, or a brain whose shared catalog is active) `query` is refused with `invalid_params` rather than ignored: filter with `section` there. No model call. |
## `list_write_requests`
diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.ts
index 11b259bff9..28f82ec217 100644
--- a/src/core/ops/skills-catalog.ts
+++ b/src/core/ops/skills-catalog.ts
@@ -30,26 +30,44 @@ const list_skills: Operation = {
publishGateKey: 'mcp.publish_skills',
params: {
schema_version: { type: 'number', description: '2 for the source-qualified catalog.' },
- limit: { type: 'number', description: 'Version 2 page size (1-100).' },
+ limit: { type: 'number', description: 'Page size or ranked count (1-100).' },
cursor: { type: 'string', description: 'Version 2 cursor.' },
source_id: { type: 'string', description: 'Version 2: one source.' },
section: {
type: 'string',
description: 'Only this routing section.',
},
+ query: {
+ type: 'string',
+ description: 'Version 1 host catalog: rank skills by word overlap with this task (name, triggers, description), drop the rest, cap at limit (default 10). Refused on a shared catalog.',
+ fullSurfaceOnly: true,
+ },
},
handler: async (ctx, p) => {
- if (p.schema_version === 2) return (await import('../shared-skills/catalog.ts')).listSharedSkills(ctx, p);
+ if (p.query !== undefined && typeof p.query !== 'string') throw invalidParam(ctx, 'list_skills', 'query', 'query must be a string naming the task.', { example: 'prepare for a meeting' });
+ const query = typeof p.query === 'string' && p.query.trim().length > 0 ? p.query : undefined;
+ // #6471: the shared catalogs do not rank yet; refusing beats a silently unranked list.
+ const refuseQueryOnSharedCatalog = (which: string) => opError('invalid_params',
+ `query ranks the version 1 host skill catalog only; ${which} does not support it yet.`,
+ 'Drop query and narrow the shared catalog with section (and source_id for version 2) instead; rank the host catalog by calling list_skills with query on a brain that serves it.');
+ if (p.schema_version === 2) {
+ if (query) throw refuseQueryOnSharedCatalog('the version 2 catalog');
+ return (await import('../shared-skills/catalog.ts')).listSharedSkills(ctx, p);
+ }
if (p.schema_version !== undefined && p.schema_version !== 1) throw invalidParam(ctx, 'list_skills', 'schema_version', 'Supported skill catalog schema versions are 1 and 2.', { choices: ['1', '2'], example: 2 });
const compatibility = await import('../shared-skills/compatibility.ts');
- if (await compatibility.sharedCatalogActive(ctx)) return compatibility.listLegacySharedSkills(ctx, typeof p.section === 'string' ? p.section : undefined);
+ if (await compatibility.sharedCatalogActive(ctx)) {
+ if (query) throw refuseQueryOnSharedCatalog("this brain's shared catalog");
+ return compatibility.listLegacySharedSkills(ctx, typeof p.section === 'string' ? p.section : undefined);
+ }
const sc = await import('../skill-catalog.ts');
const publish = await sc.readMcpPublishSkills(ctx);
sc.assertPublishEnabled(ctx, publish);
const override = await sc.readMcpSkillsDir(ctx);
const { dir, source } = sc.resolveSkillsDir(ctx, override);
const section = typeof p.section === 'string' ? p.section : undefined;
- return sc.buildSkillCatalog(ctx, dir, source, { section, gateDisabled: await sc.readSkillToolGates(ctx) });
+ const limit = typeof p.limit === 'number' ? p.limit : undefined;
+ return sc.buildSkillCatalog(ctx, dir, source, { section, query, limit, gateDisabled: await sc.readSkillToolGates(ctx) });
},
scope: 'read',
cliHints: { name: 'skills', positional: [] },
diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.ts
index b35d02c325..f0abb26987 100644
--- a/src/core/skill-catalog.ts
+++ b/src/core/skill-catalog.ts
@@ -97,6 +97,14 @@ export interface SkillCatalogEntry {
unavailable_tools: string[];
writes_pages: boolean;
mutating: boolean;
+ /** #6471: present only when the call carried `query`; see `scoreSkillMatch`. */
+ match?: SkillMatch;
+}
+
+/** #6471: lexical relevance of a skill to a task. `matched_on` names the strongest contributor. */
+export interface SkillMatch {
+ score: number;
+ matched_on: 'trigger' | 'name' | 'description';
}
export interface ListSkillsResult {
@@ -473,21 +481,62 @@ function dirNameOf(entry: ManifestEntry): string {
return entry.path.split('/')[0] ?? entry.name;
}
+const QUERY_STOPWORDS = new Set(['a', 'an', 'the', 'and', 'or', 'of', 'to', 'for', 'in', 'on', 'at', 'by', 'with', 'my', 'me', 'is', 'it', 'be', 'this', 'that', 'from', 'as']);
+const QUERY_RESULT_LIMIT_DEFAULT = 10;
+const QUERY_RESULT_LIMIT_MAX = 100;
+
+/** Lowercased word tokens; hyphens and punctuation split, so `meeting-prep` is `meeting` + `prep`. */
+function queryTokens(text: string): string[] {
+ return text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(t => t.length >= 2 && !QUERY_STOPWORDS.has(t));
+}
+
+/**
+ * #6471: lexical token overlap between a task and one catalog entry. Trigger
+ * tokens count 2 each and a whole trigger phrase inside the query counts
+ * double again; name tokens count 3; description tokens count 1. Null when
+ * nothing overlaps (the entry is dropped from a ranked list). No model call:
+ * the catalog is ~100 entries and `list_skills` must stay keyless and fast.
+ */
+export function scoreSkillMatch(entry: Pick<SkillCatalogEntry, 'name' | 'description' | 'triggers'>, query: string): SkillMatch | null {
+ const queryWords = queryTokens(query);
+ if (queryWords.length === 0) return null;
+ const inQuery = new Set(queryWords);
+ const queryText = ` ${queryWords.join(' ')} `;
+ const overlap = (text: string): number => new Set(queryTokens(text).filter(t => inQuery.has(t))).size;
+ let trigger = 0;
+ for (const phrase of entry.triggers) {
+ const words = queryTokens(phrase);
+ if (words.length === 0) continue;
+ trigger += queryText.includes(` ${words.join(' ')} `) ? 4 * words.length : 2 * overlap(phrase);
+ }
+ const name = 3 * overlap(entry.name);
+ const description = overlap(entry.description);
+ const score = trigger + name + description;
+ if (score === 0) return null;
+ const matched_on = trigger >= name && trigger >= description ? 'trigger' : name >= description ? 'name' : 'description';
+ return { score, matched_on };
+}
+
/**
* Build the flat host-repo skill catalog + the instructional envelope. Resilient:
* a single malformed/escaping skill is skipped, never throws the whole call.
+ * With `opts.query` (#6471) the section-filtered catalog is ranked by
+ * `scoreSkillMatch`, zero-score entries are dropped, ties break by name and
+ * `opts.limit` (default 10, max 100) caps the list; without it the output is
+ * unchanged.
*/
export function buildSkillCatalog(
ctx: OperationContext,
skillsDir: string,
source: ResolvedSkillsDirSource,
- opts: { section?: string; gateDisabled?: ReadonlySet<string> } = {},
+ opts: { section?: string; gateDisabled?: ReadonlySet<string>; query?: string; limit?: number } = {},
): ListSkillsResult {
const { skills: manifest } = loadOrDeriveManifest(skillsDir);
const triggerMap = buildTriggerMap(skillsDir);
const sectionFilter = opts.section?.trim();
+ const query = opts.query?.trim();
- const skills: SkillCatalogEntry[] = [];
+ let skills: SkillCatalogEntry[] = [];
for (const entry of manifest) {
let path: string;
try {
@@ -529,6 +578,13 @@ export function buildSkillCatalog(
}
skills.sort((a, b) => a.name.localeCompare(b.name));
+ if (query) {
+ const limit = Math.min(QUERY_RESULT_LIMIT_MAX, Math.max(1, Math.floor(opts.limit ?? QUERY_RESULT_LIMIT_DEFAULT)));
+ skills = skills
+ .flatMap(entry => { const match = scoreSkillMatch(entry, query); return match ? [{ ...entry, match }] : []; })
+ .sort((a, b) => b.match!.score - a.match!.score || a.name.localeCompare(b.name))
+ .slice(0, limit);
+ }
return {
schema_version: 1,
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index e3d0c9c34b..706b3843c2 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 230679,
- "stdoutSha256": "dc9a2b59ffbb454139bd202eb28d827cd45dc57b91605771d154625920306eda",
+ "stdoutBytes": 230965,
+ "stdoutSha256": "3e00a7ce055b60f677e86bee01d09fd205763f9ca776f8f6f301575c4b05d3af",
"toolNames": [
"remember",
"entity",
@@ -2513,6 +2513,7 @@
"parameters": {
"cursor": "string?",
"limit": "number?",
+ "query": "string?",
"schema_version": "number?",
"section": "string?",
"source_id": "string?"
@@ -2525,9 +2526,13 @@
"type": "string"
},
"limit": {
- "description": "Version 2 page size (1-100).",
+ "description": "Page size or ranked count (1-100).",
"type": "number"
},
+ "query": {
+ "description": "Version 1 host catalog: rank skills by word overlap with this task (name, triggers, description), drop the rest, cap at limit (default 10). Refused on a shared catalog.",
+ "type": "string"
+ },
"schema_version": {
"description": "2 for the source-qualified catalog.",
"type": "number"
diff --git a/test/fixtures/skill-catalog-query/skills/RESOLVER.md b/test/fixtures/skill-catalog-query/skills/RESOLVER.md
new file mode 100644
index 0000000000..5542577061
--- /dev/null
+++ b/test/fixtures/skill-catalog-query/skills/RESOLVER.md
@@ -0,0 +1,5 @@
+# Skill routing
+
+| Trigger | Skill |
+|---------|-------|
+| who am I meeting today | `skills/meeting-prep/SKILL.md` |
diff --git a/test/fixtures/skill-catalog-query/skills/deal-memo/SKILL.md b/test/fixtures/skill-catalog-query/skills/deal-memo/SKILL.md
new file mode 100644
index 0000000000..e3eb13e876
--- /dev/null
+++ b/test/fixtures/skill-catalog-query/skills/deal-memo/SKILL.md
@@ -0,0 +1,14 @@
+---
+name: deal-memo
+description: Draft an investment memo from the deal pages and the founder history already in the brain.
+triggers:
+ - write a deal memo
+ - investment memo
+tools:
+ - search
+writes_pages: true
+---
+
+# deal-memo
+
+Draft the memo from brain evidence only.
diff --git a/test/fixtures/skill-catalog-query/skills/inbox-zero/SKILL.md b/test/fixtures/skill-catalog-query/skills/inbox-zero/SKILL.md
new file mode 100644
index 0000000000..c43052a4f2
--- /dev/null
+++ b/test/fixtures/skill-catalog-query/skills/inbox-zero/SKILL.md
@@ -0,0 +1,13 @@
+---
+name: inbox-zero
+description: Triage the inbox into replies, delegations and archives.
+triggers:
+ - clear my inbox
+tools:
+ - search
+writes_pages: false
+---
+
+# inbox-zero
+
+Sort the inbox.
diff --git a/test/fixtures/skill-catalog-query/skills/meeting-prep/SKILL.md b/test/fixtures/skill-catalog-query/skills/meeting-prep/SKILL.md
new file mode 100644
index 0000000000..d90aef7518
--- /dev/null
+++ b/test/fixtures/skill-catalog-query/skills/meeting-prep/SKILL.md
@@ -0,0 +1,15 @@
+---
+name: meeting-prep
+description: Build a briefing before you meet someone, from their recent threads, open loops and what they care about.
+triggers:
+ - prepare for a meeting
+ - brief me on
+tools:
+ - search
+ - query
+writes_pages: false
+---
+
+# meeting-prep
+
+Pull the person page, their recent threads and open loops into one briefing.
diff --git a/test/list-skills-query-6471.test.ts b/test/list-skills-query-6471.test.ts
new file mode 100644
index 0000000000..4aa41c5b99
--- /dev/null
+++ b/test/list-skills-query-6471.test.ts
@@ -0,0 +1,138 @@
+/**
+ * #6471 (wave 15 P7.6): `list_skills query` ranks the version 1 host catalog
+ * by lexical token overlap over each skill's name, triggers and description,
+ * drops skills that match nothing, caps the list at `limit` (default 10) and
+ * annotates each kept skill with `match`. Without `query` the response is
+ * byte-identical to before. On the shared catalogs (`schema_version: 2`, or an
+ * active shared catalog on a version 1 call) `query` is refused with
+ * `invalid_params` before any catalog read, never silently ignored.
+ *
+ * Protects: the ranked order, the drop of zero-score skills, the unchanged
+ * no-query bytes and the shared-catalog refusal. Fails when: ranking stops
+ * reading descriptions (the query below shares no trigger words), when the
+ * no-query shape changes, or when a shared catalog starts ignoring `query`.
+ * Why new: `test/skill-catalog.test.ts` covers the unranked catalog only.
+ * Seam: none; the ranking is a pure function of the catalog.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { buildSkillCatalog } from '../src/core/skill-catalog.ts';
+import { skillsCatalogOperations } from '../src/core/ops/skills-catalog.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'skill-catalog-query', 'skills');
+const listSkills = skillsCatalogOperations.find(op => op.name === 'list_skills')!;
+
+function stubCtx(remote: boolean, scopes?: string[]): OperationContext {
+ return {
+ remote,
+ auth: scopes ? { token: 't', clientId: 'c', scopes } : undefined,
+ config: {} as OperationContext['config'],
+ engine: null as unknown as OperationContext['engine'],
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ sourceId: 'default',
+ } as OperationContext;
+}
+
+describe('buildSkillCatalog with query (#6471)', () => {
+ test('ranks by description overlap when the query shares no trigger words; zero-match skills are dropped', () => {
+ const ranked = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'open loops and recent threads with a person' });
+ expect(ranked.skills.map(s => s.name)).toEqual(['meeting-prep']);
+ expect(ranked.count).toBe(1);
+ expect(ranked.skills[0].match).toEqual({ score: expect.any(Number), matched_on: 'description' });
+ expect(ranked.skills[0].match!.score).toBeGreaterThan(0);
+ });
+
+ test('a trigger phrase contained in the query outranks a description-only match', () => {
+ const ranked = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'write a deal memo about the founder history before the meeting' });
+ expect(ranked.skills.map(s => s.name)).toEqual(['deal-memo', 'meeting-prep']);
+ expect(ranked.skills[0].match!.matched_on).toBe('trigger');
+ expect(ranked.skills[0].match!.score).toBeGreaterThan(ranked.skills[1].match!.score);
+ });
+
+ test('RESOLVER.md triggers count, name tokens count, and limit caps the ranked list', () => {
+ const byResolver = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'who am I meeting today' });
+ expect(byResolver.skills[0]).toMatchObject({ name: 'meeting-prep', match: { matched_on: 'trigger' } });
+ const byName = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'inbox' });
+ expect(byName.skills.map(s => s.name)).toEqual(['inbox-zero']);
+ const capped = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'memo meeting inbox', limit: 1 });
+ expect(capped.skills).toHaveLength(1);
+ expect(capped.count).toBe(1);
+ });
+
+ test('without query the catalog is byte-identical to the unranked build (no match field, name order, full count)', () => {
+ const plain = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config');
+ const withEmpty = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: ' ' });
+ expect(JSON.stringify(withEmpty)).toBe(JSON.stringify(plain));
+ expect(plain.skills.map(s => s.name)).toEqual(['deal-memo', 'inbox-zero', 'meeting-prep']);
+ expect(plain.skills.every(s => !('match' in s))).toBe(true);
+ expect(plain.count).toBe(3);
+ });
+
+ test('section filtering runs before ranking', () => {
+ const ranked = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'meeting memo inbox', section: 'no-such-section' });
+ expect(ranked.skills).toEqual([]);
+ });
+
+ test('a query that matches nothing returns an empty ranked list, not the whole catalog', () => {
+ const ranked = buildSkillCatalog(stubCtx(true, ['read']), FIXTURE, 'config', { query: 'zxqv plorth' });
+ expect(ranked.skills).toEqual([]);
+ expect(ranked.count).toBe(0);
+ });
+});
+
+describe('list_skills query over the operation (#6471)', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('mcp.publish_skills', 'true');
+ await engine.setConfig('mcp.skills_dir', FIXTURE);
+ });
+ const ctx = (): OperationContext => ({
+ engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['read'] } as never, sourceId: 'default',
+ });
+
+ test('host catalog: query ranks, no query stays byte-identical', async () => {
+ const plain = await listSkills.handler(ctx(), {}) as { skills: Array<{ name: string }> };
+ const again = await listSkills.handler(ctx(), {}) as unknown;
+ expect(JSON.stringify(again)).toBe(JSON.stringify(plain));
+ expect(plain.skills.map(s => s.name)).toEqual(['deal-memo', 'inbox-zero', 'meeting-prep']);
+ const ranked = await listSkills.handler(ctx(), { query: 'open loops and recent threads with a person' }) as { skills: Array<{ name: string; match?: unknown }> };
+ expect(ranked.skills.map(s => s.name)).toEqual(['meeting-prep']);
+ expect(ranked.skills[0].match).toMatchObject({ matched_on: 'description' });
+ });
+
+ test('schema_version 2 with query is refused invalid_params before any read', async () => {
+ const queries: string[] = [];
+ const recording = { ...ctx(), engine: { ...engine, executeRaw: async (sql: string) => { queries.push(sql); return []; } } as unknown as PGLiteEngine };
+ await expect(listSkills.handler(recording, { schema_version: 2, query: 'meeting' })).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(queries).toEqual([]);
+ });
+
+ test('an active shared catalog with query is refused invalid_params; the catalog itself is never read', async () => {
+ // A brain with skill bundles on: persistence_brain.skill_bundles_enabled is what routes list_skills to the shared catalog.
+ const queries: string[] = [];
+ const shared = { ...ctx(), engine: {
+ getConfig: async (key: string) => (key === 'mcp.publish_skills' ? 'true' : null),
+ executeRaw: async (sql: string) => {
+ queries.push(sql);
+ if (sql.includes('FROM persistence_brain')) return [{ skill_bundles_enabled: true }];
+ throw new Error(`shared catalog read reached the engine: ${sql}`);
+ },
+ } as unknown as PGLiteEngine };
+ const error = await listSkills.handler(shared, { query: 'meeting' }).catch((e: unknown) => e) as { code?: string; message?: string };
+ expect(error.code).toBe('invalid_params');
+ expect(String(error.message)).toContain('query');
+ expect(queries.filter(q => !q.includes('FROM persistence_brain'))).toEqual([]);
+ });
+});