:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): rank project skills before search limit (#104310)
Richard Solomoucd98c05b6310
diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex dd4631f8c7fd..ddfdd7b8e6f3 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -236,6 +236,10 @@ class LLMSkillSearchMatchSerializer(serializers.Serializer):class LLMSkillSearchResultSerializer(serializers.Serializer):name = serializers.CharField(help_text="Unique skill name.")description = serializers.CharField(help_text="What this skill does and when to use it.")+ score = serializers.IntegerField(+ min_value=1,+ help_text="Relevance score used to rank this result. Higher scores are more relevant.",+ )matches = LLMSkillSearchMatchSerializer(many=True,help_text="Up to two locations that matched the search query, ordered by field relevance.",diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 9387f6b48323..201ff24e8266 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,12 +1,14 @@+import reimport hashlibfrom collections.abc import Sequencefrom difflib import get_close_matches-from typing import Any, cast+from typing import Any, Literal, Protocol, castfrom urllib.parse import urlencodefrom uuid import UUIDfrom django.db import IntegrityError, OperationalError, transaction-from django.db.models import Case, Exists, IntegerField, OuterRef, Q, QuerySet, Value, When+from django.db.models import Case, Exists, Expression, IntegerField, OuterRef, Q, QuerySet, Subquery, Value, When+from django.db.models.functions import Coalescefrom django.http import HttpResponse, HttpResponseBasefrom django.utils.cache import get_conditional_response, patch_cache_control, patch_vary_headers@@ -163,6 +165,20 @@ SKILL_SEARCH_RESULT_LIMIT = 10SKILL_SEARCH_MATCH_LIMIT = 2SKILL_SEARCH_EXCERPT_LENGTH = 300SKILL_SEARCH_TIMEOUT_MS = 5_000+SKILL_SEARCH_EXACT_NAME_BONUS = 5_000+SKILL_SEARCH_MAX_TOKENS = 8+SKILL_SEARCH_MIN_TOKEN_LENGTH = 2+SKILL_SEARCH_MIN_STEM_LENGTH = 5+SKILL_SEARCH_DERIVATIONAL_SUFFIXES = ("ations", "ation", "tions", "tion", "ings", "ing", "ed")+SKILL_SEARCH_SIBILANT_ES_ENDINGS = ("ches", "shes", "sses", "xes", "zes")+SkillSearchField = Literal["name", "description", "body", "path", "content"]+SKILL_SEARCH_FIELD_LOOKUPS: dict[SkillSearchField, str] = {+ "name": "name__icontains",+ "description": "description__icontains",+ "body": "body__icontains",+ "path": "path__icontains",+ "content": "content__icontains",+}# A 404 offers a few near-miss names, not a listing: `skill-list` is still the way to browse.MAX_SKILL_NAME_SUGGESTIONS = 3SKILL_NAME_SUGGESTION_CUTOFF = 0.6@@ -193,6 +209,111 @@ def _content_search_match(content: str, query: str, *, matched_field: str, path:}+def _skill_search_tokens(query: str) -> list[tuple[str, ...]]:+ raw_tokens = list(dict.fromkeys(re.findall(r"[^\W_]+", query.lower())))+ informative_tokens = [token for token in raw_tokens if len(token) >= SKILL_SEARCH_MIN_TOKEN_LENGTH]+ bounded_tokens = sorted(informative_tokens, key=len, reverse=True)[:SKILL_SEARCH_MAX_TOKENS] or raw_tokens[:1]+ return [_skill_search_variants(token) for token in bounded_tokens]+++def _skill_search_variants(token: str) -> tuple[str, ...]:+ if len(token) < 6 or not token.isascii() or not token.isalpha():+ return (token,)++ stems: list[str] = []+ suffix = next(+ (+ candidate+ for candidate in SKILL_SEARCH_DERIVATIONAL_SUFFIXES+ if len(token) > len(candidate) and token.endswith(candidate)+ ),+ None,+ )+ if suffix is not None:+ stems.append(token[: -len(suffix)])+ elif token.endswith("ies"):+ stems.append(f"{token[:-3]}y")+ elif token.endswith(SKILL_SEARCH_SIBILANT_ES_ENDINGS):+ stems.append(token[:-2])+ elif token.endswith("es"):+ stems.extend((token[:-1], token[:-2]))+ elif token.endswith("s") and token != "status" and not token.endswith(("is", "ss")):+ stems.append(token[:-1])+ else:+ return (token,)++ variants = [token]+ for stem in stems:+ variants.append(stem)+ if len(stem) >= 2 and stem[-1] == stem[-2]:+ variants.append(stem[:-1])+ return tuple(dict.fromkeys(variant for variant in variants if len(variant) >= SKILL_SEARCH_MIN_STEM_LENGTH))+++def _skill_search_variant_query(field: SkillSearchField, variants: Sequence[str]) -> Q:+ lookup = SKILL_SEARCH_FIELD_LOOKUPS[field]+ query = Q()+ for variant in variants:+ query |= Q(**{lookup: variant})+ return query+++def _skill_search_all_tokens_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:+ query = Q()+ for variants in tokens:+ query &= _skill_search_variant_query(field, variants)+ return query+++def _skill_search_any_token_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:+ query = Q()+ for variants in tokens:+ query |= _skill_search_variant_query(field, variants)+ return query+++def _skill_search_field_query(field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]]) -> Q:+ return Q(**{SKILL_SEARCH_FIELD_LOOKUPS[field]: phrase}) | _skill_search_any_token_query(field, tokens)+++def _skill_search_field_score(+ field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]], weight: int+) -> Expression:+ phrase_score = Case(+ When(_skill_search_field_query(field, phrase, ()), then=Value(weight * 2)),+ default=Value(0),+ output_field=IntegerField(),+ )+ if not tokens:+ return phrase_score++ partial_weight = max(1, weight // len(tokens) // 4)+ partial_score: Expression = Value(0, output_field=IntegerField())+ for variants in tokens:+ partial_score += Case(+ When(_skill_search_variant_query(field, variants), then=Value(partial_weight)),+ default=Value(0),+ output_field=IntegerField(),+ )+ token_score = Case(+ When(_skill_search_all_tokens_query(field, tokens), then=Value(weight)),+ default=partial_score,+ output_field=IntegerField(),+ )+ return phrase_score + token_score+++class _ScoredSkill(Protocol):+ search_score: int+++def _skill_search_match_term(content: str, phrase: str, tokens: Sequence[Sequence[str]]) -> str | None:+ lowered = content.lower()+ if phrase.lower() in lowered:+ return phrase+ return next((variant for variants in tokens for variant in variants if variant in lowered), None)++def _is_markdown_file_query() -> Q:return Q(path__iendswith=".md") | Q(content_type__icontains="markdown")@@ -373,12 +494,12 @@ class SkillBundleSustainedThrottle(_SkillUserThrottle):class SkillSearchBurstThrottle(_SkillUserThrottle):scope = "skills_search_burst"- rate = BurstRateThrottle.rate+ rate = "60/minute"class SkillSearchSustainedThrottle(_SkillUserThrottle):scope = "skills_search_sustained"- rate = SustainedRateThrottle.rate+ rate = "600/hour"class SkillListBurstThrottle(_SkillUserThrottle):@@ -691,47 +812,69 @@ class LLMSkillViewSet(def _get_search_queryset(self, query: str) -> QuerySet[LLMSkill]:skill_files = LLMSkillFile.objects.filter(skill_id=OuterRef("pk"))+ tokens = _skill_search_tokens(query)+ matching_skill_files = skill_files.filter(+ _skill_search_field_query("path", query, tokens)+ | (_is_markdown_file_query() & _skill_search_field_query("content", query, tokens))+ )+ file_path_score = Coalesce(+ Subquery(+ skill_files.annotate(score=_skill_search_field_score("path", query, tokens, 120))+ .order_by("-score")+ .values("score")[:1],+ output_field=IntegerField(),+ ),+ Value(0),+ )+ file_content_score = Coalesce(+ Subquery(+ skill_files.filter(_is_markdown_file_query())+ .annotate(score=_skill_search_field_score("content", query, tokens, 40))+ .order_by("-score")+ .values("score")[:1],+ output_field=IntegerField(),+ ),+ Value(0),+ )+queryset = LLMSkill.objects.filter(team=self.team,deleted=False,is_latest=True,category="",- ).annotate(- search_file_path_match=Exists(skill_files.filter(path__icontains=query)),- search_file_content_match=Exists(skill_files.filter(_is_markdown_file_query(), content__icontains=query)),)queryset = self.user_access_control.filter_queryset_by_access_level(queryset, resource="llm_skill")- return (- queryset.filter(- Q(name__icontains=query)- | Q(description__icontains=query)- | Q(body__icontains=query)- | Q(search_file_path_match=True)- | Q(search_file_content_match=True)- )- .annotate(- search_rank=Case(- When(name__iexact=query, then=Value(0)),- When(name__icontains=query, then=Value(1)),- When(description__icontains=query, then=Value(2)),- When(body__icontains=query, then=Value(3)),- When(search_file_path_match=True, then=Value(4)),- When(search_file_content_match=True, then=Value(5)),- default=Value(6),- output_field=IntegerField(),- )- )- .order_by("search_rank", "name", "id")[:SKILL_SEARCH_RESULT_LIMIT]+ queryset = queryset.filter(+ _skill_search_field_query("name", query, tokens)+ | _skill_search_field_query("description", query, tokens)+ | _skill_search_field_query("body", query, tokens)+ | Q(Exists(matching_skill_files)))+ exact_name_score = Case(+ When(name__iexact=query, then=Value(SKILL_SEARCH_EXACT_NAME_BONUS)),+ default=Value(0),+ output_field=IntegerField(),+ )+ score = (+ exact_name_score+ + _skill_search_field_score("name", query, tokens, 1_000)+ + _skill_search_field_score("description", query, tokens, 300)+ + _skill_search_field_score("body", query, tokens, 80)+ + file_path_score+ + file_content_score+ )+ return queryset.annotate(search_score=score).order_by("-search_score", "name", "id")[:SKILL_SEARCH_RESULT_LIMIT]+def _get_search_matches(self, skill: LLMSkill, query: str) -> list[dict[str, Any]]:matches: list[dict[str, Any]] = []- lowered_query = query.lower()+ tokens = _skill_search_tokens(query)- if lowered_query in skill.name.lower():+ if _skill_search_match_term(skill.name, query, tokens) is not None:matches.append({"matched_field": "name", "excerpt": skill.name})- if lowered_query in skill.description.lower():- match_index = skill.description.lower().find(lowered_query)+ description_match = _skill_search_match_term(skill.description, query, tokens)+ if description_match is not None:+ match_index = skill.description.lower().find(description_match.lower())excerpt_start = max(0, match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)matches.append({@@ -739,15 +882,21 @@ class LLMSkillViewSet("excerpt": skill.description[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH],})- body_match = _content_search_match(skill.body, query, matched_field="body", path="SKILL.md")+ body_match_term = _skill_search_match_term(skill.body, query, tokens)+ body_match = (+ _content_search_match(skill.body, body_match_term, matched_field="body", path="SKILL.md")+ if body_match_term is not None+ else None+ )if body_match is not None:matches.append(body_match)if len(matches) < SKILL_SEARCH_MATCH_LIMIT:remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)matching_paths = (- skill.files.filter(path__icontains=query)- .order_by("path")+ skill.files.filter(_skill_search_field_query("path", query, tokens))+ .annotate(search_match_score=_skill_search_field_score("path", query, tokens, 120))+ .order_by("-search_match_score", "path").values_list("path", flat=True)[:remaining_match_count])for path in matching_paths:@@ -755,15 +904,22 @@ class LLMSkillViewSet(if len(matches) < SKILL_SEARCH_MATCH_LIMIT:remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)+ file_content_query = Q(content__icontains=query)+ for variants in tokens:+ file_content_query |= _skill_search_variant_query("content", variants)content_files = (- skill.files.filter(_is_markdown_file_query(), content__icontains=query)- .order_by("path")+ skill.files.filter(_is_markdown_file_query(), file_content_query)+ .annotate(search_match_score=_skill_search_field_score("content", query, tokens, 40))+ .order_by("-search_match_score", "path").values_list("path", "content"))[:remaining_match_count]for path, content in content_files:+ match_term = _skill_search_match_term(content, query, tokens)+ if match_term is None:+ continuematch = _content_search_match(content,- query,+ match_term,matched_field="file_content",path=path,)@@ -795,14 +951,16 @@ class LLMSkillViewSet(query = self._get_search_query(request)try:with execute_with_timeout(SKILL_SEARCH_TIMEOUT_MS):- results = [- {- "name": skill.name,- "description": skill.description,- "matches": self._get_search_matches(skill, query),- }- for skill in self._get_search_queryset(query)- ]+ results: list[dict[str, Any]] = []+ for skill in self._get_search_queryset(query):+ results.append(+ {+ "name": skill.name,+ "description": skill.description,+ "score": cast(_ScoredSkill, skill).search_score,+ "matches": self._get_search_matches(skill, query),+ }+ )except OperationalError as err:if not isinstance(err.__cause__, psycopg.errors.QueryCanceled):raisediff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 94beec99fd26..6e0142ac3f49 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -45,6 +45,7 @@ from ...api.skill_services import (resolve_skill_owners,set_skill_owners,)+from ...api.skills import SKILL_SEARCH_RESULT_LIMITfrom ...marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH, parse_skill_mdfrom ...models.skills import LLMSkill, LLMSkillFile@@ -606,21 +607,135 @@ class TestLLMSkillAPI(APIBaseTest):"needle","needle-name","description-skill",- "body-skill","file-path-skill",+ "body-skill","file-content-skill",]assert [result["matches"][0]["matched_field"] for result in results] == ["name","name","description",- "body","file_path",+ "body","file_content",]- assert results[3]["matches"][0]["path"] == "SKILL.md"+ assert [result["score"] for result in results] == [8000, 3000, 900, 360, 240, 120]+ assert results[4]["matches"][0]["path"] == "SKILL.md"assert results[5]["matches"][0]["line"] == 2+ @parameterized.expand(+ [+ (+ "path",+ [+ {"path": "references/a-support.txt", "content": "No match."},+ {"path": "references/z-support-queue.txt", "content": "No match."},+ ],+ "references/z-support-queue.txt",+ ),+ (+ "content",+ [+ {"path": "references/a.md", "content": "Support only.", "content_type": "text/markdown"},+ {+ "path": "references/z.md",+ "content": "Support queue.",+ "content_type": "text/markdown",+ },+ ],+ "references/z.md",+ ),+ ]+ )+ def test_search_skills_returns_the_file_that_produced_the_highest_score(+ self, _label: str, files: list[dict[str, str]], expected_path: str+ ) -> None:+ skill = self.create_skill(name="ranked-file-match", description="A ranked file match.", body="# Body")+ for file in files:+ LLMSkillFile.objects.create(skill=skill, **file)++ response = self.client.get(self._url("search?query=support%20queue"))++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"][0]["matches"][0]["path"] == expected_path++ def test_search_skills_ranks_multi_token_project_workflow_before_generic_matches(self):+ self.create_skill(+ name="self-driving-support-hero",+ description="Run the prioritized support inbox for tickets by SLA and priority.",+ body="# Support hero\nWork the queue without missing tickets.",+ )+ for index in range(12):+ self.create_skill(+ name=f"generic-support-queue-{index:02d}",+ description="Generic project workflow.",+ body="# Generic\nLook up tickets.",+ )++ response = self.client.get(self._url("search?query=support%20queue%20tickets"))++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert results[0]["name"] == "self-driving-support-hero"+ assert results[0]["score"] == 213+ assert len(results) == SKILL_SEARCH_RESULT_LIMIT++ def test_search_skills_ranks_exact_name_before_substring_matches(self):+ self.create_skill(name="support", description="Exact match.", body="# Support")+ for index in range(SKILL_SEARCH_RESULT_LIMIT):+ self.create_skill(+ name=f"{chr(ord('a') + index)}-support",+ description="Substring match.",+ body="# Support",+ )++ response = self.client.get(self._url("search?query=support"))++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"][0]["name"] == "support"++ def test_search_skills_bounds_token_expansion(self):+ self.create_skill(name="first-token-match", description="Contains alpha.", body="# First")+ self.create_skill(name="long-token-match", description="Contains ninthtoken.", body="# Long")+ self.create_skill(name="overflow-match", description="Contains golf.", body="# Overflow")++ response = self.client.get(+ self._url("search?query=a%20alpha%20bravo%20charlie%20delta%20echo%20foxtrot%20golf%20hotel%20ninthtoken")+ )++ assert response.status_code == status.HTTP_200_OK+ assert [result["name"] for result in response.json()["results"]] == [+ "first-token-match",+ "long-token-match",+ ]++ @parameterized.expand(+ [+ ("ies_plural", "queries", "querying", "Run a query.", True),+ ("u_plural", "bayous", "wetlands", "Explore a bayou.", True),+ ("short_derived_stem", "types", "classification", "Review a stereotype.", False),+ ("distinct_final_character", "states", "statistics", "Analyze numerical data.", False),+ ]+ )+ def test_search_skills_applies_bounded_stemming(+ self, _label: str, query: str, name: str, description: str, should_match: bool+ ) -> None:+ self.create_skill(name=name, description=description, body="# Guide")++ response = self.client.get(self._url(f"search?query={query}"))++ assert response.status_code == status.HTTP_200_OK+ assert [result["name"] for result in response.json()["results"]] == ([name] if should_match else [])++ def test_search_skills_does_not_stem_singular_s_words(self):+ self.create_skill(name="statue", description="Sculpture reference.", body="# Statue")+ self.create_skill(name="support-workflow", description="Track support status.", body="# Support workflow")++ response = self.client.get(self._url("search?query=status"))++ assert response.status_code == status.HTTP_200_OK+ assert [result["name"] for result in response.json()["results"]] == ["support-workflow"]+def test_search_skills_limits_file_queries_to_remaining_matches(self):path_skill = self.create_skill(name="path-skill", body="# Path\nContains needle.")content_skill = self.create_skill(name="content-skill", description="Contains needle.")@@ -2242,6 +2357,7 @@ class TestSkillAccessControlRBAC(APIBaseTest):{"name": self.skill.name,"description": self.skill.description,+ "score": 240,"matches": [{"matched_field": "body",diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex a83ca21ce104..6dedaecbe8a6 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -826,6 +826,11 @@ export interface LLMSkillSearchResultApi {name: string/** What this skill does and when to use it. */description: string+ /**+ * Relevance score used to rank this result. Higher scores are more relevant.+ * @minimum 1+ */+ score: number/** Up to two locations that matched the search query, ordered by field relevance. */matches: LLMSkillSearchMatchApi[]}diff --git a/services/mcp/README.md b/services/mcp/README.mdindex 9d5e9d0539f4..a3c941cd8b1d 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -297,11 +297,11 @@ Optional, task-specific guidance is served through the same tool:- `learn urls` loads the PostHog app link formatting rules (kept inline for other clients; served as a guide on Claude web and desktop to protect the schema budget).- `learn feedback` loads feedback guidance when feedback is available.- `learn skills` lists qualified names from the published PostHog bundle (`posthog:`) and the current project's Skills store (`project:`).-- `learn -s <query>` searches both sources in names, descriptions, Markdown bodies, and bundled file paths. Results from both sources are merged into one relevance order.+- `learn -s "<up to 8 keywords>"` searches both sources in names, descriptions, Markdown bodies, and bundled file paths. Longer keywords take priority when a query contains more than eight. Results from both sources are merged into one relevance order.- `learn -d <source>:<skill> [...]` prints the one-line description of each named skill without reading its body (up to 20 per call). Unknown names are reported inline without failing the batch.- `learn posthog:<skill> [path]` or `learn project:<skill> [path]` reads a skill or one of its bundled files.- `learn <source>:<skill> <path> [path...]` reads several bundled files, and `learn <source>:<skill> [<source>:<skill>...]` reads several skills, in one call (up to 10 targets).-- `learn <source>:<skill> <path> -s <query>` searches within one Markdown file.+- `learn <source>:<skill> <path> -s "<up to 8 keywords>"` searches within one Markdown file.- `learn <source>:<skill> <path> --lines <start>:<end>` reads an inclusive line range.Built-in guides are specific to Claude web and desktop. Skill discovery is independently available to every cli-mode client when the `mcp-exec-skills` feature flag is enabled. Other clients, including Claude Code, receive only the skill commands and do not receive Claude's built-in guides. If the flag is missing, disabled, or cannot be evaluated, skill commands are omitted from the schema and rejected at runtime.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ccf419d426ef..3ad73ac232a1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53818,6 +53818,11 @@ export namespace Schemas {name: string;/** What this skill does and when to use it. */description: string;+ /**+ * Relevance score used to rank this result. Higher scores are more relevant.+ * @minimum 1+ */+ score: number;/** Up to two locations that matched the search query, ordered by field relevance. */matches: LLMSkillSearchMatch[];}diff --git a/services/mcp/src/skills/project-skill-catalog.ts b/services/mcp/src/skills/project-skill-catalog.tsindex caa4c4b017d0..60b697c1bfd3 100644--- a/services/mcp/src/skills/project-skill-catalog.ts+++ b/services/mcp/src/skills/project-skill-catalog.ts@@ -1,14 +1,11 @@import type { Schemas } from '@/api/generated'import {- extractQueryTokens,formatLearnDocument,formatLearnFile,type LearnSearchResult,type LearnSearchSnippet,makeSkillFile,- MIN_STEM_VARIANT_LENGTH,readLearnLines,- scoreProjectSearchResult,searchLearnFile,type SkillFile,} from '@/skills/skill-catalog'@@ -18,8 +15,6 @@ const PROJECT_SKILL_LIST_PAGE_SIZE = 100const PROJECT_SKILL_LIST_LIMIT = 200// Matches MAX_SKILL_BODY_BYTES in products/skills/backend/api/skill_serializers.py.const MAX_PROJECT_SKILL_BODY_BYTES = 1_000_000-// Zero-hit fallback fan-out: at most this many single-token backend searches, longest tokens first.-const MAX_FALLBACK_SEARCH_TOKENS = 3export interface ProjectSkillList {count: number@@ -86,72 +81,15 @@ export class ProjectSkillCatalog {async searchResults(query: string): Promise<LearnSearchResult[]> {const response = await this.search(query)- const results = response.results.map((skill) =>- this.toSearchResult(query, skill.name, skill.description, skill.matches)- )- if (results.length > 0) {- return results- }- // The backend icontains-matches the WHOLE query, so a natural multi-word query returns- // nothing even when a skill's body or bundled files match individual words — which would- // bias the cross-source merge against project skills, since PostHog skills are searched- // locally over full content. Recover cheapest-first: bounded per-token backend searches- // (these do reach body/file content), then a purely local rank of the memoized listing.- const tokenResults = await this.searchByTokens(query)- if (tokenResults.length > 0) {- return tokenResults- }- return await this.rankListing(query)- }-- /**- * Whole-query backend search yielded nothing: retry with a few informative single tokens so- * body/file-content matches surface. Each token search runs independently — a failing one must- * not sink the fallback — and hits are merged by skill name, then scored against the ORIGINAL- * full query so cross-source merge ordering stays consistent.- */- private async searchByTokens(query: string): Promise<LearnSearchResult[]> {- const tokens = informativeSearchTokens(query)- if (tokens.length === 0) {- return []- }- const responses = await Promise.allSettled(tokens.map((token) => this.search(token)))- const merged = new Map<string, { description: string; matches: Schemas.LLMSkillSearchMatch[] }>()- for (const outcome of responses) {- if (outcome.status !== 'fulfilled') {- continue- }- for (const skill of outcome.value.results) {- const existing = merged.get(skill.name)- if (existing) {- existing.matches.push(...skill.matches)- } else {- merged.set(skill.name, { description: skill.description, matches: [...skill.matches] })- }- }- }- return [...merged.entries()].map(([name, { description, matches }]) =>- this.toSearchResult(query, name, description, matches)+ return response.results.map((skill) =>+ this.toSearchResult(skill.name, skill.description, skill.score, skill.matches))}- /** Last-resort local rank of the memoized listing (name + description only) when even per-token search finds nothing. */- private async rankListing(query: string): Promise<LearnSearchResult[]> {- const { skills } = await this.list()- return skills- .map((skill) => ({- identifier: `project:${skill.name}`,- description: skill.description,- snippets: [] as LearnSearchSnippet[],- score: scoreProjectSearchResult(query, skill.name, skill.description, []),- }))- .filter((result) => result.score > 0)- }-private toSearchResult(- query: string,name: string,description: string,+ score: number,matches: readonly Schemas.LLMSkillSearchMatch[]): LearnSearchResult {return {@@ -169,13 +107,7 @@ export class ProjectSkillCatalog {text: match.excerpt,}))),- // Scored client-side so project and PostHog results merge into one relevance order.- score: scoreProjectSearchResult(- query,- name,- description,- matches.map((match) => match.matched_field)- ),+ score,}}@@ -309,17 +241,6 @@ export class ProjectSkillCatalog {}}-/**- * Informative single tokens for the zero-hit per-token fallback: the scorer's own tokenization,- * dropping tokens too short to be selective, longest first (more specific), capped for fan-out.- */-function informativeSearchTokens(query: string): string[] {- return extractQueryTokens(query)- .filter((token) => token.length >= MIN_STEM_VARIANT_LENGTH)- .sort((left, right) => right.length - left.length)- .slice(0, MAX_FALLBACK_SEARCH_TOKENS)-}-function dedupeSnippets(snippets: LearnSearchSnippet[]): LearnSearchSnippet[] {const seen = new Set<string>()const unique: LearnSearchSnippet[] = []diff --git a/services/mcp/src/skills/skill-catalog.ts b/services/mcp/src/skills/skill-catalog.tsindex 3f85cdcaf4aa..aaafe926c81e 100644--- a/services/mcp/src/skills/skill-catalog.ts+++ b/services/mcp/src/skills/skill-catalog.ts@@ -11,6 +11,7 @@ const SEARCH_CONTEXT_LINES = 2const MAX_ARCHIVE_FILES = 5_000const MAX_ARCHIVE_FILE_BYTES = 8 * 1024 * 1024const MAX_ARCHIVE_UNCOMPRESSED_BYTES = 64 * 1024 * 1024+const EXACT_NAME_SCORE_BONUS = 5_000type SkillFileKind = 'markdown' | 'script' | 'other'@@ -423,45 +424,23 @@ export function formatLearnSearchResults(results: readonly LearnSearchResult[]):return fitLearnOutput(sections.join('\n\n'))}-// Per-match tier bonuses mirroring `rankSkill`'s content weights, keyed by the-// backend's `matched_field`. Name and description already score via their own-// text below, so they add no tier bonus here.-const MATCHED_FIELD_TIER_BONUS: Record<string, number> = {- body: 80,- file_path: 120,- file_content: 40,-}--/**- * Client-side relevance score for a project search result, comparable to `SkillCatalog`'s- * `rankSkill` scores so both sources can merge into one ranked list. The project body/file- * text is not available client-side, so per-match tier bonuses derived from `matched_field`- * stand in for content scoring.- */-export function scoreProjectSearchResult(- query: string,- name: string,- description: string,- matchedFields: readonly string[]-): number {- const normalizedQuery = normalizeQuery(query)- let score = scoreText(name, normalizedQuery, 1_000) + scoreText(description, normalizedQuery, 300)- for (const field of matchedFields) {- score += MATCHED_FIELD_TIER_BONUS[field] ?? 0- }- return score-}-function rankSkill(skill: SkillDefinition, query: NormalizedQuery): RankedSkill | null {- let score = scoreText(skill.name, query, 1_000) + scoreText(skill.description, query, 300)- const snippets: LearnSearchSnippet[] = []+ let score =+ (skill.name.toLowerCase() === query.phrase ? EXACT_NAME_SCORE_BONUS : 0) ++ scoreText(skill.name, query, 1_000) ++ scoreText(skill.description, query, 300)+ let filePathScore = 0+ let fileContentScore = 0+ const snippetCandidates: { score: number; snippet: LearnSearchSnippet }[] = []for (const file of skill.files) {- score += scoreText(file.path, query, 120)+ const isSkillFile = file.path === 'SKILL.md'+ if (!isSkillFile) {+ filePathScore = Math.max(filePathScore, scoreText(file.path, query, 120))+ }if (file.kind !== 'markdown') {continue}- const isSkillFile = file.path === 'SKILL.md'// Exclude the YAML frontmatter from SKILL.md scoring and snippets: the// description already scores via `skill.description` (avoid double-counting)// and its snippet would just repeat the description line already printed.@@ -469,21 +448,30 @@ function rankSkill(skill: SkillDefinition, query: NormalizedQuery): RankedSkillconst contentWeight = isSkillFile ? 80 : 40const scoredContent =frontmatterLines > 0 ? splitLines(file.content).slice(frontmatterLines).join('\n') : file.content- score += scoreText(scoredContent, query, contentWeight)- if (snippets.length < MAX_GLOBAL_SNIPPETS) {- const snippet = findSnippet(file, query, frontmatterLines)- if (snippet) {- snippets.push(snippet)- }+ const contentScore = scoreText(scoredContent, query, contentWeight)+ if (isSkillFile) {+ score += contentScore+ } else {+ fileContentScore = Math.max(fileContentScore, contentScore)+ }+ const snippet = findSnippet(file, query, frontmatterLines)+ if (snippet) {+ snippetCandidates.push({ score: contentScore, snippet })}}+ score += filePathScore + fileContentScore+ const snippets = snippetCandidates+ .sort((left, right) => right.score - left.score || left.snippet.path.localeCompare(right.snippet.path))+ .slice(0, MAX_GLOBAL_SNIPPETS)+ .map(({ snippet }) => snippet)+return score > 0 ? { skill, score, snippets } : null}interface QueryToken {// A token matches text if the text includes ANY variant. Variants add light- // stemming (analyzing → analyz → analy) so related word forms still match.+ // stemming so related word forms still match.variants: string[]}@@ -492,17 +480,19 @@ interface NormalizedQuery {tokens: QueryToken[]}-// Longest-first so the longest matching suffix is stripped (e.g. "sessions" → "session", not "sessionation").-const STEM_SUFFIXES = ['ations', 'ation', 'tions', 'tion', 'ings', 'ing', 'es', 'ed', 's']+const DERIVATIONAL_STEM_SUFFIXES = ['ations', 'ation', 'tions', 'tion', 'ings', 'ing', 'ed']+const SIBILANT_ES_ENDINGS = ['ches', 'shes', 'sses', 'xes', 'zes']+const MAX_SEARCH_TOKENS = 8+const MIN_SEARCH_TOKEN_LENGTH = 2// Shortest token length the scorer treats as informative — also the floor for derived stems.export const MIN_STEM_VARIANT_LENGTH = 5/**- * Deduped, lower-cased query tokens using the same tokenization the scorer applies, exported so- * callers derive tokens identically instead of inventing a divergent tokenizer.+ * Bounded, deduped, lower-cased query tokens using the same tokenization the scorer applies,+ * exported so callers derive tokens identically instead of inventing a divergent tokenizer.*/export function extractQueryTokens(query: string): string[] {- return [+ const rawTokens = [...new Set(query.trim()@@ -510,6 +500,12 @@ export function extractQueryTokens(query: string): string[] {.match(/[\p{L}\p{N}]+/gu) ?? []),]+ const informativeTokens = rawTokens.filter((token) => token.length >= MIN_SEARCH_TOKEN_LENGTH)+ return (informativeTokens.length > 0 ? informativeTokens : rawTokens.slice(0, 1))+ .map((token, index) => ({ index, token }))+ .sort((left, right) => right.token.length - left.token.length || left.index - right.index)+ .slice(0, MAX_SEARCH_TOKENS)+ .map(({ token }) => token)}function normalizeQuery(query: string): NormalizedQuery {@@ -530,12 +526,31 @@ function stemVariants(token: string): string[] {if (token.length < 6 || !/^[a-z]+$/.test(token)) {return [token]}- const suffix = STEM_SUFFIXES.find((candidate) => token.length > candidate.length && token.endsWith(candidate))- if (!suffix) {+ const stems: string[] = []+ const suffix = DERIVATIONAL_STEM_SUFFIXES.find(+ (candidate) => token.length > candidate.length && token.endsWith(candidate)+ )+ if (suffix) {+ stems.push(token.slice(0, -suffix.length))+ } else if (token.endsWith('ies')) {+ stems.push(`${token.slice(0, -3)}y`)+ } else if (SIBILANT_ES_ENDINGS.some((ending) => token.endsWith(ending))) {+ stems.push(token.slice(0, -2))+ } else if (token.endsWith('es')) {+ stems.push(token.slice(0, -1), token.slice(0, -2))+ } else if (token.endsWith('s') && token !== 'status' && !token.endsWith('is') && !token.endsWith('ss')) {+ stems.push(token.slice(0, -1))+ } else {return [token]}- const stem = token.slice(0, -suffix.length)- const variants = [token, stem, stem.slice(0, -1)]++ const variants = [token]+ for (const stem of stems) {+ variants.push(stem)+ if (stem.length >= 2 && stem.at(-1) === stem.at(-2)) {+ variants.push(stem.slice(0, -1))+ }+ }return [...new Set(variants.filter((variant) => variant.length >= MIN_STEM_VARIANT_LENGTH))]}diff --git a/services/mcp/src/templates/sections/cli-learn-compact.md b/services/mcp/src/templates/sections/cli-learn-compact.mdindex bb352955e56c..51eeb159bb42 100644--- a/services/mcp/src/templates/sections/cli-learn-compact.md+++ b/services/mcp/src/templates/sections/cli-learn-compact.md@@ -4,7 +4,7 @@ For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, evenLoad exact qualified names; never guess. Follow `SKILL.md`; fetch references on demand. If no match, continue. Advertised topics load separately.-Syntax: `learn [skills|-s <query>|-d <name...>|(posthog|project):<skill> [path...] [-s <query>|--lines <start>:<end>]]`+Syntax: `learn [skills|-s "<up to 8 keywords>"|-d <name...>|(posthog|project):<skill> [path...] [-s "<up to 8 keywords>"|--lines <start>:<end>]]`<example>User: Investigate why checkout conversion dropped this week.diff --git a/services/mcp/src/templates/sections/cli-learn.md b/services/mcp/src/templates/sections/cli-learn.mdindex 57db79345f66..08ed1141022e 100644--- a/services/mcp/src/templates/sections/cli-learn.md+++ b/services/mcp/src/templates/sections/cli-learn.md@@ -6,7 +6,7 @@ For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, evenLoad exact qualified names; never guess. Follow `SKILL.md`; fetch references on demand. If no match, continue. Advertised topics load separately.-Syntax: `learn [skills|-s <query>|-d <name...>|(posthog|project):<skill> [path...] [-s <query>|--lines <start>:<end>]]`+Syntax: `learn [skills|-s "<up to 8 keywords>"|-d <name...>|(posthog|project):<skill> [path...] [-s "<up to 8 keywords>"|--lines <start>:<end>]]`<example>User: At what exposure share does the experiment bias warning fire?diff --git a/services/mcp/src/tools/exec-learn.ts b/services/mcp/src/tools/exec-learn.tsindex 03b98782f707..6f9c33ccf4f6 100644--- a/services/mcp/src/tools/exec-learn.ts+++ b/services/mcp/src/tools/exec-learn.ts@@ -31,13 +31,13 @@ export class SkillsUnavailableError extends Error {const SKILL_COMMANDS = ['learn skills',- 'learn -s <query>',+ 'learn -s "<up to 8 keywords>"','learn -d <source>:<skill> [...]','learn posthog:<skill> [path]','learn project:<skill> [path]','learn <source>:<skill> <path> [path...]','learn <source>:<skill> [<source>:<skill>...]',- 'learn <source>:<skill> <path> -s <query>',+ 'learn <source>:<skill> <path> -s "<up to 8 keywords>"','learn <source>:<skill> <path> --lines <start>:<end>',] as constconst MAX_SEARCH_QUERY_LENGTH = 200diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 1d5ae72fe324..95dbf085f564 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -384,6 +384,7 @@ describe('ToolExecutor', () => {{name: 'team-retention',description: 'Project-specific retention guidance.',+ score: 900,matches: [{matched_field: 'body',diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txtindex 5370d4117838..58a95084cbc3 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt@@ -19,7 +19,7 @@ For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, evenLoad exact qualified names; never guess. Follow `SKILL.md`; fetch references on demand. If no match, continue. Advertised topics load separately.-Syntax: `learn [skills|-s <query>|-d <name...>|(posthog|project):<skill> [path...] [-s <query>|--lines <start>:<end>]]`+Syntax: `learn [skills|-s "<up to 8 keywords>"|-d <name...>|(posthog|project):<skill> [path...] [-s "<up to 8 keywords>"|--lines <start>:<end>]]`<example>User: Investigate why checkout conversion dropped this week.diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 3ac8b906ec6e..8ed71100e8a7 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -105,13 +105,13 @@ describe('exec tool', () => {projectAvailable: false,commands: ['learn skills',- 'learn -s <query>',+ 'learn -s "<up to 8 keywords>"','learn -d <source>:<skill> [...]','learn posthog:<skill> [path]','learn project:<skill> [path]','learn <source>:<skill> <path> [path...]','learn <source>:<skill> [<source>:<skill>...]',- 'learn <source>:<skill> <path> -s <query>',+ 'learn <source>:<skill> <path> -s "<up to 8 keywords>"','learn <source>:<skill> <path> --lines <start>:<end>',],},diff --git a/services/mcp/tests/unit/project-skill-catalog.test.ts b/services/mcp/tests/unit/project-skill-catalog.test.tsindex 3896dd194ed7..0b0cd6f8e0c6 100644--- a/services/mcp/tests/unit/project-skill-catalog.test.ts+++ b/services/mcp/tests/unit/project-skill-catalog.test.ts@@ -227,12 +227,13 @@ describe('ProjectSkillCatalog', () => {expect(request).toHaveBeenCalledTimes(1)})- it('renders only path-bearing matches as snippets', async () => {+ it('preserves the endpoint score and renders only path-bearing matches as snippets', async () => {const request = vi.fn(async () => ({results: [{name: 'retention-analysis',description: 'Find where users stop returning.',+ score: 900,matches: [{ matched_field: 'name', excerpt: 'retention-analysis' },{ matched_field: 'body', path: 'SKILL.md', line: 3, excerpt: 'Weekly retention cohorts.' },@@ -244,60 +245,8 @@ describe('ProjectSkillCatalog', () => {const [result] = await catalog.searchResults('retention')+ expect(result!.score).toBe(900)expect(result!.snippets).toEqual([{ path: 'SKILL.md', line: 3, text: 'Weekly retention cohorts.' }])- })-- it('surfaces a body-only match via per-token search when the whole query misses', async () => {- const request = vi.fn(async ({ path, query }: { path: string; query?: any }) => {- if (path.endsWith('/search/')) {- // Whole multi-word query misses; a single informative token hits on body content.- if (query.query === 'revenue') {- return {- results: [- {- name: 'billing-internals',- description: 'Unrelated title.',- matches: [- {- matched_field: 'body',- path: 'SKILL.md',- line: 12,- excerpt: 'revenue recognition rules',- },- ],- },- ],- }- }- return { results: [] }- }- // Listing has no matching name/description, so only the body match can surface this skill.- return { count: 1, results: [{ name: 'billing-internals', description: 'Unrelated title.' }] }- })- const catalog = new ProjectSkillCatalog(makeContext(request))-- const results = await catalog.searchResults('where is revenue recognized')-- expect(results.map((result) => result.identifier)).toEqual(['project:billing-internals'])- expect(results[0]!.snippets).toContainEqual({ path: 'SKILL.md', line: 12, text: 'revenue recognition rules' })- expect(results[0]!.score).toBeGreaterThan(0)- })-- it('degrades to the listing rank when every per-token search fails', async () => {- const request = vi.fn(async ({ path, query }: { path: string; query?: any }) => {- if (path.endsWith('/search/')) {- if (query.query === 'retention analysis guide') {- return { results: [] } // whole-query miss- }- throw new Error('token search failed') // a failing per-token search must not sink the fallback- }- return { count: 1, results: [{ name: 'retention-analysis', description: 'Analyze retention cohorts.' }] }- })- const catalog = new ProjectSkillCatalog(makeContext(request))-- const results = await catalog.searchResults('retention analysis guide')-- expect(results.map((result) => result.identifier)).toEqual(['project:retention-analysis'])- expect(results[0]!.score).toBeGreaterThan(0)+ expect(request).toHaveBeenCalledTimes(1)})})diff --git a/services/mcp/tests/unit/skill-catalog.test.ts b/services/mcp/tests/unit/skill-catalog.test.tsindex 41fdbd728890..50276a0f8cb3 100644--- a/services/mcp/tests/unit/skill-catalog.test.ts+++ b/services/mcp/tests/unit/skill-catalog.test.ts@@ -6,6 +6,7 @@ import {formatLearnFile,LEARN_OUTPUT_CHAR_LIMIT,makeSkillFile,+ MAX_GLOBAL_SKILLS,readLearnLines,searchLearnFile,SkillCatalog,@@ -89,6 +90,53 @@ describe('SkillCatalog and exec learn', () => {)})+ it('uses the strongest companion file match for its score and snippets', () => {+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'team-guide/SKILL.md': makeSkill('team-guide', 'Internal workflow.', '# Team guide'),+ 'team-guide/references/a.md': '# Guide\n\nSupport only.',+ 'team-guide/references/z.md': '# Guide\n\nSupport queue.',+ })+ )++ expect(catalog.searchResults('support queue')[0]).toMatchObject({+ score: 120,+ snippets: [{ path: 'references/z.md' }],+ })+ })++ it('ranks an exact name before substring matches at the result limit', () => {+ const names = [+ ...Array.from({ length: MAX_GLOBAL_SKILLS }, (_, index) => `${String.fromCharCode(97 + index)}-support`),+ 'support',+ ]+ const catalog = SkillCatalog.fromZip(+ makeArchive(+ Object.fromEntries(+ names.map((name) => [`${name}/SKILL.md`, makeSkill(name, 'Internal workflow.', '# Guide')])+ )+ )+ )++ expect(catalog.searchResults('support')[0]?.identifier).toBe('support')+ })++ it('bounds token expansion while preserving informative matches', () => {+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'first-token-match/SKILL.md': makeSkill('first-token-match', 'Contains alpha.', '# First'),+ 'long-token-match/SKILL.md': makeSkill('long-token-match', 'Contains ninthtoken.', '# Long'),+ 'overflow-match/SKILL.md': makeSkill('overflow-match', 'Contains golf.', '# Overflow'),+ })+ )++ expect(+ catalog+ .searchResults('a alpha bravo charlie delta echo foxtrot golf hotel ninthtoken')+ .map((result) => result.identifier)+ ).toEqual(['first-token-match', 'long-token-match'])+ })+it('returns the rendered skill with a manifest and supports scoped reads', async () => {const catalog = makeCatalog()const learn = new ExecLearnCatalog([], { posthog: catalog })@@ -238,27 +286,43 @@ describe('SkillCatalog and exec learn', () => {})it.each([- ['analyzing', 'trends', true], // analyzing → analy ⊂ "analysis"+ ['analyzing', 'trends', true], // analyzing → analyz ⊂ "analyze"['funnels', 'conversion', true], // funnels → funnel+ ['queries', 'querying', true], // queries → query+ ['bayous', 'wetlands', true], // bayous → bayou+ ['types', 'classification', false], // four-character derived stems remain excluded['sessions', 'assessment', false], // min-5 guard: "sessions" must not reach "assessing"+ ['states', 'statistics', false], // "states" must not lose the distinct final e in "state"])('light stemming links query "%s" to %s content (match=%s)', (query, skill, shouldMatch) => {const catalog = SkillCatalog.fromZip(makeArchive({'trends/SKILL.md': makeSkill('trends','Chart product metrics over time.',- '# Trends\n\nRun a cohort analysis.'+ '# Trends\n\nAnalyze a cohort.'),'conversion/SKILL.md': makeSkill('conversion','Chart product metrics over time.','# Conversion\n\nBuild a conversion funnel.'),+ 'querying/SKILL.md': makeSkill('querying', 'Run database lookups.', '# Querying\n\nRun a query.'),+ 'wetlands/SKILL.md': makeSkill('wetlands', 'Explore waterways.', '# Wetlands\n\nExplore a bayou.'),+ 'classification/SKILL.md': makeSkill(+ 'classification',+ 'Review classification labels.',+ '# Classification\n\nReview a stereotype.'+ ),'assessment/SKILL.md': makeSkill('assessment','Review internal controls.','# Assessment\n\nStart by assessing exposure.'),+ 'statistics/SKILL.md': makeSkill(+ 'statistics',+ 'Calculate descriptive measures.',+ '# Statistics\n\nSummarize the sample.'+ ),}))@@ -269,6 +333,21 @@ describe('SkillCatalog and exec learn', () => {}})+ it('does not stem singular words ending in s', () => {+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'statue/SKILL.md': makeSkill('statue', 'Sculpture reference.', '# Statue'),+ 'support-workflow/SKILL.md': makeSkill(+ 'support-workflow',+ 'Track support status.',+ '# Support workflow'+ ),+ })+ )++ expect(catalog.searchResults('status').map((result) => result.identifier)).toEqual(['support-workflow'])+ })+it('excludes SKILL.md frontmatter from snippets while keeping raw line numbers', () => {const catalog = SkillCatalog.fromZip(makeArchive({