: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
feat(mcp): add posthog and project skill discovery (#70424)
Georgiy Tarasove93d34af6915
diff --git a/.agents/skills/writing-evals/SKILL.md b/.agents/skills/writing-evals/SKILL.mdindex ddbaed3f9cd8..36b89d448c83 100644--- a/.agents/skills/writing-evals/SKILL.md+++ b/.agents/skills/writing-evals/SKILL.md@@ -83,10 +83,11 @@ async def eval_my_generation(ctx: EvalContext) -> None:## Case anatomy-`SandboxedEvalCase` (`products/posthog_ai/eval_harness/config.py`) has five author-facing fields: `name`, `prompt`, `expected`, `metadata`, `setup`.+`SandboxedEvalCase` (`products/posthog_ai/eval_harness/config.py`) has seven author-facing fields: `name`, `prompt`, `repo_fixture`, `expected`, `metadata`, `disable_bundled_skills`, `setup`.- `name` doubles as the `--eval <substr>` filter target and the per-case log filename — keep it unique within the suite.- `expected` is keyed by each scorer's `_name()`. A scorer reads only its own sub-dict and self-skips (or falls back to default behavior) when its key is absent — that is what lets one scorer list span a suite's cases. Judges take payloads like `{"warehouse_answer_correctness": {"expected_answer": "..."}}`.+- `--skill-delivery exec` enables MCP skill distribution and removes native skills for every case in the run. `disable_bundled_skills=True` is an additional per-case override for other delivery-path evals.- Every sandboxed case runs in a fresh isolated org/team/user copied from the master Hedgebox team, so cases never see each other's state. One-shot cases share the master team read-only.## Seeding data: seeders and synthesizers@@ -151,6 +152,7 @@ It runs agent sandboxes in parallel without the local Docker memory ceiling, sohogli evals --list # suite ids, no infrahogli evals eval_my_thing --eval my_case # one case, dockerhogli evals cli_mcp --provider modal # a domain, remote, fully parallel+hogli evals eval_skill_distribution --skill-delivery exec # exec-distributed skills only````hogli evals:sandboxed` is a back-compat alias of `hogli evals`.@@ -160,6 +162,7 @@ hogli evals cli_mcp --provider modal # a domain, remote, fully parallel- `--provider docker` (default) caps at 4 concurrent sandboxes (16 GB each); `--provider modal` is unbounded — every case runs at once, `--max-sandboxes` is the cost knob.- Team cloning and case seeding use one setup slot on ordinary local machines and four when `CODER` or `CI` is set.- `--trials N` repeats every case for variance on stochastic behavior; `--fail-under <fraction>` gates the run's mean score.+- `--skill-delivery bundled` is the default native-skill path. `--skill-delivery exec` enables the MCP skill prompt and clears all native skill directories; compare the modes in separate runs because MCP configuration is process-wide.- `--agent-runtime codex` runs the OpenAI Codex harness (default model `gpt-5.5`) instead of Claude; it requires `LLM_GATEWAY_OPENAI_API_KEY`. The runtime/model land in the Braintrust experiment metadata, so compare scores within one runtime.- Every real eval invocation mirrors its complete stdout and stderr to `products/posthog_ai/eval_harness/logs/harness/<timestamp>_<id>.log`. The ending label identifies it as the full run transcript, the last terminal line is its absolute path, and `logs/harness/latest.log` points to the newest transcript. `--list` and argument errors do not create one.- The plain-text summary is stable for people and agents: only the overall run says `PASS` or `FAIL`; completed suites, experiments, and cases say `DONE`; experiment blocks label scores, URLs, and agent-log directories.diff --git a/.agents/skills/writing-evals/references/authoring-reference.md b/.agents/skills/writing-evals/references/authoring-reference.mdindex d5d849b7988c..6d810596b5d2 100644--- a/.agents/skills/writing-evals/references/authoring-reference.md+++ b/.agents/skills/writing-evals/references/authoring-reference.md@@ -5,16 +5,17 @@ When anything here disagrees with the code, the code wins — the sources of tru## `SandboxedEvalCase` (`config.py`)-| Field | Type | Meaning |-| -------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `name` | `str` | Case name. Also the `--eval <substr>` filter target and the per-case log filename. Unique within the suite. |-| `prompt` | `str` | The natural-language task given to the agent. |-| `repo_fixture` | `str = ""` | Informational only (tracking). |-| `expected` | `dict = {}` | Per-scorer expected values, keyed by each scorer's `_name()`. A scorer reads only its own sub-dict; a missing key means default behavior or self-skip. |-| `metadata` | `dict = {}` | Arbitrary tracking/filtering metadata. |-| `setup` | `Callable[[CustomPromptSandboxContext], dict] \| None` | The seed hook. Excluded from serialization (callables don't survive Braintrust's JSON round-trip); the runner re-binds it from the original case by name. |--There is no per-case `skills` field (skills are built once per run and available globally in every sandbox — assert skill _outcomes_, not attachment) and no per-case timeout (`--case-timeout` is run-level, counted from sandbox acquisition).+| Field | Type | Meaning |+| ------------------------ | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `name` | `str` | Case name. Also the `--eval <substr>` filter target and the per-case log filename. Unique within the suite. |+| `prompt` | `str` | The natural-language task given to the agent. |+| `repo_fixture` | `str = ""` | Informational only (tracking). |+| `expected` | `dict = {}` | Per-scorer expected values, keyed by each scorer's `_name()`. A scorer reads only its own sub-dict; a missing key means default behavior or self-skip. |+| `metadata` | `dict = {}` | Arbitrary tracking/filtering metadata. |+| `disable_bundled_skills` | `bool = False` | Clears native skill directories before agent startup. Use when evaluating a separate skill distribution path. |+| `setup` | `Callable[[CustomPromptSandboxContext], dict] \| None` | The seed hook. Excluded from serialization (callables don't survive Braintrust's JSON round-trip); the runner re-binds it from the original case by name. |++There is no per-case `skills` attachment field. Skills are built once per run and use native bundled delivery by default. `--skill-delivery exec` enables MCP distribution and clears native skills for every case; `disable_bundled_skills` is an additional per-case override. There is no per-case timeout (`--case-timeout` is run-level, counted from sandbox acquisition).## Seeder contractdiff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex fcf11d329288..58515218c713 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -76,6 +76,36 @@ giving it richer context about PostHog's data model.Primarily oriented toward coding agents (PostHog Code, PostHog AI, Claude Code).+## Claude web and desktop exec schema budget++Claude web and desktop silently drop a tool when its serialized `inputSchema` reaches 16,384 characters.+The final, post-injection `exec` input schema has a strict test budget below that limit.++Keep guidance needed for routine tool calls inline.+This includes the compact tool-domain index, which must remain in the `command` schema for tool discovery.+Put optional or task-specific global guidance in the Claude exec learn catalog, available through `learn` and `learn <guide>`.+The built-in guides are listed in the `command` description so the model can load the relevant guide before starting a task.+PostHog and project skills are enabled independently of the client through the `mcp-exec-skills` feature flag and discovered at runtime through `learn skills` or `learn -s <query>`.+Read bundled PostHog skills with `learn posthog:<skill> [path]` and current-project Skills store entries with `learn project:<skill> [path]`.+Search merges both sources into one relevance order, so an exact project match can outrank a weak PostHog one.+Preview descriptions without reading bodies with `learn -d <source>:<skill> [...]`, and read several targets in one call with `learn <source>:<skill> <path> [path...]` or `learn <source>:<skill> [<source>:<skill>...]`.+When the flag is enabled, every non-plugin cli client is instructed to run `learn -s "<task keywords>"` before non-trivial PostHog work, load matches by exact qualified name, and follow the loaded `SKILL.md` before selecting tools.+Claude web and desktop keep their built-in learning topics when the flag is off. Other cli-mode clients receive only skill commands when the flag is on, without the Claude-specific learning topics.+Keep skill names, descriptions, bodies, and references out of the tool schema.+The fixed learn grammar and compact tool-domain index must remain inline so Claude can discover both capabilities.++The MCP server loads the published `skills.zip` release into a Redis stale-while-revalidate cache. Custom archive URLs use isolated cache namespaces.+It reads project skills from the request-authenticated project without caching them in the MCP service.+Project discovery includes only latest, active, uncategorized skills and requires `llm_skill:read`.+Skill reads include a file manifest, and references that exceed the output budget return a heading outline.+Use `learn <source>:<skill> <path> -s <query>` for scoped full-text search or `learn <source>:<skill> <path> --lines <start>:<end>` for a bounded inclusive range.+Script paths are searchable and their contents are readable directly or by line range, but script contents are not part of the full-text index.+The plugin and posthog-code consumers do not receive `learn`, because both already supply PostHog skills directly.++Do not remove information from endpoint serializers or generated tool schemas to meet this budget.+Those descriptions remain the source of truth for `info` and `schema` discovery.+When adding global prompt guidance, keep it inline only when it is useful on nearly every call; otherwise add it to an existing learn guide or create a globally unique guide ID.+## SQL-first MCP: HogQL system tablesEvery list/get endpoint exposed as an MCP tool must have a corresponding HogQL system table.diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex c5760dcac59f..02e82379239d 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -3,6 +3,9 @@These evals run the real coding agent inside a real sandbox against a seeded Hedgebox project, then score what it did.Each eval case gets its own isolated org/team/user, so cases never see each other's state.+The harness builds product skills from the current checkout and uses native bundled skills by default.+`--skill-delivery exec` instead packages those skills for MCP distribution, enables the exec skill prompt, and removes native skills from every sandbox so the two paths cannot satisfy the same case.+Unlike `ee/hogai/eval/ci/`, this tree does **not** run under pytest.It runs on a standalone harness that boots the shared infrastructure once (test database, Django live server, LLM gateway, MCP server, Temporal) and then runs every selected suite concurrently.See [`harness/README.md`](harness/README.md) for how that works internally.@@ -60,32 +63,46 @@ python -m products.posthog_ai.eval_harness.harness --provider modalpython -m products.posthog_ai.eval_harness.harness --list```-| Flag | Meaning |-| -------------------------------- | -------------------------------------------------------------------------------- |-| `--eval <substr>` | Only run cases whose name contains the substring. |-| `--provider {docker,modal}` | Where sandboxes run. Default `docker`. |-| `--max-sandboxes N` | Cap concurrently live sandboxes across all suites. |-| `--agent-model <model>` | Model the sandboxed agent runs against, pinned for stable cross-run comparison. |-| `--agent-runtime {claude,codex}` | Agent runtime serving the model. Default `claude`. |-| `--reasoning-effort <effort>` | Agent reasoning effort; valid values depend on runtime+model. |-| `--keep-sandbox-containers` | Skip the end-of-run Docker sweep, to inspect a leftover container. Docker only. |-| `--rebuild-sandbox-image` | Force a rebuild of the `posthog-sandbox-base` image before the run. Docker only. |-| `--create-db` | Rebuild the eval test database instead of reusing it. |-| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |-| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |-| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |-| `--list` | Print the discovered suite ids (with their kinds) and exit. |--Sandbox-only flags (`--provider`, `--max-sandboxes`, `--agent-runtime`, `--reasoning-effort`, `--keep-sandbox-containers`, `--rebuild-sandbox-image`) are rejected in preflight when no selected suite is sandboxed, instead of being silently ignored.+| Flag | Meaning |+| --------------------------------- | -------------------------------------------------------------------------------- |+| `--eval <substr>` | Only run cases whose name contains the substring. |+| `--provider {docker,modal}` | Where sandboxes run. Default `docker`. |+| `--max-sandboxes N` | Cap concurrently live sandboxes across all suites. |+| `--agent-model <model>` | Model the sandboxed agent runs against, pinned for stable cross-run comparison. |+| `--agent-runtime {claude,codex}` | Agent runtime serving the model. Default `claude`. |+| `--skill-delivery {bundled,exec}` | Skill delivery path. Default `bundled`; `exec` removes native sandbox skills. |+| `--reasoning-effort <effort>` | Agent reasoning effort; valid values depend on runtime+model. |+| `--keep-sandbox-containers` | Skip the end-of-run Docker sweep, to inspect a leftover container. Docker only. |+| `--rebuild-sandbox-image` | Force a rebuild of the `posthog-sandbox-base` image before the run. Docker only. |+| `--create-db` | Rebuild the eval test database instead of reusing it. |+| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |+| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |+| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |+| `--list` | Print the discovered suite ids (with their kinds) and exit. |++Sandbox-only flags (`--provider`, `--max-sandboxes`, `--agent-runtime`, `--skill-delivery`, `--reasoning-effort`, `--keep-sandbox-containers`, `--rebuild-sandbox-image`) are rejected in preflight when no selected suite is sandboxed, instead of being silently ignored.`EXPORT_EVAL_RESULTS=1` additionally appends one structured JSON summary per experiment to `eval_results.jsonl`.The full plain-text run transcript is always written without this setting.+### Comparing skill delivery++MCP instructions are configured once for the whole harness process, so bundled and exec skill delivery must run separately.+Use the same suite, model, runtime, provider, case filter, and trial count in both commands:++```bash+hogli evals eval_skill_distribution --skill-delivery bundled --agent-runtime claude --agent-model claude-opus-4-8 --trials 3+hogli evals eval_skill_distribution --skill-delivery exec --agent-runtime claude --agent-model claude-opus-4-8 --trials 3+```++Both runs use the same six prompts and Braintrust history key.+The experiment metadata records `skill_delivery`; compare the shared `expected_skill_loaded` and `skill_loaded_before_tool` scores rather than the aggregate mean, because the exec arm also reports search and discovery diagnostics.+### Codex runtime`--agent-runtime codex` runs the same agent-server with OpenAI's Codex harness instead of Claude, defaulting the model to `gpt-5.5`.It requires `LLM_GATEWAY_OPENAI_API_KEY` in the environment (checked by preflight), which the harness's LLM gateway uses to proxy the agent's OpenAI calls.-Experiment names don't change with the runtime — each Braintrust experiment records `agent_runtime` and `agent_model` in its metadata instead — so compare cross-run scores within one runtime.+Experiment names don't change with the runtime or skill delivery. Each Braintrust experiment records `agent_runtime`, `agent_model`, and `skill_delivery` in its metadata, so compare cross-run scores within one runtime and delivery mode.## Providersdiff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex bc0d133abbb3..423110992278 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -365,7 +365,13 @@ class _SandboxedEvalRun(_BaseEvalRun):# The factory does Django ORM work. Django's async-safety# guard rejects sync ORM calls from async contexts, so run it# in a worker thread.- sandbox_context = await asyncio.to_thread(self._demo_data.make_context, eval_case.name)+ sandbox_context = await asyncio.to_thread(+ self._demo_data.make_context,+ eval_case.name,+ disable_bundled_skills=(+ ctx.skill_delivery == "exec" or bool(original_case and original_case.disable_bundled_skills)+ ),+ )if original_case is not None and original_case.setup is not None:try:seed_result = await asyncio.to_thread(original_case.setup, sandbox_context)@@ -469,7 +475,11 @@ class _SandboxedEvalRun(_BaseEvalRun):return f"sandboxed-agent-{self.experiment_name}" if self.is_public else self.experiment_namedef _experiment_metadata(self) -> dict[str, Any]:- return {"agent_model": self.ctx.agent_model, "agent_runtime": self.ctx.agent_runtime}+ return {+ "agent_model": self.ctx.agent_model,+ "agent_runtime": self.ctx.agent_runtime,+ "skill_delivery": self.ctx.skill_delivery,+ }async def SandboxedEval(diff --git a/products/posthog_ai/eval_harness/config.py b/products/posthog_ai/eval_harness/config.pyindex 7398eb9c1839..421f42e3832d 100644--- a/products/posthog_ai/eval_harness/config.py+++ b/products/posthog_ai/eval_harness/config.py@@ -40,6 +40,14 @@ class SandboxedEvalCase(BaseEvalCase):repo_fixture: str = """""Name of the repo fixture (informational, for tracking)."""+ disable_bundled_skills: bool = False+ """Remove skills baked into the sandbox image for this case.++ Use this when the behavior under evaluation is a separate skill delivery+ path, so native agent skill discovery cannot satisfy the task by accident.+ Exec skill-delivery mode applies the same behavior to every case.+ """+setup: Callable[[CustomPromptSandboxContext], dict[str, Any]] | None = Field(default=None,exclude=True,diff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.mdindex 01191be5b9f9..2e97134abb2a 100644--- a/products/posthog_ai/eval_harness/harness/AGENTS.md+++ b/products/posthog_ai/eval_harness/harness/AGENTS.md@@ -90,7 +90,7 @@ Braintrust's `EvalAsync` always dispatches through `eval_async`, and the base `SBootstrap registers teardown on an `ExitStack` as each resource comes up, so a failure halfway through still unwinds what already started.`atexit` hooks plus the subprocess manager's signal handlers cover Ctrl-C, where neither stack unwinds.-After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 14040 / 15051 / 15052, no `task-sandbox-*` containers, and no Temporal dev server.+After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 18788 / 14040 / 15051 / 15052, no `task-sandbox-*` containers, and no Temporal dev server.Three layers tear a case's sandbox down, outermost last:diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.mdindex dcceac4bef96..e79107fffac6 100644--- a/products/posthog_ai/eval_harness/harness/README.md+++ b/products/posthog_ai/eval_harness/harness/README.md@@ -25,13 +25,13 @@ A run of one-shot suites never pays for — or fails preflight on — the sandbo| `__main__.py` | Entry point. Parses args, starts the transcript, configures Django, then hands off to `lifecycle`. || `cli.py` | `HarnessOptions` and the argparse builder. Resolves per-provider defaults. || `env_preflight.py` | Loads the repo-root `.env` (stdlib parser, shell wins) and validates per-kind env vars via pydantic models. |-| `ports.py` | The six port constants. Deliberately free of Django imports. |+| `ports.py` | The seven port constants. Deliberately free of Django imports. || `providers.py` | `SandboxProviderStrategy` and its docker/modal implementations: preflight, settings overrides, sandbox TTL, cleanup. || `tunnels.py` | `NgrokTunnels`. Modal only: generates an ngrok config, starts the agent, waits for public URLs. || `requirements.py` | `SuiteKind`, `Infra`, and the kind → infrastructure mapping (with implication closure). || `django_env.py` | `setup_django()`, the `NullDbBlocker` shim, and `EvalDatabase` (test database lifecycle). || `live_server.py` | `EvalLiveServer`, a session-lifetime Uvicorn server for PostHog's full ASGI application. |-| `services.py` | Starts the LLM gateway, MCP server, and personhog subprocesses; builds local skills. |+| `services.py` | Starts the LLM gateway, MCP server, skill archive server, and personhog subprocesses; builds local skills. || `temporal_env.py` | Local Temporal dev server, stale-workflow cleanup, and the worker thread. || `demo_data.py` | `SandboxedDemoData`: seeds the master Hedgebox team once, then mints an isolated team per case. || `discovery.py` | Walks the tree for `eval_*.py` and collects `eval_*` coroutines into `EvalSuite` objects. |@@ -53,9 +53,9 @@ The bootstrap is deliberately synchronous and runs before any event loop exists,2. `EvalDatabase.setup()` creates the `default` test database and drives PostHog's own eval database setup (persons database, ClickHouse).3. `personhog-replica` (`:15051`) and `personhog-router` (`:15052`) start against the test persons database — before anything can query, so a dead router never poisons the negative group-types cache.4. `EvalLiveServer` serves PostHog's ASGI application on `0.0.0.0:18000`, including the sandbox event-ingest route.-5. The LLM gateway (`:13308`) and MCP server (`:18787`) start as subprocesses.+5. The LLM gateway (`:13308`) starts and local skills are built. In bundled mode, the MCP server (`:18787`) starts with exec skill distribution forced off. In exec mode, the skills are packaged, the local archive server (`:18788`) starts, and MCP receives its content-addressed URL with distribution forced on.6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding on a new `@posthog/agent` version or Dockerfile change). Modal only: ngrok tunnels come up, exposing the callback services publicly.-7. Local skills are built. Docker bind-mounts them; Modal bakes them into the image it builds.+7. Bundled mode bind-mounts the built skills on Docker and bakes them into the Modal image. Exec mode suppresses those skills and clears native skill directories before every case; `disable_bundled_skills=True` remains available as a per-case override in other modes.8. The master Hedgebox team is seeded.The async phase then starts the Temporal dev server on the main loop, applies the provider's settings overrides, terminates stale workflows, starts the Temporal worker on its own thread and loop, and fans the suites out with `asyncio.gather`.diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.pyindex 7f929856c1a6..cae08bea1f60 100644--- a/products/posthog_ai/eval_harness/harness/cli.py+++ b/products/posthog_ai/eval_harness/harness/cli.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osimport argparsefrom dataclasses import dataclass-from typing import cast, get_args+from typing import Literal, cast, get_argsfrom .providers import DockerProviderStrategy, ModalProviderStrategy, SandboxProvider@@ -17,6 +17,8 @@ DEFAULT_CODEX_AGENT_MODEL = "gpt-5.5"# Django-free (see harness/AGENTS.md), so it cannot import the enum.AGENT_RUNTIMES = ("claude", "codex")DEFAULT_AGENT_MODEL_BY_RUNTIME = {"claude": DEFAULT_AGENT_MODEL, "codex": DEFAULT_CODEX_AGENT_MODEL}+SkillDelivery = Literal["bundled", "exec"]+DEFAULT_SKILL_DELIVERY: SkillDelivery = "bundled"DEFAULT_CASE_TIMEOUT_SECONDS = 60 * 15OFFLINE_CASE_TIMEOUT_SECONDS = 60 * 60@@ -40,6 +42,7 @@ class HarnessOptions:case_filter: str | Noneagent_model: stragent_runtime: str+ skill_delivery: SkillDeliveryreasoning_effort: str | Nonemax_sandboxes: intteam_setup_concurrency: int@@ -104,6 +107,15 @@ def build_parser() -> argparse.ArgumentParser:default=None,help="Agent runtime serving the model (default: claude). 'codex' additionally requires LLM_GATEWAY_OPENAI_API_KEY.",)+ parser.add_argument(+ "--skill-delivery",+ choices=get_args(SkillDelivery),+ default=None,+ help=(+ "How product skills reach the agent. 'bundled' uses the harness's normal native skills; "+ "'exec' enables MCP skill distribution and removes native skills from every sandbox."+ ),+ )parser.add_argument("--reasoning-effort",default=None,@@ -167,6 +179,7 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:for flag, is_set in (("--provider", args.provider is not None),("--agent-runtime", args.agent_runtime is not None),+ ("--skill-delivery", args.skill_delivery is not None),("--reasoning-effort", args.reasoning_effort is not None),("--max-sandboxes", args.max_sandboxes is not None),("--keep-sandbox-containers", args.keep_sandbox_containers),@@ -176,6 +189,7 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:)provider = cast(SandboxProvider, args.provider or "docker")agent_runtime = args.agent_runtime or "claude"+ skill_delivery = cast(SkillDelivery, args.skill_delivery or DEFAULT_SKILL_DELIVERY)if args.max_sandboxes is not None and args.max_sandboxes < 1:parser.error("--max-sandboxes must be at least 1")@@ -211,6 +225,7 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:case_filter=args.case_filter,agent_model=agent_model,agent_runtime=agent_runtime,+ skill_delivery=skill_delivery,reasoning_effort=args.reasoning_effort,max_sandboxes=max_sandboxes,team_setup_concurrency=_default_team_setup_concurrency(),diff --git a/products/posthog_ai/eval_harness/harness/context.py b/products/posthog_ai/eval_harness/harness/context.pyindex 1cf6bdc03a98..9800374d9b2a 100644--- a/products/posthog_ai/eval_harness/harness/context.py+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -6,6 +6,7 @@ from dataclasses import dataclassfrom posthoganalytics import Posthogfrom ..engines.base import EvalEngine+from .cli import SkillDeliveryfrom .demo_data import SandboxedDemoDatafrom .providers import SandboxProvider, SandboxProviderStrategyfrom .reporting import ProgressReporter@@ -38,6 +39,9 @@ class EvalContext:agent_runtime: str"""Runtime adapter serving the sandboxed agent's model (``"claude"`` | ``"codex"``)."""+ skill_delivery: SkillDelivery+ """Whether the run uses native bundled skills or MCP exec distribution."""+reasoning_effort: str | None"""Agent reasoning effort override; ``None`` keeps the agent server's default."""diff --git a/products/posthog_ai/eval_harness/harness/demo_data.py b/products/posthog_ai/eval_harness/harness/demo_data.pyindex 1f8de0e3ec80..a83c6284a381 100644--- a/products/posthog_ai/eval_harness/harness/demo_data.py+++ b/products/posthog_ai/eval_harness/harness/demo_data.py@@ -12,7 +12,7 @@ from products.posthog_ai.eval_harness.data_setup import (create_core_memory,ensure_master_demo_team,)-from products.tasks.backend.facade.agents import CustomPromptSandboxContext+from products.tasks.backend.facade.agents import ENV_DISABLE_BUNDLED_SKILLS, CustomPromptSandboxContextfrom ee.clickhouse.materialized_columns.columns import (backfill_materialized_columns,@@ -51,20 +51,32 @@ class SandboxedDemoData:self.reasoning_effort = reasoning_effortself.sandbox_timeout_seconds = sandbox_timeout_seconds- def make_context(self, case_label: str) -> CustomPromptSandboxContext:+ def make_context(self, case_label: str, *, disable_bundled_skills: bool = False) -> CustomPromptSandboxContext:CodeInvite = apps.get_model("tasks", "CodeInvite")CodeInviteRedemption = apps.get_model("tasks", "CodeInviteRedemption")+ SandboxEnvironment = apps.get_model("tasks", "SandboxEnvironment")org, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)create_core_memory(team, self._django_db_blocker)+ sandbox_environment_id: str | None = Nonewith self._django_db_blocker.unblock():invite, _ = CodeInvite.objects.get_or_create(code="eval-harness", max_redemptions=0, is_active=True)CodeInviteRedemption.objects.get_or_create(invite_code=invite, user=user, organization=org)+ if disable_bundled_skills:+ sandbox_environment = SandboxEnvironment.objects.create(+ team=team,+ created_by=user,+ name=f"Eval skill isolation: {case_label}",+ environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},+ internal=True,+ )+ sandbox_environment_id = str(sandbox_environment.id)logger.info("Case %r assigned team_id=%d user_id=%d", case_label, team.id, user.id)return CustomPromptSandboxContext(team_id=team.id,user_id=user.id,repository="posthog/hedgebox",+ sandbox_environment_id=sandbox_environment_id,model=self.agent_model,runtime_adapter=self.agent_runtime,reasoning_effort=self.reasoning_effort,diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.pyindex 868e445f5bb8..6ee3f6d273cd 100644--- a/products/posthog_ai/eval_harness/harness/lifecycle.py+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -35,9 +35,11 @@ from .requirements import Infra, infra_unionfrom .services import (build_local_skills,ensure_personhog_binaries,+ package_local_skills_archive,start_llm_gateway,start_mcp_server,start_personhog,+ start_skill_archive_server,stop_all_subprocesses,)from .temporal_env import (@@ -197,7 +199,22 @@ class SandboxedEvalHarness:self._stack.callback(start_llm_gateway(self._live_server.url))if Infra.MCP_SERVER in required:assert self._live_server is not None- self._stack.callback(start_mcp_server(self._live_server.url))++ # Both delivery modes use rendered skills from this checkout, never a+ # previously published bundle.+ skills_dir = build_local_skills(set_bind_mount_env=self.options.provider == "docker")+ skill_archive_url: str | None = None+ if self.options.skill_delivery == "exec":+ skill_archive = package_local_skills_archive(skills_dir)+ skill_archive_url, stop_skill_archive = start_skill_archive_server(skill_archive)+ self._stack.callback(stop_skill_archive)+ self._stack.callback(+ start_mcp_server(+ self._live_server.url,+ skill_archive_url,+ exec_skills_enabled=self.options.skill_delivery == "exec",+ )+ )if Infra.SANDBOX in required:assert self.provider is not None@@ -205,10 +222,6 @@ class SandboxedEvalHarness:# publicly reachable before any settings pointing at them are computed.self.provider.start(self._stack)- # DockerSandbox bind-mounts the built skills; ModalSandbox bakes them into- # the image it builds from the local context, so it wants no host path.- build_local_skills(set_bind_mount_env=self.options.provider == "docker")-self._posthog_client = get_client("US")if self._posthog_client is not None:self._stack.callback(self._posthog_client.shutdown)@@ -274,9 +287,10 @@ class SandboxedEvalHarness:if Infra.SANDBOX in required:logger.info(- "Running %d suite(s) on provider=%s with %d sandbox slot(s)",+ "Running %d suite(s) on provider=%s with skill_delivery=%s and %d sandbox slot(s)",len(suites),self.options.provider,+ self.options.skill_delivery,self.options.max_sandboxes,)else:@@ -292,6 +306,7 @@ class SandboxedEvalHarness:provider_strategy=self.provider,agent_model=self.options.agent_model,agent_runtime=self.options.agent_runtime,+ skill_delivery=self.options.skill_delivery,reasoning_effort=self.options.reasoning_effort,case_filter=self.options.case_filter,demo_data=self._demo_data,diff --git a/products/posthog_ai/eval_harness/harness/ports.py b/products/posthog_ai/eval_harness/harness/ports.pyindex 4bab2053b998..0b7765cd0f5d 100644--- a/products/posthog_ai/eval_harness/harness/ports.py+++ b/products/posthog_ai/eval_harness/harness/ports.py@@ -3,6 +3,9 @@ from __future__ import annotationsMCP_PORT = 18787"""Non-default port to avoid conflicts with a running dev MCP server."""+SKILL_ARCHIVE_PORT = 18788+"""Local HTTP server for the working-tree skill archive consumed by MCP."""+DJANGO_LIVE_PORT = 18000"""Non-default port for the in-process Django server."""diff --git a/products/posthog_ai/eval_harness/harness/requirements.py b/products/posthog_ai/eval_harness/harness/requirements.pyindex 08b4447b52b8..b9143f4ffa53 100644--- a/products/posthog_ai/eval_harness/harness/requirements.py+++ b/products/posthog_ai/eval_harness/harness/requirements.py@@ -32,7 +32,7 @@ class Infra(enum.Enum):"""The master Hedgebox seed team and per-case team factory."""SANDBOX = "sandbox"- """The sandbox provider, local skills build, and the Temporal environment."""+ """The sandbox provider and the Temporal environment."""class SuiteKind(enum.Enum):diff --git a/products/posthog_ai/eval_harness/harness/services.py b/products/posthog_ai/eval_harness/harness/services.pyindex 0b8af7863dd5..1622879cd886 100644--- a/products/posthog_ai/eval_harness/harness/services.py+++ b/products/posthog_ai/eval_harness/harness/services.py@@ -1,9 +1,12 @@from __future__ import annotationsimport os+import sysimport jsonimport shutil+import hashlibimport logging+import zipfileimport subprocessfrom collections.abc import Callablefrom pathlib import Path@@ -14,12 +17,14 @@ from django.db import connectionsfrom products.posthog_ai.eval_harness.long_lived_subprocess import LongLivedSubprocessManager, SubprocessStartupErrorfrom products.tasks.backend.facade.agents import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache-from .ports import LLM_GATEWAY_PORT, MCP_PORT, PERSONHOG_REPLICA_PORT, PERSONHOG_ROUTER_PORT+from .ports import LLM_GATEWAY_PORT, MCP_PORT, PERSONHOG_REPLICA_PORT, PERSONHOG_ROUTER_PORT, SKILL_ARCHIVE_PORTfrom .providers import PreflightErrorlogger = logging.getLogger(__name__)LONG_LIVED_SUBPROCESSES = LongLivedSubprocessManager()+MCP_EXEC_SKILLS_FEATURE_FLAG = "mcp-exec-skills"+_ZIP_FIXED_TIME = (2020, 1, 1, 0, 0, 0)def start_llm_gateway(live_server_url: str) -> Callable[[], None]:@@ -83,7 +88,12 @@ def start_llm_gateway(live_server_url: str) -> Callable[[], None]:return stop-def start_mcp_server(live_server_url: str) -> Callable[[], None]:+def start_mcp_server(+ live_server_url: str,+ skill_archive_url: str | None,+ *,+ exec_skills_enabled: bool,+) -> Callable[[], None]:"""Start the MCP server as a subprocess for the eval session.Pointed at the in-process Django live server (which uses the test DB).@@ -93,6 +103,9 @@ def start_mcp_server(live_server_url: str) -> Callable[[], None]:Cloudflare Worker is now a proxy that forwards to a regional Honodeployment, so Hono is what real users hit."""+ if exec_skills_enabled and skill_archive_url is None:+ raise ValueError("skill_archive_url is required when exec skills are enabled")+mcp_dir = Path(settings.BASE_DIR) / "services" / "mcp"if not (mcp_dir / "node_modules").exists():logger.info("Installing MCP server dependencies")@@ -113,14 +126,26 @@ def start_mcp_server(live_server_url: str) -> Callable[[], None]:"HOST": "0.0.0.0",# The MCP server evaluates feature flags via posthog-node, which is disabled# here (no POSTHOG_ANALYTICS_* config), so every flag would resolve false.- # Force flag-gated behavior on for evals via the dev/test-only override seam+ # Force the selected behavior via the dev/test-only override seam# (honored only when NODE_ENV is explicitly development/test — set above).# product-data-catalog gates the metric-discovery section of the execute-sql# description; the governed-metrics evals exercise that path.- "FEATURE_FLAG_OVERRIDES": json.dumps({"product-data-catalog": True}),+ "FEATURE_FLAG_OVERRIDES": json.dumps(+ {"product-data-catalog": True, MCP_EXEC_SKILLS_FEATURE_FLAG: exec_skills_enabled}+ ),}- logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)+ # Never let a shell-level archive URL contaminate the bundled-skills baseline.+ env.pop("POSTHOG_MCP_SKILLS_URL", None)+ if exec_skills_enabled and skill_archive_url is not None:+ env["POSTHOG_MCP_SKILLS_URL"] = skill_archive_url++ logger.info(+ "Starting MCP server (Hono runtime) on port %d (API: %s, exec skills: %s)",+ MCP_PORT,+ api_url,+ exec_skills_enabled,+ )_, stop = LONG_LIVED_SUBPROCESSES.start(name="MCP server",port=MCP_PORT,@@ -270,5 +295,49 @@ def build_local_skills(*, set_bind_mount_env: bool) -> Path:return dist_dir+def package_local_skills_archive(skills_dir: Path, archive_path: Path | None = None) -> Path:+ """Create a deterministic MCP archive from the rendered working-tree skills."""+ destination = archive_path or skills_dir.parent / "skills.zip"+ destination.parent.mkdir(parents=True, exist_ok=True)++ with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as archive:+ for file_path in sorted(skills_dir.rglob("*")):+ if not file_path.is_file():+ continue+ relative_path = file_path.relative_to(skills_dir)+ if any(part.startswith(".") or part == "__pycache__" for part in relative_path.parts):+ continue+ info = zipfile.ZipInfo(relative_path.as_posix(), date_time=_ZIP_FIXED_TIME)+ info.compress_type = zipfile.ZIP_DEFLATED+ archive.writestr(info, file_path.read_bytes())++ return destination+++def start_skill_archive_server(archive_path: Path) -> tuple[str, Callable[[], None]]:+ """Serve the local skill archive to MCP under a content-addressed URL."""+ archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()[:16]+ archive_url = f"http://127.0.0.1:{SKILL_ARCHIVE_PORT}/{archive_path.name}?v={archive_digest}"+ logger.info("Starting skill archive server on port %d", SKILL_ARCHIVE_PORT)+ _, stop = LONG_LIVED_SUBPROCESSES.start(+ name="skill archive server",+ port=SKILL_ARCHIVE_PORT,+ cmd=[+ sys.executable,+ "-m",+ "http.server",+ str(SKILL_ARCHIVE_PORT),+ "--bind",+ "127.0.0.1",+ "--directory",+ str(archive_path.parent),+ ],+ cwd=archive_path.parent,+ env={**os.environ},+ log_prefix="skill-archive",+ )+ return archive_url, stop++def stop_all_subprocesses() -> None:LONG_LIVED_SUBPROCESSES.stop_all()diff --git a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py b/products/posthog_ai/eval_harness/test/test_one_shot_runner.pyindex 62abad424e7f..3983b39aefb2 100644--- a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py+++ b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py@@ -58,6 +58,7 @@ def _build_ctx(timeout_seconds: int = 30, one_shot_slots: int = 2, case_filter:provider_strategy=None,agent_model="claude-test",agent_runtime="claude",+ skill_delivery="bundled",reasoning_effort=None,case_filter=case_filter,demo_data=None,diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.pynew file mode 100644index 000000000000..a5edfc1be4b8--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py@@ -0,0 +1,16 @@+from __future__ import annotations++import pytest++from products.posthog_ai.eval_harness.harness.cli import SkillDelivery, parse_args+++ "argv,expected_delivery",+ [+ ([], "bundled"),+ (["--skill-delivery", "exec"], "exec"),+ ],+)+def test_skill_delivery_defaults_to_bundled_and_allows_exec(argv: list[str], expected_delivery: SkillDelivery) -> None:+ assert parse_args(argv).skill_delivery == expected_deliverydiff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.pynew file mode 100644index 000000000000..34da10e294ad--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py@@ -0,0 +1,71 @@+from __future__ import annotations++import os+import zipfile+from pathlib import Path++import pytest+from unittest.mock import MagicMock, patch++from products.posthog_ai.eval_harness.harness.services import package_local_skills_archive, start_mcp_server+++def test_package_local_skills_archive_is_deterministic_and_excludes_cache_markers(tmp_path: Path) -> None:+ skills_dir = tmp_path / "skills"+ skill_dir = skills_dir / "sample"+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text("# Sample\n")+ (skills_dir / ".build-hash").write_text("cache")+ hidden_dir = skills_dir / ".cache"+ hidden_dir.mkdir()+ (hidden_dir / "state").write_text("cache")++ first = package_local_skills_archive(skills_dir, tmp_path / "first.zip")+ second = package_local_skills_archive(skills_dir, tmp_path / "second.zip")++ assert first.read_bytes() == second.read_bytes()+ with zipfile.ZipFile(first) as archive:+ assert archive.namelist() == ["sample/SKILL.md"]+++ "exec_skills_enabled,skill_archive_url,expected_flag_value",+ [+ (True, "http://localhost:18788/skills.zip?v=abc", True),+ (False, None, False),+ ],+)+def test_start_mcp_server_isolates_the_selected_skill_delivery(+ tmp_path: Path,+ exec_skills_enabled: bool,+ skill_archive_url: str | None,+ expected_flag_value: bool,+) -> None:+ mcp_dir = tmp_path / "services" / "mcp"+ (mcp_dir / "node_modules").mkdir(parents=True)+ stop = MagicMock()++ with (+ patch.dict(os.environ, {"POSTHOG_MCP_SKILLS_URL": "https://stale.example/skills.zip"}),+ patch("products.posthog_ai.eval_harness.harness.services.settings.BASE_DIR", tmp_path),+ patch(+ "products.posthog_ai.eval_harness.harness.services.LONG_LIVED_SUBPROCESSES.start",+ return_value=(MagicMock(), stop),+ ) as start,+ ):+ result = start_mcp_server(+ "http://localhost:18000",+ skill_archive_url,+ exec_skills_enabled=exec_skills_enabled,+ )++ env = start.call_args.kwargs["env"]+ assert (+ env["FEATURE_FLAG_OVERRIDES"]+ == f'{{"product-data-catalog": true, "mcp-exec-skills": {str(expected_flag_value).lower()}}}'+ )+ if skill_archive_url is None:+ assert "POSTHOG_MCP_SKILLS_URL" not in env+ else:+ assert env["POSTHOG_MCP_SKILLS_URL"] == skill_archive_url+ assert result is stopdiff --git a/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.pynew file mode 100644index 000000000000..9294779918fa--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py@@ -0,0 +1,276 @@+from __future__ import annotations++import json++import pytest++from braintrust_core.score import Score, Scorer++from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ ExpectedSkillDiscovered,+ ExpectedSkillLoaded,+ NoBundledSkillBypass,+ NoExecSkillBypass,+ SkillLoadedBeforeTool,+ SkillSearchFirst,+ skill_distribution_expectations,+)++SKILL = "querying-posthog-data"+QUALIFIED_SKILL = f"posthog:{SKILL}"+PROJECT_QUALIFIED_SKILL = f"project:{SKILL}"+EXEC_EXPECTED = skill_distribution_expectations(SKILL, ["execute-sql"], "exec")+BUNDLED_EXPECTED = skill_distribution_expectations(SKILL, ["execute-sql"], "bundled")+PROJECT_EXEC_EXPECTED = skill_distribution_expectations(SKILL, ["execute-sql"], "exec", source="project")+++def _acp_line(update: dict) -> str:+ return json.dumps(+ {+ "notification": {"method": "session/update", "params": {"update": update}},+ "timestamp": "2026-01-01T00:00:00Z",+ }+ )+++def _tool_call(call_id: str, tool_name: str, raw_input: dict, output: str = "ok", *, failed: bool = False) -> list[str]:+ return [+ _acp_line(+ {+ "sessionUpdate": "tool_call",+ "toolCallId": call_id,+ "_meta": {"claudeCode": {"toolName": tool_name}},+ "rawInput": raw_input,+ }+ ),+ _acp_line(+ {+ "sessionUpdate": "tool_call_update",+ "toolCallId": call_id,+ "status": "failed" if failed else "completed",+ "rawOutput": output,+ }+ ),+ ]+++def _exec(call_id: str, command: str, output: str = "ok", *, failed: bool = False) -> list[str]:+ return _tool_call(call_id, "mcp__posthog__exec", {"command": command}, output, failed=failed)+++def _output(*calls: list[str]) -> dict[str, object]:+ return {"raw_log": "\n".join(line for call in calls for line in call), "prompt": "analyze revenue"}+++def _score(scorer: Scorer, output: dict[str, object], expected: dict[str, dict[str, object]] = EXEC_EXPECTED) -> Score:+ return scorer._run_eval_sync(output, expected=expected)+++def _happy_path() -> dict[str, object]:+ return _output(+ _exec("search", 'learn -s "paid bill revenue by plan"', f'{{"name":"{QUALIFIED_SKILL}"}}'),+ _exec("load", f"learn {QUALIFIED_SKILL}", "# Querying data"),+ _exec("query", "call execute-sql {}", "[]"),+ )+++ "scorer",+ [+ SkillSearchFirst(),+ ExpectedSkillDiscovered(),+ ExpectedSkillLoaded(),+ SkillLoadedBeforeTool(),+ NoBundledSkillBypass(),+ ],+)+def test_skill_distribution_scorers_accept_the_exec_distribution_path(scorer: Scorer) -> None:+ assert _score(scorer, _happy_path()).score == 1.0+++ "earlier_call,expected_score",+ [+ (_exec("info", "info execute-sql"), 0.0),+ (_exec("failed-info", "info execute-sql", failed=True), 1.0),+ (_exec("guide", "learn analytics"), 1.0),+ ],+)+def test_skill_search_must_precede_successful_non_learning_exec_commands(+ earlier_call: list[str], expected_score: float+) -> None:+ output = _output(earlier_call, _exec("search", "learn -s revenue", QUALIFIED_SKILL))+ assert _score(SkillSearchFirst(), output).score == expected_score+++def test_skill_search_must_not_be_parallelized_with_non_learning_exec_commands() -> None:+ search = _exec("search", "learn -s revenue", QUALIFIED_SKILL)+ data_call = _exec("data", 'call read-data-schema {"query":{"kind":"events"}}')+ output: dict[str, object] = {+ "raw_log": "\n".join([search[0], data_call[0], search[1], data_call[1]]),+ "prompt": "analyze revenue",+ }++ assert _score(SkillSearchFirst(), output).score == 0.0+++ "output,scorer",+ [+ (_output(_exec("search", "learn -s revenue", "posthog:other-skill")), ExpectedSkillDiscovered()),+ (+ _output(_exec("search", "learn -s revenue", f"{QUALIFIED_SKILL}-extended")),+ ExpectedSkillDiscovered(),+ ),+ (+ _output(+ _exec("search", "learn -s revenue", "posthog:other-skill"),+ _exec("load", f"learn {QUALIFIED_SKILL}"),+ ),+ ExpectedSkillLoaded(),+ ),+ (+ _output(+ _exec("search", "learn -s revenue", QUALIFIED_SKILL),+ _exec("query", "call execute-sql {}"),+ _exec("load", f"learn {QUALIFIED_SKILL}"),+ ),+ SkillLoadedBeforeTool(),+ ),+ ],+)+def test_skill_distribution_scorers_reject_missing_discovery_or_wrong_order(+ output: dict[str, object], scorer: Scorer+) -> None:+ assert _score(scorer, output).score == 0.0+++ "bypass_call,expected_score",+ [+ (_tool_call("native", "Skill", {"skill": "querying-posthog-data"}), 0.0),+ (+ _tool_call(+ "read",+ "Read",+ {"file_path": "/root/.claude/skills/querying-posthog-data/SKILL.md"},+ ),+ 0.0,+ ),+ (_tool_call("failed-native", "Skill", {"skill": "querying-posthog-data"}, failed=True), 1.0),+ ],+)+def test_bundled_skill_bypass_counts_only_successful_calls(bypass_call: list[str], expected_score: float) -> None:+ assert _score(NoBundledSkillBypass(), _output(bypass_call)).score == expected_score+++ "load_call",+ [+ _tool_call("native", "Skill", {"skill": SKILL}),+ _tool_call(+ "read",+ "Read",+ {"file_path": f"/root/.claude/skills/{SKILL}/SKILL.md"},+ ),+ _tool_call(+ "shell",+ "Bash",+ {"command": f"sed -n '1,200p' /root/.agents/skills/{SKILL}/SKILL.md"},+ ),+ ],+)+def test_bundled_distribution_accepts_native_skill_loading_paths(load_call: list[str]) -> None:+ output = _output(load_call, _exec("query", "call execute-sql {}", "[]"))++ for scorer in (ExpectedSkillLoaded(), SkillLoadedBeforeTool(), NoExecSkillBypass()):+ assert _score(scorer, output, BUNDLED_EXPECTED).score == 1.0+++ "output,scorer",+ [+ (_output(_tool_call("wrong", "Skill", {"skill": "other-skill"})), ExpectedSkillLoaded()),+ (_output(_tool_call("failed", "Skill", {"skill": SKILL}, failed=True)), ExpectedSkillLoaded()),+ (+ _output(+ _exec("query", "call execute-sql {}", "[]"),+ _tool_call("native", "Skill", {"skill": SKILL}),+ ),+ SkillLoadedBeforeTool(),+ ),+ ],+)+def test_bundled_distribution_rejects_wrong_failed_or_late_skill_loads(+ output: dict[str, object], scorer: Scorer+) -> None:+ assert _score(scorer, output, BUNDLED_EXPECTED).score == 0.0+++ "command,failed,expected_score",+ [+ ("learn -s revenue", False, 0.0),+ ("learn skills", False, 0.0),+ (f"learn {QUALIFIED_SKILL}", False, 0.0),+ ("learn project:team-retention", False, 0.0),+ (f"learn -d {QUALIFIED_SKILL}", False, 0.0),+ ("learn analytics", False, 1.0),+ ("learn -s revenue", True, 1.0),+ ],+)+def test_exec_skill_bypass_counts_only_successful_distribution_commands(+ command: str, failed: bool, expected_score: float+) -> None:+ output = _output(_exec("learn", command, failed=failed))++ assert _score(NoExecSkillBypass(), output, BUNDLED_EXPECTED).score == expected_score+++ "load_command,expected_score",+ [+ (f"learn posthog:other {QUALIFIED_SKILL}", 1.0),+ (f"learn -d {QUALIFIED_SKILL}", 0.0),+ ],+)+def test_exec_batch_read_counts_as_load_but_describe_does_not(load_command: str, expected_score: float) -> None:+ output = _output(+ _exec("search", "learn -s revenue", QUALIFIED_SKILL),+ _exec("load", load_command),+ )++ assert _score(ExpectedSkillLoaded(), output).score == expected_score+++ "scorer,expected",+ [+ (SkillSearchFirst(), BUNDLED_EXPECTED),+ (ExpectedSkillDiscovered(), BUNDLED_EXPECTED),+ (NoBundledSkillBypass(), BUNDLED_EXPECTED),+ (NoExecSkillBypass(), EXEC_EXPECTED),+ ],+)+def test_delivery_specific_scorers_skip_the_other_arm(scorer: Scorer, expected: dict[str, dict[str, object]]) -> None:+ assert _score(scorer, _happy_path(), expected).score is None+++ "scorer,output",+ [+ (+ ExpectedSkillDiscovered(),+ _output(_exec("search", "learn -s revenue", f'{{"name":"{PROJECT_QUALIFIED_SKILL}"}}')),+ ),+ (+ ExpectedSkillLoaded(),+ _output(+ _exec("search", "learn -s revenue", PROJECT_QUALIFIED_SKILL),+ _exec("load", f"learn {PROJECT_QUALIFIED_SKILL}"),+ ),+ ),+ ],+)+def test_project_source_discovery_and_loading(scorer: Scorer, output: dict[str, object]) -> None:+ assert _score(scorer, output, PROJECT_EXEC_EXPECTED).score == 1.0diff --git a/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.pynew file mode 100644index 000000000000..052e194b2441--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py@@ -0,0 +1,140 @@+from __future__ import annotations++import pytest++from braintrust import Score++from products.posthog_ai.eval_harness.test.test_skill_distribution_scorers import _exec, _output, _score, _tool_call+from products.posthog_ai.evals.cli_mcp.skill_usage_scorers import (+ ExpectedReferencePulled,+ SearchRecoveryAfterZeroHit,+ SkillAnswerCorrectness,+)++ZERO_HIT = 'No skills matched "xyz". None of the query words appear in any skill.'+++def _ref_expected(+ paths: list[str], *, skill: str = "s", source: str = "posthog", delivery: str = "exec"+) -> dict[str, dict[str, object]]:+ return {"expected_reference_pulled": {"skill": skill, "delivery": delivery, "source": source, "paths": paths}}+++def _recovery_expected() -> dict[str, dict[str, object]]:+ return {"search_recovery_after_zero_hit": {}}+++ "command,paths,skill,source",+ [+ ("learn posthog:s references/a.md", ["references/a.md"], "s", "posthog"),+ ("learn posthog:s references/a.md references/b.md", ["references/b.md"], "s", "posthog"),+ ("learn posthog:s references/a.md -s query", ["references/a.md"], "s", "posthog"),+ ("learn posthog:s references/a.md --lines 1:40", ["references/a.md"], "s", "posthog"),+ ("learn project:p references/policy-details.md", ["references/policy-details.md"], "p", "project"),+ ("learn posthog:s ./references/a.md", ["references/a.md"], "s", "posthog"),+ ],+)+def test_expected_reference_pulled_accepts_exec_reference_reads(+ command: str, paths: list[str], skill: str, source: str+) -> None:+ output = _output(_exec("ref", command))+ expected = _ref_expected(paths, skill=skill, source=source)+ assert _score(ExpectedReferencePulled(), output, expected).score == 1.0+++ "command,paths,skill,failed",+ [+ ("learn posthog:s", ["references/a.md"], "s", False),+ ("learn posthog:s SKILL.md", ["references/a.md"], "s", False),+ ("learn posthog:other references/a.md", ["references/a.md"], "s", False),+ ("learn posthog:s references/a.md", ["references/a.md"], "s", True),+ ("learn posthog:s posthog:other", ["references/a.md"], "s", False),+ ("learn posthog:s -s query", ["references/a.md"], "s", False),+ ],+)+def test_expected_reference_pulled_rejects_non_reference_exec_calls(+ command: str, paths: list[str], skill: str, failed: bool+) -> None:+ output = _output(_exec("ref", command, failed=failed))+ assert _score(ExpectedReferencePulled(), output, _ref_expected(paths, skill=skill)).score == 0.0+++ "file_path,expected_score",+ [+ ("/root/.claude/skills/s/references/a.md", 1.0),+ ("/root/.claude/skills/s/references/unrelated.md", 0.0),+ ],+)+def test_expected_reference_pulled_bundled_arm_matches_reference_file_path(+ file_path: str, expected_score: float+) -> None:+ output = _output(_tool_call("read", "Read", {"file_path": file_path}))+ expected = _ref_expected(["references/a.md"], delivery="bundled")+ assert _score(ExpectedReferencePulled(), output, expected).score == expected_score+++def test_expected_reference_pulled_self_skips_when_not_requested() -> None:+ output = _output(_exec("ref", "learn posthog:s references/a.md"))+ assert _score(ExpectedReferencePulled(), output, {}).score is None+++ "calls,expected_score",+ [+ ([_exec("search", "learn -s revenue", "posthog:s")], None),+ ([_exec("zero", "learn -s xyz", ZERO_HIT), _exec("recover", "learn skills", "posthog:s")], 1.0),+ ([_exec("zero", "learn -s xyz", ZERO_HIT), _exec("recover", "learn -s broader", "posthog:s")], 1.0),+ ([_exec("zero", "learn -s xyz", ZERO_HIT), _exec("give-up", "call execute-sql {}", "[]")], 0.0),+ # A gate-rejected (errored) product call is still the agent jumping to product+ # tools — a later learn must not hide it from the ordering.+ (+ [+ _exec("zero", "learn -s xyz", ZERO_HIT),+ _exec("gated", "call execute-sql {}", "No skills loaded this session.", failed=True),+ _exec("recover", "learn skills", "posthog:s"),+ ],+ 0.0,+ ),+ ([_exec("zero", "learn -s xyz", ZERO_HIT)], 0.0),+ ([_exec("zero", "learn -s xyz", ZERO_HIT, failed=True)], None),+ (+ [+ _exec("zero-1", "learn -s xyz", ZERO_HIT),+ _exec("zero-2", "learn -s abc", ZERO_HIT),+ _exec("give-up", "call execute-sql {}", "[]"),+ ],+ 0.0,+ ),+ ],+)+def test_search_recovery_after_zero_hit(calls: list[list[str]], expected_score: float | None) -> None:+ result = _score(SearchRecoveryAfterZeroHit(), _output(*calls), _recovery_expected())+ if expected_score is None:+ assert result.score is None+ else:+ assert result.score == expected_score+++def test_skill_answer_correctness_self_skips_when_not_requested() -> None:+ prepared = SkillAnswerCorrectness()._prepare({"last_message": "anything"}, {})+ assert isinstance(prepared, Score)+ assert prepared.score is None+++def test_skill_answer_correctness_fails_without_final_message() -> None:+ expected = {"skill_answer_correctness": {"expected_answer": "the answer"}}+ prepared = SkillAnswerCorrectness()._prepare({"last_message": " "}, expected)+ assert isinstance(prepared, Score)+ assert prepared.score == 0.0+++def test_skill_answer_correctness_forwards_answer_to_judge() -> None:+ expected = {"skill_answer_correctness": {"expected_answer": "the answer"}}+ output = {"last_message": "some final answer", "prompt": "the question"}+ prepared = SkillAnswerCorrectness()._prepare(output, expected)+ assert isinstance(prepared, dict)+ assert prepared["expected"]["expected_answer"] == "the answer"+ assert prepared["output"]["final_message"] == "some final answer"diff --git a/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py b/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.pynew file mode 100644index 000000000000..999ce4e3789b--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py@@ -0,0 +1,109 @@+from __future__ import annotations++from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.cli import SkillDelivery+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ ExpectedSkillDiscovered,+ ExpectedSkillLoaded,+ NoBundledSkillBypass,+ NoExecSkillBypass,+ SkillLoadedBeforeTool,+ SkillSearchFirst,+ skill_distribution_expectations,+)+++def _case(+ name: str,+ prompt: str,+ skill: str,+ downstream_tools: list[str],+ skill_delivery: SkillDelivery,+) -> SandboxedEvalCase:+ return SandboxedEvalCase(+ name=name,+ prompt=prompt,+ expected=skill_distribution_expectations(skill, downstream_tools, skill_delivery),+ metadata={"expected_skill": skill, "skill_delivery": skill_delivery},+ )+++async def eval_skill_distribution(ctx: EvalContext) -> None:+ cases = [+ _case(+ name="paid_bill_revenue_by_account_plan",+ prompt=(+ "Which account plans generated the most paid-bill revenue over the last 90 days? "+ "Return each plan, its total revenue, and the number of unique accounts that paid."+ ),+ skill="querying-posthog-data",+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="outbound_autocapture_hrefs",+ prompt=(+ "Using our autocapture data from the last 120 days, list the outbound link hrefs people clicked "+ "and the click count for each href."+ ),+ skill="exploring-autocapture-events",+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="historical_traffic_share_by_type",+ prompt=(+ "For the last 30 days, what share of pageviews came from each human or bot traffic type? "+ "This is a historical analysis, not the Live tab."+ ),+ skill="filtering-bot-traffic",+ downstream_tools=["query-trends", "execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="weekly_file_volume_drop",+ prompt=(+ "Investigate why the existing 'Weekly file volume' metric fell in the most recent full week "+ "compared with the previous full week. Use project data to identify the likely drivers."+ ),+ skill="investigate-metric",+ downstream_tools=["insight-query", "query-trends", "execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="uneven_split_bias_warning",+ prompt=(+ "Diagnose the bias warning on the 'bias-warning-demo-uneven-split' experiment. "+ "Explain what in this experiment is causing the warning and what should be checked next."+ ),+ skill="diagnosing-experiment-results",+ downstream_tools=["experiment-get", "experiment-stats", "execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="seven_day_live_top_pages_equivalent",+ prompt=(+ "The Web analytics Live tab shows top pages for the current window. "+ "Build and run the equivalent top-pages analysis for the last seven days."+ ),+ skill="exploring-live-traffic",+ downstream_tools=["query-trends"],+ skill_delivery=ctx.skill_delivery,+ ),+ ]++ await SandboxedPublicEval(+ experiment_name="sandboxed-cli-mcp-skill-distribution-cli",+ cases=cases,+ scorers=[+ SkillSearchFirst(),+ ExpectedSkillDiscovered(),+ ExpectedSkillLoaded(),+ SkillLoadedBeforeTool(),+ NoBundledSkillBypass(),+ NoExecSkillBypass(),+ ],+ ctx=ctx,+ )diff --git a/products/posthog_ai/evals/cli_mcp/eval_skill_usage.py b/products/posthog_ai/evals/cli_mcp/eval_skill_usage.pynew file mode 100644index 000000000000..085da513a2a0--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/eval_skill_usage.py@@ -0,0 +1,145 @@+from __future__ import annotations++from collections.abc import Callable+from typing import Any++from products.posthog_ai.eval_harness.base import SandboxedPublicEval+from products.posthog_ai.eval_harness.config import SandboxedEvalCase+from products.posthog_ai.eval_harness.harness.cli import SkillDelivery+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ ExpectedSkillDiscovered,+ ExpectedSkillLoaded,+ NoBundledSkillBypass,+ NoExecSkillBypass,+ SkillLoadedBeforeTool,+ SkillSearchFirst,+)+from products.posthog_ai.evals.cli_mcp.skill_usage_scorers import (+ ExpectedReferencePulled,+ SearchRecoveryAfterZeroHit,+ SkillAnswerCorrectness,+ skill_usage_expectations,+)+from products.posthog_ai.evals.cli_mcp.skill_usage_seeder import (+ PROJECT_SKILL_EXPECTED_ANSWER,+ PROJECT_SKILL_NAME,+ PROJECT_SKILL_REFERENCE_PATH,+ seed_project_skill,+)+++def _case(+ name: str,+ prompt: str,+ skill: str,+ downstream_tools: list[str],+ skill_delivery: SkillDelivery,+ *,+ source: str = "posthog",+ reference_paths: list[str] | None = None,+ expected_answer: str | None = None,+ setup: Callable[[Any], dict[str, Any]] | None = None,+) -> SandboxedEvalCase:+ return SandboxedEvalCase(+ name=name,+ prompt=prompt,+ expected=skill_usage_expectations(+ skill,+ downstream_tools,+ skill_delivery,+ source=source,+ reference_paths=reference_paths,+ expected_answer=expected_answer,+ ),+ metadata={"expected_skill": skill, "skill_delivery": skill_delivery},+ setup=setup,+ )+++async def eval_skill_usage(ctx: EvalContext) -> None:+ cases = [+ _case(+ name="bias_threshold_reference_pull",+ prompt=(+ "The 'bias-warning-demo-uneven-split' experiment is showing a bias warning. "+ "At exactly what multi-variant ($multiple) exposure share does that warning fire, "+ "and at what share does the Exposures tab show a $multiple row? "+ "Compute this experiment's actual $multiple exposure share from its data and state "+ "whether the row is visible for it."+ ),+ skill="diagnosing-experiment-results",+ downstream_tools=["experiment-get", "experiment-stats", "execute-sql"],+ skill_delivery=ctx.skill_delivery,+ reference_paths=["references/bias-and-skew.md"],+ expected_answer=(+ "The bias warning fires when the $multiple exposure share is above 0.1%. "+ "The Exposures tab hides the $multiple row when its share is at or below 0.5%. "+ "This experiment's actual $multiple exposure share is above 0.5%, "+ "so the $multiple row is visible for it."+ ),+ ),+ _case(+ name="error_volume_schema_reference_pull",+ prompt=(+ "Which error tracking issue had the most exceptions over the last 30 days? "+ "Return the issue's exact title and its issue id."+ ),+ skill="querying-posthog-data",+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ reference_paths=["references/models-error-tracking.md", "references/example-error-tracking.md"],+ expected_answer=(+ "The answer names exactly one error tracking issue as the highest-volume one — one of "+ '"Checkout API timeout", "File preview render failure", or "Team invite rejected" — '+ "and includes that issue's UUID issue id."+ ),+ ),+ _case(+ name="automated_visitor_share_paraphrase",+ prompt=(+ "Our pageview numbers for the last 30 days look inflated by non-human visitors. "+ "Work out what share of pageviews came from scrapers and AI agents crawling the site, "+ "and report a cleaned pageview figure that counts people only."+ ),+ skill="filtering-bot-traffic",+ downstream_tools=["query-trends", "execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ ]++ if ctx.skill_delivery == "exec":+ cases.append(+ _case(+ name="project_enterprise_revenue_policy",+ prompt=(+ "Finance asked for our qualified enterprise revenue over the last 90 days. "+ "Compute it, apply the standard definition our team has documented for this, "+ "and quote the exact rules you applied, including any exclusions."+ ),+ skill=PROJECT_SKILL_NAME,+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ source="project",+ reference_paths=[PROJECT_SKILL_REFERENCE_PATH],+ expected_answer=PROJECT_SKILL_EXPECTED_ANSWER,+ setup=seed_project_skill,+ )+ )++ await SandboxedPublicEval(+ experiment_name="sandboxed-cli-mcp-skill-usage-cli",+ cases=cases,+ scorers=[+ SkillSearchFirst(),+ ExpectedSkillDiscovered(),+ ExpectedSkillLoaded(),+ SkillLoadedBeforeTool(),+ NoBundledSkillBypass(),+ NoExecSkillBypass(),+ ExpectedReferencePulled(),+ SearchRecoveryAfterZeroHit(),+ SkillAnswerCorrectness(),+ ],+ ctx=ctx,+ )diff --git a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.pynew file mode 100644index 000000000000..025fe23948a2--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py@@ -0,0 +1,446 @@+from __future__ import annotations++import re+import json+from dataclasses import dataclass+from typing import cast++from braintrust import Score+from braintrust_core.score import Scorer++from products.posthog_ai.eval_harness.harness.cli import SkillDelivery+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall, normalize_tool_name++_BUNDLED_SKILL_PATH_MARKERS = (+ "/scripts/plugins/posthog/skills/",+ "/root/.claude/skills/",+ "/root/.agents/skills/",+ "~/.claude/skills/",+ "~/.agents/skills/",+)+++@dataclass(frozen=True)+class _SkillLoad:+ position: int+ call_id: str+ matched_via: str+++def skill_distribution_expectations(+ skill: str, downstream_tools: list[str], skill_delivery: SkillDelivery, *, source: str = "posthog"+) -> dict[str, dict[str, object]]:+ expectations: dict[str, dict[str, object]] = {+ "expected_skill_loaded": {"skill": skill, "delivery": skill_delivery, "source": source},+ "skill_loaded_before_tool": {+ "skill": skill,+ "delivery": skill_delivery,+ "source": source,+ "tools": downstream_tools,+ },+ }+ if skill_delivery == "exec":+ expectations.update(+ {+ "skill_search_first": {},+ "expected_skill_discovered": {"skill": skill, "source": source},+ "no_bundled_skill_bypass": {},+ }+ )+ else:+ expectations["no_exec_skill_bypass"] = {}+ return expectations+++def _expected_spec(expected: dict[str, object] | None, scorer_name: str) -> dict[str, object] | None:+ if not isinstance(expected, dict) or scorer_name not in expected:+ return None+ spec = expected[scorer_name]+ return cast(dict[str, object], spec) if isinstance(spec, dict) else None+++def _parser(output: dict[str, object] | None) -> LogParser | None:+ if not output:+ return None+ raw_log = output.get("raw_log")+ if not isinstance(raw_log, str) or not raw_log:+ return None+ prompt = output.get("prompt")+ return LogParser.cached(raw_log, initial_prompt=prompt if isinstance(prompt, str) else "")+++def _exec_command(call: ToolCall) -> tuple[str, str]:+ if call.is_exec_unwrapped or normalize_tool_name(call.raw_name) != EXEC_TOOL_NAME:+ return ("", "")+ command = call.input.get("command")+ if not isinstance(command, str):+ return ("", "")+ verb, _, rest = command.strip().partition(" ")+ return (verb.lower(), rest.strip())+++def _successful_exec_calls(parser: LogParser) -> list[ToolCall]:+ return [+ call+ for call in parser.get_tool_calls()+ if not call.is_error and normalize_tool_name(call.raw_name) == EXEC_TOOL_NAME+ ]+++def _is_skill_search(call: ToolCall) -> bool:+ verb, rest = _exec_command(call)+ return verb == "learn" and (rest == "-s" or rest.startswith("-s "))+++def _skill_search_calls(parser: LogParser) -> list[ToolCall]:+ return [call for call in _successful_exec_calls(parser) if _is_skill_search(call)]+++def _qualified_skill(skill: str, source: str = "posthog") -> str:+ return f"{source}:{skill}"+++def _output_mentions_skill(output: str, qualified_skill: str) -> bool:+ return re.search(rf"(?<![a-zA-Z0-9_-]){re.escape(qualified_skill)}(?![a-zA-Z0-9_-])", output) is not None+++def _is_qualified_skill_token(token: str) -> bool:+ return token.startswith(("posthog:", "project:"))+++def _exec_skill_load_calls(parser: LogParser, qualified_skill: str) -> list[ToolCall]:+ loads: list[ToolCall] = []+ for call in _successful_exec_calls(parser):+ verb, rest = _exec_command(call)+ if verb != "learn" or not rest:+ continue+ # A batch read (`learn posthog:a posthog:b`) is all qualified names; a `<skill> <path>`+ # read (`learn posthog:a SKILL.md`) is not, so it is not counted as a load.+ tokens = rest.split()+ if all(_is_qualified_skill_token(token) for token in tokens) and qualified_skill in tokens:+ loads.append(call)+ return loads+++def _bundled_skill_loads(parser: LogParser, skill: str) -> list[_SkillLoad]:+ loads = [+ _SkillLoad(position=call.position, call_id=call.call_id, matched_via="skill_tool")+ for call in parser.get_skill_calls(skill)+ if not call.is_error+ ]++ skill_file_ref = f"{skill}/skill.md".lower()+ for call in parser.get_tool_calls():+ if call.is_error:+ continue+ reference = f"{call.name}\n{json.dumps(call.input, default=str)}".lower()+ if skill_file_ref in reference:+ loads.append(_SkillLoad(position=call.position, call_id=call.call_id, matched_via="skill_file_reference"))++ return sorted(loads, key=lambda load: load.position)+++def _skill_loads(parser: LogParser, skill: str, delivery: SkillDelivery, source: str = "posthog") -> list[_SkillLoad]:+ if delivery == "bundled":+ return _bundled_skill_loads(parser, skill)+ return [+ _SkillLoad(position=call.position, call_id=call.call_id, matched_via="exec_learn")+ for call in _exec_skill_load_calls(parser, _qualified_skill(skill, source))+ ]+++def _skill_and_delivery(spec: dict[str, object]) -> tuple[str, SkillDelivery, str] | None:+ skill = spec.get("skill")+ delivery = spec.get("delivery")+ source = spec.get("source", "posthog")+ if not isinstance(skill, str) or not skill or delivery not in ("bundled", "exec"):+ return None+ if source not in ("posthog", "project"):+ return None+ return skill, cast(SkillDelivery, delivery), cast(str, source)+++def _is_exec_skill_command(call: ToolCall) -> bool:+ verb, rest = _exec_command(call)+ return verb == "learn" and (+ rest == "skills"+ or rest == "-s"+ or rest.startswith("-s ")+ or rest == "-d"+ or rest.startswith("-d ")+ or rest.startswith("posthog:")+ or rest.startswith("project:")+ )+++class SkillSearchFirst(Scorer):+ def _name(self) -> str:+ return "skill_search_first"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ if _expected_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ searches = _skill_search_calls(parser)+ if not searches:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No successful learn -s command"})++ first_search = searches[0]+ earlier_non_learning = [+ call+ for call in _successful_exec_calls(parser)+ if _exec_command(call)[0] != "learn" and call.position <= first_search.position+ ]+ if earlier_non_learning:+ first = earlier_non_learning[0]+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "A non-learning PostHog command ran before skill search",+ "call_id": first.call_id,+ "tool": first.name,+ },+ )+ return Score(name=self._name(), score=1.0, metadata={"call_id": first_search.call_id})+++class ExpectedSkillDiscovered(Scorer):+ def _name(self) -> str:+ return "expected_skill_discovered"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ skill = spec.get("skill")+ if not isinstance(skill, str) or not skill:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Expected skill is missing"})+ source = spec.get("source", "posthog")+ if source not in ("posthog", "project"):+ return Score(name=self._name(), score=0.0, metadata={"reason": "Invalid scorer expectation"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ qualified_skill = _qualified_skill(skill, cast(str, source))+ for call in _skill_search_calls(parser):+ if _output_mentions_skill(call.output, qualified_skill):+ return Score(name=self._name(), score=1.0, metadata={"skill": qualified_skill, "call_id": call.call_id})+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "Skill search did not return the expected qualified name",+ "skill": qualified_skill,+ },+ )+++class ExpectedSkillLoaded(Scorer):+ def _name(self) -> str:+ return "expected_skill_loaded"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ skill_spec = _skill_and_delivery(spec)+ if skill_spec is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Invalid scorer expectation"})+ skill, delivery, source = skill_spec+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ loads = _skill_loads(parser, skill, delivery, source)+ if delivery == "bundled" and loads:+ load = loads[0]+ return Score(+ name=self._name(),+ score=1.0,+ metadata={+ "skill": skill,+ "delivery": delivery,+ "call_id": load.call_id,+ "matched_via": load.matched_via,+ },+ )++ qualified_skill = _qualified_skill(skill, source)+ matching_searches = [+ call for call in _skill_search_calls(parser) if _output_mentions_skill(call.output, qualified_skill)+ ]+ if any(search.position < load.position for search in matching_searches for load in loads):+ load = next(load for load in loads if any(search.position < load.position for search in matching_searches))+ return Score(+ name=self._name(),+ score=1.0,+ metadata={"skill": qualified_skill, "delivery": delivery, "call_id": load.call_id},+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": (+ "Expected bundled skill was not loaded"+ if delivery == "bundled"+ else "Expected skill was not loaded by exact qualified name after discovery"+ ),+ "skill": skill,+ "delivery": delivery,+ },+ )+++class SkillLoadedBeforeTool(Scorer):+ def _name(self) -> str:+ return "skill_loaded_before_tool"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ skill_spec = _skill_and_delivery(spec)+ tools = spec.get("tools")+ if skill_spec is None or not isinstance(tools, list) or not all(isinstance(tool, str) for tool in tools):+ return Score(name=self._name(), score=0.0, metadata={"reason": "Invalid scorer expectation"})+ skill, delivery, source = skill_spec+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ loads = _skill_loads(parser, skill, delivery, source)+ downstream_calls = [call for call in parser.get_tool_calls() if not call.is_error and call.name in tools]+ for load in loads:+ for downstream in downstream_calls:+ if load.position < downstream.position:+ return Score(+ name=self._name(),+ score=1.0,+ metadata={+ "skill": skill,+ "delivery": delivery,+ "tool": downstream.name,+ "call_id": downstream.call_id,+ "matched_via": load.matched_via,+ },+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "No expected downstream tool ran after the skill was loaded",+ "skill": skill,+ "delivery": delivery,+ "tools": tools,+ },+ )+++class NoBundledSkillBypass(Scorer):+ def _name(self) -> str:+ return "no_bundled_skill_bypass"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ if _expected_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ native_skill_calls = [call for call in parser.get_skill_calls() if not call.is_error]+ if native_skill_calls:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "A native Skill tool bypassed exec distribution",+ "skill": native_skill_calls[0].name,+ },+ )++ for call in parser.get_tool_calls():+ if call.is_error:+ continue+ serialized_input = json.dumps(call.input, sort_keys=True).lower()+ if "skill.md" in serialized_input and any(+ marker in serialized_input for marker in _BUNDLED_SKILL_PATH_MARKERS+ ):+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "A bundled SKILL.md was read directly", "call_id": call.call_id},+ )++ return Score(name=self._name(), score=1.0)+++class NoExecSkillBypass(Scorer):+ def _name(self) -> str:+ return "no_exec_skill_bypass"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ if _expected_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ bypasses = [call for call in _successful_exec_calls(parser) if _is_exec_skill_command(call)]+ if bypasses:+ verb, rest = _exec_command(bypasses[0])+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "An exec skill command bypassed bundled delivery",+ "call_id": bypasses[0].call_id,+ "command": f"{verb} {rest}".strip(),+ },+ )+ return Score(name=self._name(), score=1.0)+++__all__ = [+ "ExpectedSkillDiscovered",+ "ExpectedSkillLoaded",+ "NoBundledSkillBypass",+ "NoExecSkillBypass",+ "SkillLoadedBeforeTool",+ "SkillSearchFirst",+ "skill_distribution_expectations",+]diff --git a/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.pynew file mode 100644index 000000000000..0fe5201d2b4c--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py@@ -0,0 +1,282 @@+"""Scorers for the skill-usage eval — the layer above skill *distribution*.++Distribution scorers (``skill_distribution_scorers``) grade whether the agent found+and loaded the right skill. These grade what it did with the skill once loaded:+pulling the reference files the skill points at, recovering from a zero-hit search+instead of giving up, and answering the question with the facts the skill teaches.++Every scorer self-skips (``Score(score=None)``) when its ``expected`` key is absent,+so one global scorer list works across every case — Braintrust drops ``None`` from+per-metric aggregates.+"""++from __future__ import annotations++import json+from typing import Any, cast++from braintrust import Score+from braintrust_core.score import Scorer++from products.posthog_ai.eval_harness.harness.cli import SkillDelivery+from products.posthog_ai.eval_harness.log_parser import EXEC_TOOL_NAME, LogParser, ToolCall, normalize_tool_name+from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ _exec_command,+ _expected_spec,+ _is_qualified_skill_token,+ _parser,+ _qualified_skill,+ _skill_search_calls,+ _successful_exec_calls,+ skill_distribution_expectations,+)++_ZERO_HIT_PREFIX = 'No skills matched "'+++def _exec_calls(parser: LogParser) -> list[ToolCall]:+ return [call for call in parser.get_tool_calls() if normalize_tool_name(call.raw_name) == EXEC_TOOL_NAME]+++class ExpectedReferencePulled(Scorer):+ """Binary: did the agent read one of the skill's reference files (not just the skill)?++ A skill's ``SKILL.md`` points at reference files under ``references/`` that hold the+ detail needed to answer well. This checks the agent actually pulled one — via+ ``learn <qualified> <path>`` in exec mode, or a native file read of the bundled+ skill's reference in bundled mode. A bare skill load or all-qualified batch load+ does not count.+ """++ def _name(self) -> str:+ return "expected_reference_pulled"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ skill = spec.get("skill")+ delivery = spec.get("delivery")+ source = spec.get("source", "posthog")+ paths = spec.get("paths")+ if (+ not isinstance(skill, str)+ or not skill+ or delivery not in ("bundled", "exec")+ or source not in ("posthog", "project")+ or not isinstance(paths, list)+ or not paths+ or not all(isinstance(path, str) and path for path in paths)+ ):+ return Score(name=self._name(), score=0.0, metadata={"reason": "Invalid scorer expectation"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ accepted = [cast(str, path) for path in paths]+ if delivery == "exec":+ matched = self._exec_match(parser, cast(str, skill), cast(str, source), accepted)+ else:+ matched = self._bundled_match(parser, cast(str, skill), accepted)+ if matched is not None:+ return Score(name=self._name(), score=1.0, metadata=matched)+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No expected reference file was pulled", "skill": skill, "paths": accepted},+ )++ def _exec_match(self, parser: LogParser, skill: str, source: str, accepted: list[str]) -> dict[str, object] | None:+ qualified = _qualified_skill(skill, source)+ for call in _successful_exec_calls(parser):+ verb, rest = _exec_command(call)+ if verb != "learn":+ continue+ tokens = rest.split()+ if not tokens or tokens[0] != qualified or len(tokens) <= 1:+ continue+ # An all-qualified token list is a batch skill load (`learn posthog:a posthog:b`),+ # not a reference pull.+ if all(_is_qualified_skill_token(token) for token in tokens):+ continue+ for token in self._path_tokens(tokens[1:]):+ normalized = token[2:] if token.startswith("./") else token+ for path in accepted:+ if token == path or normalized == path:+ return {"call_id": call.call_id, "matched_path": path}+ return None++ @staticmethod+ def _path_tokens(rest_tokens: list[str]) -> list[str]:+ # Path tokens run until the first scoped-search / line-range flag; anything after+ # that is search or slicing arguments, not a file path.+ tokens: list[str] = []+ for token in rest_tokens:+ if token in ("-s", "--lines"):+ break+ tokens.append(token)+ return tokens++ def _bundled_match(self, parser: LogParser, skill: str, accepted: list[str]) -> dict[str, object] | None:+ for call in parser.get_tool_calls():+ if call.is_error:+ continue+ reference = f"{call.name}\n{json.dumps(call.input, default=str)}".lower()+ for path in accepted:+ if f"{skill}/{path}".lower() in reference:+ return {"call_id": call.call_id, "matched_path": path}+ return None+++class SearchRecoveryAfterZeroHit(Scorer):+ """Binary: after a zero-hit skill search, did the agent keep learning rather than give up?++ A ``learn -s`` that matches nothing returns text starting with ``No skills matched "``.+ The right move is another ``learn`` command (broaden the query, list skills, describe) —+ not to jump straight into product tools guessing. Self-skips when no zero-hit search ran.+ """++ def _name(self) -> str:+ return "search_recovery_after_zero_hit"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ if _expected_spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ zero_hits = [call for call in _skill_search_calls(parser) if call.output.startswith(_ZERO_HIT_PREFIX)]+ if not zero_hits:+ return Score(name=self._name(), score=None, metadata={"reason": "No zero-hit search occurred"})++ # Ordering must see errored calls too: a gate-rejected product call after a+ # zero-hit search is still the agent jumping to product tools, even though+ # the agent may run `learn` right after the rejection.+ exec_calls = _exec_calls(parser)+ for zero_hit in zero_hits:+ following = [call for call in exec_calls if call.position > zero_hit.position]+ if not following:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No learning follow-up after zero-hit search", "call_id": zero_hit.call_id},+ )+ nxt = min(following, key=lambda call: call.position)+ verb, rest = _exec_command(nxt)+ if verb != "learn":+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": "A non-learning command followed a zero-hit search",+ "call_id": nxt.call_id,+ "command": f"{verb} {rest}".strip(),+ },+ )+ return Score(name=self._name(), score=1.0, metadata={"zero_hits": len(zero_hits)})+++SKILL_ANSWER_PROMPT = """+You are judging whether an agent's final answer states every fact from an expected answer.++The agent was asked USER_PROMPT and produced FINAL_MESSAGE. EXPECTED_ANSWER lists the facts the final message must convey.++Grade only whether FINAL_MESSAGE states every fact in EXPECTED_ANSWER:+- Paraphrase is fine — the wording does not need to match.+- Numeric values must match; a different number is a failure.+- Extra correct material in FINAL_MESSAGE is fine and never a reason to fail.+- Missing or contradicting any fact from EXPECTED_ANSWER is a failure.++<user_prompt>+{{output.prompt}}+</user_prompt>++<expected_answer>+{{expected.expected_answer}}+</expected_answer>++<final_message>+{{output.final_message}}+</final_message>++Does the final message state every fact in the expected answer? Answer `yes` or `no`.+""".strip()+++class SkillAnswerCorrectness(JudgedScorer):+ """Binary LLM judge: does the final message state every fact the skill's answer requires?++ Self-skips (``None``) when not requested. Scores 0.0 (not ``None``) when the expected+ answer is missing/blank or the agent produced no final message, so a broken run surfaces+ as a failing score rather than being silently dropped from the aggregate.+ """++ def __init__(self, **kwargs: Any) -> None:+ super().__init__(+ name="skill_answer_correctness",+ prompt_template=SKILL_ANSWER_PROMPT,+ choice_scores=BINARY_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=512,+ **kwargs,+ )++ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ expected_answer = spec.get("expected_answer")+ if not isinstance(expected_answer, str) or not expected_answer.strip():+ return Score(name=self._name(), score=0.0, metadata={"reason": "No expected answer configured"})+ last_message = output.get("last_message") if isinstance(output, dict) else None+ if not isinstance(last_message, str) or not last_message.strip():+ return Score(name=self._name(), score=0.0, metadata={"reason": "No final agent message"})+ prompt = output.get("prompt") if isinstance(output, dict) else ""+ return {+ "output": {"prompt": prompt if isinstance(prompt, str) else "", "final_message": last_message},+ "expected": {"expected_answer": expected_answer},+ }+++def skill_usage_expectations(+ skill: str,+ downstream_tools: list[str],+ skill_delivery: SkillDelivery,+ *,+ source: str = "posthog",+ reference_paths: list[str] | None = None,+ expected_answer: str | None = None,+) -> dict[str, dict[str, object]]:+ expectations = skill_distribution_expectations(skill, downstream_tools, skill_delivery, source=source)+ if reference_paths:+ expectations["expected_reference_pulled"] = {+ "skill": skill,+ "delivery": skill_delivery,+ "source": source,+ "paths": reference_paths,+ }+ if expected_answer:+ expectations["skill_answer_correctness"] = {"expected_answer": expected_answer}+ if skill_delivery == "exec":+ expectations["search_recovery_after_zero_hit"] = {}+ return expectations+++__all__ = [+ "ExpectedReferencePulled",+ "SearchRecoveryAfterZeroHit",+ "SkillAnswerCorrectness",+ "skill_usage_expectations",+]diff --git a/products/posthog_ai/evals/cli_mcp/skill_usage_seeder.py b/products/posthog_ai/evals/cli_mcp/skill_usage_seeder.pynew file mode 100644index 000000000000..e72ca918230d--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/skill_usage_seeder.py@@ -0,0 +1,104 @@+"""Seeder hook that installs a project-scoped skill into a per-case team.++The skill-usage eval's ``project`` source arm needs a real ``project:`` skill the+agent can discover, load, and pull a reference file from. This seeder writes one+``LLMSkill`` (with a body that instructs applying an exclusion rule documented in a+reference file) and its ``LLMSkillFile`` reference onto the per-case team, so the+MCP ``learn`` command surfaces it under ``project:``.++Runs synchronously in a worker thread (``asyncio.to_thread``) from ``base.py:task()``+after the per-case team/user has been provisioned; the returned dict is merged into+the task output under ``seed`` for scorers.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext++__all__ = [+ "PROJECT_SKILL_NAME",+ "PROJECT_SKILL_DESCRIPTION",+ "PROJECT_SKILL_REFERENCE_PATH",+ "PROJECT_SKILL_PLAN",+ "PROJECT_SKILL_EXCLUSION_FLOOR_USD",+ "PROJECT_SKILL_RULE_LABEL",+ "PROJECT_SKILL_BODY",+ "PROJECT_SKILL_REFERENCE_CONTENT",+ "PROJECT_SKILL_EXPECTED_ANSWER",+ "seed_project_skill",+]++PROJECT_SKILL_NAME = "hedgebox-revenue-policy"+PROJECT_SKILL_REFERENCE_PATH = "references/policy-details.md"+PROJECT_SKILL_PLAN = "business/enterprise"+PROJECT_SKILL_EXCLUSION_FLOOR_USD = 500+PROJECT_SKILL_RULE_LABEL = "REV-7"++PROJECT_SKILL_DESCRIPTION = (+ "How Hedgebox defines qualified enterprise revenue for finance reporting. Qualified enterprise "+ f"revenue counts only `paid_bill` events on the `{PROJECT_SKILL_PLAN}` plan, and rule "+ f"{PROJECT_SKILL_RULE_LABEL} must be applied to drop pilot-tier bills before the figure is reported "+ f"to finance. Read `{PROJECT_SKILL_REFERENCE_PATH}` for the exact exclusions before quoting a number."+)++PROJECT_SKILL_BODY = f"""# Hedgebox revenue policy++Use this skill whenever finance asks for **qualified enterprise revenue**.++## Definition++Qualified enterprise revenue is the SUM of the `paid_bill` event's `amount_usd`+property, filtered to bills on the `{PROJECT_SKILL_PLAN}` plan (the `plan` property+equals `'{PROJECT_SKILL_PLAN}'`). Bills on any other plan do not count.++## Before reporting++Before reporting the number to finance, apply the exclusions documented in+`{PROJECT_SKILL_REFERENCE_PATH}`. Quoting a total without applying those exclusions+is incorrect. Read that reference file and state which rules you applied.+"""++PROJECT_SKILL_REFERENCE_CONTENT = f"""# Policy details++## Rule {PROJECT_SKILL_RULE_LABEL}++Exclude any individual `paid_bill` whose `amount_usd` is below+${PROJECT_SKILL_EXCLUSION_FLOOR_USD} from qualified enterprise revenue. These are+pilot-tier billing charges and must not be counted toward the figure reported to+finance, even when they sit on the `{PROJECT_SKILL_PLAN}` plan.+"""++PROJECT_SKILL_EXPECTED_ANSWER = (+ "Revenue was computed from the `paid_bill` event's `amount_usd` filtered to the "+ f"`{PROJECT_SKILL_PLAN}` plan. Rule {PROJECT_SKILL_RULE_LABEL} was applied, excluding any individual "+ f"paid_bill under ${PROJECT_SKILL_EXCLUSION_FLOOR_USD} (pilot-tier billing) from qualified revenue. "+ "The answer reports a total USD figure."+)+++def seed_project_skill(context: CustomPromptSandboxContext) -> dict[str, Any]:+ """Create the project-scoped revenue-policy skill and its reference file for the case team."""+ from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, category_for_skill_name++ skill = LLMSkill.objects.create(+ team_id=context.team_id,+ name=PROJECT_SKILL_NAME,+ description=PROJECT_SKILL_DESCRIPTION,+ body=PROJECT_SKILL_BODY,+ category=category_for_skill_name(PROJECT_SKILL_NAME),+ created_by_id=context.user_id,+ )+ LLMSkillFile.objects.create(+ skill=skill,+ path=PROJECT_SKILL_REFERENCE_PATH,+ content=PROJECT_SKILL_REFERENCE_CONTENT,+ content_type="text/markdown",+ )+ return {+ "project_skill_id": str(skill.id),+ "project_skill_name": PROJECT_SKILL_NAME,+ "reference_path": PROJECT_SKILL_REFERENCE_PATH,+ }diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex 67ee4ac09f38..a236a4bb15c3 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -2,8 +2,10 @@ import refrom typing import Anyfrom django.db import transaction+from django.db.models import Value+from django.db.models.functions import Length, Replace-from drf_spectacular.utils import extend_schema_field+from drf_spectacular.utils import extend_schema_field, extend_schema_serializerfrom rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer@@ -159,6 +161,51 @@ class LLMSkillListQuerySerializer(serializers.Serializer):)+class LLMSkillSearchQuerySerializer(serializers.Serializer):+ query = serializers.CharField(+ min_length=1,+ max_length=200,+ trim_whitespace=True,+ help_text="Case-insensitive substring to search across ordinary skill names, descriptions, bodies, file paths, and Markdown file contents.",+ )+++class LLMSkillSearchMatchSerializer(serializers.Serializer):+ matched_field = serializers.ChoiceField(+ choices=["name", "description", "body", "file_path", "file_content"],+ help_text="Skill field that matched the search query.",+ )+ path = serializers.CharField(+ required=False,+ help_text="Skill-relative file path for body or bundled-file matches. Omitted for name and description matches.",+ )+ line = serializers.IntegerField(+ min_value=1,+ required=False,+ help_text="One-based line containing the match when the result came from a body or bundled file.",+ )+ excerpt = serializers.CharField(help_text="Short excerpt showing why this skill matched.")+++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.")+ matches = LLMSkillSearchMatchSerializer(+ many=True,+ help_text="Up to two locations that matched the search query, ordered by field relevance.",+ )+++@extend_schema_serializer(many=False)+class LLMSkillSearchResponseSerializer(serializers.Serializer):+ count = serializers.IntegerField(help_text="Number of matching skills returned, capped at 10.")+ results = LLMSkillSearchResultSerializer(many=True, help_text="Matching ordinary skills in relevance order.")+++class LLMSkillSearchErrorSerializer(serializers.Serializer):+ detail = serializers.CharField(help_text="Explanation of why the skill search could not complete.")++class LLMSkillResolveQuerySerializer(LLMSkillFetchQuerySerializer):version_id = serializers.UUIDField(required=False,@@ -200,9 +247,12 @@ class LLMSkillFileSerializer(serializers.ModelSerializer):class LLMSkillFileManifestSerializer(serializers.ModelSerializer):+ line_count = serializers.IntegerField(help_text="Number of lines in the file content.")+ char_count = serializers.IntegerField(help_text="Number of characters in the file content.")+class Meta:model = LLMSkillFile- fields = ["path", "content_type"]+ fields = ["path", "content_type", "line_count", "char_count"]class LLMSkillFileInputSerializer(serializers.Serializer):@@ -376,7 +426,7 @@ class LLMSkillSerializer(serializers.ModelSerializer):"(e.g. the Scouts tab) independently of the skill name.",)files = serializers.SerializerMethodField(- help_text="Bundled files manifest. Each entry is path + content_type only; fetch content via /llm_skills/name/{name}/files/{path}/.",+ help_text="Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/.",)outline = serializers.SerializerMethodField(help_text="Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents.",@@ -466,7 +516,12 @@ class LLMSkillSerializer(serializers.ModelSerializer):@extend_schema_field(LLMSkillFileManifestSerializer(many=True))def get_files(self, instance: LLMSkill) -> list[dict[str, Any]]:- return [dict(row) for row in LLMSkillFile.objects.filter(skill=instance).values("path", "content_type")]+ # Counts are computed in the database so the manifest never fetches file contents.+ annotated = LLMSkillFile.objects.filter(skill=instance).annotate(+ char_count=Length("content"),+ line_count=Length("content") - Length(Replace("content", Value("\n"))) + 1,+ )+ return [dict(row) for row in annotated.values("path", "content_type", "line_count", "char_count")]@extend_schema_field(LLMSkillOutlineEntrySerializer(many=True))def get_outline(self, instance: LLMSkill) -> list[dict[str, Any]]:diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 69fd0e2ecca3..cb5803f8a77a 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,13 +1,14 @@from typing import Any, castfrom uuid import UUID-from django.db import IntegrityError-from django.db.models import Q, QuerySet+from django.db import IntegrityError, OperationalError+from django.db.models import Case, Exists, IntegerField, OuterRef, Q, QuerySet, Value, Whenfrom django.http import HttpResponse+import psycopgimport structlogfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.parsers import FormParser, MultiPartParser@@ -25,6 +26,7 @@ from posthog.auth import ()from posthog.event_usage import report_user_actionfrom posthog.models import User+from posthog.models.utils import execute_with_timeoutfrom posthog.permissions import AccessControlPermissionfrom posthog.rate_limit import BurstRateThrottle, SustainedRateThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -61,6 +63,9 @@ from .skill_serializers import (LLMSkillPublishSerializer,LLMSkillResolveQuerySerializer,LLMSkillResolveResponseSerializer,+ LLMSkillSearchErrorSerializer,+ LLMSkillSearchQuerySerializer,+ LLMSkillSearchResponseSerializer,LLMSkillSerializer,LLMSkillVersionSummarySerializer,validate_allowed_tool,@@ -95,6 +100,10 @@ logger = structlog.get_logger(__name__)# Generous ceiling for an uploaded skill zip — per-skill content (body, 50 files × 1 MB) is# already bounded by create_skill, this just caps the upload before we read it into memory.MAX_IMPORT_ZIP_BYTES = 10_000_000+SKILL_SEARCH_RESULT_LIMIT = 10+SKILL_SEARCH_MATCH_LIMIT = 2+SKILL_SEARCH_EXCERPT_LENGTH = 300+SKILL_SEARCH_TIMEOUT_MS = 5_000def _file_extension(path: str) -> str:@@ -109,6 +118,33 @@ def _is_uuid(value: str) -> bool:return False+def _content_search_match(content: str, query: str, *, matched_field: str, path: str) -> dict[str, Any] | None:+ match_index = content.lower().find(query.lower())+ if match_index == -1:+ return None++ line = content.count("\n", 0, match_index) + 1+ line_start = content.rfind("\n", 0, match_index) + 1+ line_end = content.find("\n", match_index)+ if line_end == -1:+ line_end = len(content)+ line_content = content[line_start:line_end].strip()+ excerpt_source = line_content or content+ excerpt_match_index = excerpt_source.lower().find(query.lower())+ excerpt_start = max(0, excerpt_match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)+ excerpt = excerpt_source[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH]+ return {+ "matched_field": matched_field,+ "path": path,+ "line": line,+ "excerpt": excerpt[:SKILL_SEARCH_EXCERPT_LENGTH],+ }+++def _is_markdown_file_query() -> Q:+ return Q(path__iendswith=".md") | Q(content_type__icontains="markdown")++def _skill_analytics_props(skill: LLMSkill) -> dict[str, Any]:"""Properties shared by every skill report_user_action event.@@ -169,7 +205,7 @@ class LLMSkillViewSet(return get_active_skill_queryset(self.team)def get_throttles(self):- if self.action in ["update_by_name", "get_by_name", "resolve_by_name"]:+ if self.action in ["update_by_name", "get_by_name", "resolve_by_name", "search"]:return [BurstRateThrottle(), SustainedRateThrottle()]return super().get_throttles()@@ -299,6 +335,134 @@ class LLMSkillViewSet(queryset = queryset.order_by(order_by if order_by in ALLOWED_LIST_ORDERINGS else "-created_at", "-id")return queryset+ def _get_search_query(self, request: Request) -> str:+ serializer = LLMSkillSearchQuerySerializer(data=request.query_params)+ serializer.is_valid(raise_exception=True)+ return cast(str, serializer.validated_data["query"])++ def _get_search_queryset(self, query: str) -> QuerySet[LLMSkill]:+ skill_files = LLMSkillFile.objects.filter(skill_id=OuterRef("pk"))+ 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)),+ )+ 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]+ )++ def _get_search_matches(self, skill: LLMSkill, query: str) -> list[dict[str, Any]]:+ matches: list[dict[str, Any]] = []+ lowered_query = query.lower()++ if lowered_query in skill.name.lower():+ matches.append({"matched_field": "name", "excerpt": skill.name})+ if lowered_query in skill.description.lower():+ match_index = skill.description.lower().find(lowered_query)+ excerpt_start = max(0, match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)+ matches.append(+ {+ "matched_field": "description",+ "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")+ 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")+ .values_list("path", flat=True)[:remaining_match_count]+ )+ for path in matching_paths:+ matches.append({"matched_field": "file_path", "path": path, "excerpt": path})++ if len(matches) < SKILL_SEARCH_MATCH_LIMIT:+ remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)+ content_files = (+ skill.files.filter(_is_markdown_file_query(), content__icontains=query)+ .order_by("path")+ .values_list("path", "content")+ )[:remaining_match_count]+ for path, content in content_files:+ match = _content_search_match(+ content,+ query,+ matched_field="file_content",+ path=path,+ )+ if match is not None:+ matches.append(match)++ return matches[:SKILL_SEARCH_MATCH_LIMIT]++ @extend_schema(+ parameters=[LLMSkillSearchQuerySerializer],+ responses={+ 200: LLMSkillSearchResponseSerializer,+ 503: OpenApiResponse(+ response=LLMSkillSearchErrorSerializer,+ description="The bounded skill search exceeded its database timeout.",+ ),+ },+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="search",+ required_scopes=["llm_skill:read"],+ pagination_class=None,+ )+ @llma_track_latency("llma_skills_search")+ @monitor(feature=None, endpoint="llma_skills_search", method="GET")+ def search(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ 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)+ ]+ except OperationalError as err:+ if not isinstance(err.__cause__, psycopg.errors.QueryCanceled):+ raise+ return Response(+ {"detail": "Skill search timed out. Use a more specific query and try again."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ return Response({"count": len(results), "results": results})+def get_serializer_class(self):if self.action == "list":return LLMSkillListSerializerdiff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex ea2dafbebb73..1687dfc1259a 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -2,6 +2,9 @@ import uuidfrom posthog.test.base import APIBaseTest+from django.db import connection+from django.test.utils import CaptureQueriesContext+from parameterized import parameterizedfrom rest_framework import status@@ -334,6 +337,133 @@ class TestLLMSkillAPI(APIBaseTest):assert response.json()["count"] == len(expected_names)assert sorted(r["name"] for r in response.json()["results"]) == sorted(expected_names)+ # --- Search ---++ def test_search_skills_orders_fields_by_relevance_and_skips_non_markdown_file_contents(self):+ self.create_skill(name="needle", description="Exact name match.", body="# Exact")+ self.create_skill(name="needle-name", description="Partial name match.", body="# Name")+ self.create_skill(name="description-skill", description="Contains the needle here.", body="# Description")+ self.create_skill(name="body-skill", description="Body match.", body="# Body\nContains the needle here.")++ path_skill = self.create_skill(name="file-path-skill", description="Path match.", body="# Path")+ LLMSkillFile.objects.create(+ skill=path_skill,+ path="references/needle-guide.txt",+ content="No matching content.",+ )+ content_skill = self.create_skill(name="file-content-skill", description="File match.", body="# File")+ LLMSkillFile.objects.create(+ skill=content_skill,+ path="references/guide.md",+ content="# Guide\nContains the needle here.",+ content_type="text/markdown",+ )+ script_skill = self.create_skill(name="script-content-skill", description="Script match.", body="# Script")+ LLMSkillFile.objects.create(+ skill=script_skill,+ path="scripts/run.py",+ content="print('needle')",+ content_type="text/x-python",+ )++ response = self.client.get(self._url("search?query=NeEdLe"))++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert [result["name"] for result in results] == [+ "needle",+ "needle-name",+ "description-skill",+ "body-skill",+ "file-path-skill",+ "file-content-skill",+ ]+ assert [result["matches"][0]["matched_field"] for result in results] == [+ "name",+ "name",+ "description",+ "body",+ "file_path",+ "file_content",+ ]+ assert results[3]["matches"][0]["path"] == "SKILL.md"+ assert results[5]["matches"][0]["line"] == 2++ 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.")+ for index in range(3):+ LLMSkillFile.objects.create(+ skill=path_skill,+ path=f"references/needle-{index}.txt",+ content="Unused file content.",+ )+ LLMSkillFile.objects.create(+ skill=content_skill,+ path=f"references/guide-{index}.md",+ content="# Guide\nContains needle.",+ content_type="text/markdown",+ )++ with CaptureQueriesContext(connection) as captured_queries:+ response = self.client.get(self._url("search?query=needle"))++ assert response.status_code == status.HTTP_200_OK+ assert [result["matches"][-1]["matched_field"] for result in response.json()["results"]] == [+ "file_content",+ "file_path",+ ]+ file_queries = [+ query["sql"]+ for query in captured_queries.captured_queries+ if query["sql"].lstrip().startswith('SELECT "llm_analytics_llmskillfile".')+ ]+ assert file_queries+ assert all("LIMIT 1" in query for query in file_queries), "\n---\n".join(file_queries)+ path_queries = [+ query+ for query in file_queries+ if query.lstrip().startswith('SELECT "llm_analytics_llmskillfile"."path" AS "path" FROM ')+ ]+ assert len(path_queries) == 2++ def test_search_skills_returns_only_latest_active_ordinary_skills_for_the_current_team(self):+ self.create_skill(name="current-skill", body="Contains boundary-match.")+ self.create_skill(name="scout-skill", body="Contains boundary-match.", category="scout")+ self.create_skill(name="deleted-skill", body="Contains boundary-match.", deleted=True)+ self.create_skill(name="versioned-skill", body="Old boundary-match.", version=1, is_latest=False)+ self.create_skill(name="versioned-skill", body="Latest content.", version=2, is_latest=True)++ other_team = self.create_team_with_organization(self.organization)+ LLMSkill.objects.create(+ team=other_team,+ name="other-team-skill",+ description="Other team.",+ body="Contains boundary-match.",+ created_by=self.user,+ )++ response = self.client.get(self._url("search?query=boundary-match"))++ assert response.status_code == status.HTTP_200_OK+ assert [result["name"] for result in response.json()["results"]] == ["current-skill"]++ @parameterized.expand(+ [+ ("read_scope_allowed", ["llm_skill:read"], status.HTTP_200_OK),+ ("unrelated_scope_denied", ["dashboard:read"], status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_search_skills_pak_scope_end_to_end(self, _label, scopes, expected_status):+ self.create_skill(name="scope-search-skill")+ api_key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")++ response = self.client.get(self._url("search?query=scope"))++ assert response.status_code == expected_status+# --- Get by name ---def test_get_skill_by_name(self):@@ -407,9 +537,9 @@ class TestLLMSkillAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKfiles = response.json()["files"]assert len(files) == 2- paths = {f["path"] for f in files}- assert "scripts/setup.sh" in paths- assert "references/guide.md" in paths+ manifest = {f["path"]: (f["line_count"], f["char_count"]) for f in files}+ assert manifest["scripts/setup.sh"] == (2, len("#!/bin/bash\necho hi"))+ assert manifest["references/guide.md"] == (1, len("# Guide"))def test_get_skill_not_found(self):response = self.client.get(self._url("name/nonexistent"))diff --git a/products/skills/frontend/LLMSkillScene.stories.tsx b/products/skills/frontend/LLMSkillScene.stories.tsxindex 031f098c520a..e18d8cb7e61f 100644--- a/products/skills/frontend/LLMSkillScene.stories.tsx+++ b/products/skills/frontend/LLMSkillScene.stories.tsx@@ -70,8 +70,8 @@ const SKILL: LLMSkillApi = {metadata: {},category: '',files: [- { path: 'scripts/extract.sh', content_type: 'text/x-shellscript' },- { path: 'references/pdf-spec.md', content_type: 'text/markdown' },+ { path: 'scripts/extract.sh', content_type: 'text/x-shellscript', line_count: 24, char_count: 512 },+ { path: 'references/pdf-spec.md', content_type: 'text/markdown', line_count: 120, char_count: 4096 },],outline: [{ level: 1, text: 'PDF extractor' },diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex 636995d4b7ee..9ea76627bc8c 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -221,6 +221,10 @@ export interface LLMSkillFileManifestApi {path: string/** @maxLength 100 */content_type?: string+ /** Number of lines in the file content. */+ line_count: number+ /** Number of characters in the file content. */+ char_count: number}export interface LLMSkillApi {@@ -260,7 +264,7 @@ export interface LLMSkillApi {metadata?: LLMSkillApiMetadata/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string- /** Bundled files manifest. Each entry is path + content_type only; fetch content via /llm_skills/name/{name}/files/{path}/. */+ /** Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/. */readonly files: readonly LLMSkillFileManifestApi[]/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */readonly outline: readonly LLMSkillOutlineEntryApi[]@@ -475,6 +479,64 @@ export interface LLMSkillResolveResponseApi {has_more: boolean}+/**+ * * `name` - name+ * * `description` - description+ * * `body` - body+ * * `file_path` - file_path+ * * `file_content` - file_content+ */+export type MatchedFieldEnumApi = (typeof MatchedFieldEnumApi)[keyof typeof MatchedFieldEnumApi]++export const MatchedFieldEnumApi = {+ Name: 'name',+ Description: 'description',+ Body: 'body',+ FilePath: 'file_path',+ FileContent: 'file_content',+} as const++export interface LLMSkillSearchMatchApi {+ /** Skill field that matched the search query.+ *+ * * `name` - name+ * * `description` - description+ * * `body` - body+ * * `file_path` - file_path+ * * `file_content` - file_content */+ matched_field: MatchedFieldEnumApi+ /** Skill-relative file path for body or bundled-file matches. Omitted for name and description matches. */+ path?: string+ /**+ * One-based line containing the match when the result came from a body or bundled file.+ * @minimum 1+ */+ line?: number+ /** Short excerpt showing why this skill matched. */+ excerpt: string+}++export interface LLMSkillSearchResultApi {+ /** Unique skill name. */+ name: string+ /** What this skill does and when to use it. */+ description: string+ /** Up to two locations that matched the search query, ordered by field relevance. */+ matches: LLMSkillSearchMatchApi[]+}++export interface LLMSkillSearchResponseApi {+ /** Number of matching skills returned, capped at 10. */+ count: number+ /** Matching ordinary skills in relevance order. */+ results: LLMSkillSearchResultApi[]+}++export interface LLMSkillSearchErrorApi {+ /** Explanation of why the skill search could not complete. */+ detail: string+}+export type LlmSkillsListParams = {/*** Filter skills to this exact category. Pass "scout" for Signals scouts, or an empty string to return only uncategorized skills. Omit the parameter entirely to return skills of every category.@@ -567,3 +629,12 @@ export type LlmSkillsResolveNameRetrieveParams = {*/version_id?: string}++export type LlmSkillsSearchRetrieveParams = {+ /**+ * Case-insensitive substring to search across ordinary skill names, descriptions, bodies, file paths, and Markdown file contents.+ * @minLength 1+ * @maxLength 200+ */+ query: string+}diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.tsindex 358f3f08d752..4ebba34bbe91 100644--- a/products/skills/frontend/generated/api.ts+++ b/products/skills/frontend/generated/api.ts@@ -19,12 +19,14 @@ import type {LLMSkillMarketplaceCommandApi,LLMSkillMarketplaceIssueApi,LLMSkillResolveResponseApi,+ LLMSkillSearchResponseApi,LlmSkillsListParams,LlmSkillsNameExportRetrieveParams,LlmSkillsNameFilesDestroyParams,LlmSkillsNameFilesRetrieveParams,LlmSkillsNameRetrieveParams,LlmSkillsResolveNameRetrieveParams,+ LlmSkillsSearchRetrieveParams,PaginatedLLMSkillListListApi,PatchedLLMSkillPublishApi,} from './api.schemas'@@ -401,3 +403,30 @@ export const llmSkillsResolveNameRetrieve = async (method: 'GET',})}++export const getLlmSkillsSearchRetrieveUrl = (projectId: string, params: LlmSkillsSearchRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/llm_skills/search/?${stringifiedParams}`+ : `/api/projects/${projectId}/llm_skills/search/`+}++export const llmSkillsSearchRetrieve = async (+ projectId: string,+ params: LlmSkillsSearchRetrieveParams,+ options?: RequestInit+): Promise<LLMSkillSearchResponseApi> => {+ return apiMutator<LLMSkillSearchResponseApi>(getLlmSkillsSearchRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yamlindex 3604229dd532..d21d4be75fa0 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -18,6 +18,9 @@ tools:llm-skills-name-export-retrieve:operation: llm_skills_name_export_retrieveenabled: false+ llm-skills-search-retrieve:+ operation: llm_skills_search_retrieve+ enabled: falseskill-archive:operation: llm_skills_name_archive_createenabled: truediff --git a/products/skills/skills/skills-store/SKILL.md b/products/skills/skills/skills-store/SKILL.mdindex d146c73e53ed..afbc5325ab25 100644--- a/products/skills/skills/skills-store/SKILL.md+++ b/products/skills/skills/skills-store/SKILL.md@@ -12,6 +12,22 @@ Skills are reusable agent workflows stored in PostHog following the [Agent SkillPostHog is the primary store for team-shared skills — always use the PostHog MCP skill tools to manage them.+## Reading skills through MCP cli mode++When the MCP exposes the `learn` command, use it for progressive-disclosure reads across both sources:++```text+learn skills+learn -s "retention runbook"+learn project:team-retention+learn project:team-retention "references/query guide.md" -s weekly+learn project:team-retention "references/query guide.md" --lines 20:60+```++`project:` identifies skills in the current project's Skills store. `posthog:` identifies skills bundled and published by PostHog. Global search checks both and returns PostHog results first. Quote a file path when it contains spaces.++Use the skill tools below for writes, version management, and MCP clients that do not expose `learn`.+## Available tools| Tool | Purpose |@@ -275,5 +291,5 @@ The bridge is intentionally minimal — it just routes to the MCP tools. The rea- **Always prefer PostHog MCP** for skill storage and retrieval- Only fall back to local files when PostHog MCP is unavailable- When asked to "save", "store", or "remember" a workflow, runbook, or multi-step procedure, store it as a PostHog skill-- When asked to use a skill by name, use `skill-get` first-- When a skill references bundled files in its body, pull them with `skill-file-get` only when needed — don't preload+- When asked to use a skill by name, use `learn project:<name>` in MCP cli mode and `skill-get` in tools mode+- When a skill references bundled files in its body, pull them with `learn project:<name> <path>` or `skill-file-get` only when needed — don't preloaddiff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.pyindex c08c7de0dfeb..45c83e40e4e7 100644--- a/products/tasks/backend/facade/agents.py+++ b/products/tasks/backend/facade/agents.py@@ -18,9 +18,14 @@ from products.tasks.backend.logic.services.custom_prompt_internals import ()from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSessionfrom products.tasks.backend.logic.services.dev_sandbox_context import resolve_sandbox_context_for_local_dev-from products.tasks.backend.logic.services.local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache+from products.tasks.backend.logic.services.local_skills import (+ ENV_DISABLE_BUNDLED_SKILLS,+ ENV_LOCAL_SKILLS_HOST_PATH,+ LocalSkillsCache,+)__all__ = [+ "ENV_DISABLE_BUNDLED_SKILLS","ENV_LOCAL_SKILLS_HOST_PATH","CustomPromptSandboxContext","EmptyAgentTurnError",diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 598ae9db63bd..a9921d1ed37c 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -43,7 +43,7 @@ from .agentsh import (generate_env_wrapper,generate_policy_yaml,)-from .local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache+from .local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache, bundled_skills_disabledfrom .sandbox import (WORKING_DIR,AgentServerResult,@@ -439,7 +439,11 @@ class DockerSandbox(SandboxBase):# the baked-in rendered skills in the image stay visible — only# the specific skills the user has on disk get overlaid.local_skills_host = os.environ.get(ENV_LOCAL_SKILLS_HOST_PATH)- if local_skills_host and os.path.isdir(local_skills_host):+ if (+ not bundled_skills_disabled(config.environment_variables)+ and local_skills_host+ and os.path.isdir(local_skills_host)+ ):for entry in sorted(os.listdir(local_skills_host)):if entry.startswith(".") or entry == "__pycache__":continue@@ -908,6 +912,8 @@ class DockerSandbox(SandboxBase):if self._host_port is None:raise RuntimeError("Sandbox was not created with port exposure.")+ self.clear_bundled_skills_if_disabled()+repo_path: str | None = Noneif repository:org, repo = repository.lower().split("/")diff --git a/products/tasks/backend/logic/services/local_skills.py b/products/tasks/backend/logic/services/local_skills.pyindex 3cc5d4dbd250..51f70e6f6078 100644--- a/products/tasks/backend/logic/services/local_skills.py+++ b/products/tasks/backend/logic/services/local_skills.py@@ -32,6 +32,16 @@ logger = logging.getLogger(__name__)BUILT_SKILLS_RELATIVE_PATH = Path("products/posthog_ai/dist/skills")BUILD_HASH_FILENAME = ".build-hash"ENV_LOCAL_SKILLS_HOST_PATH = "SANDBOX_LOCAL_SKILLS_HOST_PATH"+ENV_DISABLE_BUNDLED_SKILLS = "POSTHOG_CODE_DISABLE_BUNDLED_SKILLS"+BUNDLED_SKILLS_PATHS: tuple[str, ...] = (+ "/scripts/plugins/posthog/skills",+ "/root/.claude/skills",+ "/root/.agents/skills",+)+++def bundled_skills_disabled(environment_variables: dict[str, str] | None) -> bool:+ return environment_variables is not None and environment_variables.get(ENV_DISABLE_BUNDLED_SKILLS) == "1"def _copy_directory_contents(source: Path, destination: Path) -> None:diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 61f3b55f87c7..3e0aec92beda 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -1094,6 +1094,7 @@ class ModalSandbox(SandboxBase):logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")returnself._free_agent_server_port()+ self.clear_bundled_skills_if_disabled()repo_path: str | None = Noneif repository:diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 7503f439e97f..a3bb274c7453 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -28,6 +28,7 @@ import structlogfrom pydantic import BaseModel, model_validatorfrom products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_FILESYSTEM, SnapshotKind+from products.tasks.backend.logic.services.local_skills import BUNDLED_SKILLS_PATHS, bundled_skills_disabledfrom products.tasks.backend.logic.services.sandbox_config import (BURSTABLE_REQUEST_CPU_CORES,BURSTABLE_REQUEST_MEMORY_MB,@@ -243,6 +244,15 @@ class SandboxBase(ABC):timeout_seconds=45,)+ def clear_bundled_skills_if_disabled(self) -> None:+ if not bundled_skills_disabled(self.config.environment_variables):+ return++ paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)+ result = self.execute(f"rm -rf {paths} && mkdir -p {paths}", timeout_seconds=30)+ if result.exit_code != 0:+ raise RuntimeError(f"Failed to clear bundled skills in sandbox {self.id}: {result.stderr}")+def agent_server_supports_auto_publish(self) -> bool:"""Sandboxes restored from old snapshots can carry an agent-server that rejects unknownCLI options, so probe the installed binary before passing --autoPublish; unsupporteddiff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.pyindex a9c9eae4be08..1378a6da712a 100644--- a/products/tasks/backend/logic/services/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py@@ -10,6 +10,7 @@ from parameterized import parameterizedfrom products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandbox+from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS, ENV_LOCAL_SKILLS_HOST_PATHfrom products.tasks.backend.logic.services.sandbox import (ExecutionResult,SandboxConfig,@@ -440,6 +441,46 @@ class TestDockerSandboxUnit:args_str = " ".join(docker_args)assert f"-v {tmp_path}:/tmp/workspace/repos/posthog/posthog" in args_str+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")+ def test_create_skips_local_skill_mounts_when_bundled_skills_disabled(self, mock_run, tmp_path) -> None:+ mock_run.return_value = MagicMock(stdout="abc123container", returncode=0)+ skill_dir = tmp_path / "sample-skill"+ skill_dir.mkdir()+ config = SandboxConfig(+ name="test-sandbox",+ environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},+ )++ with (+ patch.dict(os.environ, {ENV_LOCAL_SKILLS_HOST_PATH: str(tmp_path)}),+ patch.object(DockerSandbox, "_get_image", return_value="posthog-sandbox-base"),+ ):+ DockerSandbox.create(config)++ docker_args = mock_run.call_args_list[-1][0][0]+ assert str(skill_dir) not in " ".join(docker_args)++ def test_start_agent_server_clears_bundled_skills_before_launch(self) -> None:+ sandbox = DockerSandbox.__new__(DockerSandbox)+ sandbox._container_id = "abc123"+ sandbox.id = "abc123"+ sandbox.config = SandboxConfig(+ name="test",+ environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},+ )+ sandbox._host_port = 12345++ with patch.object(sandbox, "is_running", return_value=True), patch.object(sandbox, "execute") as mock_execute:+ mock_execute.return_value = ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None)+ sandbox.start_agent_server("posthog/posthog", "task-123", "run-456", wait_for_health=False)++ commands = [call.args[0] for call in mock_execute.call_args_list]+ clear_index = next(+ index for index, command in enumerate(commands) if "rm -rf" in command and "skills" in command+ )+ launch_index = next(index for index, command in enumerate(commands) if "agent-server" in command)+ assert clear_index < launch_index+def test_start_agent_server_without_domains_skips_agentsh(self):sandbox = DockerSandbox.__new__(DockerSandbox)sandbox._container_id = "abc123"diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 679265c42090..cea86bc6395a 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -22,6 +22,7 @@ from products.tasks.backend.exceptions import (SnapshotTimeoutError,)from products.tasks.backend.logic.services.local_packages import LocalPackage+from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.modal_provision_diagnostics import (MAX_PROVISION_LOG_EXCERPT_LINES,summarize_modal_output,@@ -448,6 +449,29 @@ class TestModalSandboxAgentServer:assert "agentsh exec" not in commandassert "nohup" in command+ def test_start_agent_server_clears_bundled_skills_before_launch(self, mock_sandbox: Any) -> None:+ mock_sandbox.config = SandboxConfig(+ name="test-sandbox",+ environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},+ )+ mock_sandbox.execute = MagicMock(+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),+ )++ mock_sandbox.start_agent_server(+ repository="posthog/posthog",+ task_id="task-123",+ run_id="run-456",+ wait_for_health=False,+ )++ commands = [call.args[0] for call in mock_sandbox.execute.call_args_list]+ clear_index = next(+ index for index, command in enumerate(commands) if "rm -rf" in command and "skills" in command+ )+ launch_index = next(index for index, command in enumerate(commands) if "agent-server" in command)+ assert clear_index < launch_index+def test_start_agent_server_waits_for_repository_before_launch(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.pyindex d7e4d8524f14..2b510aa99846 100644--- a/products/tasks/backend/tests/test_agentsh.py+++ b/products/tasks/backend/tests/test_agentsh.py@@ -453,7 +453,7 @@ class TestModalSandboxAgentShWrapping(TestCase):def test_start_agent_server_drops_auto_publish_when_binary_lacks_support(self, provider, supported):from products.tasks.backend.logic.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.logic.services.modal_sandbox import ModalSandbox- from products.tasks.backend.logic.services.sandbox import ExecutionResult+ from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig# Snapshots restored from old images carry an agent-server that rejects unknown# options; the launch probe must drop --autoPublish instead of crashing the run.@@ -473,6 +473,7 @@ class TestModalSandboxAgentShWrapping(TestCase):sandbox = DockerSandbox.__new__(DockerSandbox)sandbox._host_port = 8080sandbox.id = "sb-test"+ sandbox.config = SandboxConfig(name="sb-test")cast_sandbox: Any = sandboxcast_sandbox.is_running = Mock(return_value=True)cast_sandbox._agent_server_is_healthy = Mock(return_value=False)diff --git a/services/mcp/README.md b/services/mcp/README.mdindex 729bee67e18b..510348a03c38 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -290,6 +290,40 @@ x-posthog-mcp-mode: toolsThe header wins when both the header and the query parameter are set.An explicit value always wins over the client auto-detection; any other value is ignored and the auto-detection takes over.+Claude web and desktop silently drop `exec` when its serialized `inputSchema` reaches 16,384 characters.+In cli mode, the `posthog` tool keeps the guidance needed for routine calls in its schema.+The compact tool-domain index stays inline in the `command` schema so Claude can discover relevant tools before making a call.+Optional, task-specific guidance is served through the same tool:++- `learn` lists the available built-in guides and, when enabled, the PostHog/project skill discovery syntax.+- `learn analytics` loads detailed analytics guidance and examples.+- `learn visualizations` loads rendering guidance when visualizations are available.+- `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 -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> --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.+When skill discovery is enabled, the inline prompt tells every non-plugin cli client, including Claude web and desktop, to search with `learn -s "<task keywords>"` before non-trivial PostHog work, load matches by exact qualified name, and follow the loaded `SKILL.md` before choosing tools. Trivial lookups and unrelated conversation skip this workflow.++The skill bundle is cached in Redis with stale-while-revalidate behavior and a seven-day hard expiry.+By default it is loaded from `https://github.com/PostHog/posthog/releases/download/agent-skills-latest/skills.zip`.+Set `POSTHOG_MCP_SKILLS_URL` to use another archive during local development.+Custom archive URLs use separate Redis cache namespaces so a local bundle cannot read or overwrite the published bundle's cache entry.+Project skills are read directly from the request-authenticated project and are not cached by the MCP server.+Only latest, active, uncategorized skills are exposed through `learn`; category-specific skills such as scouts stay on their own surfaces.+Project full-text search is bounded to 10 skills, two short snippets per skill, and a five-second database timeout.+Individual `learn` responses stay below 44,000 characters; large references return a heading outline for follow-up search or line reads.+The fixed command syntax stays in the tool schema, while skill names and bodies are loaded only when requested.+`consumer=plugin` and `consumer=posthog-code` omit `learn` because both surfaces already supply their own bundled skill context, regardless of the feature flag.++Other clients keep the full inline command reference.+### Consumer attributionWrapping apps and AI-tool plugins that install or proxy the PostHog MCP can self-identify so usage can be attributed to the install path (e.g. plugin-installed vs. manually-pasted URL). The wrapped MCP client (Claude Code, Cursor, …) is already captured separately via the MCP `clientInfo` handshake — this signal is only for the wrapping context.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 73dd4a70861c..97436e77772b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36733,6 +36733,10 @@ export namespace Schemas {path: string;/** @maxLength 100 */content_type?: string;+ /** Number of lines in the file content. */+ line_count: number;+ /** Number of characters in the file content. */+ char_count: number;}export interface LLMSkillOutlineEntry {@@ -36783,7 +36787,7 @@ export namespace Schemas {metadata?: LLMSkillMetadata;/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string;- /** Bundled files manifest. Each entry is path + content_type only; fetch content via /llm_skills/name/{name}/files/{path}/. */+ /** Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/. */readonly files: readonly LLMSkillFileManifest[];/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */readonly outline: readonly LLMSkillOutlineEntry[];@@ -37087,6 +37091,65 @@ export namespace Schemas {has_more: boolean;}+ export interface LLMSkillSearchError {+ /** Explanation of why the skill search could not complete. */+ detail: string;+ }++ /**+ * * `name` - name+ * * `description` - description+ * * `body` - body+ * * `file_path` - file_path+ * * `file_content` - file_content+ */+ export type MatchedFieldEnum = typeof MatchedFieldEnum[keyof typeof MatchedFieldEnum];+++ export const MatchedFieldEnum = {+ Name: 'name',+ Description: 'description',+ Body: 'body',+ FilePath: 'file_path',+ FileContent: 'file_content',+ } as const;++ export interface LLMSkillSearchMatch {+ /** Skill field that matched the search query.+ *+ * * `name` - name+ * * `description` - description+ * * `body` - body+ * * `file_path` - file_path+ * * `file_content` - file_content */+ matched_field: MatchedFieldEnum;+ /** Skill-relative file path for body or bundled-file matches. Omitted for name and description matches. */+ path?: string;+ /**+ * One-based line containing the match when the result came from a body or bundled file.+ * @minimum 1+ */+ line?: number;+ /** Short excerpt showing why this skill matched. */+ excerpt: string;+ }++ export interface LLMSkillSearchResult {+ /** Unique skill name. */+ name: string;+ /** What this skill does and when to use it. */+ description: string;+ /** Up to two locations that matched the search query, ordered by field relevance. */+ matches: LLMSkillSearchMatch[];+ }++ export interface LLMSkillSearchResponse {+ /** Number of matching skills returned, capped at 10. */+ count: number;+ /** Matching ordinary skills in relevance order. */+ results: LLMSkillSearchResult[];+ }+export interface LLMTaggerConfig {/*** Prompt instructing the LLM how to tag generations@@ -77744,6 +77807,15 @@ export namespace Schemas {version_id?: string;};+ export type LlmSkillsSearchRetrieveParams = {+ /**+ * Case-insensitive substring to search across ordinary skill names, descriptions, bodies, file paths, and Markdown file contents.+ * @minLength 1+ * @maxLength 200+ */+ query: string;+ };+export type LogsAlertsListParams = {/*** Only return log alerts created by the user with this UUID.diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 6eea5501a662..fd8d06a61bb0 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -10,6 +10,7 @@ import {MCP_ANALYTICS_VERSION,type MCPAnalyticsContext,} from '@/lib/posthog/analytics'+import type { SkillInvocation } from '@/tools/exec-learn'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { getToolCategory } from '@/tools/toolDefinitions'@@ -221,3 +222,35 @@ export async function trackToolsList(toolNames: string[], state: ResolvedState):// never break the request for analytics}}++/**+ * Captures `skill invoked` when a skill's content is consumed through exec `learn`,+ * whichever read kind delivered it (full load, file read, file search, line range) —+ * the consumption counterpart of the authoring `llma skill *` events emitted by+ * `products/skills`. The caller dedupes per skill identifier per request, so a+ * command that reads one skill several ways still counts once. Keep property keys+ * additive: they feed the same LLMA skills adoption dashboards.+ */+export async function trackSkillInvoked(state: ResolvedState, invocation: SkillInvocation): Promise<void> {+ try {+ const analyticsContext = await state.reqCtx.safelyGetAnalyticsContext(state.context)+ const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)+ const { properties, groups } = buildBaseProperties(state, analyticsContext)++ getPostHogClient().capture({+ distinctId: state.distinctId,+ event: 'skill invoked',+ groups,+ properties: {+ ...properties,+ ...(sessionUuid ? { $session_id: sessionUuid } : {}),+ skill_source: invocation.source,+ skill_name: invocation.skill,+ skill_identifier: `${invocation.source}:${invocation.skill}`,+ skill_read_kind: invocation.readKind,+ },+ })+ } catch {+ // never break the request for analytics+ }+}diff --git a/services/mcp/src/hono/cache/SharedBlobCache.ts b/services/mcp/src/hono/cache/SharedBlobCache.tsindex 185ea0a86634..418b643bc80e 100644--- a/services/mcp/src/hono/cache/SharedBlobCache.ts+++ b/services/mcp/src/hono/cache/SharedBlobCache.ts@@ -32,6 +32,7 @@ export class SharedBlobCache {public readonly cacheKey: stringpublic readonly freshKey: stringpublic readonly lockKey: string+ public readonly etagKey: stringprivate cacheTtlSeconds: numberprivate freshSeconds: number@@ -48,6 +49,7 @@ export class SharedBlobCache {this.cacheKey = `${prefix}:bytes`this.freshKey = `${prefix}:fresh`this.lockKey = `${prefix}:lock`+ this.etagKey = `${prefix}:etag`this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDSthis.freshSeconds = opts.freshSeconds ?? DEFAULT_FRESH_SECONDS@@ -56,8 +58,12 @@ export class SharedBlobCache {this.waitTimeoutMs = opts.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS}- protected async readCache(): Promise<{ bytes: Uint8Array; fresh: boolean } | null> {- const [raw, freshUntilStr] = await Promise.all([this.redis.get(this.cacheKey), this.redis.get(this.freshKey)])+ protected async readCache(): Promise<{ bytes: Uint8Array; fresh: boolean; etag?: string } | null> {+ const [raw, freshUntilStr, etag] = await Promise.all([+ this.redis.get(this.cacheKey),+ this.redis.get(this.freshKey),+ this.redis.get(this.etagKey),+ ])if (raw === null) {return null}@@ -65,15 +71,45 @@ export class SharedBlobCache {const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)const freshUntil = freshUntilStr !== null ? Number(freshUntilStr) : 0const fresh = Number.isFinite(freshUntil) && Date.now() < freshUntil- return { bytes, fresh }+ return { bytes, fresh, etag: etag ?? undefined }}- protected async writeCache(bytes: Uint8Array): Promise<void> {+ protected async writeCache(bytes: Uint8Array, validator?: string): Promise<void> {const b64 = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')+ const freshUntil = Date.now() + this.freshSeconds * 1000+ // Land the bytes before their validator, since the two live under separate+ // Redis keys with no cross-key transaction. If the validator write landed+ // first (or in parallel) and the bytes write then failed, Redis would keep+ // old bytes paired with the new validator — a stuck state where every later+ // conditional refresh sends the new validator, gets a 304, and touches the+ // stale bytes fresh again. Ordering it the other way makes both partial+ // failures self-heal: if the bytes write fails, the old bytes keep the old+ // validator (consistent); if only the validator write fails after new bytes+ // land, the next conditional refresh sends the old validator, gets a full+ // 200, and rewrites everything.+ await this.redis.set(this.cacheKey, b64, 'EX', this.cacheTtlSeconds)+ await Promise.all([+ this.redis.set(this.freshKey, String(freshUntil), 'EX', this.cacheTtlSeconds),+ // Keep the validator in lockstep with the bytes: store it when present,+ // clear any stale one otherwise so a later conditional request can't+ // send a validator that no longer matches the cached bytes.+ validator !== undefined+ ? this.redis.set(this.etagKey, validator, 'EX', this.cacheTtlSeconds)+ : this.redis.del(this.etagKey),+ ])+ }++ /**+ * Refresh the freshness marker and re-extend the hard TTLs without rewriting+ * the payload. Used when a conditional refresh confirms the cached bytes are+ * still current (HTTP 304), so the re-download and re-parse are skipped.+ */+ protected async touchCache(): Promise<void> {const freshUntil = Date.now() + this.freshSeconds * 1000await Promise.all([- this.redis.set(this.cacheKey, b64, 'EX', this.cacheTtlSeconds),this.redis.set(this.freshKey, String(freshUntil), 'EX', this.cacheTtlSeconds),+ this.redis.expire(this.cacheKey, this.cacheTtlSeconds),+ this.redis.expire(this.etagKey, this.cacheTtlSeconds),])}diff --git a/services/mcp/src/hono/cache/SkillArchiveCache.ts b/services/mcp/src/hono/cache/SkillArchiveCache.tsnew file mode 100644index 000000000000..01a5735ee7cb--- /dev/null+++ b/services/mcp/src/hono/cache/SkillArchiveCache.ts@@ -0,0 +1,139 @@+import { createHash, randomUUID } from 'node:crypto'++import type { RedisLike } from './RedisCache'+import { SharedBlobCache, type SharedBlobCacheOptions } from './SharedBlobCache'++export const DEFAULT_SKILL_ARCHIVE_URL =+ 'https://github.com/PostHog/posthog/releases/download/agent-skills-latest/skills.zip'++const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024+const ARCHIVE_DOWNLOAD_TIMEOUT_MS = 15_000+const NAMESPACE = 'product-skills'++export type SkillArchiveCacheResult = 'fresh_hit' | 'stale_hit' | 'cold_refresh' | 'waited' | 'fallback'++export interface SkillArchiveLoadResult {+ bytes: Uint8Array+ result: SkillArchiveCacheResult+}++/**+ * Outcome of a (possibly conditional) archive download. `not_modified` is the+ * 304 sentinel returned when we sent `If-None-Match` and the asset is unchanged.+ */+export type SkillArchiveFetchResult =+ | { status: 'downloaded'; bytes: Uint8Array; etag?: string }+ | { status: 'not_modified' }++export interface SkillArchiveCacheOptions extends SharedBlobCacheOptions {+ archiveUrl?: string+ fetchArchive?: (url: string, etag?: string) => Promise<SkillArchiveFetchResult>+}++/** Redis-backed stale-while-revalidate cache for the published skills.zip. */+export class SkillArchiveCache extends SharedBlobCache {+ private readonly archiveUrl: string+ private readonly fetchArchive: (url: string, etag?: string) => Promise<SkillArchiveFetchResult>++ constructor(redis: RedisLike, opts: SkillArchiveCacheOptions = {}) {+ const archiveUrl = opts.archiveUrl ?? DEFAULT_SKILL_ARCHIVE_URL+ const namespace =+ archiveUrl === DEFAULT_SKILL_ARCHIVE_URL+ ? NAMESPACE+ : `${NAMESPACE}:${createHash('sha256').update(archiveUrl).digest('hex').slice(0, 16)}`+ super(redis, namespace, opts)+ this.archiveUrl = archiveUrl+ this.fetchArchive = opts.fetchArchive ?? downloadArchive+ }++ async loadOrRefresh(): Promise<SkillArchiveLoadResult> {+ const cached = await this.readCache()+ if (cached?.fresh) {+ return { bytes: cached.bytes, result: 'fresh_hit' }+ }+ if (cached) {+ void this.refreshInBackground(cached.etag)+ return { bytes: cached.bytes, result: 'stale_hit' }+ }++ const token = randomUUID()+ if (await this.acquireLock(token)) {+ try {+ const { bytes, etag } = await this.downloadFull()+ await this.writeCache(bytes, etag)+ return { bytes, result: 'cold_refresh' }+ } finally {+ await this.releaseLock(token)+ }+ }++ const waited = await this.waitForCache()+ if (waited) {+ return { bytes: waited, result: 'waited' }+ }+ return { bytes: (await this.downloadFull()).bytes, result: 'fallback' }+ }++ private async refreshInBackground(etag?: string): Promise<void> {+ const token = randomUUID()+ if (!(await this.acquireLock(token))) {+ return+ }+ try {+ const result = await this.fetchArchiveChecked(etag)+ if (result.status === 'not_modified') {+ // Archive unchanged since we cached it: bump freshness and re-extend+ // the hard TTLs in place, skipping the re-download and re-parse.+ await this.touchCache()+ } else {+ await this.writeCache(result.bytes, result.etag)+ }+ } catch (error) {+ console.error('[SkillArchiveCache] background refresh failed:', error)+ } finally {+ await this.releaseLock(token)+ }+ }++ /** Fetch a full archive body. Callers without cached bytes never revalidate. */+ private async downloadFull(): Promise<{ bytes: Uint8Array; etag?: string }> {+ const result = await this.fetchArchiveChecked()+ if (result.status === 'not_modified') {+ // Only reachable if the server 304s without an If-None-Match request.+ throw new Error('Skill archive server returned 304 Not Modified without a conditional request')+ }+ return { bytes: result.bytes, etag: result.etag }+ }++ private async fetchArchiveChecked(etag?: string): Promise<SkillArchiveFetchResult> {+ const result = await this.fetchArchive(this.archiveUrl, etag)+ if (result.status === 'downloaded' && (result.bytes.length === 0 || result.bytes.length > MAX_ARCHIVE_BYTES)) {+ throw new Error(`Invalid skill archive size: ${result.bytes.length} bytes`)+ }+ return result+ }+}++async function downloadArchive(url: string, etag?: string): Promise<SkillArchiveFetchResult> {+ const headers: Record<string, string> = {}+ if (etag) {+ headers['If-None-Match'] = etag+ }+ const response = await fetch(url, { headers, signal: AbortSignal.timeout(ARCHIVE_DOWNLOAD_TIMEOUT_MS) })+ if (response.status === 304) {+ return { status: 'not_modified' }+ }+ if (!response.ok) {+ throw new Error(`Failed to download skill archive: HTTP ${response.status}`)+ }+ const contentLength = Number(response.headers.get('content-length'))+ if (Number.isFinite(contentLength) && contentLength > MAX_ARCHIVE_BYTES) {+ throw new Error(`Skill archive is too large: ${contentLength} bytes`)+ }+ const bytes = new Uint8Array(await response.arrayBuffer())+ // `response.headers` is the final response after redirects (GitHub release+ // assets 302 to objects.githubusercontent.com), so this is the asset's own+ // validator. Absent → we store no etag and behave exactly as before.+ const validator = response.headers.get('etag') ?? undefined+ return { status: 'downloaded', bytes, etag: validator }+}diff --git a/services/mcp/src/hono/constants.ts b/services/mcp/src/hono/constants.tsindex 6fcb0ed71080..9e746277d92c 100644--- a/services/mcp/src/hono/constants.ts+++ b/services/mcp/src/hono/constants.ts@@ -1,5 +1,7 @@import type { Env } from '@/tools/types'+export const MCP_EXEC_SKILLS_FEATURE_FLAG = 'mcp-exec-skills'+export {USER_AGENT,type GetUserAgentOptions,@@ -28,6 +30,7 @@ export function getEnv(): Env {POSTHOG_UI_APPS_TOKEN: process.env.POSTHOG_UI_APPS_TOKEN || undefined,POSTHOG_ANALYTICS_API_KEY: process.env.POSTHOG_ANALYTICS_API_KEY || undefined,POSTHOG_ANALYTICS_HOST: process.env.POSTHOG_ANALYTICS_HOST || undefined,+ POSTHOG_MCP_SKILLS_URL: process.env.POSTHOG_MCP_SKILLS_URL || undefined,...extras,}}diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.tsindex 065fafb05064..788dadd25307 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -41,6 +41,7 @@ import { InstructionsBuilder } from './instructions'import { initDurationSeconds, initTotal } from './metrics'import { RequestStateResolver, type ResolvedState } from './request-state-resolver'import { ResourceCatalog } from './resource-catalog'+import { SkillCatalogService } from './skill-catalog-service'import { ToolCatalog } from './tool-catalog'import { ToolExecutor } from './tool-executor'@@ -134,6 +135,7 @@ class McpDispatcher {private readonly stateResolver: RequestStateResolverprivate readonly toolExecutor: ToolExecutorprivate readonly instructionsBuilder: InstructionsBuilder+ private readonly skillCatalogService: SkillCatalogServiceprivate warmupPromise: Promise<void> | undefined@@ -143,7 +145,8 @@ class McpDispatcher {this.resourceCatalog = new ResourceCatalog(env, redis)this.stateResolver = new RequestStateResolver(catalog, redis, env)this.instructionsBuilder = new InstructionsBuilder(GUIDELINES)- this.toolExecutor = new ToolExecutor(catalog, this.instructionsBuilder)+ this.skillCatalogService = new SkillCatalogService(redis, { archiveUrl: env.POSTHOG_MCP_SKILLS_URL })+ this.toolExecutor = new ToolExecutor(catalog, this.instructionsBuilder, this.skillCatalogService)}async warmup(): Promise<void> {@@ -153,7 +156,7 @@ class McpDispatcher {private async doWarmup(): Promise<void> {await this.catalog.warmup()- await this.resourceCatalog.warmup()+ await Promise.all([this.resourceCatalog.warmup(), this.skillCatalogService.warmup()])}async handleRequest(req: Request, props: RequestProperties): Promise<Response> {@@ -392,6 +395,7 @@ class McpDispatcher {): Promise<string | undefined> {try {await this.resourceCatalog.revalidateContextMillResources(source)+ await this.skillCatalogService.revalidate()const instructions = this.instructionsBuilder.build(state)initDurationSeconds.observe(props.requestStartTime ? (Date.now() - props.requestStartTime) / 1000 : 0)diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex dbe173f8bb46..b9bbd2d1184e 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -1,17 +1,21 @@import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'+import { hasScope } from '@/lib/api'+import { isPostHogCodeConsumer } from '@/lib/client-detection'import { PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'import type { QueryToolInfo } from '@/lib/instructions'import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'import type { EvaluatedFlags } from '@/lib/posthog/flags'import { formatPrompt } from '@/lib/utils'import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'+import { ProjectSkillCatalog } from '@/skills/project-skill-catalog'+import type { SkillCatalog } from '@/skills/skill-catalog'import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'import CATALOG_TRUST_DISCOVERY from '@/templates/sections/catalog-trust-discovery.md'import METRIC_DISCOVERY from '@/templates/sections/metric-discovery.md'import SCHEMA_DISCOVERY from '@/templates/sections/schema-discovery.md'-import { ExecHelpCatalog } from '@/tools/exec-help'+import { ExecLearnCatalog } from '@/tools/exec-learn'import {getRenderableToolNames,makeRenderUiSchema,@@ -21,6 +25,9 @@ import {} from '@/tools/render-ui'import { getToolDefinition } from '@/tools/toolDefinitions'+import { trackSkillInvoked } from './analytics'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'+import { getEffectiveMCPClientContext } from './mcp-context'import type { ResolvedState } from './request-state-resolver'import { toMcpInputSchema } from './tool-catalog'@@ -114,24 +121,60 @@ export class InstructionsBuilder {// `supportsInstructions: false`, already gets the full env-context via the// un-stripped path.)const keepEnvContext = state.clientProfile.isClaudeChatHost()+ const { guidesEnabled, skillsEnabled } = this.getExecLearnCapabilities(state)const ctx = this.buildContext(state)if (keepEnvContext) {- return this.formatter.buildClaudeExecCommandReference(ctx)+ return this.formatter.buildClaudeExecCommandReference(ctx, {+ learnEnabled: guidesEnabled || skillsEnabled,+ skillsEnabled,+ })}return this.formatter.buildExecCommandReference(ctx, {stripEnvContext: supportsInstructions,+ learnEnabled: skillsEnabled,})}- buildExecHelpCatalog(state: ResolvedState): ExecHelpCatalog | undefined {- if (!state.clientProfile.isClaudeChatHost()) {+ buildExecLearnCatalog(state: ResolvedState, skills: SkillCatalog | undefined): ExecLearnCatalog | undefined {+ const { guidesEnabled, skillsEnabled } = this.getExecLearnCapabilities(state)+ if (!guidesEnabled && !skillsEnabled) {return undefined}- return new ExecHelpCatalog(this.formatter.buildClaudeExecHelpEntries(this.buildContext(state)))+ const guides = guidesEnabled ? this.formatter.buildClaudeExecLearnGuides(this.buildContext(state)) : []+ const canReadProjectSkills = skillsEnabled && hasScope(state.apiKeyScopes, 'llm_skill:read')+ // The catalog (and this closure) is rebuilt per request, so this Set dedupes+ // within one exec command — a 5-file batch of one skill fires a single event,+ // while separate commands each still count.+ const invokedIdentifiers = new Set<string>()+ return new ExecLearnCatalog(+ guides,+ skillsEnabled+ ? {+ posthog: skills,+ project: canReadProjectSkills ? new ProjectSkillCatalog(state.context) : undefined,+ projectUnavailableReason: canReadProjectSkills+ ? undefined+ : 'This connection is missing the llm_skill:read scope. Reconnect with that scope to read project skills.',+ }+ : undefined,+ (invocation) => {+ const identifier = `${invocation.source}:${invocation.skill}`+ if (invokedIdentifiers.has(identifier)) {+ return+ }+ invokedIdentifiers.add(identifier)+ void trackSkillInvoked(state, invocation)+ }+ )}- buildExecToolDescription(): string {- return this.formatter.buildExecToolDescription()+ buildExecToolDescription(state?: ResolvedState): string {+ const skillsEnabled = state ? this.getExecLearnCapabilities(state).skillsEnabled : false+ return this.formatter.buildExecToolDescription({ skillsEnabled })+ }++ execSkillsEnabled(state: ResolvedState): boolean {+ return this.getExecLearnCapabilities(state).skillsEnabled}getGuidelines(): string {@@ -150,4 +193,17 @@ export class InstructionsBuilder {schema_discovery: schemaDiscovery,})}++ private getExecLearnCapabilities(state: ResolvedState): { guidesEnabled: boolean; skillsEnabled: boolean } {+ const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)+ // The plugin and PostHog Code sandboxes bundle their own skill context, so+ // learn stays off for them regardless of the feature flag.+ if (clientContext.mcpConsumer === 'plugin' || isPostHogCodeConsumer(clientContext.mcpConsumer)) {+ return { guidesEnabled: false, skillsEnabled: false }+ }+ return {+ guidesEnabled: state.clientProfile.isClaudeChatHost(),+ skillsEnabled: state.toolFeatureFlags?.[MCP_EXEC_SKILLS_FEATURE_FLAG] === true,+ }+ }}diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex ac53b607a58b..7948f91a8920 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -16,6 +16,7 @@ import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } fromimport type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'import type { RedisLike } from './cache/RedisCache'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'import {buildMCPRequestContext,getEffectiveMCPClientContext,@@ -131,7 +132,9 @@ export class RequestStateResolver {// PRODUCT_DATA_CATALOG_FLAG gates instructions content (the metric-discovery prompt// section), not a tool, so the tool-definition scan can't discover it.- const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), PRODUCT_DATA_CATALOG_FLAG])]+ const allFlagKeys = [+ ...new Set([...getRequiredFeatureFlags(), PRODUCT_DATA_CATALOG_FLAG, MCP_EXEC_SKILLS_FEATURE_FLAG]),+ ]const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefineddiff --git a/services/mcp/src/hono/skill-catalog-service.ts b/services/mcp/src/hono/skill-catalog-service.tsnew file mode 100644index 000000000000..697ecefcde7c--- /dev/null+++ b/services/mcp/src/hono/skill-catalog-service.ts@@ -0,0 +1,44 @@+import { createHash } from 'node:crypto'++import { SkillCatalog } from '@/skills/skill-catalog'++import type { RedisLike } from './cache/RedisCache'+import { SkillArchiveCache, type SkillArchiveCacheOptions } from './cache/SkillArchiveCache'++/** Keeps the last valid parsed catalog available when refreshes fail. */+export class SkillCatalogService {+ private readonly archiveCache: SkillArchiveCache+ private catalog: SkillCatalog | undefined+ private archiveHash: string | undefined++ constructor(redis: RedisLike, opts: SkillArchiveCacheOptions = {}) {+ this.archiveCache = new SkillArchiveCache(redis, opts)+ }++ getCatalog(): SkillCatalog | undefined {+ return this.catalog+ }++ async warmup(): Promise<void> {+ await this.loadSafely('warmup')+ }++ async revalidate(): Promise<void> {+ await this.loadSafely('revalidation')+ }++ private async loadSafely(operation: string): Promise<void> {+ try {+ const { bytes } = await this.archiveCache.loadOrRefresh()+ const hash = createHash('sha256').update(bytes).digest('hex')+ if (hash === this.archiveHash) {+ return+ }+ const catalog = SkillCatalog.fromZip(bytes)+ this.catalog = catalog+ this.archiveHash = hash+ } catch (error) {+ console.error(`[SkillCatalogService] ${operation} failed; continuing without refreshed skills:`, error)+ }+ }+}diff --git a/services/mcp/src/hono/skills-session.ts b/services/mcp/src/hono/skills-session.tsnew file mode 100644index 000000000000..abe13d04b882--- /dev/null+++ b/services/mcp/src/hono/skills-session.ts@@ -0,0 +1,31 @@+import type { RequestContext } from '@/hono/request-context'+import type { SkillsSessionState } from '@/tools/exec'++/**+ * Session-scoped skill-usage markers for the exec skills-first gate, backed by+ * the same Redis session cache that stores MCP client context. Requires an MCP+ * session id — stateless clients get no gate rather than a per-request one.+ */+export function buildSkillsSessionState(+ reqCtx: RequestContext,+ mcpSessionId: string | undefined+): SkillsSessionState | undefined {+ if (!mcpSessionId) {+ return undefined+ }+ const cache = reqCtx.sessionCache+ return {+ async hasLearned(): Promise<boolean> {+ return (await cache.get('skillsLearnedAt')) !== undefined+ },+ async markLearned(): Promise<void> {+ await cache.set('skillsLearnedAt', Date.now())+ },+ async hasAcknowledgedNoSkills(): Promise<boolean> {+ return (await cache.get('skillsNoSkillsAckAt')) !== undefined+ },+ async markAcknowledgedNoSkills(): Promise<void> {+ await cache.set('skillsNoSkillsAckAt', Date.now())+ },+ }+}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex aa26e3f667cd..7cdd2598b5d0 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -28,6 +28,8 @@ import type { InstructionsBuilder } from './instructions'import { getEffectiveMCPClientContext } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'import type { ResolvedState } from './request-state-resolver'+import type { SkillCatalogService } from './skill-catalog-service'+import { buildSkillsSessionState } from './skills-session'import type { ToolCatalog } from './tool-catalog'interface ResolvedTool {@@ -44,10 +46,16 @@ interface ExecMetricState {export class ToolExecutor {private readonly catalog: ToolCatalogprivate readonly instructionsBuilder: InstructionsBuilder+ private readonly skillCatalogService: SkillCatalogService | undefined- constructor(catalog: ToolCatalog, instructionsBuilder: InstructionsBuilder) {+ constructor(+ catalog: ToolCatalog,+ instructionsBuilder: InstructionsBuilder,+ skillCatalogService?: SkillCatalogService+ ) {this.catalog = catalogthis.instructionsBuilder = instructionsBuilder+ this.skillCatalogService = skillCatalogService}async handleToolsList(state: ResolvedState): Promise<ListToolsResult> {@@ -406,14 +414,20 @@ export class ToolExecutor {const execTool = createExecTool(execTools,state.context,- this.instructionsBuilder.buildExecToolDescription(),+ this.instructionsBuilder.buildExecToolDescription(state),commandReference,clientContext.mcpConsumer,trackInnerCall,state.scopeGatedTools,{isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),- helpCatalog: this.instructionsBuilder.buildExecHelpCatalog(state),+ learnCatalog: this.instructionsBuilder.buildExecLearnCatalog(+ state,+ this.skillCatalogService?.getCatalog()+ ),+ skillsSession: this.instructionsBuilder.execSkillsEnabled(state)+ ? buildSkillsSessionState(state.reqCtx, state.requestContext.mcpSessionId)+ : undefined,})diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 2fcb8e1f9769..f77bd3b62f5a 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -15,6 +15,8 @@ import CLI_DATA_DISCOVERY from '@/templates/sections/cli-data-discovery.md'import CLI_ERROR_HANDLING from '@/templates/sections/cli-error-handling.md'import CLI_EXAMPLES_CLAUDE from '@/templates/sections/cli-examples-claude.md'import CLI_EXAMPLES from '@/templates/sections/cli-examples.md'+import CLI_LEARN_COMPACT from '@/templates/sections/cli-learn-compact.md'+import CLI_LEARN from '@/templates/sections/cli-learn.md'import CLI_RENDERING from '@/templates/sections/cli-rendering.md'import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'@@ -28,9 +30,10 @@ import METRIC_DISCOVERY_COMPACT from '@/templates/sections/metric-discovery-compimport METRIC_DISCOVERY from '@/templates/sections/metric-discovery.md'import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'+import SKILLS_FIRST from '@/templates/sections/skills-first.md'import TOOL_SEARCH from '@/templates/sections/tool-search.md'import URL_PATTERNS from '@/templates/sections/url-patterns.md'-import type { ExecHelpEntry } from '@/tools/exec-help'+import type { ExecLearnGuide } from '@/tools/exec-learn'export interface InstructionsContext {guidelines: string@@ -77,14 +80,24 @@ export class InstructionsFormatter {/** Build the compact `instructions` payload for single-exec clients (~2KB budget).* The bulk of the system prompt lives on the exec tool's `command` parameter- * description (`buildExecCommandReference`) — this is just env + tool index. */+ * description (`buildExecCommandReference`) — this is just env + tool index.+ * The skills-first mandate stays out of here to protect the budget; it lives+ * on the exec tool description and command reference instead. */buildExecInstructions(ctx: InstructionsContext): string {return this.compose([COMPACT_INSTRUCTIONS], ctx, { compact: true })}- /** Build the top-level description of the `posthog:exec` tool. */- buildExecToolDescription(): string {- return EXEC_TOOL_BLURB.trim()+ /** Build the top-level description of the `posthog:exec` tool. Lives in the+ * uncapped top-level `description`, so the skills text costs no schema budget.+ * The skills mandate LEADS the description: it is the only signal that reaches+ * an agent before its first tool call, and agents that answer PostHog-behavior+ * questions by cloning the public repo never make a call for the gate to catch. */+ buildExecToolDescription(opts: { skillsEnabled?: boolean } = {}): string {+ const blurb = EXEC_TOOL_BLURB.trim()+ if (!opts.skillsEnabled) {+ return blurb+ }+ return `${SKILLS_FIRST.trim()}\n\n${blurb}`}/**@@ -92,11 +105,10 @@ export class InstructionsFormatter {* existing prompt sections remain the source of truth; only their delivery* moves from the advertised schema to `exec learn`.*/- buildClaudeExecHelpEntries(ctx: InstructionsContext): ExecHelpEntry[] {- const entries: ExecHelpEntry[] = [+ buildClaudeExecLearnGuides(ctx: InstructionsContext): ExecLearnGuide[] {+ const entries: ExecLearnGuide[] = [{id: 'analytics',- kind: 'guide',title: 'Analytics',description: ctx.dataCatalogEnabled? 'Query or analyze PostHog data; governed metrics, certified tables, and verified joins live in the catalog.'@@ -118,16 +130,21 @@ export class InstructionsFormatter {if (ctx.renderUiEnabled) {entries.push({id: 'visualizations',- kind: 'guide',title: 'Visualizations',description: 'Create or render a visualization.',content: this.compose([CLI_RENDERING], ctx, { compact: false }),})}+ entries.push({+ id: 'urls',+ title: 'URL patterns',+ description: 'Load before writing any PostHog app link or URL.',+ content: this.compose([URL_PATTERNS], ctx, { compact: false }),+ })+entries.push({id: 'feedback',- kind: 'guide',title: 'Feedback',description: 'Send feedback about PostHog.',content: this.compose([AGENT_FEEDBACK], ctx, { compact: false }),@@ -143,10 +160,19 @@ export class InstructionsFormatter {* guidance inline and move only task-specific sections behind `learn <topic...>`.* Enforced by the budget test in `instructions-formatter-snapshot.test.ts`.*/- buildClaudeExecCommandReference(ctx: InstructionsContext): string {- const helpEntries = this.buildClaudeExecHelpEntries(ctx)- const helpTopics = helpEntries.map((entry) => `- ${entry.id}: ${entry.description}`).join('\n')- const helpSection = formatPrompt(EXEC_LEARN, { help_topics: helpTopics })+ buildClaudeExecCommandReference(+ ctx: InstructionsContext,+ opts: { learnEnabled?: boolean; skillsEnabled?: boolean } = {}+ ): string {+ const learnEnabled = opts.learnEnabled ?? true+ const skillsEnabled = opts.skillsEnabled ?? true+ const learnGuides = this.buildClaudeExecLearnGuides(ctx)+ const learnGuideList = learnGuides.map((entry) => `- ${entry.id}: ${entry.description}`).join('\n')+ const learnSection = learnEnabled+ ? formatPrompt(EXEC_LEARN, {+ help_topics: learnGuideList,+ })+ : undefinedconst renderCtx: InstructionsContext = {guidelines: ctx.guidelines,metadata: ctx.metadata,@@ -157,7 +183,11 @@ export class InstructionsFormatter {return this.compose([CLI_SYNTAX,- helpSection,+ // Compact skills-first variant: this reference lives inside the+ // schema-capped `command` description (see the budget test), so the+ // content-routing paragraph is reserved for the uncapped full reference.+ ...(skillsEnabled ? [CLI_LEARN_COMPACT] : []),+ ...(learnSection ? [learnSection] : []),...(ctx.dataCatalogEnabled ? [METRIC_DISCOVERY_COMPACT] : []),CLI_SCHEMA_DRILLDOWN,CLI_DATA_DISCOVERY,@@ -166,13 +196,15 @@ export class InstructionsFormatter {BASIC_FUNCTIONALITY,TOOL_SEARCH,ENV_CONTEXT,- URL_PATTERNS,+ // URL patterns live behind `learn urls` to protect the schema budget;+ // with learn unavailable there is no topic to load, so stay inline.+ ...(learnSection ? [] : [URL_PATTERNS]),],renderCtx,{compact: false,compactToolDomains: true,- extraCommands: 'learn <topic...> - load one or more learning topics\n',+ extraCommands: learnEnabled ? 'learn <topic...> - load one or more learning topics\n' : undefined,})}@@ -194,10 +226,11 @@ export class InstructionsFormatter {* its complete JSON schema has a smaller client-enforced size budget. */buildExecCommandReference(ctx: InstructionsContext,- opts: { stripEnvContext: boolean; keepEnvContext?: boolean }+ opts: { stripEnvContext: boolean; keepEnvContext?: boolean; learnEnabled?: boolean }): string {const sections = [CLI_SYNTAX,+ ...((opts.learnEnabled ?? true) ? [CLI_LEARN] : []),...(ctx.dataCatalogEnabled ? [METRIC_DISCOVERY] : []),CLI_SCHEMA_DRILLDOWN,CLI_DATA_DISCOVERY,diff --git a/services/mcp/src/skills/project-skill-catalog.ts b/services/mcp/src/skills/project-skill-catalog.tsnew file mode 100644index 000000000000..7151b96d06b2--- /dev/null+++ b/services/mcp/src/skills/project-skill-catalog.ts@@ -0,0 +1,311 @@+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'+import type { Context } from '@/tools/types'++const PROJECT_SKILL_LIST_PAGE_SIZE = 100+const PROJECT_SKILL_LIST_LIMIT = 200+// Zero-hit fallback fan-out: at most this many single-token backend searches, longest tokens first.+const MAX_FALLBACK_SEARCH_TOKENS = 3++export interface ProjectSkillList {+ count: number+ names: string[]+ truncated: boolean+}++interface ProjectSkillListing {+ count: number+ skills: Array<{ name: string; description: string }>+ truncated: boolean+}++/**+ * Request-scoped access to the current project's Skills store.+ *+ * The instance lives for a single MCP request, so every fetch is memoized with no+ * invalidation: repeated reads and concurrent batch calls within one request dedupe to a+ * single API round-trip. Promises (not resolved values) are cached so in-flight concurrent+ * calls share one request; a rejected promise is evicted so a transient error doesn't poison+ * the rest of the request.+ */+export class ProjectSkillCatalog {+ private readonly skillMemo = new Map<string, Promise<Schemas.LLMSkill>>()+ private readonly fileMemo = new Map<string, Promise<SkillFile>>()+ private listMemo?: Promise<ProjectSkillListing>++ constructor(private readonly context: Context) {}++ async listNames(): Promise<ProjectSkillList> {+ const { count, skills, truncated } = await this.list()+ return { count, names: skills.map((skill) => skill.name), truncated }+ }++ /**+ * name → description for the requested skills. Seeds from the memoized listing; for names the+ * listing missed only because it was capped (`truncated`), resolves each via the uncapped+ * exact-name endpoint so a real skill past the cap isn't misreported as unknown. When the+ * listing is complete, a miss is authoritative and no extra fetch is made. Fan-out is bounded+ * by the caller (at most `MAX_DESCRIBE_SKILLS` names).+ */+ async describe(names: string[]): Promise<Map<string, string>> {+ const listing = await this.list()+ const descriptions = new Map(listing.skills.map((skill) => [skill.name, skill.description]))+ if (!listing.truncated) {+ return descriptions+ }+ const missing = [...new Set(names)].filter((name) => !descriptions.has(name))+ if (missing.length === 0) {+ return descriptions+ }+ const fetched = await Promise.allSettled(missing.map((name) => this.getSkill(name)))+ missing.forEach((name, index) => {+ const outcome = fetched[index]!+ if (outcome.status === 'fulfilled') {+ descriptions.set(name, outcome.value.description)+ }+ // Rejected: a 404 is an authoritative "no such skill"; any other transient error also+ // degrades to the same `[unknown skill]` rendering. Both omit — the exact-name read+ // path still resolves a real skill, so a described-as-unknown result stays recoverable.+ })+ return descriptions+ }++ 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)+ )+ }++ /** 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,+ matches: readonly Schemas.LLMSkillSearchMatch[]+ ): LearnSearchResult {+ return {+ identifier: `project:${name}`,+ description,+ snippets: dedupeSnippets(+ matches.map((match) => ({+ path: match.path ?? match.matched_field,+ line: match.line ?? 1,+ 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)+ ),+ }+ }++ private async search(query: string): Promise<Schemas.LLMSkillSearchResponse> {+ const projectId = await this.context.stateManager.getProjectId()+ return await this.context.api.request<Schemas.LLMSkillSearchResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/search/`,+ query: { query },+ })+ }++ async read(name: string, path?: string): Promise<string> {+ const identifier = `project:${name}`+ if (path) {+ const file = await this.getFile(name, path)+ return formatLearnFile(identifier, file)+ }++ const skill = await this.getSkill(name)+ const skillFile = makeSkillFile('SKILL.md', skill.body, 'text/markdown')+ return formatLearnDocument(identifier, skill.description, skillFile, [+ skillFile,+ ...skill.files.map((file) => ({+ path: file.path,+ lineCount: file.line_count,+ charCount: file.char_count,+ })),+ ])+ }++ async searchFile(name: string, path: string, query: string): Promise<string> {+ return searchLearnFile(`project:${name}`, await this.getFile(name, path), query)+ }++ async readLines(name: string, path: string, start: number, end: number): Promise<string> {+ return readLearnLines(`project:${name}`, await this.getFile(name, path), start, end)+ }++ private getSkill(name: string): Promise<Schemas.LLMSkill> {+ return this.memoize(this.skillMemo, name, async () => {+ const projectId = await this.context.stateManager.getProjectId()+ return await this.context.api.request<Schemas.LLMSkill>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/name/${encodeURIComponent(name)}/`,+ })+ })+ }++ private getFile(name: string, path: string): Promise<SkillFile> {+ // Name can't contain a space (validated lowercase-alphanumeric-hyphen), so it's a safe separator from the free-form path.+ return this.memoize(this.fileMemo, `${name} ${path}`, async () => {+ if (path === 'SKILL.md') {+ const skill = await this.getSkill(name)+ return makeSkillFile('SKILL.md', skill.body, 'text/markdown')+ }+ const projectId = await this.context.stateManager.getProjectId()+ const file = await this.context.api.request<Schemas.LLMSkillFile>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/name/${encodeURIComponent(name)}/files/${encodeURIComponent(path)}/`,+ })+ return makeSkillFile(file.path, file.content, file.content_type)+ })+ }++ /** Shared pagination for `listNames`/`descriptions` — memoized so a request never pages the list endpoint twice. */+ private list(): Promise<ProjectSkillListing> {+ if (!this.listMemo) {+ this.listMemo = this.fetchList().catch((error) => {+ this.listMemo = undefined+ throw error+ })+ }+ return this.listMemo+ }++ private async fetchList(): Promise<ProjectSkillListing> {+ const projectId = await this.context.stateManager.getProjectId()+ const skills: Array<{ name: string; description: string }> = []+ let count = 0++ while (skills.length < PROJECT_SKILL_LIST_LIMIT) {+ const response = await this.context.api.request<Schemas.PaginatedLLMSkillListList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/`,+ query: {+ category: '',+ limit: Math.min(PROJECT_SKILL_LIST_PAGE_SIZE, PROJECT_SKILL_LIST_LIMIT - skills.length),+ offset: skills.length,+ order_by: 'name',+ },+ })+ count = response.count+ skills.push(...response.results.map((skill) => ({ name: skill.name, description: skill.description })))+ if (response.results.length === 0 || skills.length >= response.count) {+ break+ }+ }++ return { count, skills, truncated: skills.length < count }+ }++ private memoize<T>(cache: Map<string, Promise<T>>, key: string, factory: () => Promise<T>): Promise<T> {+ const existing = cache.get(key)+ if (existing) {+ return existing+ }+ const promise = factory().catch((error) => {+ // Evict on rejection so a transient API error doesn't poison later reads in the same request.+ cache.delete(key)+ throw error+ })+ cache.set(key, promise)+ return promise+ }+}++/**+ * 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[] = []+ for (const snippet of snippets) {+ const key = `${snippet.path}:${snippet.line}`+ if (!seen.has(key)) {+ seen.add(key)+ unique.push(snippet)+ }+ }+ return unique+}diff --git a/services/mcp/src/skills/skill-catalog.ts b/services/mcp/src/skills/skill-catalog.tsnew file mode 100644index 000000000000..c3408e3b2131--- /dev/null+++ b/services/mcp/src/skills/skill-catalog.ts@@ -0,0 +1,572 @@+import { strFromU8, unzipSync } from 'fflate'+import { parse as parseYaml } from 'yaml'++export const LEARN_OUTPUT_CHAR_LIMIT = 44_000++// Also the cap applied after merging PostHog and project results in `learn -s`.+export const MAX_GLOBAL_SKILLS = 10+const MAX_GLOBAL_SNIPPETS = 2+const MAX_SCOPED_MATCHES = 50+const SEARCH_CONTEXT_LINES = 2+const MAX_ARCHIVE_FILES = 5_000+const MAX_ARCHIVE_FILE_BYTES = 8 * 1024 * 1024+const MAX_ARCHIVE_UNCOMPRESSED_BYTES = 64 * 1024 * 1024++type SkillFileKind = 'markdown' | 'script' | 'other'++export interface SkillFile {+ path: string+ content: string+ lineCount: number+ charCount: number+ kind: SkillFileKind+}++export interface SkillDefinition {+ name: string+ description: string+ files: readonly SkillFile[]+}++export interface SkillManifestEntry {+ path: string+ lineCount?: number+ charCount?: number+}++export interface LearnSearchSnippet {+ path: string+ line: number+ text: string+}++export interface LearnSearchResult {+ identifier: string+ description: string+ snippets: LearnSearchSnippet[]+ // Populated by `SkillCatalog.searchResults`; optional so client-scored project+ // results (which merge in via a separate path) can omit it until they are scored.+ score?: number+}++interface RankedSkill {+ skill: SkillDefinition+ score: number+ snippets: LearnSearchSnippet[]+}++/**+ * Runtime view of the published product skill bundle. The bundle is parsed+ * once per refresh; all learn operations use this in-memory representation.+ */+export class SkillCatalog {+ private readonly skillsByName: Map<string, SkillDefinition>++ constructor(skills: readonly SkillDefinition[]) {+ this.skillsByName = new Map()+ for (const skill of skills) {+ if (this.skillsByName.has(skill.name)) {+ throw new Error(`Duplicate skill name: "${skill.name}"`)+ }+ this.skillsByName.set(skill.name, skill)+ }+ }++ static fromZip(bytes: Uint8Array): SkillCatalog {+ let fileCount = 0+ let totalUncompressedBytes = 0+ const archive = unzipSync(bytes, {+ filter: (file) => {+ if (file.name.endsWith('/')) {+ return false+ }+ validateArchivePath(file.name)+ fileCount += 1+ totalUncompressedBytes += file.originalSize+ if (+ fileCount > MAX_ARCHIVE_FILES ||+ file.originalSize > MAX_ARCHIVE_FILE_BYTES ||+ totalUncompressedBytes > MAX_ARCHIVE_UNCOMPRESSED_BYTES+ ) {+ throw new Error('Skill archive exceeds the extraction limit')+ }+ return true+ },+ })+ const filesByDirectory = new Map<string, SkillFile[]>()++ for (const [archivePath, fileBytes] of Object.entries(archive)) {+ if (archivePath.endsWith('/')) {+ continue+ }+ const pathParts = validateArchivePath(archivePath)+ const directory = pathParts[0]!+ const relativePath = pathParts.slice(1).join('/')+ const content = normalizeText(strFromU8(fileBytes))+ if (content.includes('\0')) {+ throw new Error(`Skill archive contains a binary file: "${archivePath}"`)+ }++ const files = filesByDirectory.get(directory) ?? []+ if (files.some((file) => file.path === relativePath)) {+ throw new Error(`Duplicate skill file path: "${archivePath}"`)+ }+ files.push(makeSkillFile(relativePath, content))+ filesByDirectory.set(directory, files)+ }++ const skills = [...filesByDirectory.entries()].map(([directory, files]) => {+ const skillFile = files.find((file) => file.path === 'SKILL.md')+ if (!skillFile) {+ throw new Error(`Skill archive entry "${directory}" has no SKILL.md`)+ }+ const metadata = parseFrontmatter(skillFile.content, `${directory}/SKILL.md`)+ if (metadata.name === 'skills') {+ throw new Error('Skill name "skills" is reserved by the learn command')+ }+ return {+ name: metadata.name,+ description: metadata.description,+ files: files.sort((left, right) => compareSkillPaths(left.path, right.path)),+ }+ })++ if (skills.length === 0) {+ throw new Error('Skill archive contains no skills')+ }+ return new SkillCatalog(skills.sort((left, right) => left.name.localeCompare(right.name)))+ }++ get size(): number {+ return this.skillsByName.size+ }++ listNames(): string[] {+ return [...this.skillsByName.keys()].sort((left, right) => left.localeCompare(right))+ }++ has(name: string): boolean {+ return this.skillsByName.has(name)+ }++ describe(name: string): string | undefined {+ return this.skillsByName.get(name)?.description+ }++ searchResults(query: string, namespace = ''): LearnSearchResult[] {+ const normalizedQuery = normalizeQuery(query)+ return [...this.skillsByName.values()]+ .map((skill) => rankSkill(skill, normalizedQuery))+ .filter((result): result is RankedSkill => result !== null)+ .sort((left, right) => right.score - left.score || left.skill.name.localeCompare(right.skill.name))+ .slice(0, MAX_GLOBAL_SKILLS)+ .map(({ skill, snippets, score }) => ({+ identifier: `${namespace}${skill.name}`,+ description: skill.description,+ snippets,+ score,+ }))+ }++ search(query: string, namespace = ''): string {+ const results = this.searchResults(query, namespace)++ if (results.length === 0) {+ return `No skills matched "${query}".`+ }+ return formatLearnSearchResults(results)+ }++ read(name: string, path?: string, identifier = name): string {+ const skill = this.requireSkill(name)+ if (path) {+ const file = this.requireFile(skill, path, identifier)+ return formatLearnFile(identifier, file)+ }++ const skillFile = this.requireFile(skill, 'SKILL.md')+ return formatLearnDocument(identifier, skill.description, skillFile, skill.files)+ }++ searchFile(name: string, path: string, query: string, identifier = name): string {+ const skill = this.requireSkill(name)+ const file = this.requireFile(skill, path, identifier)+ return searchLearnFile(identifier, file, query)+ }++ readLines(name: string, path: string, start: number, end: number, identifier = name): string {+ const skill = this.requireSkill(name)+ const file = this.requireFile(skill, path, identifier)+ return readLearnLines(identifier, file, start, end)+ }++ private requireSkill(name: string): SkillDefinition {+ const skill = this.skillsByName.get(name)+ if (!skill) {+ throw new Error(`Unknown skill: "${name}". Use \`learn -s <query>\` to find a skill.`)+ }+ return skill+ }++ private requireFile(skill: SkillDefinition, path: string, identifier = skill.name): SkillFile {+ validateRelativePath(path)+ const file = skill.files.find((candidate) => candidate.path === path)+ if (!file) {+ throw new Error(+ `Unknown file: "${path}" in skill "${identifier}". Run \`learn ${identifier}\` for its manifest.`+ )+ }+ return file+ }+}++const FRONTMATTER_PATTERN = /^---\n([\s\S]*?)\n---(?:\n|$)/++function parseFrontmatter(content: string, source: string): { name: string; description: string } {+ const match = content.match(FRONTMATTER_PATTERN)+ if (!match?.[1]) {+ throw new Error(`Missing YAML frontmatter in "${source}"`)+ }+ const parsed: unknown = parseYaml(match[1])+ if (!isRecord(parsed) || typeof parsed.name !== 'string' || typeof parsed.description !== 'string') {+ throw new Error(`Invalid name or description in "${source}" frontmatter`)+ }+ const name = parsed.name.trim()+ const description = parsed.description.trim()+ if (!name || !description || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {+ throw new Error(`Invalid skill metadata in "${source}"`)+ }+ return { name, description }+}++function validateArchivePath(path: string): string[] {+ if (!path || path.startsWith('/') || path.includes('\\') || path.includes('\0')) {+ throw new Error(`Unsafe skill archive path: "${path}"`)+ }+ const parts = path.split('/')+ if (parts.length < 2 || parts.some((part) => !part || part === '.' || part === '..')) {+ throw new Error(`Unsafe skill archive path: "${path}"`)+ }+ return parts+}++function validateRelativePath(path: string): void {+ if (!path || path.startsWith('/') || path.includes('\\') || path.includes('\0')) {+ throw new Error(`Unsafe skill path: "${path}"`)+ }+ const parts = path.split('/')+ if (parts.some((part) => !part || part === '.' || part === '..')) {+ throw new Error(`Unsafe skill path: "${path}"`)+ }+}++export function makeSkillFile(path: string, content: string, contentType?: string): SkillFile {+ const kind: SkillFileKind =+ path.toLowerCase().endsWith('.md') || contentType?.toLowerCase().includes('markdown')+ ? 'markdown'+ : path === 'scripts' || path.startsWith('scripts/')+ ? 'script'+ : 'other'+ return {+ path,+ content,+ lineCount: splitLines(content).length,+ charCount: content.length,+ kind,+ }+}++function compareSkillPaths(left: string, right: string): number {+ if (left === 'SKILL.md') {+ return -1+ }+ if (right === 'SKILL.md') {+ return 1+ }+ return left.localeCompare(right)+}++// The read output deliberately avoids Markdown structure: the embedded skill+// content is itself Markdown, so wrapper headings would collide with its own.+function formatManifest(files: readonly SkillManifestEntry[]): string {+ const lines = files.map((file) =>+ file.lineCount === undefined || file.charCount === undefined+ ? `- ${file.path}`+ : `- ${file.path} (${file.lineCount} lines, ${file.charCount} chars)`+ )+ return `Files:\n${lines.join('\n')}`+}++function stripFrontmatter(content: string): string {+ return content.replace(FRONTMATTER_PATTERN, '').replace(/^\n+/, '')+}++export function formatLearnDocument(+ identifier: string,+ description: string,+ skillFile: SkillFile,+ manifestFiles: readonly SkillManifestEntry[]+): string {+ const manifest = formatManifest(manifestFiles)+ const full = `Skill: ${identifier}\nDescription: ${description}\n\n${manifest}\n\nSKILL.md content (frontmatter omitted):\n\n${stripFrontmatter(skillFile.content)}`+ if (full.length <= LEARN_OUTPUT_CHAR_LIMIT) {+ return full+ }+ return formatOversizedFile(identifier, skillFile, manifest)+}++export function formatLearnFile(identifier: string, file: SkillFile): string {+ const header = `File: ${identifier}/${file.path} (${file.lineCount} lines, ${file.charCount} chars)`+ const full = `${header}\n\n${file.content}`+ if (full.length <= LEARN_OUTPUT_CHAR_LIMIT) {+ return full+ }+ return formatOversizedFile(identifier, file)+}++function formatOversizedFile(identifier: string, file: SkillFile, manifest?: string): string {+ const headings = splitLines(file.content)+ .map((line, index) => ({ line, number: index + 1 }))+ .filter(({ line }) => /^#{1,6}\s+/.test(line))+ .map(({ line, number }) => `${number}: ${line}`)+ const outline = headings.length > 0 ? headings.join('\n') : '(No Markdown headings found.)'+ const scope = manifest ? `${manifest}\n\n` : ''+ return fitLearnOutput(+ `File: ${identifier}/${file.path} (${file.lineCount} lines, ${file.charCount} chars)\nThis file is too large to return in full. Use \`learn ${identifier} ${file.path} -s <query>\` or \`learn ${identifier} ${file.path} --lines <start>:<end>\`.\n\n${scope}Heading outline:\n${outline}`+ )+}++export function searchLearnFile(identifier: string, file: SkillFile, query: string): string {+ if (file.kind !== 'markdown') {+ throw new Error('Only Markdown contents are searchable. Read the file directly or use --lines instead.')+ }++ const normalizedQuery = normalizeQuery(query)+ const lines = splitLines(file.content)+ const matchingLines = lines+ .map((line, index) => ({ line, index }))+ .filter(({ line }) => matchesQuery(line, normalizedQuery))+ .slice(0, MAX_SCOPED_MATCHES)++ if (matchingLines.length === 0) {+ return (+ `No matches for "${query}" in ${identifier}/${file.path}.\n` ++ `Read it with \`learn ${identifier} ${file.path}\` (${file.lineCount} lines, ${file.charCount} chars) or \`learn ${identifier} ${file.path} --lines <start>:<end>\`.`+ )+ }++ const blocks = matchingLines.map(({ index }) => {+ const start = Math.max(0, index - SEARCH_CONTEXT_LINES)+ const end = Math.min(lines.length - 1, index + SEARCH_CONTEXT_LINES)+ return lines+ .slice(start, end + 1)+ .map((line, offset) => `${start + offset + 1}: ${line}`)+ .join('\n')+ })+ return fitLearnOutput(`Matches in ${identifier}/${file.path}:\n\n${blocks.join('\n\n')}`)+}++export function readLearnLines(identifier: string, file: SkillFile, start: number, end: number): string {+ const lines = splitLines(file.content)+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 1 || end < start || end > lines.length) {+ throw new Error(`Invalid line range ${start}:${end}. ${identifier}/${file.path} has ${lines.length} lines.`)+ }++ const body = lines+ .slice(start - 1, end)+ .map((line, index) => `${start + index}: ${line}`)+ .join('\n')+ const result = `File: ${identifier}/${file.path} lines ${start}:${end}\n\n${body}`+ if (result.length > LEARN_OUTPUT_CHAR_LIMIT) {+ throw new Error(+ `Requested line range is ${result.length} characters. Narrow it to at most ${LEARN_OUTPUT_CHAR_LIMIT} characters.`+ )+ }+ return result+}++export function formatLearnSearchResults(results: readonly LearnSearchResult[]): string {+ const sections = results.map(({ identifier, description, snippets }) => {+ const lines = [`## ${identifier}`, '', description]+ if (snippets.length > 0) {+ lines.push('', ...snippets.map((snippet) => `${snippet.path}:${snippet.line}: ${snippet.text}`))+ }+ return lines.join('\n')+ })+ 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[] = []++ for (const file of skill.files) {+ score += 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.+ const frontmatterLines = isSkillFile ? frontmatterLineSpan(file.content) : 0+ const contentWeight = isSkillFile ? 80 : 40+ const 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)+ }+ }+ }++ 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.+ variants: string[]+}++interface NormalizedQuery {+ phrase: string+ 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']+// 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.+ */+export function extractQueryTokens(query: string): string[] {+ return [+ ...new Set(+ query+ .trim()+ .toLowerCase()+ .match(/[\p{L}\p{N}]+/gu) ?? []+ ),+ ]+}++function normalizeQuery(query: string): NormalizedQuery {+ const phrase = query.trim().toLowerCase()+ if (!phrase) {+ throw new Error('Search query cannot be empty.')+ }+ const rawTokens = extractQueryTokens(query)+ if (rawTokens.length === 0) {+ throw new Error('Search query must contain a letter or number.')+ }+ return { phrase, tokens: rawTokens.map((token) => ({ variants: stemVariants(token) })) }+}++// Only ASCII-alpha tokens of 6+ chars are stemmed; the min-5 guard on derived stems+// prevents over-matching (e.g. "sessions" must not reach "assessing" via a 4-char "sess").+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) {+ return [token]+ }+ const stem = token.slice(0, -suffix.length)+ const variants = [token, stem, stem.slice(0, -1)]+ return [...new Set(variants.filter((variant) => variant.length >= MIN_STEM_VARIANT_LENGTH))]+}++function tokenMatches(token: QueryToken, normalizedText: string): boolean {+ return token.variants.some((variant) => normalizedText.includes(variant))+}++function scoreText(text: string, query: NormalizedQuery, weight: number): number {+ const normalizedText = text.toLowerCase()+ let score = normalizedText.includes(query.phrase) ? weight * 2 : 0+ const matchingTokens = query.tokens.filter((token) => tokenMatches(token, normalizedText)).length+ if (matchingTokens === query.tokens.length) {+ score += weight+ } else {+ score += matchingTokens * Math.max(1, Math.floor(weight / query.tokens.length / 4))+ }+ return score+}++function matchesQuery(text: string, query: NormalizedQuery): boolean {+ const normalizedText = text.toLowerCase()+ return normalizedText.includes(query.phrase) || query.tokens.every((token) => tokenMatches(token, normalizedText))+}++// `skipLines` drops leading frontmatter lines while preserving raw line numbers, so the+// emitted `path:line` still matches what `--lines`/file reads return.+function findSnippet(file: SkillFile, query: NormalizedQuery, skipLines = 0): LearnSearchSnippet | undefined {+ const lines = splitLines(file.content)+ for (let index = skipLines; index < lines.length; index += 1) {+ if (matchesQuery(lines[index]!, query)) {+ return { path: file.path, line: index + 1, text: lines[index]!.trim() }+ }+ }+ return undefined+}++// Number of leading lines occupied by the YAML frontmatter block (0 when absent).+function frontmatterLineSpan(content: string): number {+ const match = FRONTMATTER_PATTERN.exec(content)+ return match ? (match[0].match(/\n/g)?.length ?? 0) : 0+}++export function fitLearnOutput(value: string): string {+ if (value.length <= LEARN_OUTPUT_CHAR_LIMIT) {+ return value+ }+ const suffix = '\n\n[Output truncated. Refine the search or request a smaller line range.]'+ return `${value.slice(0, LEARN_OUTPUT_CHAR_LIMIT - suffix.length)}${suffix}`+}++function normalizeText(value: string): string {+ return value.replace(/\r\n?/g, '\n')+}++function splitLines(value: string): string[] {+ return value.split('\n')+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}diff --git a/services/mcp/src/templates/sections/cli-learn-compact.md b/services/mcp/src/templates/sections/cli-learn-compact.mdnew file mode 100644index 000000000000..bb352955e56c--- /dev/null+++ b/services/mcp/src/templates/sections/cli-learn-compact.md@@ -0,0 +1,12 @@+**SKILLS FIRST: HARD REQUIREMENT**++For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, even if unasked. Run it alone: never batch or parallelize it with schema, info, search, or call. Wait, load matches, then continue. Skip only trivial lookups or unrelated chat.++Load 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>]]`++<example>+User: Investigate why checkout conversion dropped this week.+Assistant: [Runs only `learn -s "checkout conversion drop"`; waits. Gets `posthog:investigate-metric`; loads it exactly, follows it, then discovers tools.]+</example>diff --git a/services/mcp/src/templates/sections/cli-learn.md b/services/mcp/src/templates/sections/cli-learn.mdnew file mode 100644index 000000000000..57db79345f66--- /dev/null+++ b/services/mcp/src/templates/sections/cli-learn.md@@ -0,0 +1,14 @@+**SKILLS FIRST: HARD REQUIREMENT**++Skills are the authoritative, instance-versioned docs for PostHog behavior: warning thresholds, scoring and visibility rules, query patterns, system-table schemas. Public docs, web search, and the PostHog GitHub repo may not match this instance — never clone, grep, or web-search PostHog internals for facts a skill can serve.++For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, even if unasked. Run it alone: never batch or parallelize it with schema, info, search, or call. Wait, load matches, then continue. Trivial means repeating a lookup you already made this session; any question about a PostHog feature's behavior or data is not trivial.++Load 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>]]`++<example>+User: At what exposure share does the experiment bias warning fire?+Assistant: [Runs only `learn -s "experiment bias warning"`; waits. Loads `posthog:diagnosing-experiment-results`, reads `references/bias-and-skew.md`, answers from it — no web search, no source clone.]+</example>diff --git a/services/mcp/src/templates/sections/exec-learn.md b/services/mcp/src/templates/sections/exec-learn.mdindex de805bba83a7..d65e52d3414c 100644--- a/services/mcp/src/templates/sections/exec-learn.md+++ b/services/mcp/src/templates/sections/exec-learn.md@@ -1,5 +1,5 @@**LEARN FIRST: HARD REQUIREMENT**-Load all matching topics in one `learn` command first. Topics are cumulative.+Load all matching advertised topics in one `learn` command before non-learning commands. Topics are cumulative.{help_topics}diff --git a/services/mcp/src/templates/sections/skills-first.md b/services/mcp/src/templates/sections/skills-first.mdnew file mode 100644index 000000000000..f532e4f8a74e--- /dev/null+++ b/services/mcp/src/templates/sections/skills-first.md@@ -0,0 +1 @@+**SKILLS FIRST — this server is the authoritative source of PostHog agent skills.** Before answering any PostHog product or data question — including questions about PostHog's own behavior, warnings, thresholds, or internals — run `learn -s "<task keywords>"` here and load the matching skills. Never answer such questions by cloning, grepping, or web-searching PostHog source or docs: they may not match this instance, and un-learned product calls are rejected.diff --git a/services/mcp/src/tools/exec-help.ts b/services/mcp/src/tools/exec-help.tsdeleted file mode 100644index f398dfd89029..000000000000--- a/services/mcp/src/tools/exec-help.ts+++ /dev/null@@ -1,37 +0,0 @@-export type ExecHelpEntryKind = 'guide' | 'skill'--export interface ExecHelpEntry {- id: string- kind: ExecHelpEntryKind- title: string- description: string- content: string-}--export type ExecHelpEntrySummary = Omit<ExecHelpEntry, 'content'>--/**- * Runtime catalog for optional exec guidance. Guide entries are bundled today;- * the same flat ID + kind contract can later include skill-backed entries.- */-export class ExecHelpCatalog {- private readonly entriesById: Map<string, ExecHelpEntry>-- constructor(entries: ExecHelpEntry[]) {- this.entriesById = new Map()- for (const entry of entries) {- if (this.entriesById.has(entry.id)) {- throw new Error(`Duplicate exec help ID: "${entry.id}"`)- }- this.entriesById.set(entry.id, entry)- }- }-- list(): ExecHelpEntrySummary[] {- return [...this.entriesById.values()].map(({ content: _content, ...summary }) => summary)- }-- get(id: string): ExecHelpEntry | undefined {- return this.entriesById.get(id)- }-}diff --git a/services/mcp/src/tools/exec-learn.ts b/services/mcp/src/tools/exec-learn.tsnew file mode 100644index 000000000000..6154deb3260b--- /dev/null+++ b/services/mcp/src/tools/exec-learn.ts@@ -0,0 +1,519 @@+import type { ProjectSkillCatalog, ProjectSkillList } from '@/skills/project-skill-catalog'+import {+ fitLearnOutput,+ formatLearnSearchResults,+ type LearnSearchResult,+ MAX_GLOBAL_SKILLS,+ type SkillCatalog,+} from '@/skills/skill-catalog'++export interface ExecLearnGuide {+ id: string+ title: string+ description: string+ content: string+}++export type ExecLearnGuideSummary = Omit<ExecLearnGuide, 'content'>++const SKILL_COMMANDS = [+ 'learn skills',+ 'learn -s <query>',+ '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> --lines <start>:<end>',+] as const+const MAX_SEARCH_QUERY_LENGTH = 200+const POSTHOG_SKILL_LIST_LIMIT = 300+// Bounds on batch fan-out to keep worst-case project-side API calls per command in check.+const MAX_DESCRIBE_SKILLS = 20+const MAX_BATCH_READS = 10+// Above this total, the zero-hit recovery links to `learn skills` instead of inlining every name.+const ZERO_HIT_INLINE_LIMIT = 25+export const QUALIFIED_IDENTIFIER = /^(posthog|project):/+// A path that itself starts with `posthog:`/`project:` parses as a multi-skill read, not a file read.+const SKILL_READ_USAGE =+ 'Usage: learn <source>:<skill> [path...], learn <source>:<skill> <path> -s <query>, or learn <source>:<skill> <path> --lines <start>:<end>. Reads with several qualified names load several skills.'++type SkillSource = 'posthog' | 'project'++interface QualifiedSkill {+ source: SkillSource+ name: string+ identifier: string+}++interface ExecLearnSkillSources {+ posthog: SkillCatalog | undefined+ project?: ProjectSkillCatalog+ projectUnavailableReason?: string+}++/** A successful skill content read — the consumption signal behind `llma skill invoked`. */+export interface SkillInvocation {+ source: SkillSource+ skill: string+ path?: string+ readKind: 'skill' | 'file' | 'file_search' | 'file_lines'+}++/** Combines small bundled guides with PostHog and current-project skills. */+export class ExecLearnCatalog {+ private readonly guidesById: Map<string, ExecLearnGuide>++ constructor(+ guides: readonly ExecLearnGuide[],+ private readonly skillSources?: ExecLearnSkillSources,+ private readonly onSkillInvoked?: (invocation: SkillInvocation) => void+ ) {+ this.guidesById = new Map()+ for (const guide of guides) {+ if (guide.id === 'skills' || guide.id.startsWith('-')) {+ throw new Error(`Reserved exec learn guide ID: "${guide.id}"`)+ }+ if (this.guidesById.has(guide.id)) {+ throw new Error(`Duplicate exec learn guide ID: "${guide.id}"`)+ }+ this.guidesById.set(guide.id, guide)+ }+ }++ async execute(input: string): Promise<string> {+ const rest = input.trim()+ if (!rest) {+ const result: Record<string, unknown> = {+ guides: this.listGuides(),+ }+ if (this.skillSources) {+ result.skills = {+ posthogAvailable: this.skillSources.posthog !== undefined,+ projectAvailable: this.skillSources.project !== undefined,+ commands: SKILL_COMMANDS,+ }+ }+ return JSON.stringify(result)+ }++ const tokens = tokenizeLearnInput(rest)+ const isSkillRequest =+ tokens[0] === 'skills' || tokens[0] === '-s' || tokens[0] === '-d' || tokens[0]!.includes(':')+ if (!this.skillSources && isSkillRequest) {+ return JSON.stringify({+ available: false,+ reason: 'Skill discovery is not enabled for this connection.',+ })+ }++ if (tokens.length === 1 && tokens[0] === 'skills') {+ return await this.listSkills()+ }++ if (tokens[0] === '-s') {+ const query = tokens.slice(1).join(' ')+ this.validateSearchQuery(query)+ return await this.searchSkills(query)+ }++ if (tokens[0] === '-d') {+ return await this.describeSkills(tokens.slice(1))+ }++ if (!tokens[0]!.includes(':')) {+ return this.readGuides(tokens)+ }++ // Every token a qualified identifier → read several skills in one command.+ if (tokens.length > 1 && tokens.every((token) => QUALIFIED_IDENTIFIER.test(token))) {+ return await this.batchReadSkills(tokens)+ }++ const [identifier, ...args] = tokens+ const skill = parseQualifiedSkill(identifier!)+ if (args.length === 0) {+ return await this.readSkill(skill)+ }++ const flagIndex = args.findIndex((token) => token === '-s' || token === '--lines')+ if (flagIndex === -1) {+ if (args.length === 1) {+ return await this.readSkill(skill, args[0])+ }+ return await this.batchReadFiles(skill, args)+ }++ const paths = args.slice(0, flagIndex)+ if (paths.length !== 1) {+ throw new Error(SKILL_READ_USAGE)+ }+ const path = paths[0]!+ const flag = args[flagIndex]+ const flagArgs = args.slice(flagIndex + 1)+ if (flag === '-s') {+ const query = flagArgs.join(' ')+ this.validateSearchQuery(query)+ return await this.searchSkillFile(skill, path, query)+ }+ if (flag === '--lines' && flagArgs.length === 1) {+ const range = flagArgs[0]!.match(/^(\d+):(\d+)$/)+ if (!range) {+ throw new Error('Usage: learn <source>:<skill> <path> --lines <start>:<end>')+ }+ return await this.readSkillLines(skill, path, Number(range[1]), Number(range[2]))+ }+ throw new Error(SKILL_READ_USAGE)+ }++ private async batchReadSkills(identifiers: string[]): Promise<string> {+ if (identifiers.length > MAX_BATCH_READS) {+ throw new Error(`learn reads at most ${MAX_BATCH_READS} skills at once. Split the batch.`)+ }+ const skills = identifiers.map((identifier) => parseQualifiedSkill(identifier))+ // Fetch all before reporting any: a mid-batch failure rejects the whole+ // command, so no already-read sibling should fire an invocation.+ const reads = await Promise.all(skills.map((skill) => this.readSkillContent(skill)))+ for (const read of reads) {+ this.reportInvocation(read.invocation)+ }+ return fitLearnOutput(reads.map((read) => read.content).join('\n\n'))+ }++ private async batchReadFiles(skill: QualifiedSkill, paths: string[]): Promise<string> {+ if (paths.length > MAX_BATCH_READS) {+ throw new Error(`learn reads at most ${MAX_BATCH_READS} files at once. Split the batch.`)+ }+ // See batchReadSkills: report only after every read resolves.+ const reads = await Promise.all(paths.map((path) => this.readSkillContent(skill, path)))+ for (const read of reads) {+ this.reportInvocation(read.invocation)+ }+ return fitLearnOutput(reads.map((read) => read.content).join('\n\n'))+ }++ private async describeSkills(identifiers: string[]): Promise<string> {+ if (identifiers.length === 0) {+ throw new Error('Usage: learn -d <source>:<skill> [<source>:<skill>...]')+ }+ if (identifiers.length > MAX_DESCRIBE_SKILLS) {+ throw new Error(`learn -d describes at most ${MAX_DESCRIBE_SKILLS} skills at once. Split the batch.`)+ }++ const parsed = identifiers.map((identifier) => ({ identifier, skill: tryParseQualifiedSkill(identifier) }))+ let projectDescriptions: Map<string, string> | undefined+ let projectUnavailable: string | undefined+ const projectNames = parsed.filter(({ skill }) => skill?.source === 'project').map(({ skill }) => skill!.name)+ if (projectNames.length > 0) {+ if (!this.skillSources?.project) {+ projectUnavailable = this.requireProjectUnavailableReason()+ } else {+ try {+ // Resolves names past a truncated listing via the exact-name endpoint, so a real+ // skill beyond the list cap isn't misreported as unknown.+ projectDescriptions = await this.skillSources.project.describe(projectNames)+ } catch (error) {+ projectUnavailable = formatProjectError(error)+ }+ }+ }++ const lines = parsed.map(({ identifier, skill }) => {+ if (!skill) {+ return `[unknown skill: ${identifier}]`+ }+ if (skill.source === 'posthog') {+ if (!this.skillSources?.posthog) {+ return '[posthog skills unavailable: PostHog skills are temporarily unavailable.]'+ }+ const description = this.skillSources.posthog.describe(skill.name)+ return description !== undefined+ ? `posthog:${skill.name}: ${description}`+ : `[unknown skill: ${identifier}]`+ }+ if (projectUnavailable !== undefined) {+ return `[project skills unavailable: ${projectUnavailable}]`+ }+ const description = projectDescriptions?.get(skill.name)+ return description !== undefined+ ? `project:${skill.name}: ${description}`+ : `[unknown skill: ${identifier}]`+ })+ return fitLearnOutput(lines.join('\n'))+ }++ private async listSkills(): Promise<string> {+ const allPosthogNames = this.skillSources?.posthog?.listNames() ?? []+ const posthogNames = allPosthogNames.slice(0, POSTHOG_SKILL_LIST_LIMIT).map((name) => `posthog:${name}`)+ let project:+ | { available: true; count: number; listed: number; truncated: boolean; skills: string[] }+ | { available: false; reason: string }++ if (!this.skillSources?.project) {+ project = { available: false, reason: this.requireProjectUnavailableReason() }+ } else {+ try {+ const result = await this.skillSources.project.listNames()+ project = {+ available: true,+ count: result.count,+ listed: result.names.length,+ truncated: result.truncated,+ skills: result.names.map((name) => `project:${name}`),+ }+ } catch (error) {+ project = { available: false, reason: formatProjectError(error) }+ }+ }++ return fitLearnOutput(+ JSON.stringify({+ posthog: {+ available: this.skillSources?.posthog !== undefined,+ count: allPosthogNames.length,+ listed: posthogNames.length,+ truncated: posthogNames.length < allPosthogNames.length,+ skills: posthogNames,+ },+ project,+ })+ )+ }++ private async searchSkills(query: string): Promise<string> {+ const results: LearnSearchResult[] = this.skillSources?.posthog?.searchResults(query, 'posthog:') ?? []+ const warnings: string[] = []+ if (!this.skillSources?.posthog) {+ warnings.push('PostHog skills are temporarily unavailable.')+ }++ if (!this.skillSources?.project) {+ warnings.push(`Project skills unavailable: ${this.requireProjectUnavailableReason()}`)+ } else {+ try {+ results.push(...(await this.skillSources.project.searchResults(query)))+ } catch (error) {+ warnings.push(`Project skills unavailable: ${formatProjectError(error)}`)+ }+ }++ // Merge both sources by relevance so an exact project match can outrank a weak PostHog one.+ const merged = results+ .sort(+ (left, right) =>+ (right.score ?? 0) - (left.score ?? 0) || left.identifier.localeCompare(right.identifier)+ )+ .slice(0, MAX_GLOBAL_SKILLS)+ const sections = merged.length > 0 ? formatLearnSearchResults(merged) : await this.zeroHitRecovery(query)+ return fitLearnOutput(+ warnings.length > 0 ? `${sections}\n\n${warnings.map((warning) => `[${warning}]`).join('\n')}` : sections+ )+ }++ private async zeroHitRecovery(query: string): Promise<string> {+ const header =+ `No skills matched "${query}".\n` ++ 'None of the query words appear in any skill. Try fewer or broader keywords (single words match best).'++ const posthogNames = this.skillSources?.posthog?.listNames() ?? []+ let projectListing: ProjectSkillList | undefined+ if (!this.skillSources?.project) {+ projectListing = { count: 0, names: [], truncated: false }+ } else {+ try {+ projectListing = await this.skillSources.project.listNames()+ } catch {+ // Fall through to the link form; the search-level warning already explains the failure.+ }+ }++ if (projectListing && posthogNames.length + projectListing.count <= ZERO_HIT_INLINE_LIMIT) {+ const lines = [header, '', 'Available skills:']+ if (posthogNames.length > 0) {+ lines.push(`posthog: ${posthogNames.join(', ')}`)+ }+ if (projectListing.names.length > 0) {+ lines.push(`project: ${projectListing.names.join(', ')}`)+ }+ return lines.join('\n')+ }++ // An unset listing means the count is unknown (transient failure), not zero —+ // claiming "0 project skills" would send the agent down the no-skill path.+ const counts = projectListing+ ? `${posthogNames.length} posthog and ${projectListing.count} project skills exist`+ : `${posthogNames.length} posthog skills exist; the project skill listing is temporarily unavailable`+ return (+ `${header}\n\n` ++ `${counts} — ` ++ 'run `learn skills` to list names, or `learn -d <source>:<skill>` to describe specific ones.'+ )+ }++ private async readSkill(skill: QualifiedSkill, path?: string): Promise<string> {+ const { content, invocation } = await this.readSkillContent(skill, path)+ this.reportInvocation(invocation)+ return content+ }++ /** Fetches skill content and builds its invocation signal without reporting it —+ * batch reads report only after every sibling read resolves, so a mid-batch+ * failure can't over-report the reads that already succeeded. */+ private async readSkillContent(+ skill: QualifiedSkill,+ path?: string+ ): Promise<{ content: string; invocation: SkillInvocation }> {+ const content =+ skill.source === 'posthog'+ ? this.requirePostHogSkills().read(skill.name, path, skill.identifier)+ : await this.requireProjectSkills().read(skill.name, path)+ return {+ content,+ invocation: { source: skill.source, skill: skill.name, path, readKind: path ? 'file' : 'skill' },+ }+ }++ private async searchSkillFile(skill: QualifiedSkill, path: string, query: string): Promise<string> {+ const content =+ skill.source === 'posthog'+ ? this.requirePostHogSkills().searchFile(skill.name, path, query, skill.identifier)+ : await this.requireProjectSkills().searchFile(skill.name, path, query)+ this.reportInvocation({ source: skill.source, skill: skill.name, path, readKind: 'file_search' })+ return content+ }++ private async readSkillLines(skill: QualifiedSkill, path: string, start: number, end: number): Promise<string> {+ const content =+ skill.source === 'posthog'+ ? this.requirePostHogSkills().readLines(skill.name, path, start, end, skill.identifier)+ : await this.requireProjectSkills().readLines(skill.name, path, start, end)+ this.reportInvocation({ source: skill.source, skill: skill.name, path, readKind: 'file_lines' })+ return content+ }++ /** Fires only after a successful read; a listener failure never breaks `learn`. */+ private reportInvocation(invocation: SkillInvocation): void {+ try {+ this.onSkillInvoked?.(invocation)+ } catch {+ // analytics must never break skill delivery+ }+ }++ private validateSearchQuery(query: string): void {+ if (!query.trim()) {+ throw new Error('Search query cannot be empty.')+ }+ if (query.length > MAX_SEARCH_QUERY_LENGTH) {+ throw new Error(`Search query must be at most ${MAX_SEARCH_QUERY_LENGTH} characters.`)+ }+ }++ private listGuides(): ExecLearnGuideSummary[] {+ return [...this.guidesById.values()].map(({ content: _content, ...summary }) => summary)+ }++ private readGuides(guideIds: string[]): string {+ const uniqueGuideIds = [...new Set(guideIds)]+ const guides = uniqueGuideIds.map((guideId) => this.guidesById.get(guideId))+ const unknownGuideIds = uniqueGuideIds.filter((_, index) => guides[index] === undefined)+ if (unknownGuideIds.length > 0) {+ const available = this.listGuides()+ .map((guide) => guide.id)+ .join(', ')+ const unknown = unknownGuideIds.map((guideId) => `"${guideId}"`).join(', ')+ throw new Error(+ `Unknown learning ${unknownGuideIds.length === 1 ? 'topic' : 'topics'}: ${unknown}. Available: ${available}`+ )+ }++ const resolvedGuides = guides.filter((guide) => guide !== undefined)+ if (resolvedGuides.length === 1) {+ return resolvedGuides[0]!.content+ }+ return resolvedGuides.map((guide) => `## ${guide.title}\n\n${guide.content}`).join('\n\n')+ }++ private requirePostHogSkills(): SkillCatalog {+ if (!this.skillSources?.posthog) {+ throw new Error('PostHog skills are temporarily unavailable. Core exec commands are still available.')+ }+ return this.skillSources.posthog+ }++ private requireProjectSkills(): ProjectSkillCatalog {+ if (!this.skillSources?.project) {+ throw new Error(this.requireProjectUnavailableReason())+ }+ return this.skillSources.project+ }++ private requireProjectUnavailableReason(): string {+ return this.skillSources?.projectUnavailableReason ?? 'Project skills are temporarily unavailable.'+ }+}++function parseQualifiedSkill(identifier: string): QualifiedSkill {+ const skill = tryParseQualifiedSkill(identifier)+ if (!skill) {+ throw new Error(+ `Unknown guide or unqualified skill: "${identifier}". Use \`learn posthog:<skill>\` or \`learn project:<skill>\`.`+ )+ }+ return skill+}++function tryParseQualifiedSkill(identifier: string): QualifiedSkill | undefined {+ const match = identifier.match(/^(posthog|project):(.+)$/)+ if (!match?.[1] || !match[2]) {+ return undefined+ }+ return { source: match[1] as SkillSource, name: match[2], identifier }+}++export function tokenizeLearnInput(input: string): string[] {+ const tokens: string[] = []+ let token = ''+ let quote: '"' | "'" | undefined+ let escaping = false++ for (const character of input) {+ if (escaping) {+ token += character+ escaping = false+ } else if (character === '\\' && quote) {+ escaping = true+ } else if (quote) {+ if (character === quote) {+ quote = undefined+ } else {+ token += character+ }+ } else if (character === '"' || character === "'") {+ quote = character+ } else if (/\s/.test(character)) {+ if (token) {+ tokens.push(token)+ token = ''+ }+ } else {+ token += character+ }+ }++ if (quote) {+ throw new Error('Unterminated quote in learn command.')+ }+ if (escaping) {+ token += '\\'+ }+ if (token) {+ tokens.push(token)+ }+ return tokens+}++function formatProjectError(error: unknown): string {+ return error instanceof Error ? error.message.slice(0, 500) : 'Project skill request failed.'+}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex dc33970527bb..e1efa2fa1a60 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -7,7 +7,7 @@ import { findRecoverableApiError, PostHogApiError, ToolInputValidationError } frimport { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'-import type { ExecHelpCatalog } from './exec-help'+import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'import type { ScopeGatedTool } from './toolDefinitions'@@ -53,9 +53,24 @@ export interface ExecInnerCallProperties {export type ExecInnerCallTracker = (toolName: string, properties: ExecInnerCallProperties) => void+/**+ * Session-scoped skill-usage markers backing the skills-first gate. Product+ * `call`s in a session that ran no `learn` load are rejected with a retryable+ * instruction — interaction-time enforcement of the SKILLS FIRST prompt section,+ * which agents demonstrably rationalize their way past when it is advisory only.+ * `call --no-skills` acknowledges that no skill applies and opens the gate for+ * the rest of the session.+ */+export interface SkillsSessionState {+ hasLearned(): Promise<boolean>+ markLearned(): Promise<void>+ hasAcknowledgedNoSkills(): Promise<boolean>+ markAcknowledgedNoSkills(): Promise<void>+}+export interface ExecToolOptions {requireDestructiveConfirmation?: boolean- helpCatalog?: ExecHelpCatalog+ learnCatalog?: ExecLearnCatalog/*** Client is an inline-exec UI-app host that renders MCP UI apps on the exec* response (Claude Code, Cowork). Gets the same UI-app payload treatment as the@@ -63,6 +78,63 @@ export interface ExecToolOptions {* re-homed onto `_meta`. Computed from the client profile at the call site.*/isInlineExecUiHost?: boolean+ /** Present only when skill distribution is enabled and the client has a session. */+ skillsSession?: SkillsSessionState+}++const SKILLS_GATE_MESSAGE =+ 'No skills loaded this session. Run `learn -s "<task keywords>"` and load the matching skills first — they carry the thresholds, schemas, and query patterns this task needs. If no skill applies, re-run this exact command as `call --no-skills ...`.'++/**+ * True when a `learn` input loads skill content (a qualified `source:skill` read,+ * including file reads within a skill). Generic guide reads, listings, searches,+ * and describes don't count — a guide is not a skill, and opening the gate on+ * `learn analytics` would restore exactly the bypass the gate exists to catch.+ *+ * Uses the dispatcher's quote-aware tokenizer so a quoted flag (`learn '-s' ...`)+ * or quoted identifier (`learn 'posthog:x'`) resolves the same way it dispatches —+ * a naive whitespace split disagrees on both. An unterminated quote can't be a+ * skill load (and `execute` would have thrown first), so it returns false.+ */+function isSkillLoad(rest: string): boolean {+ let tokens: string[]+ try {+ tokens = tokenizeLearnInput(rest)+ } catch {+ return false+ }+ if (tokens[0] === 'skills' || tokens[0] === '-s' || tokens[0] === '-d') {+ return false+ }+ return tokens.some((token) => QUALIFIED_IDENTIFIER.test(token))+}++/**+ * Returns the gate rejection message, or undefined when the call may proceed.+ * A session-store hiccup opens the gate — enforcement must never break tools.+ */+async function resolveSkillsGate(+ session: SkillsSessionState | undefined,+ noSkillsFlag: boolean+): Promise<string | undefined> {+ if (!session) {+ return undefined+ }+ try {+ if (noSkillsFlag) {+ await session.markAcknowledgedNoSkills()+ return undefined+ }+ if (await session.hasLearned()) {+ return undefined+ }+ if (await session.hasAcknowledgedNoSkills()) {+ return undefined+ }+ return SKILLS_GATE_MESSAGE+ } catch {+ return undefined+ }}function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {@@ -80,10 +152,11 @@ function parseCommand(input: string): { verb: string; rest: string } {return { verb: trimmed.slice(0, idx), rest: trimmed.slice(idx + 1).trim() }}-function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; rest: string } {+function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; noSkills: boolean; rest: string } {let rest = input.trim()let forceJson = falselet confirmed = false+ let noSkills = falsewhile (rest) {const parsed = parseCommand(rest)@@ -97,10 +170,15 @@ function parseCallFlags(input: string): { forceJson: boolean; confirmed: booleanrest = parsed.restcontinue}+ if (parsed.verb === '--no-skills') {+ noSkills = true+ rest = parsed.rest+ continue+ }break}- return { forceJson, confirmed, rest }+ return { forceJson, confirmed, noSkills, rest }}// Extracts the inner tool name from an exec `call` command, e.g.@@ -329,32 +407,17 @@ export function createExecTool(switch (verb) {case 'learn': {- const helpCatalog = options.helpCatalog- if (!helpCatalog) {- throw new Error('The learning catalog is not available for this client.')+ const learnCatalog = options.learnCatalog+ if (!learnCatalog) {+ throw new Error('The learn command is not available for this client.')}- if (!rest) {- return JSON.stringify(helpCatalog.list())+ const learnResult = await learnCatalog.execute(rest)+ // Only skill loads count as "learned" — a search whose results are+ // then ignored is exactly the bypass the gate exists to catch.+ if (options.skillsSession && isSkillLoad(rest)) {+ await options.skillsSession.markLearned().catch(() => undefined)}- const topicIds = [...new Set(rest.split(/\s+/))]- const entries = topicIds.map((topicId) => helpCatalog.get(topicId))- const unknownTopicIds = topicIds.filter((_, index) => entries[index] === undefined)- if (unknownTopicIds.length > 0) {- const available = helpCatalog- .list()- .map((item) => item.id)- .join(', ')- if (unknownTopicIds.length === 1) {- throw new Error(`Unknown learning topic: "${unknownTopicIds[0]}". Available: ${available}`)- }- const unknownTopics = unknownTopicIds.map((topicId) => `"${topicId}"`).join(', ')- throw new Error(`Unknown learning topics: ${unknownTopics}. Available: ${available}`)- }- const resolvedEntries = entries.filter((entry) => entry !== undefined)- if (resolvedEntries.length === 1) {- return resolvedEntries[0]!.content- }- return resolvedEntries.map((entry) => `## ${entry.title}\n\n${entry.content}`).join('\n\n')+ return learnResult}case 'tools': {@@ -520,17 +583,21 @@ export function createExecTool(case 'call': {if (!rest) {- throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')+ throw new Error('Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>')}if (!context) {throw new Error('Cannot call PostHog tools without an API context')}- const { forceJson, confirmed, rest: callArgs } = parseCallFlags(rest)+ const { forceJson, confirmed, noSkills, rest: callArgs } = parseCallFlags(rest)if (!callArgs) {- throw new Error('Usage: call [--json] [--confirm] <tool_name> <json_input>')+ throw new Error('Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>')}const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)const tool = findTool(allTools, scopeGatedTools, toolName)+ const gateMessage = await resolveSkillsGate(options.skillsSession, noSkills)+ if (gateMessage) {+ throw new Error(gateMessage)+ }if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {throw new Error(`Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`@@ -697,7 +764,7 @@ export function createExecTool(default:throw new Error(- `Unknown command: "${verb}". Supported commands: ${options.helpCatalog ? 'learn, ' : ''}tools, search, info, schema, call`+ `Unknown command: "${verb}". Supported commands: ${options.learnCatalog ? 'learn, ' : ''}tools, search, info, schema, call`)}},diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.tsindex 1bdb34dba3a7..d0bce3c6bc19 100644--- a/services/mcp/src/tools/types.ts+++ b/services/mcp/src/tools/types.ts@@ -31,6 +31,8 @@ export type State = {mcpProtocolVersion: string | undefinedmcpConsumer: string | undefinedmcpVendorClient: string | undefined+ skillsLearnedAt: number | undefined+ skillsNoSkillsAckAt: number | undefined} & Record<PrefixedString<'session'>, SessionState> &Record<PrefixedString<'groupTypes'>, GroupType[] | undefined> &Record<PrefixedString<'groupTypesFetchedAt'>, number | undefined> &@@ -85,6 +87,8 @@ export type Env = {* Falls back to the production US host if not set.*/POSTHOG_ANALYTICS_HOST: string | undefined+ /** Override the published product skills archive, primarily for local development. */+ POSTHOG_MCP_SKILLS_URL?: string | undefined}export type Context = {diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.tsindex 4b2f67e34149..891ff2205c22 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -15,8 +15,12 @@ vi.mock('@/lib/posthog', () => ({})),}))-import { trackExecuteSqlGeneration, trackInitEvent, trackToolCall } from '@/hono/analytics'+import { trackExecuteSqlGeneration, trackInitEvent, trackSkillInvoked, trackToolCall } from '@/hono/analytics'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'+import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'+import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'+import type { SkillInvocation } from '@/tools/exec-learn'function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {return {@@ -179,4 +183,68 @@ describe('Hono MCP analytics contexts', () => {expect(mockCapture).not.toHaveBeenCalled()})})++ describe('trackSkillInvoked', () => {+ it.each<SkillInvocation['readKind']>(['skill', 'file', 'file_search', 'file_lines'])(+ 'captures %s reads with skill_read_kind so file-only consumption still counts',+ async (readKind) => {+ await trackSkillInvoked(makeState(), {+ source: 'posthog',+ skill: 'retention-analysis',+ path: readKind === 'skill' ? undefined : 'references/functions.md',+ readKind,+ })++ expect(mockCapture).toHaveBeenCalledTimes(1)+ expect(mockCapture.mock.calls[0]![0]).toMatchObject({+ event: 'skill invoked',+ properties: {+ skill_identifier: 'posthog:retention-analysis',+ skill_read_kind: readKind,+ },+ })+ }+ )+ })++ describe('exec learn catalog skill-invoked dedupe', () => {+ function skillsCatalog(): SkillCatalog {+ return new SkillCatalog([+ {+ name: 'retention-analysis',+ description: 'Retention.',+ files: [+ makeSkillFile('SKILL.md', '# Retention'),+ makeSkillFile('a.md', 'alpha'),+ makeSkillFile('b.md', 'beta'),+ ],+ },+ { name: 'funnels', description: 'Funnels.', files: [makeSkillFile('SKILL.md', '# Funnels')] },+ ])+ }++ function skillsState(): ResolvedState {+ return makeState({+ clientProfile: { isClaudeChatHost: () => false } as any,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },+ })+ }++ it('counts one skill once per command but each command separately', async () => {+ const catalog = new InstructionsBuilder('').buildExecLearnCatalog(skillsState(), skillsCatalog())!++ // A batch that reads two files of one skill must dedupe to a single event.+ await catalog.execute('posthog:retention-analysis a.md b.md')+ await vi.waitFor(() => expect(mockCapture).toHaveBeenCalledTimes(1))++ // A separate command reading another skill still counts.+ await catalog.execute('posthog:funnels')+ await vi.waitFor(() => expect(mockCapture).toHaveBeenCalledTimes(2))++ expect(mockCapture.mock.calls.map((call) => call[0].properties.skill_identifier)).toEqual([+ 'posthog:retention-analysis',+ 'posthog:funnels',+ ])+ })+ })})diff --git a/services/mcp/tests/hono/constants.test.ts b/services/mcp/tests/hono/constants.test.tsindex a608d469a6b7..ee8768017760 100644--- a/services/mcp/tests/hono/constants.test.ts+++ b/services/mcp/tests/hono/constants.test.ts@@ -153,6 +153,7 @@ describe('Hono Constants', () => {expect(env).toHaveProperty('POSTHOG_UI_APPS_TOKEN')expect(env).toHaveProperty('POSTHOG_ANALYTICS_API_KEY')expect(env).toHaveProperty('POSTHOG_ANALYTICS_HOST')+ expect(env).toHaveProperty('POSTHOG_MCP_SKILLS_URL')})})})diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 21b1c48738f1..8a5266297b69 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -69,8 +69,9 @@ vi.mock('@/hono/request-context', () => {})import type { RedisLike } from '@/hono/cache/RedisCache'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'import { RequestStateResolver } from '@/hono/request-state-resolver'-import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'+import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import type { Env } from '@/tools/types'@@ -98,6 +99,9 @@ function makeResolver(): RequestStateResolver {describe('RequestStateResolver MCP client contexts', () => {beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(evaluateFeatureFlags).mockResolvedValue({})+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValue({})mockSessionStore.clear()mockTokenStore.clear()})@@ -305,6 +309,19 @@ describe('RequestStateResolver MCP client contexts', () => {expect(result.toolFeatureFlags?.['dev-forced-flag']).toBe(true)})+ it('evaluates the exec skills flag independently of generated tool flags', async () => {+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ [MCP_EXEC_SKILLS_FEATURE_FLAG]: true })++ const result = await makeResolver().resolve(makeProps())++ expect(evaluateFeatureFlags).toHaveBeenCalledWith(+ expect.arrayContaining([MCP_EXEC_SKILLS_FEATURE_FLAG]),+ 'distinct-id',+ undefined+ )+ expect(result.toolFeatureFlags?.[MCP_EXEC_SKILLS_FEATURE_FLAG]).toBe(true)+ })+it('captures consumer from a later request when initialize omitted the header', async () => {await makeResolver().resolve(makeProps({diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.tsindex 1e27e7a4b90c..57c39fe18074 100644--- a/services/mcp/tests/hono/setup.ts+++ b/services/mcp/tests/hono/setup.ts@@ -28,6 +28,18 @@ vi.mock('@/resources/ui-apps', async (importOriginal) => {vi.mock('@/resources/ui-apps.generated', async (importOriginal) => importOriginal())+// Product skills use a live release archive in production. Archive parsing and+// cache behavior have fixture-backed unit coverage; Hono wiring stays offline.+vi.mock('@/hono/skill-catalog-service', () => ({+ SkillCatalogService: class {+ getCatalog(): undefined {+ return undefined+ }+ async warmup(): Promise<void> {}+ async revalidate(): Promise<void> {}+ },+}))+// Mock template imports that may not existvi.mock('@/templates/cli-proxy-command.md', async () => {try {diff --git a/services/mcp/tests/hono/shared-blob-cache.test.ts b/services/mcp/tests/hono/shared-blob-cache.test.tsindex 775bcc0f1cd4..e52af45a3555 100644--- a/services/mcp/tests/hono/shared-blob-cache.test.ts+++ b/services/mcp/tests/hono/shared-blob-cache.test.ts@@ -14,8 +14,8 @@ class TestSharedBlobCache extends SharedBlobCache {return this.readCache()}- write(bytes: Uint8Array): Promise<void> {- return this.writeCache(bytes)+ write(bytes: Uint8Array, validator?: string): Promise<void> {+ return this.writeCache(bytes, validator)}acquire(token: string): Promise<boolean> {@@ -70,6 +70,7 @@ const NAMESPACE = 'test-blob'const BYTES_KEY = `mcp:shared-blob:${NAMESPACE}:bytes`const FRESH_KEY = `mcp:shared-blob:${NAMESPACE}:fresh`const LOCK_KEY = `mcp:shared-blob:${NAMESPACE}:lock`+const ETAG_KEY = `mcp:shared-blob:${NAMESPACE}:etag`describe('SharedBlobCache', () => {let redis: MockRedis@@ -90,6 +91,24 @@ describe('SharedBlobCache', () => {expect(redis._store.has(FRESH_KEY)).toBe(true)})+ it('leaves the etag untouched and rejects when the bytes write fails', async () => {+ // Ordering guard: bytes must land before the validator. If a bytes SET+ // fails, the etag must keep its old value so a later conditional refresh+ // can't send a new validator that no longer matches the cached bytes.+ redis._store.set(ETAG_KEY, 'etag-old')+ redis.set = vi.fn(async (key: string, ...rest: (string | number)[]) => {+ if (key === BYTES_KEY) {+ throw new Error('bytes write failed')+ }+ redis._store.set(key, String(rest[0]))+ return 'OK'+ })+ const cache = new TestSharedBlobCache(redis, NAMESPACE)++ await expect(cache.write(new Uint8Array([1, 2, 3]), 'etag-new')).rejects.toThrow('bytes write failed')+ expect(redis._store.get(ETAG_KEY)).toBe('etag-old')+ })+it('marks cached bytes stale after the freshness window', async () => {const cache = new TestSharedBlobCache(redis, NAMESPACE, { freshSeconds: 0 })await cache.write(new Uint8Array([9, 8, 7]))diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 33d625c6506d..60a0c79a66f0 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -11,12 +11,14 @@ vi.mock('@/resources', () => ({getPromptsFromManifest: vi.fn().mockResolvedValue([]),}))+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'import { buildToolDomainsCompact } from '@/lib/instructions'import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'+import { SkillCatalog } from '@/skills/skill-catalog'import { getToolDefinition } from '@/tools/toolDefinitions'// A tool with a renderable (dispatchable) UI app — used to exercise the render-ui path.@@ -186,6 +188,139 @@ describe('ToolExecutor', () => {expect(result.tools[0]!.name).toBe('exec')})+ it.each([+ {+ label: 'Claude web/desktop with flag off',+ isClaudeChatHost: true,+ skillsEnabled: false,+ consumer: undefined,+ expectGuides: true,+ expectSkills: false,+ },+ {+ label: 'Claude web/desktop with flag on',+ isClaudeChatHost: true,+ skillsEnabled: true,+ consumer: undefined,+ expectGuides: true,+ expectSkills: true,+ },+ {+ label: 'Claude Code with flag off',+ isClaudeChatHost: false,+ skillsEnabled: false,+ consumer: undefined,+ expectGuides: false,+ expectSkills: false,+ },+ {+ label: 'Claude Code with flag on',+ isClaudeChatHost: false,+ skillsEnabled: true,+ consumer: undefined,+ expectGuides: false,+ expectSkills: true,+ },+ {+ label: 'plugin consumer with flag on',+ isClaudeChatHost: true,+ skillsEnabled: true,+ consumer: 'plugin',+ expectGuides: false,+ expectSkills: false,+ },+ {+ label: 'posthog-code consumer with flag on',+ isClaudeChatHost: false,+ skillsEnabled: true,+ consumer: 'posthog-code',+ expectGuides: false,+ expectSkills: false,+ },+ ])(+ 'advertises and serves the expected learn capabilities for $label',+ async ({ isClaudeChatHost, skillsEnabled, consumer, expectGuides, expectSkills }) => {+ const skills = new SkillCatalog([+ {+ name: 'sample-skill',+ description: 'A sample skill.',+ files: [+ {+ path: 'SKILL.md',+ content: '# Sample skill',+ lineCount: 1,+ charCount: 14,+ kind: 'markdown',+ },+ ],+ },+ ])+ const skillExecutor = new ToolExecutor(catalog, new InstructionsBuilder(''), {+ getCatalog: () => skills,+ } as any)+ const state = makeState([], {+ useSingleExec: true,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: skillsEnabled },+ clientProfile: {+ capabilities: { supportsInstructions: true },+ isCliModeEnabled: vi.fn(() => true),+ isClaudeUiHost: vi.fn(() => isClaudeChatHost),+ isInlineExecUiHost: vi.fn(() => false),+ isClaudeChatHost: vi.fn(() => isClaudeChatHost),+ } as any,+ ...(consumer+ ? {+ sessionContext: {+ mcpClientName: 'claude-ai',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: consumer,+ mcpVendorClient: undefined,+ },+ }+ : {}),+ })++ const listed = await skillExecutor.handleToolsList(state)+ const commandDescription = (listed.tools[0]!.inputSchema.properties as any).command+ .description as string+ const advertisesSkills =+ commandDescription.includes('learn posthog:<skill>') ||+ commandDescription.includes('(posthog|project):<skill>')+ expect(commandDescription.includes('- analytics:')).toBe(expectGuides)+ expect(advertisesSkills).toBe(expectSkills)+ expect(commandDescription.includes('**SKILLS FIRST: HARD REQUIREMENT**')).toBe(expectSkills)+ expect(commandDescription.includes('never batch or parallelize it')).toBe(expectSkills)+ expect(commandDescription.includes('learn <topic...>')).toBe(expectGuides)++ const result = (await skillExecutor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn' } },+ state+ )) as { content: { text: string }[]; isError?: boolean }+ if (!expectGuides && !expectSkills) {+ expect(result.isError).toBe(true)+ expect(result.content[0]!.text).toContain('learn command is not available')+ return+ }++ const catalogResult = JSON.parse(result.content[0]!.text)+ expect(catalogResult.guides.length > 0).toBe(expectGuides)+ expect('skills' in catalogResult).toBe(expectSkills)++ if (!expectSkills) {+ const skillResult = (await skillExecutor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn skills' } },+ state+ )) as { content: { text: string }[]; isError?: boolean }+ expect(skillResult.isError).toBeFalsy()+ expect(JSON.parse(skillResult.content[0]!.text)).toEqual({+ available: false,+ reason: 'Skill discovery is not enabled for this connection.',+ })+ }+ }+ )+// Env-context (active project metadata + tool-domain index) must reach the model// on the exec `command` for clients that don't otherwise receive the `instructions`// payload: Codex reports `supportsInstructions: false` so never gets it, and Claude@@ -281,6 +416,124 @@ describe('ToolExecutor', () => {expect(result.content[0]!.text).toContain('### Rendering visualizations')})+ it('serves the runtime product skill catalog to non-plugin consumers', async () => {+ const skills = new SkillCatalog([+ {+ name: 'sample-skill',+ description: 'A sample skill.',+ files: [+ {+ path: 'SKILL.md',+ content: '# Sample skill',+ lineCount: 1,+ charCount: 14,+ kind: 'markdown',+ },+ ],+ },+ ])+ const skillExecutor = new ToolExecutor(catalog, new InstructionsBuilder(''), {+ getCatalog: () => skills,+ } as any)+ const state = makeState([], { useSingleExec: true })+ state.toolFeatureFlags = { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true }++ const result = (await skillExecutor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn skills' } },+ state+ )) as { content: { text: string }[] }++ expect(result.content[0]!.text).toContain('sample-skill')+ })++ it('discovers and searches current-project skills when the connection has read scope', async () => {+ const apiRequest = vi.fn().mockImplementation(async ({ path }: { path: string }) => {+ if (path.endsWith('/search/')) {+ return {+ count: 1,+ results: [+ {+ name: 'team-retention',+ description: 'Project-specific retention guidance.',+ matches: [+ {+ matched_field: 'body',+ path: 'SKILL.md',+ line: 3,+ excerpt: 'Use weekly retention cohorts.',+ },+ ],+ },+ ],+ }+ }+ return { count: 1, results: [{ name: 'team-retention' }] }+ })+ const state = makeState([], {+ useSingleExec: true,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },+ apiKeyScopes: ['llm_skill:read'],+ context: {+ api: { request: apiRequest },+ stateManager: { getProjectId: vi.fn().mockResolvedValue(12) },+ } as any,+ })++ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn -s retention' } },+ state+ )) as { content: { text: string }[] }++ expect(result.content[0]!.text).toContain('## project:team-retention')+ expect(apiRequest).toHaveBeenCalledWith({+ method: 'GET',+ path: '/api/projects/12/llm_skills/search/',+ query: { query: 'retention' },+ })++ const listResult = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn skills' } },+ state+ )) as { content: { text: string }[] }+ expect(listResult.content[0]!.text).toContain('project:team-retention')+ expect(apiRequest).toHaveBeenCalledWith({+ method: 'GET',+ path: '/api/projects/12/llm_skills/',+ query: { category: '', limit: 100, offset: 0, order_by: 'name' },+ })+ })++ it('does not advertise or serve learn for the effective plugin consumer', async () => {+ const state = makeState(+ catalog+ .getPreBuiltEntries()+ .slice(0, 5)+ .map(({ name }) => ({ name })),+ {+ useSingleExec: true,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },+ sessionContext: {+ mcpClientName: 'claude-ai',+ mcpClientVersion: '1.0',+ mcpProtocolVersion: '2025-03-26',+ mcpConsumer: 'plugin',+ mcpVendorClient: undefined,+ },+ }+ )++ const listed = await executor.handleToolsList(state)+ const commandDescription = (listed.tools[0]!.inputSchema.properties as any).command.description as string+ expect(commandDescription).not.toContain('learn <')++ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn' } },+ state+ )) as { content: { text: string }[]; isError?: boolean }+ expect(result.isError).toBe(true)+ expect(result.content[0]!.text).toContain('learn command is not available')+ })+it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txtindex 07f4956ef9b8..84ca9c2eeed1 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt@@ -11,12 +11,26 @@ call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON inp**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.+**SKILLS FIRST: HARD REQUIREMENT**++For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, even if unasked. Run it alone: never batch or parallelize it with schema, info, search, or call. Wait, load matches, then continue. Skip only trivial lookups or unrelated chat.++Load 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>]]`++<example>+User: Investigate why checkout conversion dropped this week.+Assistant: [Runs only `learn -s "checkout conversion drop"`; waits. Gets `posthog:investigate-metric`; loads it exactly, follows it, then discovers tools.]+</example>+**LEARN FIRST: HARD REQUIREMENT**-Load all matching topics in one `learn` command first. Topics are cumulative.+Load all matching advertised topics in one `learn` command before non-learning commands. Topics are cumulative.- analytics: Query or analyze PostHog data, metrics, and events.- visualizations: Create or render a visualization.+- urls: Load before writing any PostHog app link or URL.- feedback: Send feedback about PostHog.**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**@@ -157,16 +171,4 @@ Defined group types: organization, projectYou are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).Project timezone: America/New_York.-The user's name is Jane Doe ([email protected]).--### URL patterns--PostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.--Choose the link source in this order:--1. If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.-2. Only when you actually want to link a specific entity (or the user asks for a link) and it has no `_posthogUrl`, call `generate-app-url` and surface the `url` verbatim — don't hand-write slugs or retype IDs into paths, both are easy to get wrong. Don't fetch a link just because a result has an ID.-3. Only for genuinely static pages not covered by `generate-app-url` (some settings / data-management pages), build the link from the Base URL in the active-environment block (don't double-prefix):- - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`.- - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\ No newline at end of file+The user's name is Jane Doe ([email protected]).\ No newline at end of filediff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex e0312f3805c4..725dc45b6d9b 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -10,6 +10,21 @@ call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON inp**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ "command": "info insights-list" })` then `posthog:exec({ "command": "call insights-list {}" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.+**SKILLS FIRST: HARD REQUIREMENT**++Skills are the authoritative, instance-versioned docs for PostHog behavior: warning thresholds, scoring and visibility rules, query patterns, system-table schemas. Public docs, web search, and the PostHog GitHub repo may not match this instance — never clone, grep, or web-search PostHog internals for facts a skill can serve.++For non-trivial PostHog/team work, first run `learn -s "<task keywords>"`, even if unasked. Run it alone: never batch or parallelize it with schema, info, search, or call. Wait, load matches, then continue. Trivial means repeating a lookup you already made this session; any question about a PostHog feature's behavior or data is not trivial.++Load 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>]]`++<example>+User: At what exposure share does the experiment bias warning fire?+Assistant: [Runs only `learn -s "experiment bias warning"`; waits. Loads `posthog:diagnosing-experiment-results`, reads `references/bias-and-skew.md`, answers from it — no web search, no source clone.]+</example>+**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**The `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 5bbf79d6d06c..04df0390b46c 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -8,6 +8,7 @@ import { estimateTokens } from '@/lib/estimate-tokens'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'+import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'import { getToolsFromContext } from '@/tools'import {createExecTool,@@ -17,7 +18,7 @@ import {formatInputValidationError,parseExecCallInnerToolName,} from '@/tools/exec'-import { ExecHelpCatalog } from '@/tools/exec-help'+import { ExecLearnCatalog } from '@/tools/exec-learn'import { withInformationalResponse } from '@/tools/tool-utils'import { getToolDefinition } from '@/tools/toolDefinitions'import {@@ -70,76 +71,192 @@ function createExec(describe('exec tool', () => {describe('learn command', () => {- const helpCatalog = new ExecHelpCatalog([- {- id: 'analytics',- kind: 'guide',- title: 'Analytics',- description: 'Detailed analytics guidance.',- content: '### Retrieving data\n\nUse the analytics tools.',- },- {- id: 'retention-analysis',- kind: 'skill',- title: 'Retention analysis',- description: 'A retention workflow.',- content: '### Retention analysis\n\nFollow the workflow.',- },- ])-- it('lists topic metadata without loading topic content', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })-- const result = JSON.parse((await exec.handler(mockContext, { command: 'learn' })) as string)-- expect(result).toEqual([+ const learnCatalog = new ExecLearnCatalog(+ [{id: 'analytics',- kind: 'guide',title: 'Analytics',description: 'Detailed analytics guidance.',+ content: '### Retrieving data\n\nUse the analytics tools.',},- {- id: 'retention-analysis',- kind: 'skill',- title: 'Retention analysis',- description: 'A retention workflow.',+ ],+ { posthog: undefined }+ )++ it('lists guide metadata and skill discovery commands without loading content', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })++ const result = JSON.parse((await exec.handler(mockContext, { command: 'learn' })) as string)++ expect(result).toEqual({+ guides: [+ {+ id: 'analytics',+ title: 'Analytics',+ description: 'Detailed analytics guidance.',+ },+ ],+ skills: {+ posthogAvailable: false,+ projectAvailable: false,+ commands: [+ 'learn skills',+ 'learn -s <query>',+ '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> --lines <start>:<end>',+ ],},- ])+ })})- it('loads a topic by its globally unique ID', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ it('loads a built-in guide', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })await expect(exec.handler(mockContext, { command: 'learn analytics' })).resolves.toBe('### Retrieving data\n\nUse the analytics tools.')})- it('loads multiple unique topics in the requested order', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ it('keeps core exec usable and reports each unavailable skill source', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })- await expect(- exec.handler(mockContext, { command: 'learn retention-analysis analytics retention-analysis' })- ).resolves.toBe(- '## Retention analysis\n\n### Retention analysis\n\nFollow the workflow.\n\n## Analytics\n\n### Retrieving data\n\nUse the analytics tools.'+ const result = JSON.parse((await exec.handler(mockContext, { command: 'learn skills' })) as string)+ expect(result.posthog.available).toBe(false)+ expect(result.project.available).toBe(false)+ await expect(exec.handler(mockContext, { command: 'learn posthog:missing' })).rejects.toThrow(+ 'PostHog skills are temporarily unavailable')+ await expect(exec.handler(mockContext, { command: 'tools' })).resolves.toContain('mock-tool')})+ })++ describe('skills-first gate', () => {+ const guideCatalog = (): ExecLearnCatalog =>+ new ExecLearnCatalog(+ [{ id: 'analytics', title: 'Analytics', description: 'Guidance.', content: 'Use the tools.' }],+ {+ posthog: new SkillCatalog([+ {+ name: 'bot-traffic',+ description: 'Filtering bot traffic.',+ files: [makeSkillFile('SKILL.md', '# Bot traffic\n\nFilter bots.')],+ },+ ]),+ }+ )++ function makeSkillsSession(): {+ session: NonNullable<ExecToolOptions['skillsSession']>+ state: { learnedAt?: number; ackAt?: number }+ } {+ const state: { learnedAt?: number; ackAt?: number } = {}+ return {+ state,+ session: {+ hasLearned: async () => state.learnedAt !== undefined,+ markLearned: async () => {+ state.learnedAt = Date.now()+ },+ hasAcknowledgedNoSkills: async () => state.ackAt !== undefined,+ markAcknowledgedNoSkills: async () => {+ state.ackAt = Date.now()+ },+ },+ }+ }- it('reports the available IDs when a topic is unknown', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ it('rejects an un-learned call and passes it after a skill load', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })- await expect(exec.handler(mockContext, { command: 'learn unknown' })).rejects.toThrow(- 'Unknown learning topic: "unknown". Available: analytics, retention-analysis'+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow(+ 'No skills loaded this session')++ await exec.handler(mockContext, { command: 'learn posthog:bot-traffic' })+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()})- it('reports every unknown ID without returning partial topic content', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ it('does not open the gate for a generic guide read', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })- await expect(- exec.handler(mockContext, { command: 'learn analytics unknown missing unknown' })- ).rejects.toThrow('Unknown learning topics: "unknown", "missing". Available: analytics, retention-analysis')+ await exec.handler(mockContext, { command: 'learn analytics' })++ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow(+ 'No skills loaded this session'+ )+ })++ it('does not open the gate for a bare search', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })++ await exec.handler(mockContext, { command: 'learn -s bot traffic' })++ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow(+ 'No skills loaded this session'+ )+ })++ it('does not open the gate when a search flag is quoted', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })++ // Quotes make a naive whitespace split miss the leading `-s`, so the+ // command reads as a skill load and wrongly opens the gate.+ await exec.handler(mockContext, { command: "learn '-s' bot traffic" })++ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow(+ 'No skills loaded this session'+ )+ })++ it('opens the gate when the skill identifier is quoted', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })++ // A leading quote defeats a naive `startsWith('posthog:')` check, so a+ // real skill load would fail to open the gate.+ await exec.handler(mockContext, { command: "learn 'posthog:bot-traffic'" })++ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()+ })++ it('call --no-skills acknowledges once and opens the gate for the session', async () => {+ const { session } = makeSkillsSession()+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: session })++ await expect(exec.handler(mockContext, { command: 'call --no-skills mock-tool {}' })).resolves.toBeDefined()+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()+ })++ it('opens the gate when the session store fails', async () => {+ const failing: NonNullable<ExecToolOptions['skillsSession']> = {+ hasLearned: async () => {+ throw new Error('redis down')+ },+ markLearned: async () => {+ throw new Error('redis down')+ },+ hasAcknowledgedNoSkills: async () => {+ throw new Error('redis down')+ },+ markAcknowledgedNoSkills: async () => {+ throw new Error('redis down')+ },+ }+ const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: failing })++ await expect(exec.handler(mockContext, { command: 'learn posthog:bot-traffic' })).resolves.toContain(+ 'Bot traffic'+ )+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()})})@@ -249,14 +366,14 @@ describe('exec tool', () => {it('throws usage error for bare call', async () => {const exec = createExec()await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow(- 'Usage: call [--json] [--confirm] <tool_name> <json_input>'+ 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>')})it('throws usage error for call --json with no tool name', async () => {const exec = createExec()await expect(exec.handler(mockContext, { command: 'call --json' })).rejects.toThrow(- 'Usage: call [--json] [--confirm] <tool_name> <json_input>'+ 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>')})diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.tsindex 92f98578f0d3..489716e5b855 100644--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest'import { PostHogMCP } from '@posthog/mcp-analytics'import type { GroupType } from '@/api/client'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { MCPClientProfile } from '@/lib/client-detection'@@ -99,10 +100,12 @@ describe('InstructionsFormatter prompt snapshots', () => {const state = {allTools: STATIC_TOOLS.map(({ name }) => ({ name })),clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI' }),- toolFeatureFlags: {},+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },renderUiEnabled: STATIC_CTX.renderUiEnabled,metadata: STATIC_CTX.metadata,groupTypes: STATIC_CTX.groupTypes,+ requestContext: { mcpConsumer: undefined },+ sessionContext: null,} as unknown as ResolvedStateconst rendered = new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(state)@@ -123,6 +126,8 @@ describe('InstructionsFormatter prompt snapshots', () => {renderUiEnabled: STATIC_CTX.renderUiEnabled,metadata: STATIC_CTX.metadata,groupTypes: STATIC_CTX.groupTypes,+ requestContext: { mcpConsumer: undefined },+ sessionContext: null,} as unknown as ResolvedStatereturn new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(state)}@@ -183,12 +188,15 @@ describe('InstructionsFormatter prompt snapshots', () => {const state = {allTools: Object.keys(getToolDefinitions()).map((name) => ({ name })),clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI', userAgent: 'Claude-User' }),- // Data catalog on: the analytics learn-topic description is longer with- // the flag, and topic descriptions are inlined in the command reference.- toolFeatureFlags: { [PRODUCT_DATA_CATALOG_FLAG]: true },+ // Both flags on is the worst case: the analytics learn-topic description is+ // longer with the data catalog, and topic descriptions are inlined in the+ // command reference.+ toolFeatureFlags: { [PRODUCT_DATA_CATALOG_FLAG]: true, [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },renderUiEnabled: true,metadata: worstCaseMetadata,groupTypes: worstCaseGroupTypes,+ requestContext: { mcpConsumer: undefined },+ sessionContext: null,} as unknown as ResolvedStateconst entry = new InstructionsBuilder('').buildExecToolEntry(state)const posthog = new PostHogMCP('phc_test', { disabled: true })diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 48cf24c061e1..9f05bd038f74 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -227,7 +227,7 @@ describe('InstructionsFormatter', () => {})describe('Claude web/desktop exec guidance', () => {- it('keeps routine guidance inline and advertises optional topics', () => {+ it('keeps routine guidance inline and advertises learn guides and skill syntax', () => {const formatter = new InstructionsFormatter()const result = formatter.buildClaudeExecCommandReference(fullCtx)@@ -246,7 +246,9 @@ describe('InstructionsFormatter', () => {)expect(result).toContain('- analytics:')expect(result).toContain('- visualizations:')+ expect(result).toContain('- urls:')expect(result).toContain('- feedback:')+ expect(result).toContain('(posthog|project):<skill> [path...]')expect(result).toContain('SCHEMA DRILL-DOWN RULE')expect(result).toContain('**Data discovery:**')expect(result).toContain('**CORRECT usage pattern:**')@@ -261,27 +263,27 @@ describe('InstructionsFormatter', () => {expect(result).not.toContain('### Retrieving data')expect(result).not.toContain('### Examples')expect(result).not.toContain('### Rendering visualizations')+ expect(result).not.toContain('### URL patterns')expect(result).not.toContain('### Sharing feedback on PostHog')expect(result).not.toContain('- `query-trends` — time series')- expect(result).not.toMatch(/\{help_topics\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/)+ expect(result).not.toMatch(+ /\{learn_guides\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/+ )})it('combines analytics guidance and examples in one learning topic', () => {const formatter = new InstructionsFormatter()- const entries = formatter.buildClaudeExecHelpEntries(fullCtx)+ const entries = formatter.buildClaudeExecLearnGuides(fullCtx)const analytics = entries.find((entry) => entry.id === 'analytics')- expect(entries.map(({ id, kind }) => ({ id, kind }))).toEqual([- { id: 'analytics', kind: 'guide' },- { id: 'visualizations', kind: 'guide' },- { id: 'feedback', kind: 'guide' },- ])+ expect(entries.map(({ id }) => id)).toEqual(['analytics', 'visualizations', 'urls', 'feedback'])expect(analytics?.content).toContain('### Retrieving data')expect(analytics?.content).toContain('### Examples')expect(analytics?.content).toContain('- `query-trends` — time series')expect(entries.find((entry) => entry.id === 'visualizations')?.content).toContain('### Rendering visualizations')+ expect(entries.find((entry) => entry.id === 'urls')?.content).toContain('### URL patterns')expect(entries.find((entry) => entry.id === 'feedback')?.content).toContain('### Sharing feedback on PostHog')@@ -294,8 +296,9 @@ describe('InstructionsFormatter', () => {renderUiEnabled: false,}- expect(formatter.buildClaudeExecHelpEntries(ctx).map((entry) => entry.id)).toEqual([+ expect(formatter.buildClaudeExecLearnGuides(ctx).map((entry) => entry.id)).toEqual(['analytics',+ 'urls','feedback',])const result = formatter.buildClaudeExecCommandReference(ctx)@@ -303,6 +306,27 @@ describe('InstructionsFormatter', () => {expect(result).not.toContain('- visualizations:')expect(result).toContain('- feedback:')})++ it('keeps built-in topics but omits skill commands when skills are disabled', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildClaudeExecCommandReference(fullCtx, { skillsEnabled: false })++ expect(result).toContain('- analytics:')+ expect(result).toContain('learn <topic...> - load one or more learning topics')+ expect(result).not.toContain('learn skills')+ expect(result).not.toContain('learn posthog:<skill>')+ })++ it('keeps URL patterns inline when learn is unavailable', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildClaudeExecCommandReference(fullCtx, {+ learnEnabled: false,+ skillsEnabled: false,+ })++ expect(result).toContain('### URL patterns')+ expect(result).not.toContain('- urls:')+ })})describe('metric discovery gating (data catalog flag)', () => {@@ -319,7 +343,7 @@ describe('InstructionsFormatter', () => {{name: 'analytics learn topic content',render: (formatter, ctx) =>- formatter.buildClaudeExecHelpEntries(ctx).find((entry) => entry.id === 'analytics')!.content,+ formatter.buildClaudeExecLearnGuides(ctx).find((entry) => entry.id === 'analytics')!.content,mustPrecede: ['### Retrieving data', '#### Schema-first workflow'],},{@@ -353,7 +377,7 @@ describe('InstructionsFormatter', () => {it('advertises governed metrics in the analytics topic description only when the catalog exists', () => {const formatter = new InstructionsFormatter()const analyticsDescription = (ctx: InstructionsContext): string =>- formatter.buildClaudeExecHelpEntries(ctx).find((entry) => entry.id === 'analytics')!.description+ formatter.buildClaudeExecLearnGuides(ctx).find((entry) => entry.id === 'analytics')!.descriptionexpect(analyticsDescription({ ...fullCtx, dataCatalogEnabled: true })).toContain('governed metrics')expect(analyticsDescription(fullCtx)).toBe('Query or analyze PostHog data, metrics, and events.')})diff --git a/services/mcp/tests/unit/project-skill-catalog.test.ts b/services/mcp/tests/unit/project-skill-catalog.test.tsnew file mode 100644index 000000000000..da97b2db9d9f--- /dev/null+++ b/services/mcp/tests/unit/project-skill-catalog.test.ts@@ -0,0 +1,180 @@+import { describe, expect, it, vi } from 'vitest'++import { PostHogApiError } from '@/lib/errors'+import { ProjectSkillCatalog } from '@/skills/project-skill-catalog'+import type { Context } from '@/tools/types'++type RequestFn = (args: { method: string; path: string; query?: unknown }) => Promise<unknown>++function makeContext(request: RequestFn): Context {+ return {+ api: { request },+ stateManager: { getProjectId: vi.fn().mockResolvedValue(12) },+ } as unknown as Context+}++const SKILL_PAYLOAD = {+ body: '# Retention\nHow to analyze retention.',+ description: 'Find where users stop returning.',+ files: [],+}++describe('ProjectSkillCatalog', () => {+ it('memoizes a skill fetch so repeated reads make one request', async () => {+ const request = vi.fn(async () => SKILL_PAYLOAD)+ const catalog = new ProjectSkillCatalog(makeContext(request))++ await catalog.read('retention-analysis')+ await catalog.read('retention-analysis')++ expect(request).toHaveBeenCalledTimes(1)+ })++ it('dedupes concurrent file reads by memoizing the in-flight promise', async () => {+ const request = vi.fn(async ({ path }: { path: string }) => {+ if (path.includes('/files/')) {+ return { path: 'reference.md', content: 'body', content_type: 'text/markdown' }+ }+ return SKILL_PAYLOAD+ })+ const catalog = new ProjectSkillCatalog(makeContext(request))++ // Both calls start before either resolves — only a promise-level memo dedupes this.+ await Promise.all([+ catalog.read('retention-analysis', 'reference.md'),+ catalog.read('retention-analysis', 'reference.md'),+ ])++ expect(request).toHaveBeenCalledTimes(1)+ })++ it('retries after a rejection because the failed memo entry is evicted', async () => {+ let calls = 0+ const request = vi.fn(async () => {+ calls += 1+ if (calls === 1) {+ throw new Error('transient')+ }+ return SKILL_PAYLOAD+ })+ const catalog = new ProjectSkillCatalog(makeContext(request))++ await expect(catalog.read('retention-analysis')).rejects.toThrow('transient')+ await catalog.read('retention-analysis')++ expect(request).toHaveBeenCalledTimes(2)+ })++ it('shares one list fetch between describe() and listNames()', async () => {+ const request = vi.fn(async () => ({+ count: 1,+ results: [{ name: 'retention-analysis', description: 'Find where users stop returning.' }],+ }))+ const catalog = new ProjectSkillCatalog(makeContext(request))++ const [descriptions, list] = await Promise.all([catalog.describe(['retention-analysis']), catalog.listNames()])++ expect(request).toHaveBeenCalledTimes(1)+ expect(descriptions.get('retention-analysis')).toBe('Find where users stop returning.')+ expect(list.names).toEqual(['retention-analysis'])+ })++ // A truncated listing (>PROJECT_SKILL_LIST_LIMIT) omits skills sorting past the cap; without the+ // exact-name fallback `learn -d` misreports a real skill as unknown.+ it.each([+ ['resolves a real skill past the list cap', 'deep-skill', 'Past the list cap.'],+ ['omits a genuinely unknown name so it renders unknown', 'ghost-skill', undefined],+ ])('describe on a truncated listing %s', async (_label, name, expected) => {+ const request = vi.fn(async ({ path, query }: { path: string; query?: any }) => {+ if (path.endsWith('/llm_skills/')) {+ // 500 skills exist but only the first page is returned → truncated listing.+ return query.offset === 0+ ? { count: 500, results: [{ name: 'listed-skill', description: 'In the listing.' }] }+ : { count: 500, results: [] }+ }+ if (path.includes('/llm_skills/name/')) {+ if (path.includes('deep-skill')) {+ return { name: 'deep-skill', body: '', description: 'Past the list cap.', files: [] }+ }+ throw new PostHogApiError({ status: 404, statusText: 'Not Found', body: '', url: path, method: 'GET' })+ }+ throw new Error(`unexpected request: ${path}`)+ })+ const catalog = new ProjectSkillCatalog(makeContext(request))++ const descriptions = await catalog.describe([name])++ expect(descriptions.get(name)).toBe(expected)+ })++ it('describe makes no exact-name fetch when the listing is complete', async () => {+ const request = vi.fn(async ({ path }: { path: string }) => {+ if (path.endsWith('/llm_skills/')) {+ return { count: 1, results: [{ name: 'listed-skill', description: 'In the listing.' }] }+ }+ throw new Error(`unexpected request: ${path}`)+ })+ const catalog = new ProjectSkillCatalog(makeContext(request))++ const descriptions = await catalog.describe(['listed-skill', 'missing-skill'])++ expect(descriptions.get('listed-skill')).toBe('In the listing.')+ // Complete listing → a miss is authoritative; no exact-name endpoint round-trip.+ expect(descriptions.has('missing-skill')).toBe(false)+ expect(request).toHaveBeenCalledTimes(1)+ })++ 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)+ })+})diff --git a/services/mcp/tests/unit/skill-archive-cache.test.ts b/services/mcp/tests/unit/skill-archive-cache.test.tsnew file mode 100644index 000000000000..915938c4b503--- /dev/null+++ b/services/mcp/tests/unit/skill-archive-cache.test.ts@@ -0,0 +1,186 @@+import { strToU8, zipSync } from 'fflate'+import { describe, expect, it, vi } from 'vitest'++import type { RedisLike } from '@/hono/cache/RedisCache'+import { SkillArchiveCache, type SkillArchiveFetchResult } from '@/hono/cache/SkillArchiveCache'+import { SkillCatalogService } from '@/hono/skill-catalog-service'++interface MockRedis extends RedisLike {+ store: Map<string, string>+}++function makeRedis(): MockRedis {+ const store = new Map<string, string>()+ return {+ store,+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {+ if (args.includes('NX') && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ }),+ del: vi.fn(async (...keys: string[]) => keys.filter((key) => store.delete(key)).length),+ scan: vi.fn(async () => ['0', []] as [string, string[]]),+ incr: vi.fn(async () => 1),+ expire: vi.fn(async () => 1),+ ttl: vi.fn(async () => -1),+ }+}++function makeArchive(seed = 'sample'): Uint8Array {+ return zipSync({+ [`${seed}/SKILL.md`]: strToU8(+ `---\nname: ${seed}\ndescription: Sample skill for tests.\n---\n\n# ${seed}\n\nUse the ${seed}.`+ ),+ })+}++function downloaded(bytes: Uint8Array = makeArchive(), etag?: string): SkillArchiveFetchResult {+ return { status: 'downloaded', bytes, etag }+}++const BYTES_KEY = 'mcp:shared-blob:product-skills:bytes'+const FRESH_KEY = 'mcp:shared-blob:product-skills:fresh'+const ETAG_KEY = 'mcp:shared-blob:product-skills:etag'++describe('SkillArchiveCache', () => {+ it('shares a downloaded archive through Redis and reuses fresh bytes', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const first = new SkillArchiveCache(redis, { fetchArchive })+ const second = new SkillArchiveCache(redis, { fetchArchive })++ await expect(first.loadOrRefresh()).resolves.toMatchObject({ result: 'cold_refresh' })+ await expect(second.loadOrRefresh()).resolves.toMatchObject({ result: 'fresh_hit' })+ expect(fetchArchive).toHaveBeenCalledTimes(1)+ })++ it('isolates custom archive URLs from the published bundle cache', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const first = new SkillArchiveCache(redis, { archiveUrl: 'http://localhost/skills.zip?v=one', fetchArchive })+ const second = new SkillArchiveCache(redis, { archiveUrl: 'http://localhost/skills.zip?v=two', fetchArchive })++ await expect(first.loadOrRefresh()).resolves.toMatchObject({ result: 'cold_refresh' })+ await expect(second.loadOrRefresh()).resolves.toMatchObject({ result: 'cold_refresh' })+ expect(first.cacheKey).not.toBe(second.cacheKey)+ expect(fetchArchive).toHaveBeenCalledTimes(2)+ })++ it('serves stale bytes immediately while one writer refreshes in the background', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive, freshSeconds: 0 })+ await cache.loadOrRefresh()++ await expect(cache.loadOrRefresh()).resolves.toMatchObject({ result: 'stale_hit' })+ await vi.waitFor(() => expect(fetchArchive).toHaveBeenCalledTimes(2))+ })++ it('revalidates a stale archive with If-None-Match and reuses cached bytes on 304', async () => {+ const redis = makeRedis()+ const archive = makeArchive()+ const fetchArchive = vi.fn(+ async (_url: string, etag?: string): Promise<SkillArchiveFetchResult> =>+ etag ? { status: 'not_modified' } : downloaded(archive, 'etag-v1')+ )+ const cache = new SkillArchiveCache(redis, { fetchArchive })++ expect((await cache.loadOrRefresh()).result).toBe('cold_refresh')+ const originalBytes = redis.store.get(BYTES_KEY)+ expect(redis.store.get(ETAG_KEY)).toBe('etag-v1')++ // Expire the soft-TTL so the next load revalidates in the background.+ redis.store.set(FRESH_KEY, String(Date.now() - 1))++ const stale = await cache.loadOrRefresh()+ expect(stale.result).toBe('stale_hit')+ expect(stale.bytes).toEqual(archive)++ await vi.waitFor(() => {+ // Refresh sent the stored validator and freshness was bumped in place.+ expect(fetchArchive).toHaveBeenCalledWith(expect.any(String), 'etag-v1')+ expect(Number(redis.store.get(FRESH_KEY))).toBeGreaterThan(Date.now())+ })++ // The 304 skipped the download and left the cached bytes untouched.+ expect(fetchArchive.mock.calls.filter(([, sent]) => sent === undefined)).toHaveLength(1)+ expect(redis.store.get(BYTES_KEY)).toBe(originalBytes)+ })++ it('replaces cached bytes and etag when revalidation returns a new archive', async () => {+ const redis = makeRedis()+ const first = makeArchive('first')+ const second = makeArchive('second')+ const fetchArchive = vi.fn(+ async (_url: string, etag?: string): Promise<SkillArchiveFetchResult> =>+ etag ? downloaded(second, 'etag-v2') : downloaded(first, 'etag-v1')+ )+ const cache = new SkillArchiveCache(redis, { fetchArchive })++ expect((await cache.loadOrRefresh()).result).toBe('cold_refresh')+ redis.store.set(FRESH_KEY, String(Date.now() - 1))++ expect((await cache.loadOrRefresh()).result).toBe('stale_hit')++ await vi.waitFor(() => expect(redis.store.get(ETAG_KEY)).toBe('etag-v2'))+ expect(redis.store.get(BYTES_KEY)).toBe(Buffer.from(second).toString('base64'))++ const fresh = await cache.loadOrRefresh()+ expect(fresh.result).toBe('fresh_hit')+ expect(fresh.bytes).toEqual(second)+ })++ it('never sends If-None-Match when the server stored no validator', async () => {+ const redis = makeRedis()+ // Server returns no etag, so nothing is stored to revalidate against.+ const fetchArchive = vi.fn(async (_url: string, _etag?: string) => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive })++ expect((await cache.loadOrRefresh()).result).toBe('cold_refresh')+ expect(redis.store.has(ETAG_KEY)).toBe(false)++ redis.store.set(FRESH_KEY, String(Date.now() - 1))+ expect((await cache.loadOrRefresh()).result).toBe('stale_hit')++ await vi.waitFor(() => expect(fetchArchive).toHaveBeenCalledTimes(2))+ for (const [, sentEtag] of fetchArchive.mock.calls) {+ expect(sentEtag).toBeUndefined()+ }+ })++ it('does not fail core startup when the archive is unavailable on a cold cache', async () => {+ const service = new SkillCatalogService(makeRedis(), {+ fetchArchive: vi.fn(async () => {+ throw new Error('offline')+ }),+ })+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)++ await expect(service.warmup()).resolves.toBeUndefined()+ expect(service.getCatalog()).toBeUndefined()+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('continuing without refreshed skills'),+ expect.any(Error)+ )+ consoleError.mockRestore()+ })++ it('keeps the last valid catalog when a refreshed archive is corrupt', async () => {+ const redis = makeRedis()+ const service = new SkillCatalogService(redis, { fetchArchive: vi.fn(async () => downloaded()) })+ await service.warmup()+ const original = service.getCatalog()+ redis.store.set(BYTES_KEY, Buffer.from('not a zip').toString('base64'))+ redis.store.set(FRESH_KEY, String(Date.now() + 60_000))+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)++ await service.revalidate()++ expect(service.getCatalog()).toBe(original)+ expect(consoleError).toHaveBeenCalled()+ consoleError.mockRestore()+ })+})diff --git a/services/mcp/tests/unit/skill-catalog.test.ts b/services/mcp/tests/unit/skill-catalog.test.tsnew file mode 100644index 000000000000..da86e960e5fb--- /dev/null+++ b/services/mcp/tests/unit/skill-catalog.test.ts@@ -0,0 +1,383 @@+import { strToU8, zipSync } from 'fflate'+import { describe, expect, it, vi } from 'vitest'++import type { ProjectSkillCatalog } from '@/skills/project-skill-catalog'+import { LEARN_OUTPUT_CHAR_LIMIT, SkillCatalog } from '@/skills/skill-catalog'+import { ExecLearnCatalog } from '@/tools/exec-learn'++function makeArchive(files: Record<string, string>): Uint8Array {+ return zipSync(Object.fromEntries(Object.entries(files).map(([path, content]) => [path, strToU8(content)])))+}++function makeSkill(name: string, description: string, body: string): string {+ return `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}`+}++function makeCatalog(): SkillCatalog {+ return SkillCatalog.fromZip(+ makeArchive({+ 'retention-analysis/SKILL.md': makeSkill(+ 'retention-analysis',+ 'Find where users stop returning. 日本語のガイド。',+ '# Retention analysis\n\nQuery weekly retention cohorts.'+ ),+ 'retention-analysis/references/functions.md':+ '# Available functions\n\nUse retention cohorts with dateDiff.',+ 'retention-analysis/scripts/run.ts': 'const privateSearchToken = "unindexed-token"',+ 'funnels/SKILL.md': makeSkill(+ 'funnels',+ 'Analyze conversion funnels.',+ '# Funnels\n\nBuild a conversion funnel.'+ ),+ })+ )+}++function makeProjectSkills(overrides: Partial<Record<string, unknown>> = {}): ProjectSkillCatalog {+ return {+ listNames: vi.fn(async () => ({ count: 1, names: ['team-conventions'], truncated: false })),+ describe: vi.fn(async () => new Map([['team-conventions', 'Team-specific conventions.']])),+ searchResults: vi.fn(async () => []),+ read: vi.fn(async () => 'project skill'),+ searchFile: vi.fn(async () => 'project file match'),+ readLines: vi.fn(async () => 'project lines'),+ ...overrides,+ } as unknown as ProjectSkillCatalog+}++describe('SkillCatalog and exec learn', () => {+ it('lists qualified names without descriptions and ranks full-text matches deterministically', async () => {+ const catalog = makeCatalog()+ const learn = new ExecLearnCatalog([], { posthog: catalog })++ expect(JSON.parse(await learn.execute('skills'))).toEqual({+ posthog: {+ available: true,+ count: 2,+ listed: 2,+ truncated: false,+ skills: ['posthog:funnels', 'posthog:retention-analysis'],+ },+ project: {+ available: false,+ reason: 'Project skills are temporarily unavailable.',+ },+ })+ const result = await learn.execute('-s weekly retention')+ expect(result).toContain('## posthog:retention-analysis')+ expect(result).toContain('SKILL.md:8: Query weekly retention cohorts.')+ expect(result).toContain('[Project skills unavailable: Project skills are temporarily unavailable.]')+ await expect(learn.execute('project:team-skill')).rejects.toThrow('Project skills are temporarily unavailable')+ })++ it('indexes every file path and Markdown content but not script contents', () => {+ const catalog = makeCatalog()++ expect(catalog.search('functions.md')).toContain('retention-analysis')+ expect(catalog.search('dateDiff')).toContain('retention-analysis')+ expect(catalog.search('run.ts')).toContain('retention-analysis')+ expect(catalog.search('unindexed-token')).toBe('No skills matched "unindexed-token".')+ expect(() => catalog.searchFile('retention-analysis', 'scripts/run.ts', 'const')).toThrow(+ 'Only Markdown contents are searchable'+ )+ })++ it('returns the rendered skill with a manifest and supports scoped reads', async () => {+ const catalog = makeCatalog()+ const learn = new ExecLearnCatalog([], { posthog: catalog })+ const result = catalog.read('retention-analysis')++ expect(result).toContain('Files:')+ expect(result).toContain('- SKILL.md (8 lines,')+ expect(result).toContain('- references/functions.md (3 lines,')+ expect(result).toContain('# Retention analysis')+ expect(result).not.toContain('name: retention-analysis')+ expect(catalog.searchFile('retention-analysis', 'references/functions.md', 'dateDiff')).toContain(+ '3: Use retention cohorts with dateDiff.'+ )+ expect(catalog.readLines('retention-analysis', 'references/functions.md', 1, 2)).toContain(+ '1: # Available functions\n2:'+ )+ expect(await learn.execute('posthog:retention-analysis references/functions.md -s dateDiff')).toContain(+ '3: Use retention cohorts with dateDiff.'+ )+ expect(await learn.execute('posthog:retention-analysis references/functions.md --lines 1:2')).toContain(+ '1: # Available functions\n2:'+ )+ })++ it('merges PostHog and project search results by relevance and supports Unicode and quoted paths', async () => {+ const projectSkills = makeProjectSkills({+ searchResults: vi.fn(async (query: string) => [+ {+ identifier: 'project:conversion-playbook',+ description: 'Team conversion playbook.',+ snippets: [{ path: 'SKILL.md', line: 4, text: 'Our conversion funnel.' }],+ // A name match on "conversion" must outrank a PostHog body-only match.+ score: query.includes('conversion') ? 3300 : 900,+ },+ ]),+ })+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog(), project: projectSkills })++ const listed = JSON.parse(await learn.execute('skills'))+ const ranked = await learn.execute('-s conversion')+ const unicodeResult = await learn.execute('-s 日本語')++ expect(listed.project).toEqual({+ available: true,+ count: 1,+ listed: 1,+ truncated: false,+ skills: ['project:team-conventions'],+ })+ // Regression guard: the name-matching project skill outranks PostHog's `funnels`,+ // which only matches on description/body — the old code always ordered PostHog first.+ expect(ranked.indexOf('## project:conversion-playbook')).toBeLessThan(ranked.indexOf('## posthog:funnels'))+ expect(ranked.indexOf('## posthog:funnels')).toBeGreaterThan(-1)+ expect(unicodeResult).toContain('## posthog:retention-analysis')+ expect(unicodeResult).toContain('## project:conversion-playbook')+ expect(projectSkills.searchResults).toHaveBeenLastCalledWith('日本語')+ await expect(+ learn.execute('project:team-conventions "references/team guide.md" -s weekly retention')+ ).resolves.toBe('project file match')+ expect(projectSkills.searchFile).toHaveBeenCalledWith(+ 'team-conventions',+ 'references/team guide.md',+ 'weekly retention'+ )+ })++ it('returns an outline for an oversized reference and rejects unsafe paths', () => {+ const largeBody = `# Function catalog\n\n${'function signature details\n'.repeat(2_000)}\n## Examples\n`+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'querying-data/SKILL.md': makeSkill('querying-data', 'Query product data.', '# Querying data'),+ 'querying-data/references/functions.md': largeBody,+ })+ )++ const result = catalog.read('querying-data', 'references/functions.md')+ expect(result.length).toBeLessThanOrEqual(LEARN_OUTPUT_CHAR_LIMIT)+ expect(result).toContain('This file is too large to return in full.')+ expect(result).toContain('1: # Function catalog')+ expect(result).toContain('2004: ## Examples')+ expect(() => catalog.read('querying-data', '../SKILL.md')).toThrow('Unsafe skill path')+ })++ it('rejects unsafe archive entries before exposing them', () => {+ const archive = makeArchive({+ '../escape/SKILL.md': makeSkill('escape', 'Unsafe archive.', '# Escape'),+ })++ expect(() => SkillCatalog.fromZip(archive)).toThrow('Unsafe skill archive path')+ })++ it.each([+ ['analyzing', 'trends', true], // analyzing → analy ⊂ "analysis"+ ['funnels', 'conversion', true], // funnels → funnel+ ['sessions', 'assessment', false], // min-5 guard: "sessions" must not reach "assessing"+ ])('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.'+ ),+ 'conversion/SKILL.md': makeSkill(+ 'conversion',+ 'Chart product metrics over time.',+ '# Conversion\n\nBuild a conversion funnel.'+ ),+ 'assessment/SKILL.md': makeSkill(+ 'assessment',+ 'Review internal controls.',+ '# Assessment\n\nStart by assessing exposure.'+ ),+ })+ )++ if (shouldMatch) {+ expect(catalog.search(query)).toContain(skill)+ } else {+ expect(catalog.search(query)).not.toContain(skill)+ }+ })++ it('excludes SKILL.md frontmatter from snippets while keeping raw line numbers', () => {+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'cohort-guide/SKILL.md': makeSkill(+ 'cohort-guide',+ 'Analyze retention cohorts.',+ '# Cohort guide\n\nAnalyze retention cohorts weekly.'+ ),+ })+ )++ const output = catalog.search('retention cohorts')+ // The `description:` frontmatter line (raw line 3) must not surface as a snippet — the+ // description already prints on its own — and the body match keeps its real line number.+ expect(output).not.toContain('description:')+ expect(output).toContain('SKILL.md:8: Analyze retention cohorts weekly.')+ })++ it('exposes descending scores from searchResults', () => {+ const catalog = SkillCatalog.fromZip(+ makeArchive({+ 'funnels/SKILL.md': makeSkill(+ 'funnels',+ 'Analyze conversion funnels.',+ '# Funnels\n\nBuild a conversion funnel.'+ ),+ 'trends/SKILL.md': makeSkill(+ 'trends',+ 'Chart metrics over time.',+ '# Trends\n\nA funnel is not a trend.'+ ),+ })+ )++ const results = catalog.searchResults('funnel')+ expect(results.map((result) => result.identifier)).toEqual(['funnels', 'trends'])+ expect(results[0]!.score!).toBeGreaterThan(results[1]!.score!)+ })++ it('offers a read and line-range recovery hint when a file search finds nothing', () => {+ const output = makeCatalog().searchFile('retention-analysis', 'references/functions.md', 'nonexistentxyz')++ expect(output).toContain('No matches for "nonexistentxyz" in retention-analysis/references/functions.md.')+ expect(output).toContain('Read it with `learn retention-analysis references/functions.md` (3 lines,')+ expect(output).toContain('--lines <start>:<end>')+ })++ it('describes a batch of qualified names, tolerating unknown names without failing the batch', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog(), project: makeProjectSkills() })++ const output = await learn.execute('-d posthog:funnels posthog:missing project:team-conventions')++ expect(output).toBe(+ 'posthog:funnels: Analyze conversion funnels.\n' ++ '[unknown skill: posthog:missing]\n' ++ 'project:team-conventions: Team-specific conventions.'+ )+ })++ it('caps the batch describe at 20 skills', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() })+ const names = Array.from({ length: 21 }, (_, index) => `posthog:s${index}`).join(' ')++ await expect(learn.execute(`-d ${names}`)).rejects.toThrow('at most 20 skills')+ })++ it('reads several skills in one command', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() })++ const output = await learn.execute('posthog:funnels posthog:retention-analysis')++ expect(output).toContain('Skill: posthog:funnels')+ expect(output).toContain('Skill: posthog:retention-analysis')+ })++ it('reads several files of one skill in one command', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() })++ const output = await learn.execute('posthog:retention-analysis SKILL.md references/functions.md')++ expect(output).toContain('File: posthog:retention-analysis/SKILL.md')+ expect(output).toContain('File: posthog:retention-analysis/references/functions.md')+ })++ it('rejects a scoped flag combined with multiple paths', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() })++ await expect(+ learn.execute('posthog:retention-analysis SKILL.md references/functions.md --lines 1:2')+ ).rejects.toThrow('Usage: learn <source>:<skill>')+ })++ it.each([+ [1, true],+ [40, false],+ ])('recovers from a zero-hit search (project count=%i, inline=%s)', async (count, inline) => {+ const projectSkills = makeProjectSkills({+ searchResults: vi.fn(async () => []),+ listNames: vi.fn(async () => ({ count, names: ['team-conventions'], truncated: false })),+ })+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog(), project: projectSkills })++ const output = await learn.execute('-s zzzznomatch')++ expect(output).toContain('No skills matched "zzzznomatch".')+ expect(output).toContain('None of the query words appear in any skill.')+ if (inline) {+ expect(output).toContain('Available skills:')+ expect(output).toContain('posthog: funnels, retention-analysis')+ expect(output).toContain('project: team-conventions')+ } else {+ expect(output).toContain('2 posthog and 40 project skills exist')+ expect(output).toContain('learn skills')+ }+ })+ describe('skill invocation reporting', () => {+ it('reports successful loads with source, path, and read kind — never searches or describes', async () => {+ const invocations: unknown[] = []+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog(), project: makeProjectSkills() }, (inv) =>+ invocations.push(inv)+ )++ await learn.execute('posthog:retention-analysis')+ await learn.execute('posthog:retention-analysis references/functions.md')+ await learn.execute('project:team-conventions notes.md --lines 1:5')+ await learn.execute('-s retention')+ await learn.execute('-d posthog:funnels')+ await learn.execute('skills')++ expect(invocations).toEqual([+ { source: 'posthog', skill: 'retention-analysis', path: undefined, readKind: 'skill' },+ { source: 'posthog', skill: 'retention-analysis', path: 'references/functions.md', readKind: 'file' },+ { source: 'project', skill: 'team-conventions', path: 'notes.md', readKind: 'file_lines' },+ ])+ })++ it('reports one invocation per file in a successful multi-file batch', async () => {+ const invocations: unknown[] = []+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() }, (inv) => invocations.push(inv))++ await learn.execute('posthog:retention-analysis references/functions.md scripts/run.ts')++ expect(invocations).toEqual([+ { source: 'posthog', skill: 'retention-analysis', path: 'references/functions.md', readKind: 'file' },+ { source: 'posthog', skill: 'retention-analysis', path: 'scripts/run.ts', readKind: 'file' },+ ])+ })++ it('fires no invocations when a file batch fails on one path', async () => {+ const invocations: unknown[] = []+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() }, (inv) => invocations.push(inv))++ // The command returns no content, so a successful sibling must not report.+ await expect(+ learn.execute('posthog:retention-analysis references/functions.md missing.md')+ ).rejects.toThrow()+ expect(invocations).toEqual([])+ })++ it('fires no invocations when a multi-skill batch fails on one skill', async () => {+ const invocations: unknown[] = []+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() }, (inv) => invocations.push(inv))++ await expect(learn.execute('posthog:retention-analysis posthog:missing')).rejects.toThrow()+ expect(invocations).toEqual([])+ })++ it('keeps learn working when the listener throws', async () => {+ const learn = new ExecLearnCatalog([], { posthog: makeCatalog() }, () => {+ throw new Error('capture failed')+ })++ await expect(learn.execute('posthog:funnels')).resolves.toContain('Build a conversion funnel.')+ })+ })+})