: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): re-land skill discovery via exec learn behind a flag (#95434)
Jake Ruthee8ddfdd6ab1
diff --git a/.agents/skills/writing-evals/SKILL.md b/.agents/skills/writing-evals/SKILL.mdindex 565cf011d4cb..ec92426e0894 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 b47284d1fa65..e106d348a217 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -77,6 +77,49 @@ giving it richer context about PostHog's data model.Primarily oriented toward coding agents (PostHog Desktop, 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, so the final `exec` input schema has a test budget below that limit.+Keep only guidance needed on nearly every call inline, including the compact tool-domain index.+Everything else belongs in the `learn` catalog: Claude web and desktop guides, and, behind the `mcp-exec-skills` flag, PostHog and project skills.+Skill names, descriptions, and bodies never go into the tool schema; agents discover them with `learn -s "<query>"` and read them with `learn <source>:<skill> [path]`.+Project skill search applies the caller's per-skill read permissions before ranking and limiting results; restricted skills contribute no metadata or excerpts.+The search endpoint uses dedicated burst and sustained budgets at the standard API rates (480 requests/minute and 4,800/hour). Personal API keys have separate budgets; OAuth and browser sessions share a budget per user. Exceeding either budget returns HTTP 429 with `Retry-After`, before the search runs.+The project skill API defaults to 8,000-character body pages. For `learn`, MCP requests up to 1,000,000 characters in one call, covering the API's 1 MB UTF-8 body limit, and rejects oversized or incomplete bodies before searching or formatting them. The separate 44,000-character display budget directs agents to search or read line ranges for larger files.++File reads and scoped searches scan lines incrementally. Search stops after 50 matches or when the display budget is full, preserving two context lines on either side where they fit. Heading outlines are bounded while being built, and oversized line ranges fail with a request to narrow the range. Files with many short lines do not require an array containing every line.+Do not trim endpoint serializers or generated tool schemas to meet the budget; they stay the source of truth for `info` and `schema`.++The eval runner's `--skill-delivery exec` mode removes bundled skills and defaults cases without an explicit interaction origin to the `eval` MCP consumer, which supports skill `learn`. Explicit case origins take precedence in both delivery modes. Bundled mode leaves unspecified origins unchanged.+The runner applies the selected delivery mode to both Python's sandbox-provisioning flag override and MCP's flag override. Bundled mode preserves native skills unless a case explicitly disables them; exec mode removes them. Compare the `expected_skill_loaded` and `skill_loaded_before_tool` scores: a completed eval run can report `PASS` despite zero scores unless `--fail-under` sets a score threshold.+Bundled-mode evals explicitly disable `mcp-exec-skills` through the dev/test process override, which skips skill-catalog warmup and polling. Exec-mode evals allow 120 seconds for MCP startup, covering the 60-second warmup budget plus an in-flight download and development build; bundled mode keeps the 30-second startup limit. Production feature-flag evaluation does not control this process lifecycle.++## Rolling out MCP skill discovery++Deploy the Django skills API, task launcher, and MCP changes before enabling `mcp-exec-skills`.+Create or reuse a boolean flag with that exact key in the analytics project used by the two services; start disabled and enable a narrow user or organization condition first.+A missing flag evaluates as off. Development `FEATURE_FLAG_OVERRIDES` do not enable production behavior.++Verify the published skills archive loads, then start a new MCP session and sandbox task for an enabled user.+Exercise `learn -s`, a qualified skill read, and a product call, and check that a disabled user retains the prior behavior.+The `plugin` and `posthog-code` consumers remain excluded regardless of the flag.+Monitor archive validation errors, catalog size, MCP memory, and task failures before expanding the release condition.++To roll back access, disable the flag and start fresh sessions/tasks. This does not restore skills already removed from an existing sandbox.+Background cache behavior during rollback is described below.++## Shared skill archive cache++Each MCP process holds a parsed catalog in memory. Redis stores immutable archive bytes under a SHA-256 key and one JSON pointer containing the current SHA, ETag, and last successful upstream validation time. Writers store the bytes before replacing the pointer; readers fetch the named blob and verify its hash before using it. Polling an unchanged version never transfers the archive bytes.++For rollout and rollback, disabling `mcp-exec-skills` blocks caller access to product and project skills but does not unload the production catalog or stop archive polling. Stopping background catalog work requires a deployment change; restarting the same deployment reloads the catalog. The dev/test override described above does not apply in production.++The `v2` keys are separate from the earlier split-key layout, so a rolling deploy starts a new cache without changing the old processes' data. A failed write leaves the previous generation readable. Missing blobs trigger a full download; a 304 refresh extends the referenced blob's TTL and updates the pointer only if that pointer is still current. Old archive generations expire after the 30-day archive TTL. The context-mill slim manifest uses the same helper with its own namespace and seven-day TTL; its resource bodies remain keyed by URI.++The shared archive is checked for upstream changes after ten minutes. Use `mcp_skill_archive_last_validated_timestamp_seconds` to detect validation outages, including across process restarts. A successful 304 advances this timestamp. `mcp_skill_catalog_age_seconds` instead measures time since parsing and can grow while an unchanged archive remains healthy.++A candidate alert expression is `time() - mcp_skill_archive_last_validated_timestamp_seconds > 1800`, sustained for five minutes. Zero means the process has not observed a successful shared validation. Pair this with `mcp_skill_archive_events_total{result="error"}` and `mcp_skill_catalog_skills` when investigating. This metric does not prove that each process has adopted the latest archive. The alert must be configured in the monitoring system; exposing the metric does not send notifications.+## SQL-first MCP: HogQL system tablesMost list/get endpoints exposed as MCP tools should have a corresponding HogQL system table.diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex 353b2c4f70c6..cef2def30286 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 ebbcdd582a4b..7e9a381a3111 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -13,6 +13,8 @@ from typing import TYPE_CHECKING, Any, Literalimport orjson+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN+from .acp_log import ParsedLog, parse_logfrom .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCasefrom .engines.base import EvalEngine@@ -437,9 +439,17 @@ 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.interaction_origin:sandbox_context = replace(sandbox_context, interaction_origin=original_case.interaction_origin)+ elif ctx.skill_delivery == "exec":+ sandbox_context = replace(sandbox_context, interaction_origin=EVAL_INTERACTION_ORIGIN)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)@@ -563,7 +573,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 6c4176a1d854..6777c75ab3e6 100644--- a/products/posthog_ai/eval_harness/config.py+++ b/products/posthog_ai/eval_harness/config.py@@ -52,11 +52,19 @@ 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.+ """+interaction_origin: str | None = None"""Surface to run the case as (e.g. ``"slack"``), for suites grading behavior that onlyexists on one surface. The agent server branches its system prompt on this, so setting it- is what makes a case exercise the real prompt instead of a copy. ``None`` runs the case- like a plain task, which is what every non-surface-specific suite wants."""+ is what makes a case exercise the real prompt instead of a copy. ``None`` uses the ``eval``+ origin in exec skill-delivery mode and leaves the origin unset in bundled mode."""setup: Callable[[CustomPromptSandboxContext], dict[str, Any]] | None = Field(default=None,diff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.mdindex 1d19acf1ceeb..10e879b43856 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 / 15051 / 15052, no `task-sandbox-*` containers, no Temporal dev server, and no Tailscale Funnel mappings left enabled on 443 / 8443 / 10000.+After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 18788 / 15051 / 15052, no `task-sandbox-*` containers, no Temporal dev server, and no Tailscale Funnel mappings left enabled on 443 / 8443 / 10000.A case can also own a sandbox the harness never created: a notebook python or duckdb cell provisions the notebook kernel through the notebook Temporal workflow.Nothing upstream reclaims it — the docker backend ignores `SandboxConfig.ttl_seconds`, and the sweeps below match agent containers by task id, which a kernel container's name never carries.diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.mdindex b9a48f51f08d..07b80913f194 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` | `TailscaleFunnel`. Modal only: enables Tailscale Funnel on the host services and resolves their 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: Tailscale Funnel comes 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 ea16227040aa..57dc21920048 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@@ -19,6 +19,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@@ -42,6 +44,7 @@ class HarnessOptions:case_filter: str | Noneagent_model: stragent_runtime: str+ skill_delivery: SkillDeliveryreasoning_effort: str | Nonemax_sandboxes: intteam_setup_concurrency: int@@ -113,6 +116,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,@@ -176,6 +188,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),@@ -185,6 +198,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")@@ -220,6 +234,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..1afc521473a5 100644--- a/products/posthog_ai/eval_harness/harness/context.py+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -6,12 +6,13 @@ 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-@dataclass+@dataclass(frozen=False)class EvalContext:"""Everything a suite function needs, assembled once per harness run.@@ -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 361b6416be38..83670d0639fb 100644--- a/products/posthog_ai/eval_harness/harness/demo_data.py+++ b/products/posthog_ai/eval_harness/harness/demo_data.py@@ -10,7 +10,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 CustomPromptSandboxContext, create_skill_isolation_environmentfrom ee.clickhouse.materialized_columns.columns import (backfill_materialized_columns,@@ -49,14 +49,25 @@ 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:_, 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 = None+ if disable_bundled_skills:+ # The sandbox reads this env var and clears its native skill directories+ # before the agent launches, so only MCP-delivered skills can satisfy the case.+ with self._django_db_blocker.unblock():+ sandbox_environment_id = create_skill_isolation_environment(+ team_id=team.id,+ user_id=user.id,+ name=f"Eval skill isolation: {case_label}",+ )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 6fc33adbe22a..3ae30d9b52e0 100644--- a/products/posthog_ai/eval_harness/harness/lifecycle.py+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -7,6 +7,7 @@ import loggingfrom collections.abc import Sequencefrom contextlib import AsyncExitStack, ExitStackfrom dataclasses import replace+from functools import partialfrom unittest.mock import patch@@ -19,6 +20,7 @@ from posthoganalytics import Posthogfrom posthog.ph_client import get_clientfrom products.tasks.backend.constants import (+ MCP_EXEC_SKILLS_FEATURE_FLAG,WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,)@@ -26,7 +28,13 @@ from products.tasks.backend.temporal.process_task.utils import get_reasoning_efffrom ..engines.base import EvalEnginefrom ..engines.registry import resolve_engine-from .cli import DEFAULT_ONE_SHOT_CONCURRENCY, MULTI_TURN_CASE_TIMEOUT_MULTIPLIER, HarnessOptions+from .cli import (+ DEFAULT_ONE_SHOT_CONCURRENCY,+ DEFAULT_SKILL_DELIVERY,+ MULTI_TURN_CASE_TIMEOUT_MULTIPLIER,+ HarnessOptions,+ SkillDelivery,+)from .context import EvalContextfrom .demo_data import SandboxedDemoData, ensure_demo_readyfrom .discovery import MULTI_TURN_MODULE_MARKER, EvalSuite, discover_suites@@ -41,9 +49,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 (@@ -68,8 +78,12 @@ FORCED_OFF_FEATURE_FLAGS = frozenset()-def eval_feature_enabled(key: str, *_args: object, **_kwargs: object) -> bool:+def eval_feature_enabled(+ key: str, *_args: object, skill_delivery: SkillDelivery = DEFAULT_SKILL_DELIVERY, **_kwargs: object+) -> bool:"""Stands in for `posthoganalytics.feature_enabled` so evals exercise flagged code paths."""+ if key == MCP_EXEC_SKILLS_FEATURE_FLAG:+ return skill_delivery == "exec"return key not in FORCED_OFF_FEATURE_FLAGS@@ -236,7 +250,24 @@ class SandboxedEvalHarness:self._stack.callback(start_llm_gateway(self._live_server.url, self.options.agent_model))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. DockerSandbox bind-mounts the built skills;+ # ModalSandbox bakes them into the image it builds from the local context,+ # so it wants no host path.+ 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@@ -244,10 +275,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)@@ -302,7 +329,13 @@ class SandboxedEvalHarness:if overrides:stack.enter_context(override_settings(**overrides))- stack.enter_context(patch.object(posthoganalytics, "feature_enabled", eval_feature_enabled))+ stack.enter_context(+ patch.object(+ posthoganalytics,+ "feature_enabled",+ partial(eval_feature_enabled, skill_delivery=self.options.skill_delivery),+ )+ )if Infra.SANDBOX in required:# Stale workflows from a prior run make the worker provision sandboxes for@@ -321,9 +354,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:@@ -350,6 +384,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 d91f62b32340..59ac1ebc7833 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 d9d652b87e40..8ff4ffb7bc55 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@@ -12,14 +15,19 @@ from django.conf import settingsfrom django.db import connectionsfrom products.posthog_ai.eval_harness.long_lived_subprocess import LongLivedSubprocessManager, SubprocessStartupError-from products.tasks.backend.facade.agents import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache+from products.tasks.backend.facade.agents import (+ ENV_LOCAL_SKILLS_HOST_PATH,+ MCP_EXEC_SKILLS_FEATURE_FLAG,+ 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()+_ZIP_FIXED_TIME = (2020, 1, 1, 0, 0, 0)def start_llm_gateway(live_server_url: str, agent_model: str) -> Callable[[], None]:@@ -91,7 +99,12 @@ def start_llm_gateway(live_server_url: str, agent_model: str) -> Callable[[], Noreturn 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).@@ -101,6 +114,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")@@ -121,17 +137,30 @@ 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).# revamped-py-notebooks gates the markdown notebook tools (create-markdown,# add-cell, update-cell, delete-cell, get, list-frames). It also *hides* the# legacy notebooks-create / notebooks-retrieve pair, which the two surfaces# being mutually exclusive makes unavoidable — an eval of the legacy tools- # needs its own lever, not this one.- "FEATURE_FLAG_OVERRIDES": json.dumps({"revamped-py-notebooks": True}),+ # needs its own lever, not this one. mcp-exec-skills follows the run's+ # skill delivery mode.+ "FEATURE_FLAG_OVERRIDES": json.dumps(+ {"revamped-py-notebooks": 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,@@ -139,6 +168,8 @@ def start_mcp_server(live_server_url: str) -> Callable[[], None]:cwd=mcp_dir,env=env,log_prefix="mcp",+ # Cover the 60-second skill warmup, an in-flight download, and the development build.+ readiness_timeout=120 if exec_skills_enabled else 30,)logger.info("MCP server ready on port %d", MCP_PORT)@@ -281,5 +312,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.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.pyindex 7d80a4a95793..e42a539ba52b 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py@@ -15,15 +15,19 @@ from parameterized import parameterizedfrom products.posthog_ai.eval_harness import runnerfrom products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCase-from products.posthog_ai.eval_harness.harness.cli import parse_args-from products.posthog_ai.eval_harness.harness.lifecycle import eval_feature_enabled+from products.posthog_ai.eval_harness.harness.cli import SkillDelivery, parse_args+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.discovery import EvalSuite+from products.posthog_ai.eval_harness.harness.lifecycle import SandboxedEvalHarness, eval_feature_enabledfrom products.posthog_ai.eval_harness.harness.live_server import EvalLiveServerfrom products.posthog_ai.eval_harness.harness.providers import ModalProviderStrategy, SandboxProviderStrategy+from products.posthog_ai.eval_harness.harness.reporting import ProgressReporterfrom products.tasks.backend.constants import (WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,)from products.tasks.backend.facade.agents import TurnPollResult+from products.tasks.backend.temporal.process_task.utils import mcp_exec_skills_env_varsclass _FakeWorkflowHandle:@@ -159,6 +163,30 @@ def test_eval_feature_enabled_leaves_dispatcher_flags_off(_name: str, flag: str,assert eval_feature_enabled(flag, distinct_id="distinct-1") is expected[email protected]("delivery", ["bundled", "exec"])[email protected]("origin", ["eval", "slack", None])+async def test_eval_run_preserves_bundled_skills_unless_exec_is_selected(+ delivery: SkillDelivery, origin: str | None+) -> None:+ harness = SandboxedEvalHarness(parse_args(["--skill-delivery", delivery]))+ environments: list[dict[str, str]] = []++ async def suite(ctx: EvalContext) -> None:+ task_context = SimpleNamespace(interaction_origin=origin, organization_id="org-1", distinct_id="user-1")+ environments.append(await asyncio.to_thread(mcp_exec_skills_env_vars, task_context))++ results = await harness._run_suites(+ [EvalSuite(domain="test", module_name="skill_delivery", fn_name="suite", fn=suite)],+ frozenset(),+ ProgressReporter(total_suites=1),+ )++ assert results[0].status == "passed", results[0].error+ expected = {"POSTHOG_CODE_DISABLE_BUNDLED_SKILLS": "1"} if delivery == "exec" and origin else {}+ assert environments == [expected]++@pytest.mark.asyncioasync def test_success_waits_for_workflow_cleanup_before_returning(monkeypatch: pytest.MonkeyPatch) -> None:handle = _FakeWorkflowHandle(complete_on_signal=False)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_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.pyindex 6036af93d231..e18797b933ee 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py@@ -2,20 +2,24 @@ from __future__ import annotationsimport sysimport json+import asynciofrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import Anyimport pytest-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockfrom products.posthog_ai.eval_harness import basefrom products.posthog_ai.eval_harness.acp_log import GenerationDescriptor, ParsedLog+from products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCasefrom products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary, NullCaseHooks+from products.posthog_ai.eval_harness.harness.cli import SkillDeliveryfrom products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResultfrom products.posthog_ai.eval_harness.harness.transcript import RunTranscriptfrom products.posthog_ai.eval_harness.scorers import ExitCodeZero+from products.tasks.backend.facade.agents import CustomPromptSandboxContextdef test_run_transcript_captures_both_streams_and_prints_its_path_last(@@ -228,3 +232,64 @@ def test_sandboxed_eval_run_adds_exit_code_scorer(monkeypatch: pytest.MonkeyPatcis_public=False,no_send_logs=True,)+++ "delivery,origin,has_original,expected_origin",+ [+ ("exec", None, True, "eval"),+ ("exec", None, False, "eval"),+ ("bundled", None, True, None),+ ("bundled", None, False, None),+ ("exec", "eval", True, "eval"),+ ("exec", "slack", True, "slack"),+ ("exec", "posthog_ai", True, "posthog_ai"),+ ("exec", "posthog-code", True, "posthog-code"),+ ("bundled", "slack", True, "slack"),+ ],+)+async def test_sandboxed_eval_skill_delivery_sets_the_agent_origin(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ delivery: SkillDelivery,+ origin: str | None,+ has_original: bool,+ expected_origin: str | None,+) -> None:+ monkeypatch.setattr(base, "build_case_dir", MagicMock(return_value=tmp_path))+ sandbox_context = CustomPromptSandboxContext(team_id=1, user_id=2)+ ctx = MagicMock(+ posthog_client=None,+ case_filter=None,+ skill_delivery=delivery,+ sandbox_slots=asyncio.Semaphore(1),+ team_setup_slots=asyncio.Semaphore(1),+ per_case_timeout_seconds=30,+ )+ ctx.demo_data.make_context.return_value = sandbox_context+ ctx.provider_strategy.keeps_sandboxes.return_value = False+ setup = MagicMock(return_value={"seeded": True})+ case = SandboxedEvalCase(name="ordinary-case", prompt="Run the task", interaction_origin=origin, setup=setup)+ run = base._SandboxedEvalRun(+ experiment_name="skill-delivery-test",+ cases=[case] if has_original else [],+ scorers=[],+ ctx=ctx,+ is_public=False,+ no_send_logs=True,+ )+ launch = AsyncMock(return_value=base.EvalCaseResult(artifacts=AgentArtifacts(exit_code=0)))+ monkeypatch.setattr(base, "run_eval_case", launch)+ monkeypatch.setattr(base, "reclaim_kernels", AsyncMock())++ _, seed = await run._run_sandbox_window(case, case if has_original else None)++ launched_context = launch.call_args.args[1]+ assert launched_context.interaction_origin == expected_origin+ assert ctx.demo_data.make_context.call_args.kwargs["disable_bundled_skills"] == (delivery == "exec")+ if has_original:+ assert setup.call_args.args[0].interaction_origin == expected_origin+ assert seed == {"seeded": True}+ else:+ assert seed == {}diff --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..73300a085eed--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py@@ -0,0 +1,73 @@+from __future__ import annotations++import os+import json+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"]+ overrides = json.loads(env["FEATURE_FLAG_OVERRIDES"])+ assert overrides["mcp-exec-skills"] is expected_flag_value+ assert start.call_args.kwargs.get("readiness_timeout", 30) == (120 if exec_skills_enabled else 30)+ # The skill delivery switch must not displace the overrides every eval run relies on.+ assert overrides["revamped-py-notebooks"] is True+ 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..d66b97617d61--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py@@ -0,0 +1,312 @@+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(_exec("query", "call execute-sql {}", "[]")), ExpectedSkillLoaded()),+ (_output(_exec("query", "call execute-sql {}", "[]")), SkillLoadedBeforeTool()),+ (_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.0+++ALTERNATE_SKILL = "debugging-experiments"+EXEC_WITH_ALTERNATE = skill_distribution_expectations(+ SKILL, ["execute-sql"], "exec", alternate_skills=[ALTERNATE_SKILL]+)+BUNDLED_WITH_ALTERNATE = skill_distribution_expectations(+ SKILL, ["execute-sql"], "bundled", alternate_skills=[ALTERNATE_SKILL]+)+++ "scorer",+ [ExpectedSkillDiscovered(), ExpectedSkillLoaded(), SkillLoadedBeforeTool()],+)+def test_exec_distribution_accepts_an_alternate_skill(scorer: Scorer) -> None:+ # A newer front-door skill that wraps the expected one satisfies the case, but only when listed.+ output = _output(+ _exec("search", 'learn -s "bias warning"', f'{{"name":"posthog:{ALTERNATE_SKILL}"}}'),+ _exec("load", f"learn posthog:{ALTERNATE_SKILL}", "# Debugging experiments"),+ _exec("query", "call execute-sql {}", "[]"),+ )+ assert _score(scorer, output, EXEC_WITH_ALTERNATE).score == 1.0+ assert _score(scorer, output, EXEC_EXPECTED).score == 0.0++[email protected]("scorer", [ExpectedSkillLoaded(), SkillLoadedBeforeTool()])+def test_bundled_distribution_accepts_an_alternate_skill(scorer: Scorer) -> None:+ output = _output(+ _tool_call("skill", "Skill", {"skill": ALTERNATE_SKILL}, "loaded"),+ _exec("query", "call execute-sql {}", "[]"),+ )+ assert _score(scorer, output, BUNDLED_WITH_ALTERNATE).score == 1.0+ assert _score(scorer, output, BUNDLED_EXPECTED).score == 0.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..f9376b300a37--- /dev/null+++ b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py@@ -0,0 +1,156 @@+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",+ alternate_skills: list[str] | None = None,+) -> dict[str, dict[str, object]]:+ spec: dict[str, object] = {"skill": skill, "delivery": delivery, "source": source, "paths": paths}+ if alternate_skills:+ spec["alternate_skills"] = alternate_skills+ return {"expected_reference_pulled": spec}+++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+++def test_expected_reference_pulled_accepts_a_reference_of_an_alternate_skill() -> None:+ output = _output(_exec("ref", "learn posthog:alt references/a.md"))+ assert _score(ExpectedReferencePulled(), output, _ref_expected(["references/a.md"])).score == 0.0+ score = _score(ExpectedReferencePulled(), output, _ref_expected(["references/a.md"], alternate_skills=["alt"]))+ assert score.score == 1.0+ assert score.metadata["skill"] == "alt"+++ "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..0e5b50381391--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py@@ -0,0 +1,119 @@+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,+)+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN+++def _case(+ name: str,+ prompt: str,+ skill: str,+ downstream_tools: list[str],+ skill_delivery: SkillDelivery,+ *,+ alternate_skills: list[str] | None = None,+) -> SandboxedEvalCase:+ return SandboxedEvalCase(+ name=name,+ prompt=prompt,+ expected=skill_distribution_expectations(+ skill, downstream_tools, skill_delivery, alternate_skills=alternate_skills+ ),+ metadata={"expected_skill": skill, "skill_delivery": skill_delivery},+ # The sandbox identifies as the eval consumer, which the MCP serves `learn` to; the default+ # (Desktop) consumer is excluded from `learn`, so the exec arm would never exercise it.+ interaction_origin=EVAL_INTERACTION_ORIGIN,+ )+++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",+ # The support front door wraps the diagnostic skill and also answers this prompt.+ alternate_skills=["debugging-experiments"],+ 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..275bce1f413d--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/eval_skill_usage.py@@ -0,0 +1,153 @@+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,+)+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN+++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,+ alternate_skills: list[str] | 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,+ alternate_skills=alternate_skills,+ ),+ metadata={"expected_skill": skill, "skill_delivery": skill_delivery},+ # The sandbox identifies as the eval consumer, which the MCP serves `learn` to; the default+ # (Desktop) consumer is excluded from `learn`, so the exec arm would never exercise it.+ interaction_origin=EVAL_INTERACTION_ORIGIN,+ 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",+ # The support front door wraps the diagnostic skill and also answers this prompt.+ alternate_skills=["debugging-experiments"],+ 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..6414e7d17990--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py@@ -0,0 +1,501 @@+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 posthog.dataclasses import frozen++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+ skill: str+++@frozen+class _ExecCommand:+ verb: str+ arguments: str+++@frozen+class _SkillExpectation:+ skills: list[str]+ delivery: SkillDelivery+ source: str+++def skill_distribution_expectations(+ skill: str,+ downstream_tools: list[str],+ skill_delivery: SkillDelivery,+ *,+ source: str = "posthog",+ alternate_skills: list[str] | None = None,+) -> dict[str, dict[str, object]]:+ """``alternate_skills`` are other skills that legitimately cover the case, such as a+ support front door that wraps the expected skill; loading any of them counts."""+ skill_spec: dict[str, object] = {"skill": skill, "source": source}+ if alternate_skills:+ skill_spec["alternate_skills"] = list(alternate_skills)+ expectations: dict[str, dict[str, object]] = {+ "expected_skill_loaded": {**skill_spec, "delivery": skill_delivery},+ "skill_loaded_before_tool": {**skill_spec, "delivery": skill_delivery, "tools": downstream_tools},+ }+ if skill_delivery == "exec":+ expectations.update(+ {+ "skill_search_first": {},+ "expected_skill_discovered": skill_spec,+ "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) -> _ExecCommand:+ if call.is_exec_unwrapped or normalize_tool_name(call.raw_name) != EXEC_TOOL_NAME:+ return _ExecCommand(verb="", arguments="")+ command = call.input.get("command")+ if not isinstance(command, str):+ return _ExecCommand(verb="", arguments="")+ verb, _, rest = command.strip().partition(" ")+ return _ExecCommand(verb=verb.lower(), arguments=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:+ command = _exec_command(call)+ return command.verb == "learn" and (command.arguments == "-s" or command.arguments.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):+ command = _exec_command(call)+ if command.verb != "learn" or not command.arguments:+ 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 = command.arguments.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", skill=skill)+ 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", skill=skill+ )+ )++ 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", skill=skill)+ for call in _exec_skill_load_calls(parser, _qualified_skill(skill, source))+ ]+++def _any_skill_loads(parser: LogParser, skills: list[str], delivery: SkillDelivery, source: str) -> list[_SkillLoad]:+ loads = [load for skill in skills for load in _skill_loads(parser, skill, delivery, source)]+ return sorted(loads, key=lambda load: load.position)+++def _matching_searches(parser: LogParser, skills: list[str], source: str) -> list[ToolCall]:+ qualified = [_qualified_skill(skill, source) for skill in skills]+ return [+ call+ for call in _skill_search_calls(parser)+ if any(_output_mentions_skill(call.output, name) for name in qualified)+ ]+++def _expected_skills(spec: dict[str, object]) -> list[str] | None:+ """The expected skill first, then any alternates; None when the spec is malformed."""+ skill = spec.get("skill")+ if not isinstance(skill, str) or not skill:+ return None+ alternates = spec.get("alternate_skills", [])+ if not isinstance(alternates, list) or not all(isinstance(alt, str) and alt for alt in alternates):+ return None+ return [skill, *alternates]+++def _skill_and_delivery(spec: dict[str, object]) -> _SkillExpectation | None:+ skills = _expected_skills(spec)+ delivery = spec.get("delivery")+ source = spec.get("source", "posthog")+ if skills is None or delivery not in ("bundled", "exec"):+ return None+ if source not in ("posthog", "project"):+ return None+ return _SkillExpectation(skills=skills, delivery=cast(SkillDelivery, delivery), source=cast(str, source))+++def _is_exec_skill_command(call: ToolCall) -> bool:+ command = _exec_command(call)+ rest = command.arguments+ return command.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).verb != "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"})+ skills = _expected_skills(spec)+ if skills is None:+ 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"})++ for skill in skills:+ 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(skills[0], cast(str, source)),+ },+ )+++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 = skill_spec.skills[0]+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ loads = _any_skill_loads(parser, skill_spec.skills, skill_spec.delivery, skill_spec.source)+ if skill_spec.delivery == "bundled" and loads:+ load = loads[0]+ return Score(+ name=self._name(),+ score=1.0,+ metadata={+ "skill": load.skill,+ "delivery": skill_spec.delivery,+ "call_id": load.call_id,+ "matched_via": load.matched_via,+ },+ )++ matching_searches = _matching_searches(parser, skill_spec.skills, skill_spec.source)+ 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(load.skill, skill_spec.source),+ "delivery": skill_spec.delivery,+ "call_id": load.call_id,+ },+ )+ return Score(+ name=self._name(),+ score=0.0,+ metadata={+ "reason": (+ "Expected bundled skill was not loaded"+ if skill_spec.delivery == "bundled"+ else "Expected skill was not loaded by exact qualified name after discovery"+ ),+ "skill": skill,+ "delivery": skill_spec.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 = skill_spec.skills[0]+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ loads = _any_skill_loads(parser, skill_spec.skills, skill_spec.delivery, skill_spec.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": load.skill,+ "delivery": skill_spec.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": skill_spec.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:+ command = _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"{command.verb} {command.arguments}".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..a3182d24008a--- /dev/null+++ b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py@@ -0,0 +1,288 @@+"""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_skills,+ _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"})+ skills = _expected_skills(spec)+ skill = skills[0] if skills else None+ delivery = spec.get("delivery")+ source = spec.get("source", "posthog")+ paths = spec.get("paths")+ if (+ skills is None+ 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]+ for candidate in skills:+ if delivery == "exec":+ matched = self._exec_match(parser, candidate, cast(str, source), accepted)+ else:+ matched = self._bundled_match(parser, candidate, accepted)+ if matched is not None:+ return Score(name=self._name(), score=1.0, metadata={**matched, "skill": candidate})+ 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):+ command = _exec_command(call)+ if command.verb != "learn":+ continue+ tokens = command.arguments.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)+ command = _exec_command(nxt)+ if command.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"{command.verb} {command.arguments}".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,+ alternate_skills: list[str] | None = None,+) -> dict[str, dict[str, object]]:+ expectations = skill_distribution_expectations(+ skill, downstream_tools, skill_delivery, source=source, alternate_skills=alternate_skills+ )+ if reference_paths:+ expectations["expected_reference_pulled"] = {+ "skill": skill,+ "delivery": skill_delivery,+ "source": source,+ "paths": reference_paths,+ **({"alternate_skills": list(alternate_skills)} if alternate_skills else {}),+ }+ 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 b18beb6d52cd..222f4ca4ead3 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -1,8 +1,10 @@from 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@@ -190,6 +192,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,@@ -231,9 +278,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):@@ -460,7 +510,7 @@ class LLMSkillSerializer(serializers.ModelSerializer):"Empty for scout sandbox fetches of skills that haven't opted into the report channel.",)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.",@@ -581,7 +631,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 f2089dd8c16d..976ffeaa57c4 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -2,13 +2,14 @@ from collections.abc import Sequencefrom typing import Any, castfrom uuid import UUID-from django.db import IntegrityError, transaction-from django.db.models import Q, QuerySet+from django.db import IntegrityError, OperationalError, transaction+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 OpenApiParameter, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound@@ -18,6 +19,7 @@ from rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer+from rest_framework.throttling import BaseThrottlefrom rest_framework.views import APIViewfrom posthog.api.monitoring import monitor@@ -30,6 +32,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 AccessControlPermission, get_authenticator_scopes, posthog_feature_flag_valuefrom posthog.rate_limit import BurstRateThrottle, PersonalApiKeyOrUserRateThrottle, SustainedRateThrottlefrom posthog.renderers import SafeJSONRenderer@@ -87,6 +90,9 @@ from .skill_serializers import (LLMSkillRenameSerializer,LLMSkillResolveQuerySerializer,LLMSkillResolveResponseSerializer,+ LLMSkillSearchErrorSerializer,+ LLMSkillSearchQuerySerializer,+ LLMSkillSearchResponseSerializer,LLMSkillSerializer,LLMSkillVersionSummarySerializer,validate_allowed_tool,@@ -130,6 +136,37 @@ logger = structlog.get_logger(__name__)# Generous ceiling for an uploaded skill zip — per-skill content (body, 200 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_000+++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 _file_extension(path: str) -> str:@@ -274,15 +311,14 @@ class CommunityPublishSustainedThrottle(_CommunityPublishThrottle):rate = "20/day"-class _SkillBundleThrottle(PersonalApiKeyOrUserRateThrottle):- """Throttle for the skill bundle, which a sandbox fetches over OAuth.+class _SkillUserThrottle(PersonalApiKeyOrUserRateThrottle):+ """Per-credential throttling for skill endpoints, including OAuth and sessions.The general BurstRateThrottle/SustainedRateThrottle only count personal-API-key traffic, so an- OAuth or session caller would reach the zip build (candidate queries, a file query per skill,- DEFLATE of up to MAX_BUNDLE_BYTES) unthrottled. PersonalApiKeyOrUserRateThrottle counts- every auth method, but its inherited key idents session and OAuth callers by project, so one- user's burst would 429 every other sandbox in the project. Those callers get a per-user bucket- instead; a personal API key keeps its own.+ OAuth or session caller would reach expensive skill operations unthrottled.+ PersonalApiKeyOrUserRateThrottle counts every auth method, but its inherited key identifies+ session and OAuth callers by project, so one user's burst would 429 every other user in the+ project. Those callers get a per-user bucket instead; a personal API key keeps its own."""def get_cache_key(self, request: Request, view: APIView) -> str:@@ -293,20 +329,30 @@ class _SkillBundleThrottle(PersonalApiKeyOrUserRateThrottle):return self.cache_format % {"scope": self.scope, "ident": f"user:{request.user.pk}"}-class SkillBundleBurstThrottle(_SkillBundleThrottle):+class SkillBundleBurstThrottle(_SkillUserThrottle):# A sandbox fetches the bundle once at session start, so 30/minute clears a burst of concurrent# starts for one user while still catching a scripted loop hammering the zip build.scope = "skills_bundle_burst"rate = "30/minute"-class SkillBundleSustainedThrottle(_SkillBundleThrottle):+class SkillBundleSustainedThrottle(_SkillUserThrottle):# A few hundred session starts an hour per user is well beyond normal use and short of what# sustained abuse of the 5 MB zip build could cost unthrottled.scope = "skills_bundle_sustained"rate = "300/hour"+class SkillSearchBurstThrottle(_SkillUserThrottle):+ scope = "skills_search_burst"+ rate = BurstRateThrottle.rate+++class SkillSearchSustainedThrottle(_SkillUserThrottle):+ scope = "skills_search_sustained"+ rate = SustainedRateThrottle.rate++class ZipRenderer(BaseRenderer):"""Lets ``Accept: application/zip`` through content negotiation on the zip actions.@@ -361,11 +407,13 @@ class LLMSkillViewSet(return [*renderers, ZipRenderer()]return renderers- def get_throttles(self):+ def get_throttles(self) -> list[BaseThrottle]:if self.action == "publish_to_community":return [CommunityPublishBurstThrottle(), CommunityPublishSustainedThrottle()]if self.action == "bundle":return [SkillBundleBurstThrottle(), SkillBundleSustainedThrottle()]+ if self.action == "search":+ return [SkillSearchBurstThrottle(), SkillSearchSustainedThrottle()]if self.action in ["update_by_name", "get_by_name", "resolve_by_name"]:return [BurstRateThrottle(), SustainedRateThrottle()]return super().get_throttles()@@ -527,6 +575,135 @@ 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)),+ )+ queryset = self.user_access_control.filter_queryset_by_access_level(queryset, resource="llm_skill")+ return (+ queryset.filter(+ Q(name__icontains=query)+ | Q(description__icontains=query)+ | Q(body__icontains=query)+ | Q(search_file_path_match=True)+ | Q(search_file_content_match=True)+ )+ .annotate(+ search_rank=Case(+ When(name__iexact=query, then=Value(0)),+ When(name__icontains=query, then=Value(1)),+ When(description__icontains=query, then=Value(2)),+ When(body__icontains=query, then=Value(3)),+ When(search_file_path_match=True, then=Value(4)),+ When(search_file_content_match=True, then=Value(5)),+ default=Value(6),+ output_field=IntegerField(),+ )+ )+ .order_by("search_rank", "name", "id")[:SKILL_SEARCH_RESULT_LIMIT]+ )++ 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 ae484a5b8edd..401c57d8ee05 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -1,16 +1,21 @@import uuid+from datetime import timedeltafrom posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.core.cache import cache+from django.db import connectionfrom django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import serializers, statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Team, User+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom products.access_control.backend.models.access_control import AccessControl@@ -384,6 +389,203 @@ 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++ @parameterized.expand(+ [+ (f"{auth_method}_{window.lower()}", auth_method, window)+ for auth_method in ["personal_key", "oauth", "session"]+ for window in ["Burst", "Sustained"]+ ]+ )+ def test_search_skills_throttles_each_auth_method(self, _label: str, auth_method: str, window: str) -> None:+ self.create_skill(name="throttle-search-skill")+ self.client.logout()+ if auth_method == "personal_key":+ token = self.create_personal_api_key_with_scopes(["llm_skill:read"])+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+ elif auth_method == "oauth":+ app = OAuthApplication.objects.create(+ name="Skill search throttle test",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=app,+ token="pha_skill_search_throttle_test",+ scope="llm_skill:read",+ expires=timezone.now() + timedelta(hours=1),+ scoped_teams=[self.team.id],+ )+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ else:+ self.client.force_login(self.user)++ period = "minute" if window == "Burst" else "hour"+ with (+ patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),+ patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False),+ patch(f"products.skills.backend.api.skills.SkillSearch{window}Throttle.rate", new=f"1/{period}"),+ patch("rest_framework.throttling.SimpleRateThrottle.timer", return_value=1000) as timer,+ ):+ url = self._url("search?query=throttle")+ first = self.client.get(url)+ assert first.status_code == status.HTTP_200_OK, first.content+ assert first.json()["results"][0]["name"] == "throttle-search-skill"+ blocked = self.client.get(url)+ assert blocked.status_code == status.HTTP_429_TOO_MANY_REQUESTS, blocked.content+ assert int(blocked["Retry-After"]) > 0++ assert self.client.get(self._url("name/throttle-search-skill")).status_code == status.HTTP_200_OK++ if auth_method == "personal_key":+ second_key = self.create_personal_api_key_with_scopes(["llm_skill:read"])+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {second_key}")+ assert self.client.get(url).status_code == status.HTTP_200_OK+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+ elif auth_method == "oauth":+ self.client.credentials()+ self.client.force_login(self.user)+ assert self.client.get(url).status_code == status.HTTP_429_TOO_MANY_REQUESTS++ timer.return_value += 60 if window == "Burst" else 3600+ assert self.client.get(url).status_code == status.HTTP_200_OK++ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.credentials()+ self.client.force_login(other_user)+ assert self.client.get(url).status_code == status.HTTP_200_OK+# --- Get by name ---def test_get_skill_by_name(self):@@ -457,9 +659,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"))@@ -1602,6 +1804,56 @@ class TestSkillAccessControlRBAC(APIBaseTest):organization_member=membership,)+ @parameterized.expand([("none",), ("viewer",)])+ def test_search_filters_object_permissions_before_limiting_results(self, resource_access: str) -> None:+ self._grant_llm_skill_access(resource_access)+ membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)+ self.skill.body = "Follow search-marker instructions."+ self.skill.save(update_fields=["body"])+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=str(self.skill.id),+ access_level="viewer",+ organization_member=membership,+ )+ for index in range(10):+ restricted = LLMSkill.objects.create(+ team=self.team,+ name=f"search-marker-{index}",+ description="Restricted description.",+ body="Restricted search-marker instructions.",+ created_by=self.user,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=str(restricted.id),+ access_level="none",+ organization_member=membership,+ )++ response = self.client.get(self._url("search"), {"query": "search-marker"})++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {+ "count": 1,+ "results": [+ {+ "name": self.skill.name,+ "description": self.skill.description,+ "matches": [+ {+ "matched_field": "body",+ "path": "SKILL.md",+ "line": 1,+ "excerpt": self.skill.body,+ }+ ],+ }+ ],+ }+@parameterized.expand([("list",),diff --git a/products/skills/frontend/LLMSkillScene.stories.tsx b/products/skills/frontend/LLMSkillScene.stories.tsxindex e52f75cefb5c..16f073009d68 100644--- a/products/skills/frontend/LLMSkillScene.stories.tsx+++ b/products/skills/frontend/LLMSkillScene.stories.tsx@@ -75,8 +75,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 fc89bdb87e58..1c33fc2ecdf2 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -240,6 +240,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 LLMSkillOutlineEntryApi {@@ -292,7 +296,7 @@ export interface LLMSkillApi {readonly category: string/** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */readonly owners: readonly UserBasicApi[]- /** 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[]@@ -715,6 +719,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 CommunitySkillsListParams = {/*** Number of results to return per page.@@ -889,3 +951,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 6f98ada0b32c..10087fb8c701 100644--- a/products/skills/frontend/generated/api.ts+++ b/products/skills/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {LLMSkillPublishToCommunityApi,LLMSkillRenameApi,LLMSkillResolveResponseApi,+ LLMSkillSearchResponseApi,LlmSkillsBundleRetrieveParams,LlmSkillsListParams,LlmSkillsNameExportRetrieveParams,@@ -33,6 +34,7 @@ import type {LlmSkillsNameFilesRetrieveParams,LlmSkillsNameRetrieveParams,LlmSkillsResolveNameRetrieveParams,+ LlmSkillsSearchRetrieveParams,PaginatedCommunitySkillListListApi,PaginatedLLMSkillListListApi,PatchedLLMSkillPublishApi,@@ -551,3 +553,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 f717d06ce5c3..7a4e9e6de637 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -36,6 +36,9 @@ tools:llm-skills-name-publish-community-create:operation: llm_skills_name_publish_community_createenabled: 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 466ce4f6f66a..2491feff18c7 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 |@@ -276,5 +292,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/constants.py b/products/tasks/backend/constants.pyindex d36d451af02a..5051dd0186ba 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -16,6 +16,11 @@ WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG = "tasks-workflow-dispatch-shadow"WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG = "tasks-workflow-dispatch-async"WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG = "tasks-workflow-dispatch-restart"AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG = "tasks-agent-proxy-keep-stream-open"+# Shared with the MCP server (services/mcp/src/hono/constants.ts): one flag decides both whether+# the MCP serves product skills through `learn` and whether a sandbox launches without bundled skills.+MCP_EXEC_SKILLS_FEATURE_FLAG = "mcp-exec-skills"+# `interaction_origin` of eval harness runs; becomes the `x-posthog-mcp-consumer` value "eval".+EVAL_INTERACTION_ORIGIN = "eval"MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"# Gates the nightly prebaked dev-stack image bake (see logic/services/dev_stack_image.py).DEV_STACK_IMAGE_BAKE_FEATURE_FLAG = "tasks-dev-stack-image-bake"diff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.pyindex 332ab2d7543a..699527db201f 100644--- a/products/tasks/backend/facade/agents.py+++ b/products/tasks/backend/facade/agents.py@@ -8,6 +8,7 @@ objects, not data, per the wiring pattern. Heavy by import, so it lives here rat``facade/api.py``."""+from products.tasks.backend.constants import EVAL_INTERACTION_ORIGIN, MCP_EXEC_SKILLS_FEATURE_FLAGfrom products.tasks.backend.logic.services.custom_prompt_internals import (CustomPromptSandboxContext,EmptyAgentTurnError,@@ -21,9 +22,30 @@ 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,+)+from products.tasks.backend.models import SandboxEnvironment+++def create_skill_isolation_environment(*, team_id: int, user_id: int, name: str) -> str:+ """Create an internal environment that disables native bundled skills for an agent run."""+ environment = SandboxEnvironment.objects.create(+ team_id=team_id,+ created_by_id=user_id,+ name=name,+ environment_variables={ENV_DISABLE_BUNDLED_SKILLS: "1"},+ internal=True,+ )+ return str(environment.id)+__all__ = [+ "ENV_DISABLE_BUNDLED_SKILLS",+ "EVAL_INTERACTION_ORIGIN",+ "MCP_EXEC_SKILLS_FEATURE_FLAG","ENV_LOCAL_SKILLS_HOST_PATH","CustomPromptSandboxContext","EmptyAgentTurnError",@@ -34,6 +56,7 @@ __all__ = ["TurnPollResult","TurnPollTimeout","create_task_and_trigger",+ "create_skill_isolation_environment","extract_json_from_text","poll_for_turn","resolve_sandbox_context_for_local_dev",diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex febf4ca79691..f53824594378 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -10,6 +10,7 @@ from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG,DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,+ MCP_EXEC_SKILLS_FEATURE_FLAG,WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG,@@ -191,3 +192,25 @@ def agent_otel_telemetry_enabled_for_state(state: dict | None) -> bool:if settings.DEBUG:return Truereturn (state or {}).get(AGENT_OTEL_TELEMETRY_STATE_KEY) is True+++def is_mcp_exec_skills_enabled(organization_id: str, distinct_id: str) -> bool:+ """Whether this run's user gets product skills through the MCP `learn` command.++ Evaluated server-side so organization rules and person rules (an email domain, a cohort)+ both resolve, the same way the MCP server evaluates the flag for the same user.+ """+ try:+ return bool(+ posthoganalytics.feature_enabled(+ MCP_EXEC_SKILLS_FEATURE_FLAG,+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("mcp_exec_skills_flag_check_failed")+ return Falsediff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex 941205b9a7da..a450842065bd 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -312,6 +312,9 @@ class AgentServerLaunchMixin(SandboxBase):if not self.is_running():raise RuntimeError("Sandbox not in running state.")+ # Before the already-healthy shortcut: images that boot the agent server never relaunch it,+ # and the agent reads its skill directories when a session starts, not when the server does.+ self.clear_bundled_skills_if_disabled()if self._agent_server_is_healthy() and (allowed_domains is None or self._agentsh_daemon_is_healthy()):logger.info(f"Agent-server already healthy in sandbox {self.id}; skipping relaunch")return 0 if wait_for_health else Nonediff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 63ec17339036..7a7efe8d55d8 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -51,7 +51,12 @@ from .agentsh import (generate_policy_yaml,read_gh_guard_script,)-from .local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache, snapshot_local_task_skills+from .local_skills import (+ ENV_LOCAL_SKILLS_HOST_PATH,+ LocalSkillsCache,+ bundled_skills_disabled,+ snapshot_local_task_skills,+)from .sandbox import (WORKING_DIR,AgentServerResult,@@ -525,7 +530,12 @@ 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 skill_source != "local" and local_skills_host and os.path.isdir(local_skills_host):+ if (+ skill_source != "local"+ and 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@@ -1080,6 +1090,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 c31d76e2cf82..2c98b3a44927 100644--- a/products/tasks/backend/logic/services/local_skills.py+++ b/products/tasks/backend/logic/services/local_skills.py@@ -33,6 +33,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/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 0c9fe6299d72..da4ef6747af7 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -38,6 +38,7 @@ from products.tasks.backend.constants import (SNAPSHOT_KIND_FILESYSTEM,SnapshotKind,)+from products.tasks.backend.logic.services.local_skills import BUNDLED_SKILLS_PATHS, ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.sandbox_config import (BURSTABLE_REQUEST_CPU_CORES,BURSTABLE_REQUEST_MEMORY_MB,@@ -465,6 +466,18 @@ class SandboxBase(ABC):)return False+ def clear_bundled_skills_if_disabled(self) -> None:+ """Delete the bundled skill folders when the sandbox environment asks for it.++ The check runs inside the sandbox: a sandbox rehydrated by id carries no config env+ vars, but the container environment still holds the value the launcher set.+ """+ paths = " ".join(shlex.quote(path) for path in BUNDLED_SKILLS_PATHS)+ command = f'if [ "${ENV_DISABLE_BUNDLED_SKILLS}" = "1" ]; then rm -rf {paths} && mkdir -p {paths}; fi'+ result = self.execute(command, 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 edf792ae53a9..85e658d41139 100644--- a/products/tasks/backend/logic/services/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py@@ -12,6 +12,7 @@ from parameterized import parameterizedfrom products.tasks.backend.exceptions import ProcessTaskError, 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,@@ -556,6 +557,9 @@ class TestDockerSandboxUnit:with (patch.object(sandbox, "is_running", return_value=True),patch.object(sandbox, "write_file"),+ patch.object(+ sandbox, "execute", return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None)+ ),patch.object(sandbox, "agent_server_supports_pi_runtime", return_value=False),pytest.raises(RuntimeError, match="does not support the Pi runtime"),):@@ -632,6 +636,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/test_local_skills.py b/products/tasks/backend/logic/services/test_local_skills.pyindex 7ea0142eeb59..0695e18b3e16 100644--- a/products/tasks/backend/logic/services/test_local_skills.py+++ b/products/tasks/backend/logic/services/test_local_skills.py@@ -9,13 +9,17 @@ from pathlib import Pathfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from products.tasks.backend.facade.agents import create_skill_isolation_environment+from products.tasks.backend.facade.api import list_sandbox_environmentsfrom products.tasks.backend.logic.services.local_skills import (BUILD_HASH_FILENAME,BUILT_SKILLS_RELATIVE_PATH,LocalSkillsCache,+ bundled_skills_disabled,populate_skills_directory,snapshot_local_task_skills,)+from products.tasks.backend.models import SandboxEnvironmentPATCH_TARGET = "products.posthog_ai.scripts.build_skills.SkillBuilder"@@ -50,6 +54,16 @@ class TestLocalSkills(BaseTest):self._make_fake_repo()self.cache = LocalSkillsCache(self.base_dir)+ def test_skill_isolation_environment_disables_bundled_skills_and_stays_internal(self) -> None:+ environment_id = create_skill_isolation_environment(+ team_id=self.team.id, user_id=self.user.id, name="Eval skill isolation"+ )++ environment = SandboxEnvironment.objects.get(team_id=self.team.id, id=environment_id)+ assert bundled_skills_disabled(environment.environment_variables)+ assert environment.created_by_id == self.user.id+ assert list_sandbox_environments(self.team.id, self.user.id) == []+def _make_fake_repo(self) -> None:skill_dir = self.base_dir / "products" / "alpha" / "skills" / "my-skill"skill_dir.mkdir(parents=True)diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.pyindex f9f5c7cb55d5..a761bbf50c18 100644--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py@@ -8,6 +8,7 @@ from parameterized import parameterizedfrom products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEXfrom products.tasks.backend.exceptions import SandboxExecutionErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandbox+from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig@@ -86,12 +87,19 @@ def test_build_agent_server_command_gates_connected_project_operations(sandbox:def test_start_agent_server_launch_failure_is_captured(sandbox: DockerSandbox):failed = ExecutionResult(stdout="", stderr="boom", exit_code=1)++ def execute(command: str, **kwargs) -> ExecutionResult:+ # Only the launch fails; the bundled-skills clear that precedes it succeeds.+ if ENV_DISABLE_BUNDLED_SKILLS in command:+ return ExecutionResult(stdout="", stderr="", exit_code=0)+ return failed+with (patch.object(sandbox, "is_running", return_value=True),patch.object(sandbox, "write_file"),patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server") as build_command,patch.object(sandbox, "agent_server_supports_exec_permission_regex", return_value=True),- patch.object(sandbox, "execute", return_value=failed),+ patch.object(sandbox, "execute", side_effect=execute),patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,pytest.raises(SandboxExecutionError),):diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 3993f3e0f56f..2e6290c39356 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -30,6 +30,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,@@ -518,6 +519,53 @@ class TestModalSandboxAgentServer:assert "nohup" in commandassert "export POSTHOG_AGENT_LAUNCH_STARTED_AT_MS=$(date +%s%3N)" 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_clears_bundled_skills_even_when_the_server_is_already_healthy(+ self, mock_sandbox: Any+ ) -> None:+ # Images that boot the agent server take the no-relaunch shortcut; the clear must still run.+ 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),+ )++ with patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True):+ 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]+ assert any("rm -rf" in command and "skills" in command for command in commands)+ assert not any("agent-server" in command for command in commands)+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),@@ -767,9 +815,13 @@ class TestModalSandboxAgentServer:mock_sandbox.write_file = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None),)- mock_sandbox.execute = MagicMock(- return_value=ExecutionResult(stdout="", stderr="npx: command not found", exit_code=127, error=None)- )++ def execute(command: str, timeout_seconds: int | None = None) -> ExecutionResult:+ if ENV_DISABLE_BUNDLED_SKILLS in command:+ return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)+ return ExecutionResult(stdout="", stderr="npx: command not found", exit_code=127, error=None)++ mock_sandbox.execute = MagicMock(side_effect=execute)with patch.object(mock_sandbox, "_setup_agentsh"):with pytest.raises(SandboxExecutionError, match="Agent-server failed to start"):@@ -782,6 +834,7 @@ class TestModalSandboxAgentServer:def test_start_agent_server_raises_on_health_check_failure(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(side_effect=[+ ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # bundled-skills clearExecutionResult(stdout="", stderr="", exit_code=0, error=None),ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim write (mv)ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim chmod@@ -822,7 +875,7 @@ class TestModalSandboxAgentServer:assert mock_sandbox.execute.call_count == 1def test_start_agent_server_skips_relaunch_when_already_healthy(self, mock_sandbox: Any):- mock_sandbox.execute = MagicMock()+ mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None))with (patch.object(mock_sandbox, "_agent_server_is_healthy", return_value=True),@@ -841,7 +894,8 @@ class TestModalSandboxAgentServer:assert health_ms == 0wait_for_ready.assert_not_called()mock_free.assert_not_called()- mock_sandbox.execute.assert_not_called()+ # Only the bundled-skills clear runs before the shortcut.+ assert [ENV_DISABLE_BUNDLED_SKILLS in call.args[0] for call in mock_sandbox.execute.call_args_list] == [True]def test_start_agent_server_relaunches_when_agentsh_is_unhealthy(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(@@ -879,6 +933,7 @@ class TestModalSandboxAgentServer:def test_start_agent_server_frees_port_before_relaunch(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(side_effect=[+ ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # bundled-skills clearExecutionResult(stdout="", stderr="", exit_code=0, error=None),ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim write (mv)ExecutionResult(stdout="", stderr="", exit_code=0, error=None), # gh shim chmoddiff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex bf348bf177df..37c57d4604f7 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -52,6 +52,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_name_for_task,get_sandbox_snapshot_metadata,get_task_run_credential_user,+ mcp_exec_skills_env_vars,parse_run_state,run_gateway_env_vars,)@@ -145,6 +146,7 @@ def _build_environment_variables(environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URLenvironment_variables.update(run_gateway_env_vars(ctx, task))+ environment_variables.update(mcp_exec_skills_env_vars(ctx))return environment_variablesdiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex bd06c1ddea17..e38b8b7fd7b8 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -98,6 +98,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_otel_env_vars,get_sandbox_snapshot_metadata,get_task_run_credential_user,+ mcp_exec_skills_env_vars,parse_run_state,run_gateway_env_vars,)@@ -520,6 +521,7 @@ def _build_environment_variables(environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URLenvironment_variables.update(run_gateway_env_vars(ctx, task))+ environment_variables.update(mcp_exec_skills_env_vars(ctx))if settings.DEBUG:# Local eval runs pin models per unit; the agent's overload rescue would silently switch adiff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 9ae112ed5969..d451aab06655 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -1,3 +1,5 @@+from types import SimpleNamespace+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, TestCase, override_settings@@ -32,6 +34,7 @@ from products.tasks.backend.temporal.process_task.utils import (is_bot_authorship_fallback,is_caller_token_run,loop_mcp_installation_allowlist,+ mcp_exec_skills_env_vars,parse_run_state,upgrade_run_to_user_authorship,)@@ -356,6 +359,7 @@ class TestGetSandboxMcpConfigs(TestCase):("slack", False, "slack"),("workflow", True, "slack"),("posthog_ai", False, "posthog_ai"),+ ("eval", False, "eval"),])def test_consumer_header_reflects_reply_context(@@ -519,6 +523,7 @@ class TestFetchUserMcpServerConfigs(TestCase):("slack", False, "slack"),("workflow", True, "slack"),("posthog_ai", False, "posthog_ai"),+ ("eval", False, "eval"),("posthog_code", False, "posthog-code"),(None, False, "posthog-code"),]@@ -1506,3 +1511,29 @@ class TestIsBotAuthorshipFallback(_AuthorshipFixture):getattr(self, f"_{case}")()assert is_bot_authorship_fallback(self.task, str(self.task_run.id), self.task_run.state) is False+++class TestMcpExecSkillsEnvVars(SimpleTestCase):+ @parameterized.expand(+ [+ ("web_phai_flag_on", "posthog_ai", True, True),+ ("slack_flag_on", "slack", True, True),+ ("eval_flag_on", "eval", True, True),+ ("desktop_keeps_bundled_skills_even_with_flag_on", None, True, False),+ ("web_phai_flag_off", "posthog_ai", False, False),+ ]+ )+ def test_strips_bundled_skills_only_for_learn_capable_runs_with_the_flag_on(+ self, _name: str, interaction_origin: str | None, flag_enabled: bool, expect_stripped: bool+ ) -> None:+ ctx = SimpleNamespace(interaction_origin=interaction_origin, organization_id="org-1", distinct_id="user-1")+ with patch(+ "products.tasks.backend.temporal.process_task.utils.is_mcp_exec_skills_enabled", return_value=flag_enabled+ ) as flag_check:+ env = mcp_exec_skills_env_vars(ctx)++ assert env == ({"POSTHOG_CODE_DISABLE_BUNDLED_SKILLS": "1"} if expect_stripped else {})+ if interaction_origin is None:+ flag_check.assert_not_called()+ else:+ flag_check.assert_called_once_with("org-1", "user-1")diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex ffbc7e8b80e6..98a9b691107f 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -22,6 +22,7 @@ from products.tasks.backend.constants import (ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,CODEX_INITIAL_PERMISSION_MODE_CHOICES,DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ EVAL_INTERACTION_ORIGIN,INITIAL_PERMISSION_MODE_CHOICES,SNAPSHOT_KIND_DIRECTORY,SNAPSHOT_KIND_FILESYSTEM,@@ -32,6 +33,8 @@ from products.tasks.backend.constants import (is_same_run_resume_state,)from products.tasks.backend.exceptions import CredentialUnavailableError+from products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled+from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.mcp_url import resolve_mcp_url as _resolve_mcp_url# Re-exported so existing activity/workflow imports keep working after the move to@@ -840,9 +843,9 @@ def get_imported_mcp_server_configs(task_run: TaskRun, existing_names: Iterable[def _resolve_mcp_consumer(interaction_origin: str | None, *, slack_reply_context: bool = False) -> str:"""Map the task's reply context to the `x-posthog-mcp-consumer` value.- Slack reply contexts send `"slack"` and posthog_ai (Max) runs send- `"posthog_ai"`; everything else (the PostHog Desktop UI, API callers, missing- origin) is treated as PostHog Desktop. Only `"posthog-code"` is a UI-apps host+ Slack reply contexts send `"slack"`, posthog_ai (Max) runs send `"posthog_ai"`,+ and eval harness runs send `"eval"`; everything else (the PostHog Desktop UI,+ API callers, missing origin) is treated as PostHog Desktop. Only `"posthog-code"` is a UI-apps hoston the MCP server — it gates UI-apps payload emission, so `"posthog_ai"` and`"slack"` deliberately don't get UI apps. Keep the `"posthog-code"` literalin sync with `POSTHOG_CODE_CONSUMER` in@@ -852,9 +855,25 @@ def _resolve_mcp_consumer(interaction_origin: str | None, *, slack_reply_contextreturn "slack"if interaction_origin == "posthog_ai":return "posthog_ai"+ if interaction_origin == EVAL_INTERACTION_ORIGIN:+ return EVAL_INTERACTION_ORIGINreturn "posthog-code"+def mcp_exec_skills_env_vars(ctx) -> dict[str, str]:+ """Env that launches the sandbox without bundled product skills when this run gets them+ through the MCP `learn` command instead.++ Desktop runs keep their bundled skills: the MCP server excludes the `posthog-code`+ consumer from `learn`, so stripping them there would leave the agent with no skills.+ """+ if _resolve_mcp_consumer(ctx.interaction_origin) == "posthog-code":+ return {}+ if not is_mcp_exec_skills_enabled(ctx.organization_id, ctx.distinct_id):+ return {}+ return {ENV_DISABLE_BUNDLED_SKILLS: "1"}++# Names capabilities rather than describing the server, because the agent's tool search reads# this before the PostHog MCP has ever connected.POSTHOG_MCP_DESCRIPTION = (@@ -1383,6 +1402,7 @@ def build_sandbox_environment_variables(env_vars["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URLenv_vars.update(run_gateway_env_vars(ctx, task))+ env_vars.update(mcp_exec_skills_env_vars(ctx))if otel_telemetry_enabled:env_vars.update(get_sandbox_otel_env_vars())diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.pyindex 79e9dcf3cdbe..dd88d919fd31 100644--- a/products/tasks/backend/tests/test_agentsh.py+++ b/products/tasks/backend/tests/test_agentsh.py@@ -573,8 +573,9 @@ 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 DockerSandbox+ from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom 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.@@ -586,6 +587,8 @@ class TestModalSandboxAgentShWrapping(TestCase):return ExecutionResult(stdout="", stderr="", exit_code=0)if "chmod" in command: # gh shim installreturn ExecutionResult(stdout="", stderr="", exit_code=0)+ if ENV_DISABLE_BUNDLED_SKILLS in command: # bundled-skills clear+ return ExecutionResult(stdout="", stderr="", exit_code=0)self.assertIn("grep", command)return ExecutionResult(stdout="", stderr="", exit_code=0 if supported else 1)@@ -596,6 +599,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/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.pyindex 3a4c06c151a7..c77ebefc93e4 100644--- a/products/tasks/backend/tests/test_feature_flags.py+++ b/products/tasks/backend/tests/test_feature_flags.py@@ -3,7 +3,11 @@ from unittest.mock import patchfrom django.test import override_settings-from products.tasks.backend.feature_flags import get_model_access_error, is_dev_stack_image_bake_enabled+from products.tasks.backend.feature_flags import (+ get_model_access_error,+ is_dev_stack_image_bake_enabled,+ is_mcp_exec_skills_enabled,+)class TestIsDevStackImageBakeEnabled:@@ -116,3 +120,25 @@ class TestGetModelAccessError:),):assert get_model_access_error("moonshotai/kimi-k3", distinct_id="d-1") is not None+++class TestIsMcpExecSkillsEnabled:+ def test_evaluates_for_the_user_and_organization_server_side(self):+ with patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=True,+ ) as feature_enabled_mock:+ assert is_mcp_exec_skills_enabled("org-1", "user-1") is True++ assert feature_enabled_mock.call_args.args[0] == "mcp-exec-skills"+ kwargs = feature_enabled_mock.call_args.kwargs+ assert kwargs["distinct_id"] == "user-1"+ assert kwargs["groups"] == {"organization": "org-1"}+ assert kwargs["only_evaluate_locally"] is False++ def test_fails_closed_on_flag_service_error(self):+ with patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flags down"),+ ):+ assert is_mcp_exec_skills_enabled("org-1", "user-1") is Falsediff --git a/services/mcp/README.md b/services/mcp/README.mdindex 61bce2051fcd..20cee6a3d26a 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -284,6 +284,47 @@ Available features:To view which tools are available per feature, see our [documentation](https://posthog.com/docs/model-context-protocol) or check `schema/tool-definitions-all.json`.+### Learning and skills in cli mode++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.+A product `call` in a session that loaded no skill is rejected with an instruction to search first; `call --no-skills ...` records that no skill applies and opens the gate for the rest of the session. Clients without an MCP session id are not gated.++The skill bundle is shared through Redis: each pod loads it once at startup, parses it into memory, and serves every `learn` command from that parsed catalog.+A background timer polls a small version key in Redis; only when the version changes does a pod read the archive bytes again.+One pod at a time refreshes the archive from its source when the shared copy is older than ten minutes, using a conditional request so an unchanged release costs a 304.+The cached bytes are kept for thirty days and re-extended on every refresh, so a source outage serves the last good archive.+No `learn`, `initialize`, or `discover` request reads the archive from Redis.+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.+### Tool filteringFor finer-grained control you can allowlist specific tools by name using the `tools` query parameter. Only the exact tool names listed will be exposed, regardless of their feature category.diff --git a/services/mcp/scripts/generate-exec-docs.ts b/services/mcp/scripts/generate-exec-docs.tsindex 5f253053373c..ff01f69c83a7 100644--- a/services/mcp/scripts/generate-exec-docs.ts+++ b/services/mcp/scripts/generate-exec-docs.ts@@ -6,7 +6,7 @@import * as fs from 'node:fs'import * as path from 'node:path'-import { LEARN_COMMAND_LINE } from '../src/tools/exec-help'+import { LEARN_COMMAND_LINE } from '../src/tools/exec-learn'const SECTIONS_DIR = path.join(__dirname, '../src/templates/sections')const OUTPUT_PATH = path.join(__dirname, '../schema/exec-command-reference.md')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c413070d0d25..979004cdf7ad 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48261,6 +48261,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 {@@ -48313,7 +48317,7 @@ export namespace Schemas {readonly category: string;/** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */readonly owners: readonly UserBasic[];- /** 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[];@@ -48661,6 +48665,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@@ -98782,6 +98845,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 46b03b55d454..2cb64e76b5b4 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -16,6 +16,7 @@ import {} from '@/lib/posthog/analytics'import type { RequestProperties } from '@/lib/request-properties'import { resolveScopePreset } from '@/lib/scope-preset'+import type { SkillInvocation } from '@/tools/exec-learn'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'@@ -487,3 +488,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/ContextMillResourceCache.ts b/services/mcp/src/hono/cache/ContextMillResourceCache.tsindex e545f85bfbcb..02dcfb5b1227 100644--- a/services/mcp/src/hono/cache/ContextMillResourceCache.ts+++ b/services/mcp/src/hono/cache/ContextMillResourceCache.ts@@ -178,7 +178,7 @@ export class ContextMillResourceCache extends SharedBlobCache {* still fresh, plain `loadOrRefresh` would short-circuit.*/async invalidate(): Promise<void> {- await Promise.all([this.redis.del(this.cacheKey), this.redis.del(this.freshKey)])+ await this.redis.del(this.currentKey)}/**diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.tsindex f775bdb52b96..7f601bc78c27 100644--- a/services/mcp/src/hono/cache/RedisCache.ts+++ b/services/mcp/src/hono/cache/RedisCache.ts@@ -21,7 +21,7 @@ const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 daysconst CLEAR_MAX_ITERATIONS = 50const CLEAR_SCAN_COUNT = 100-export type CachePrefix = 'token' | 'user'+export type CachePrefix = 'token' | 'user' | 'session'export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {private redis: RedisLikediff --git a/services/mcp/src/hono/cache/SharedBlobCache.ts b/services/mcp/src/hono/cache/SharedBlobCache.tsindex 185ea0a86634..baa9149517cd 100644--- a/services/mcp/src/hono/cache/SharedBlobCache.ts+++ b/services/mcp/src/hono/cache/SharedBlobCache.ts@@ -1,3 +1,6 @@+import { createHash } from 'node:crypto'+import { z } from 'zod'+import type { RedisLike } from './RedisCache'const DEFAULT_CACHE_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days — hard expiry@@ -6,6 +9,27 @@ const DEFAULT_LOCK_TTL_SECONDS = 60 // writer lock auto-expiresconst DEFAULT_WAIT_INTERVAL_MS = 200const DEFAULT_WAIT_TIMEOUT_MS = 10_000+const pointerSchema = z.object({+ sha: z.string().regex(/^[a-f0-9]{64}$/),+ etag: z.string().optional(),+ validatedAt: z.number().finite(),+})++// A delayed 304 must not replace a newer pointer or refresh metadata for an evicted blob.+const TOUCH_CACHE = `+if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end+if redis.call('EXPIRE', KEYS[2], ARGV[3]) == 0 then return 0 end+redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])+return 1+`++const RELEASE_LOCK = `+if redis.call('GET', KEYS[1]) == ARGV[1] then+ return redis.call('DEL', KEYS[1])+end+return 0+`+export interface SharedBlobCacheOptions {cacheTtlSeconds?: numberfreshSeconds?: number@@ -19,7 +43,7 @@ export interface SharedBlobCacheOptions {** - Callers can coordinate single-writer refreshes with the `SET NX EX` lock,* wait for another writer to publish on cold cache misses, and read/write- * the shared bytes plus freshness marker.+ * immutable bytes through a single current-version pointer.* - Hard TTL keeps the cache available across long writer outages; a separate* freshness timestamp lets callers decide when to refresh after the soft* window.@@ -28,10 +52,20 @@ export interface SharedBlobCacheOptions {* many independent shared blobs (e.g. context-mill archive, future bundles)* without colliding.*/+export interface SharedBlobRecord extends SharedBlobVersion {+ bytes: Uint8Array+}++export interface SharedBlobVersion extends z.infer<typeof pointerSchema> {+ fresh: boolean+ serialized: string+}+export class SharedBlobCache {- public readonly cacheKey: string- public readonly freshKey: string+ public readonly currentKey: stringpublic readonly lockKey: string+ private readonly blobKeyPrefix: string+ private validatedAt: number | undefinedprivate cacheTtlSeconds: numberprivate freshSeconds: number@@ -44,9 +78,10 @@ export class SharedBlobCache {namespace: string,opts: SharedBlobCacheOptions = {}) {- const prefix = `mcp:shared-blob:${namespace}`- this.cacheKey = `${prefix}:bytes`- this.freshKey = `${prefix}:fresh`+ // Separate layouts let old and new processes coexist during a rolling deploy.+ const prefix = `mcp:shared-blob:${namespace}:v2`+ this.currentKey = `${prefix}:current`+ this.blobKeyPrefix = `${prefix}:blob`this.lockKey = `${prefix}:lock`this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS@@ -56,25 +91,78 @@ 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)])+ getLastValidatedAt(): number | undefined {+ return this.validatedAt+ }++ protected blobKey(sha: string): string {+ return `${this.blobKeyPrefix}:${sha}`+ }++ protected async readCache(version?: SharedBlobVersion): Promise<SharedBlobRecord | null> {+ const pointer = version ?? (await this.readVersion())+ if (!pointer) {+ return null+ }+ const key = this.blobKey(pointer.sha)+ const raw = await this.redis.get(key)if (raw === null) {return null}const buf = Buffer.from(raw, 'base64')const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)- const freshUntil = freshUntilStr !== null ? Number(freshUntilStr) : 0- const fresh = Number.isFinite(freshUntil) && Date.now() < freshUntil- return { bytes, fresh }+ if (hashBytes(bytes) !== pointer.sha) {+ // Remove only the corrupt content-addressed blob so a subsequent miss can repair it.+ await this.redis.del(key)+ throw new Error('Shared archive bytes do not match their content hash')+ }+ return { ...pointer, bytes }}- protected async writeCache(bytes: Uint8Array): Promise<void> {+ /**+ * The small pointer is enough to check for updates without transferring archive bytes.+ */+ protected async readVersion(): Promise<SharedBlobVersion | null> {+ const serialized = await this.redis.get(this.currentKey)+ if (serialized === null) {+ return null+ }+ const pointer = pointerSchema.parse(JSON.parse(serialized))+ this.validatedAt = pointer.validatedAt+ return { ...pointer, fresh: Date.now() < pointer.validatedAt + this.freshSeconds * 1000, serialized }+ }++ protected async writeCache(bytes: Uint8Array, etag?: string): Promise<SharedBlobVersion> {const b64 = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64')- const freshUntil = Date.now() + this.freshSeconds * 1000- await Promise.all([- this.redis.set(this.cacheKey, b64, 'EX', this.cacheTtlSeconds),- this.redis.set(this.freshKey, String(freshUntil), 'EX', this.cacheTtlSeconds),- ])+ const pointer = { sha: hashBytes(bytes), etag, validatedAt: Date.now() }+ const serialized = JSON.stringify(pointer)+ // Publish immutable content first. A failed pointer write leaves the previous generation intact.+ await this.redis.set(this.blobKey(pointer.sha), b64, 'EX', this.cacheTtlSeconds)+ await this.redis.set(this.currentKey, serialized, 'EX', this.cacheTtlSeconds)+ this.validatedAt = pointer.validatedAt+ return { ...pointer, fresh: this.freshSeconds > 0, serialized }+ }++ /**+ * Refresh the validation timestamp 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(version: SharedBlobVersion): Promise<boolean> {+ const pointer = { sha: version.sha, etag: version.etag, validatedAt: Date.now() }+ const result = await this.redis.eval(+ TOUCH_CACHE,+ 2,+ this.currentKey,+ this.blobKey(version.sha),+ version.serialized,+ JSON.stringify(pointer),+ this.cacheTtlSeconds+ )+ if (result === 1) {+ this.validatedAt = pointer.validatedAt+ }+ return result === 1}protected async acquireLock(token: string): Promise<boolean> {@@ -82,30 +170,36 @@ export class SharedBlobCache {return result === 'OK'}- protected async releaseLock(_token: string): Promise<void> {- // Best-effort. The lock TTL bounds the worst case (another writer's- // entry being deleted on top); a Lua CAS could close that window but- // would require widening the RedisLike interface.+ protected async releaseLock(token: string): Promise<void> {try {- await this.redis.del(this.lockKey)+ await this.redis.eval(RELEASE_LOCK, 1, this.lockKey, token)} catch (err) {console.error(`[SharedBlobCache:${this.lockKey}] failed to release lock:`, err)}}protected async waitForCache(): Promise<Uint8Array | null> {+ const record = await this.waitForRecord()+ return record?.bytes ?? null+ }++ protected async waitForRecord(): Promise<SharedBlobRecord | null> {const start = Date.now()while (Date.now() - start < this.waitTimeoutMs) {await sleep(this.waitIntervalMs)const cached = await this.readCache()if (cached) {- return cached.bytes+ return cached}}return null}}+export function hashBytes(bytes: Uint8Array): string {+ return createHash('sha256').update(bytes).digest('hex')+}+function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms))}diff --git a/services/mcp/src/hono/cache/SkillArchiveCache.ts b/services/mcp/src/hono/cache/SkillArchiveCache.tsnew file mode 100644index 000000000000..2a065a6d283c--- /dev/null+++ b/services/mcp/src/hono/cache/SkillArchiveCache.ts@@ -0,0 +1,197 @@+import { createHash, randomUUID } from 'node:crypto'++import type { RedisLike } from './RedisCache'+import { hashBytes, SharedBlobCache, type SharedBlobCacheOptions, type SharedBlobVersion } 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'+// Revalidation keeps the current generation alive; superseded blobs expire naturally.+const DEFAULT_ARCHIVE_TTL_SECONDS = 30 * 24 * 60 * 60++export type SkillArchiveCacheResult = 'fresh_hit' | 'stale_hit' | 'cold_refresh' | 'waited' | 'fallback'++export type SkillArchiveRefreshResult = 'fresh' | 'not_modified' | 'downloaded' | 'lock_busy' | 'missing'++export interface SkillArchiveLoadResult {+ bytes: Uint8Array+ sha: string+ 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>+ /**+ * Rejects downloaded bytes before they reach Redis. A throw keeps the previous+ * shared copy, so one bad release cannot take every pod's catalog with it.+ */+ validateArchive?: (bytes: Uint8Array) => void+}++/**+ * Redis-backed shared copy of the published skills.zip.+ *+ * Request handling never touches this class. A pod reads the archive once at+ * startup (`loadOrRefresh`), then a background poller asks for the small version+ * pointer (`readIfChanged`) and reads the bytes again only when the sha moved.+ * Staleness is repaired by whichever poller wins the writer lock+ * (`refreshIfStale`), with a conditional request so an unchanged release costs+ * a 304 and no bytes.+ */+export class SkillArchiveCache extends SharedBlobCache {+ private readonly archiveUrl: string+ private readonly fetchArchive: (url: string, etag?: string) => Promise<SkillArchiveFetchResult>+ private readonly validateArchive: (bytes: Uint8Array) => void++ 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, { cacheTtlSeconds: DEFAULT_ARCHIVE_TTL_SECONDS, ...opts })+ this.archiveUrl = archiveUrl+ this.fetchArchive = opts.fetchArchive ?? downloadArchive+ this.validateArchive = opts.validateArchive ?? (() => undefined)+ }++ /**+ * Startup read. Serves the shared copy whether or not it is fresh — the poller+ * owns freshness — and downloads from the source only when the fleet has no+ * copy at all. Then one pod writes while the others wait for its result.+ */+ async loadOrRefresh(): Promise<SkillArchiveLoadResult> {+ const cached = await this.readCache()+ if (cached) {+ return { bytes: cached.bytes, sha: cached.sha, result: cached.fresh ? 'fresh_hit' : 'stale_hit' }+ }++ const token = randomUUID()+ if (await this.acquireLock(token)) {+ try {+ const { bytes, etag } = await this.downloadFull()+ const { sha } = await this.writeCache(bytes, etag)+ return { bytes, sha, result: 'cold_refresh' }+ } finally {+ await this.releaseLock(token)+ }+ }++ const waited = await this.waitForRecord()+ if (waited) {+ return { bytes: waited.bytes, sha: waited.sha, result: 'waited' }+ }+ const { bytes } = await this.downloadFull()+ return { bytes, sha: hashBytes(bytes), result: 'fallback' }+ }++ /** The shared copy's bytes when its sha differs from `currentSha`, else null. Reads the small pointer first. */+ async readIfChanged(currentSha: string | undefined): Promise<{ bytes: Uint8Array; sha: string } | null> {+ const version = await this.readVersion()+ if (!version || version.sha === currentSha) {+ return null+ }+ const cached = await this.readCache(version)+ if (!cached) {+ return null+ }+ return { bytes: cached.bytes, sha: cached.sha }+ }++ /**+ * Refreshes the shared copy from the source when it is past its fresh window.+ * At most one pod does the network work; the rest see `lock_busy` and pick up+ * the new sha on their next poll. `missing` means the fleet has no copy, which+ * `loadOrRefresh` repairs.+ */+ async refreshIfStale(): Promise<SkillArchiveRefreshResult> {+ const version = await this.readVersion()+ if (!version) {+ return 'missing'+ }+ if ((await this.redis.ttl(this.blobKey(version.sha))) === -2) {+ return 'missing'+ }+ if (version.fresh) {+ return 'fresh'+ }++ const token = randomUUID()+ if (!(await this.acquireLock(token))) {+ return 'lock_busy'+ }+ try {+ return await this.refreshUnderLock(version)+ } finally {+ await this.releaseLock(token)+ }+ }++ private async refreshUnderLock(version: SharedBlobVersion): Promise<SkillArchiveRefreshResult> {+ const result = await this.fetchArchiveChecked(version.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.+ return (await this.touchCache(version)) ? 'not_modified' : 'missing'+ }+ await this.writeCache(result.bytes, result.etag)+ return 'downloaded'+ }++ /** 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') {+ if (result.bytes.length === 0 || result.bytes.length > MAX_ARCHIVE_BYTES) {+ throw new Error(`Invalid skill archive size: ${result.bytes.length} bytes`)+ }+ this.validateArchive(result.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 d7dc3f50a2ef..5c24f10a8a11 100644--- a/services/mcp/src/hono/dispatcher.ts+++ b/services/mcp/src/hono/dispatcher.ts@@ -23,6 +23,7 @@ import { randomUUID } from 'node:crypto'import { mapErrorToAuthResponse } from '@/lib/auth-errors'import { isLegacyDialectOnlyClient } from '@/lib/client-detection'import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'+import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'import type { RequestProperties } from '@/lib/request-properties'import {isModernRequest,@@ -37,11 +38,12 @@ import {import { trackInitEvent } from './analytics'import type { RedisLike } from './cache/RedisCache'-import { getEnv } from './constants'+import { getEnv, MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'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'@@ -135,6 +137,7 @@ class McpDispatcher {private readonly stateResolver: RequestStateResolverprivate readonly toolExecutor: ToolExecutorprivate readonly instructionsBuilder: InstructionsBuilder+ private readonly skillCatalogService: SkillCatalogServiceprivate warmupPromise: Promise<void> | undefined@@ -144,7 +147,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> {@@ -154,7 +158,16 @@ class McpDispatcher {private async doWarmup(): Promise<void> {await this.catalog.warmup()- await this.resourceCatalog.warmup()+ const skillsEnabled = resolveFeatureFlagOverrides()[MCP_EXEC_SKILLS_FEATURE_FLAG] !== false+ await Promise.all([+ this.resourceCatalog.warmup(),+ skillsEnabled ? this.skillCatalogService.warmup() : undefined,+ ])+ if (skillsEnabled) {+ // Skills refresh on a timer, never on a request: the July incident was every+ // handshake re-reading the archive from Redis.+ this.skillCatalogService.start()+ }}async handleRequest(req: Request, props: RequestProperties): Promise<Response> {diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.tsindex 8c98e615e3b1..954d06ba0684 100644--- a/services/mcp/src/hono/instructions.ts+++ b/services/mcp/src/hono/instructions.ts@@ -1,15 +1,19 @@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 type { QueryToolInfo } from '@/lib/instructions'import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'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,@@ -19,6 +23,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'@@ -80,7 +87,7 @@ export class InstructionsBuilder {return {name: 'exec',title: 'Execute PostHog command',- description: this.formatter.buildExecToolDescription(),+ description: this.buildExecToolDescription(state),inputSchema: { type: 'object', properties: ExecSchema, required: ['command'] },}}@@ -115,9 +122,13 @@ export class InstructionsBuilder {// own smaller-budget reference. (Codex, which reports// `supportsInstructions: false`, gets the full env-context via the// un-stripped path.)+ const { guidesEnabled, skillsEnabled } = this.getExecLearnCapabilities(state)const ctx = this.buildContext(state)if (state.clientProfile.isClaudeChatHost()) {- return this.formatter.buildClaudeExecCommandReference(ctx)+ return this.formatter.buildClaudeExecCommandReference(ctx, {+ learnEnabled: guidesEnabled || skillsEnabled,+ skillsEnabled,+ })}return this.formatter.buildExecCommandReference(ctx, {stripEnvContext: supportsInstructions,@@ -126,18 +137,50 @@ export class InstructionsBuilder {// on the tool-domain index, which is the part that can't be recovered by// any later tool call. This description has no such cap.keepEnvContext: true,+ 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 {@@ -153,4 +196,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/metrics.ts b/services/mcp/src/hono/metrics.tsindex af499de15c58..ba3a0e8bcb17 100644--- a/services/mcp/src/hono/metrics.ts+++ b/services/mcp/src/hono/metrics.ts@@ -159,6 +159,38 @@ export const contextMillBodyReadsTotal = new Counter({labelNames: ['status'] as const,})+// Product skill archive. `phase` is `warmup` (blocking boot load) or `poll` (the+// background timer); `result` is the cache outcome, `reloaded` when a pod adopted+// a newer shared archive, or `error`. Request handling never touches the archive,+// so a rising `poll` rate with no `reloaded` is the shape of a healthy fleet.+export const skillArchiveEventsTotal = new Counter({+ name: 'mcp_skill_archive_events_total',+ help: 'Product skill archive load and refresh outcomes by phase.',+ labelNames: ['phase', 'result'] as const,+})++export const skillCatalogSkills = new Gauge({+ name: 'mcp_skill_catalog_skills',+ help: 'Skills in the product skill catalog this pod serves.',+})++export const skillCatalogAgeSeconds = new Gauge({+ name: 'mcp_skill_catalog_age_seconds',+ help: 'Seconds since this pod last parsed a product skill archive.',+})++export const skillArchiveLastValidatedTimestampSeconds = new Gauge({+ name: 'mcp_skill_archive_last_validated_timestamp_seconds',+ help: 'Last successful upstream validation of the shared skill archive, observed by this pod. Zero until observed.',+})++export const skillCatalogLoadDurationSeconds = new Histogram({+ name: 'mcp_skill_catalog_load_duration_seconds',+ help: 'Time to parse a product skill archive into the in-memory catalog.',+ labelNames: ['phase'] as const,+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5],+})+export function routeLabel(pathname: string): string {if (pathname === '/mcp' || pathname.startsWith('/mcp/')) {return '/mcp'diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex eb953f386791..75f0c5536c37 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -25,6 +25,9 @@ import {type MCPSessionContext,} from './mcp-context'+// A session's gate markers only need to outlive the session itself.+const SESSION_CACHE_TTL_SECONDS = 24 * 60 * 60+export class RequestContext {private tokenCacheInstance: RedisCache<State> | undefinedprivate userCacheInstance: RedisCache<State> | undefined@@ -66,6 +69,11 @@ export class RequestContext {return this.userCacheInstance}+ /** State scoped to one MCP session, such as the skills-first gate markers. */+ getSessionCache(mcpSessionId: string): RedisCache<State> {+ return new RedisCache<State>(hash(mcpSessionId), this.redis, 'session', SESSION_CACHE_TTL_SECONDS)+ }+get cache(): RedisCache<State> {return this.tokenCache}diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex 200e85b0ccb1..f8dbff1501a9 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -24,6 +24,7 @@ import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'import { McpSessionRedisStore } from './cache/McpSessionRedisStore'import type { RedisLike } from './cache/RedisCache'+import { MCP_EXEC_SKILLS_FEATURE_FLAG } from './constants'import {buildMCPRequestContext,getEffectiveMCPClientContext,@@ -169,7 +170,8 @@ export class RequestStateResolver {// MCP_GATEWAY_FLAG gates no tool of its own — it gates the third-party tools `exec`// resolves — so the tool-definition scan can't discover it; join it in explicitly.- const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), MCP_GATEWAY_FLAG])]+ // MCP_EXEC_SKILLS_FEATURE_FLAG gates the `learn` skill commands the same way.+ const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), MCP_GATEWAY_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..d441115a130c--- /dev/null+++ b/services/mcp/src/hono/skill-catalog-service.ts@@ -0,0 +1,172 @@+import { SkillCatalog } from '@/skills/skill-catalog'++import type { RedisLike } from './cache/RedisCache'+import { SkillArchiveCache, type SkillArchiveCacheOptions } from './cache/SkillArchiveCache'+import {+ skillArchiveEventsTotal,+ skillArchiveLastValidatedTimestampSeconds,+ skillCatalogAgeSeconds,+ skillCatalogLoadDurationSeconds,+ skillCatalogSkills,+} from './metrics'++const DEFAULT_POLL_INTERVAL_MS = 60_000+const DEFAULT_POLL_JITTER_MS = 15_000+const DEFAULT_WARMUP_TIMEOUT_MS = 60_000+const DEFAULT_WARMUP_RETRY_MS = 2_000++export interface SkillCatalogServiceOptions extends SkillArchiveCacheOptions {+ /** Base interval between polls of the shared version key. */+ pollIntervalMs?: number+ /** Random extra per pod, so a fleet does not poll in lockstep. */+ pollJitterMs?: number+ /** How long startup waits for a catalog before the pod serves without one. */+ warmupTimeoutMs?: number+ warmupRetryMs?: number+}++type LoadPhase = 'warmup' | 'poll'++/**+ * Holds the parsed product skill catalog for this pod.+ *+ * Requests only ever read `getCatalog()` from memory. Startup blocks on the first+ * load, then `start()` runs a background poller that adopts a newer shared+ * archive and refreshes the shared copy when it is stale. A failed refresh or a+ * bad archive keeps the last catalog that parsed.+ */+export class SkillCatalogService {+ private readonly archiveCache: SkillArchiveCache+ private readonly pollIntervalMs: number+ private readonly pollJitterMs: number+ private readonly warmupTimeoutMs: number+ private readonly warmupRetryMs: number++ private catalog: SkillCatalog | undefined+ private archiveSha: string | undefined+ private loadedAt: number | undefined+ private timer: ReturnType<typeof setInterval> | undefined+ private polling = false++ constructor(redis: RedisLike, opts: SkillCatalogServiceOptions = {}) {+ const { pollIntervalMs, pollJitterMs, warmupTimeoutMs, warmupRetryMs, ...cacheOptions } = opts+ this.archiveCache = new SkillArchiveCache(redis, {+ ...cacheOptions,+ // Parse before the bytes can reach Redis: a release that does not parse+ // never becomes the fleet's shared copy.+ validateArchive: cacheOptions.validateArchive ?? ((bytes) => void SkillCatalog.fromZip(bytes)),+ })+ this.pollIntervalMs = pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS+ this.pollJitterMs = pollJitterMs ?? DEFAULT_POLL_JITTER_MS+ this.warmupTimeoutMs = warmupTimeoutMs ?? DEFAULT_WARMUP_TIMEOUT_MS+ this.warmupRetryMs = warmupRetryMs ?? DEFAULT_WARMUP_RETRY_MS+ }++ getCatalog(): SkillCatalog | undefined {+ return this.catalog+ }++ /**+ * Blocks boot until a catalog is in memory, retrying inside a fixed budget.+ * Past the budget the pod starts without skills rather than holding the whole+ * fleet unready during a source and Redis outage; the poller keeps trying.+ */+ async warmup(): Promise<void> {+ const deadline = Date.now() + this.warmupTimeoutMs+ for (;;) {+ try {+ const loaded = await this.archiveCache.loadOrRefresh()+ skillArchiveEventsTotal.inc({ phase: 'warmup', result: loaded.result })+ this.install(loaded.bytes, loaded.sha, 'warmup')+ return+ } catch (error) {+ skillArchiveEventsTotal.inc({ phase: 'warmup', result: 'error' })+ if (Date.now() + this.warmupRetryMs >= deadline) {+ console.error('[SkillCatalogService] warmup failed; starting without product skills:', error)+ return+ }+ console.error('[SkillCatalogService] warmup attempt failed; retrying:', error)+ await sleep(this.warmupRetryMs)+ } finally {+ skillArchiveLastValidatedTimestampSeconds.set((this.archiveCache.getLastValidatedAt() ?? 0) / 1000)+ }+ }+ }++ /** Starts the background poller. Idempotent; the timer never keeps the process alive. */+ start(): void {+ if (this.timer) {+ return+ }+ const interval = this.pollIntervalMs + Math.floor(Math.random() * this.pollJitterMs)+ this.timer = setInterval(() => void this.poll(), interval)+ this.timer.unref?.()+ }++ stop(): void {+ if (this.timer) {+ clearInterval(this.timer)+ this.timer = undefined+ }+ }++ /**+ * One poll: adopt a newer shared archive, then repair the shared copy if it is+ * stale or missing. Overlapping polls collapse into one.+ */+ async poll(): Promise<void> {+ if (this.polling) {+ return+ }+ this.polling = true+ try {+ await this.adoptSharedArchive()+ const refresh = await this.archiveCache.refreshIfStale()+ skillArchiveEventsTotal.inc({ phase: 'poll', result: refresh })+ if (refresh === 'downloaded') {+ await this.adoptSharedArchive()+ } else if (refresh === 'missing') {+ const loaded = await this.archiveCache.loadOrRefresh()+ skillArchiveEventsTotal.inc({ phase: 'poll', result: loaded.result })+ this.install(loaded.bytes, loaded.sha, 'poll')+ }+ } catch (error) {+ skillArchiveEventsTotal.inc({ phase: 'poll', result: 'error' })+ console.error('[SkillCatalogService] poll failed; keeping the current catalog:', error)+ } finally {+ this.polling = false+ skillArchiveLastValidatedTimestampSeconds.set((this.archiveCache.getLastValidatedAt() ?? 0) / 1000)+ if (this.loadedAt !== undefined) {+ skillCatalogAgeSeconds.set((Date.now() - this.loadedAt) / 1000)+ }+ }+ }++ private async adoptSharedArchive(): Promise<void> {+ const changed = await this.archiveCache.readIfChanged(this.archiveSha)+ if (!changed) {+ return+ }+ skillArchiveEventsTotal.inc({ phase: 'poll', result: 'reloaded' })+ this.install(changed.bytes, changed.sha, 'poll')+ }++ private install(bytes: Uint8Array, sha: string, phase: LoadPhase): void {+ if (sha === this.archiveSha) {+ return+ }+ const start = Date.now()+ const catalog = SkillCatalog.fromZip(bytes)+ this.catalog = catalog+ this.archiveSha = sha+ this.loadedAt = Date.now()+ skillCatalogLoadDurationSeconds.observe({ phase }, (this.loadedAt - start) / 1000)+ skillCatalogSkills.set(catalog.size)+ skillCatalogAgeSeconds.set(0)+ console.info(`[SkillCatalogService] installed ${catalog.size} skills (${phase}, sha ${sha.slice(0, 12)})`)+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}diff --git a/services/mcp/src/hono/skills-session.ts b/services/mcp/src/hono/skills-session.tsnew file mode 100644index 000000000000..1952a4cee173--- /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+ * a Redis cache keyed on the MCP session id. Requires that 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.getSessionCache(mcpSessionId)+ 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 0c7fc2973ec9..77e6f4c1f52b 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -47,6 +47,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 {@@ -95,10 +97,16 @@ function shouldSuppressStructuredContent(args: {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> {@@ -558,15 +566,21 @@ 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()+ ),flagGatedTools: state.flagGatedTools,+ skillsSession: this.instructionsBuilder.execSkillsEnabled(state)+ ? buildSkillsSessionState(state.reqCtx, state.requestContext.mcpSessionId)+ : undefined,...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),// A verb-only report lands first; `search` then reports again with its query// and counts. Merge so the richer report wins without losing the verb.diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex 36e50a9bdd92..e538f41d8051 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -154,6 +154,7 @@ export type ExecCommandErrorReason =| 'invalid_regex'| 'unknown_learn_topic'| 'needs_confirmation'+ | 'skills_gate'/*** Thrown by the `exec` dispatcher when it rejects a command before any innerdiff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 2b774f527c38..8c60f9deab01 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -18,6 +18,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'@@ -32,9 +34,10 @@ import METRIC_DISCOVERY from '@/templates/sections/metric-discovery.md'import NOTEBOOK_PYTHON from '@/templates/sections/notebook-python.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, LEARN_COMMAND_LINE } from '@/tools/exec-help'+import { type ExecLearnGuide, LEARN_COMMAND_LINE } from '@/tools/exec-learn'export interface InstructionsContext {guidelines: string@@ -116,9 +119,17 @@ export class InstructionsFormatter {})}- /** 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}`}/**@@ -126,11 +137,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:'Query or analyze PostHog data; governed metrics, certified tables, and verified joins live in the catalog.',@@ -152,7 +162,6 @@ 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 }),@@ -162,7 +171,6 @@ export class InstructionsFormatter {// URL rules are task-specific and load on demand instead of consuming Claude's capped input schema.entries.push({id: 'urls',- kind: 'guide',title: 'URL patterns',description: 'Load before writing any PostHog app link or URL.',content: this.compose([URL_PATTERNS], ctx, { compact: false }),@@ -170,7 +178,6 @@ export class InstructionsFormatter {entries.push({id: 'feedback',- kind: 'guide',title: 'Feedback',description: 'Send feedback about PostHog.',content: this.compose([AGENT_FEEDBACK], ctx, { compact: false }),@@ -186,10 +193,15 @@ 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 ?? false+ 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.metadataCompact ?? ctx.metadata,@@ -200,7 +212,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] : []),METRIC_DISCOVERY_COMPACT,CLI_SCHEMA_DRILLDOWN,CLI_DATA_DISCOVERY,@@ -209,12 +225,15 @@ export class InstructionsFormatter {BASIC_FUNCTIONALITY,TOOL_SEARCH,ENV_CONTEXT,+ // 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_COMMAND_LINE,+ extraCommands: learnEnabled ? LEARN_COMMAND_LINE : undefined,})}@@ -236,10 +255,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 ? [CLI_LEARN] : []),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..55d9d024f1fa--- /dev/null+++ b/services/mcp/src/skills/project-skill-catalog.ts@@ -0,0 +1,329 @@+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+// Matches MAX_SKILL_BODY_BYTES in products/skills/backend/api/skill_serializers.py.+const MAX_PROJECT_SKILL_BODY_BYTES = 1_000_000+// Zero-hit fallback fan-out: at most this many single-token backend searches, longest tokens first.+const MAX_FALLBACK_SEARCH_TOKENS = 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()+ const path = `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/name/${encodeURIComponent(name)}/`+ const skill = await this.context.api.request<Schemas.LLMSkill>({+ method: 'GET',+ path,+ // A character count this large covers every valid UTF-8 body without the API's default paging.+ query: { body_length: MAX_PROJECT_SKILL_BODY_BYTES },+ })+ if (new TextEncoder().encode(skill.body).byteLength > MAX_PROJECT_SKILL_BODY_BYTES) {+ throw new Error('Skill body exceeds the 1 MB limit. Split detailed instructions into companion files.')+ }++ // Django counts Unicode code points; JavaScript string.length counts UTF-16 code units.+ let bodyLength = 0+ for (const _character of skill.body) {+ bodyLength+++ }+ if (skill.body_next_offset !== null || bodyLength !== skill.body_total_length) {+ throw new Error('The API returned an incomplete skill body. Try fetching the skill again.')+ }+ return skill+ })+ }++ 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..d8a83276e40e--- /dev/null+++ b/services/mcp/src/skills/skill-catalog.ts@@ -0,0 +1,624 @@+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: countLines(content),+ 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 scope = manifest ? `${manifest}\n\n` : ''+ let output = appendLearnOutput(+ '',+ `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`+ )+ let hasHeadings = false+ for (const line of scanLines(file.content)) {+ if (output.length > LEARN_OUTPUT_CHAR_LIMIT) {+ break+ }+ const text = file.content.slice(line.start, line.end)+ if (/^#{1,6}\s+/.test(text)) {+ output = appendLearnOutput(output, `${hasHeadings ? '\n' : ''}${line.number}: `)+ output = appendLearnOutput(output, text)+ hasHeadings = true+ }+ }+ return fitLearnOutput(hasHeadings ? output : appendLearnOutput(output, '(No Markdown headings found.)'))+}++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)+ let output = appendLearnOutput('', `Matches in ${identifier}/${file.path}:\n\n`)+ let matches = 0+ const previousStarts: number[] = []+ for (const line of scanLines(file.content)) {+ if (matchesQuery(file.content.slice(line.start, line.end), normalizedQuery)) {+ if (matches > 0) {+ output = appendLearnOutput(output, '\n\n')+ }+ const startNumber = line.number - previousStarts.length+ for (const context of scanLines(file.content, previousStarts[0] ?? line.start, startNumber)) {+ output = appendLearnOutput(output, `${context.number === startNumber ? '' : '\n'}${context.number}: `)+ output = appendLearnOutput(output, file.content.slice(context.start, context.end))+ if (context.number === line.number + SEARCH_CONTEXT_LINES || output.length > LEARN_OUTPUT_CHAR_LIMIT) {+ break+ }+ }+ matches += 1+ if (matches === MAX_SCOPED_MATCHES || output.length > LEARN_OUTPUT_CHAR_LIMIT) {+ break+ }+ }+ previousStarts.push(line.start)+ if (previousStarts.length > SEARCH_CONTEXT_LINES) {+ previousStarts.shift()+ }+ }++ if (matches === 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>\`.`+ )+ }++ return fitLearnOutput(output)+}++export function readLearnLines(identifier: string, file: SkillFile, start: number, end: number): string {+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 1 || end < start || end > file.lineCount) {+ throw new Error(`Invalid line range ${start}:${end}. ${identifier}/${file.path} has ${file.lineCount} lines.`)+ }++ let result = `File: ${identifier}/${file.path} lines ${start}:${end}\n\n`+ for (const line of scanLines(file.content)) {+ if (line.number < start) {+ continue+ }+ result = appendLearnOutput(result, `${line.number === start ? '' : '\n'}${line.number}: `)+ result = appendLearnOutput(result, file.content.slice(line.start, line.end))+ if (result.length > LEARN_OUTPUT_CHAR_LIMIT) {+ throw new Error(+ `Requested line range exceeds ${LEARN_OUTPUT_CHAR_LIMIT} characters. Request a smaller line range.`+ )+ }+ if (line.number === end) {+ break+ }+ }+ 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}`+}++// Keep one extra character so fitLearnOutput can distinguish exact fits from truncated output.+function appendLearnOutput(output: string, value: string): string {+ return output + value.slice(0, Math.max(0, LEARN_OUTPUT_CHAR_LIMIT + 1 - output.length))+}++function countLines(content: string): number {+ let count = 1+ for (let index = content.indexOf('\n'); index !== -1; index = content.indexOf('\n', index + 1)) {+ count += 1+ }+ return count+}++function* scanLines(content: string, start = 0, number = 1): Generator<{ start: number; end: number; number: number }> {+ for (;;) {+ const newline = content.indexOf('\n', start)+ yield { start, end: newline === -1 ? content.length : newline, number }+ if (newline === -1) {+ return+ }+ start = newline + 1+ number += 1+ }+}++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/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 777bbb1a0907..000000000000--- a/services/mcp/src/tools/exec-help.ts+++ /dev/null@@ -1,42 +0,0 @@-// Syntax line for the `learn` verb, appended to the command reference on hosts-// that receive the help catalog. Shared with scripts/generate-exec-docs.ts so the-// published docs can't drift from the runtime declaration.-export const LEARN_COMMAND_LINE = 'learn <topic...> - load one or more learning topics\n'--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..92ab3765a888--- /dev/null+++ b/services/mcp/src/tools/exec-learn.ts@@ -0,0 +1,534 @@+import type { ProjectSkillCatalog, ProjectSkillList } from '@/skills/project-skill-catalog'+import {+ fitLearnOutput,+ formatLearnSearchResults,+ type LearnSearchResult,+ MAX_GLOBAL_SKILLS,+ type SkillCatalog,+} from '@/skills/skill-catalog'++// Syntax line for the `learn` verb, appended to the command reference on hosts+// that receive a learn catalog. Shared with scripts/generate-exec-docs.ts so the+// published docs can't drift from the runtime declaration.+export const LEARN_COMMAND_LINE = 'learn <topic...> - load one or more learning topics\n'++export interface ExecLearnGuide {+ id: string+ title: string+ description: string+ content: string+}++export type ExecLearnGuideSummary = Omit<ExecLearnGuide, 'content'>++/** A skill source is down or not configured — an operational condition, not an agent mistake. */+export class SkillsUnavailableError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'SkillsUnavailableError'+ }+}++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 SkillsUnavailableError(+ 'PostHog skills are temporarily unavailable. Core exec commands are still available.'+ )+ }+ return this.skillSources.posthog+ }++ private requireProjectSkills(): ProjectSkillCatalog {+ if (!this.skillSources?.project) {+ throw new SkillsUnavailableError(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 0914251aa45e..bca486cafc96 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -3,12 +3,18 @@ import { z } from 'zod'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'-import { ExecCommandError, findRecoverableApiError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'+import {+ ExecCommandError,+ type ExecCommandErrorReason,+ findRecoverableApiError,+ PostHogApiError,+ ToolInputValidationError,+} from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'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 { getToolDefinitions, type FlagGatedTool, type ScopeGatedTool } from './toolDefinitions'@@ -115,9 +121,26 @@ export interface ExecCommandMeta {export type ExecCommandTracker = (meta: ExecCommandMeta) => 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+ /** Present only when skill distribution is enabled and the client has a session. */+ skillsSession?: SkillsSessionState/*** 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@@ -141,6 +164,77 @@ export interface ExecToolOptions {flagGatedTools?: FlagGatedTool[]}+const CALL_USAGE = 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>'++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 ...`.'++/**+ * Plain errors out of the learn catalog are agent mistakes — unknown names, bad+ * line ranges, empty queries — so type them to keep them out of the `internal`+ * bucket ops alerts on. Anything that already carries its own class (an API+ * failure, a source outage, an exec error) propagates untouched.+ */+function classifyLearnError(error: unknown): unknown {+ if (!(error instanceof Error) || error.constructor !== Error) {+ return error+ }+ const reason: ExecCommandErrorReason = error.message.startsWith('Unknown ') ? 'unknown_learn_topic' : 'usage'+ return new ExecCommandError(error.message, reason)+}++/**+ * 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 }> {return z.object({command: z.string().describe(commandReference),@@ -156,10 +250,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)@@ -173,10 +268,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.@@ -933,37 +1033,27 @@ export function createExecTool(switch (verb) {case 'learn': {- const helpCatalog = options.helpCatalog- if (!helpCatalog) {+ const learnCatalog = options.learnCatalog+ if (!learnCatalog) {// `learn` is only advertised when a catalog exists, so without one// it's an unsupported verb rather than a misuse of a real command.throw new ExecCommandError(- 'The learning catalog is not available for this client.',+ 'The learn command is not available for this client.','unknown_command')}- if (!rest) {- return JSON.stringify(helpCatalog.list())- }- 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(', ')- const unknownTopics = unknownTopicIds.map((topicId) => `"${topicId}"`).join(', ')- throw new ExecCommandError(- `Unknown learning topic${unknownTopicIds.length === 1 ? '' : 's'}: ${unknownTopics}. Available: ${available}`,- 'unknown_learn_topic'- )+ let learnResult: string+ try {+ learnResult = await learnCatalog.execute(rest)+ } catch (error) {+ throw classifyLearnError(error)}- const resolvedEntries = entries.filter((entry) => entry !== undefined)- if (resolvedEntries.length === 1) {- return resolvedEntries[0]!.content+ // 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)}- return resolvedEntries.map((entry) => `## ${entry.title}\n\n${entry.content}`).join('\n\n')+ return learnResult}case 'tools': {@@ -1169,19 +1259,23 @@ export function createExecTool(case 'call': {if (!rest) {- throw new ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')+ throw new ExecCommandError(CALL_USAGE, 'usage')}if (!context) {// Deliberately untyped: a wiring fault, not an agent mistake, so it// belongs in the `internal` bucket its siblings are kept out of.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 ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')+ throw new ExecCommandError(CALL_USAGE, 'usage')}const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, toolName)+ const gateMessage = await resolveSkillsGate(options.skillsSession, noSkills)+ if (gateMessage) {+ throw new ExecCommandError(gateMessage, 'skills_gate')+ }if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {throw new ExecCommandError(`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.`,@@ -1359,7 +1453,7 @@ export function createExecTool(default:throw new ExecCommandError(- `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`,'unknown_command')}diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.tsindex 5f6b99b92c5d..c2e4ed3e30de 100644--- a/services/mcp/src/tools/types.ts+++ b/services/mcp/src/tools/types.ts@@ -32,6 +32,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> &@@ -90,6 +92,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 674a24cddba7..eccbdfefe494 100644--- a/services/mcp/tests/hono/analytics.test.ts+++ b/services/mcp/tests/hono/analytics.test.ts@@ -15,8 +15,18 @@ vi.mock('@/lib/posthog', () => ({})),}))-import { trackExecuteSqlGeneration, trackInitEvent, trackToolCall, trackToolSpan } from '@/hono/analytics'+import {+ trackExecuteSqlGeneration,+ trackInitEvent,+ trackSkillInvoked,+ trackToolCall,+ trackToolSpan,+} 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'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolDefinition } from '@/tools/toolDefinitions'function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {@@ -481,4 +491,68 @@ describe('Hono MCP analytics contexts', () => {expect(JSON.parse($ai_input_state).payload[field]).toBe(redacted ? '[redacted]' : 'sensitive-value')})})++ 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/context-mill-resource-cache.test.ts b/services/mcp/tests/hono/context-mill-resource-cache.test.tsindex 6e93a18553e3..f2ed54e865ba 100644--- a/services/mcp/tests/hono/context-mill-resource-cache.test.ts+++ b/services/mcp/tests/hono/context-mill-resource-cache.test.ts@@ -16,6 +16,7 @@ import type { RedisLike } from '@/hono/cache/RedisCache'import type { ContextMillResource } from '@/resources/manifest-types'import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'+import { makeSharedBlobRedisStubs } from './helpers/shared-blob-redis-stubs'type EntryLoader = () => Promise<ContextMillResource[]>@@ -67,14 +68,14 @@ function createMockRedis(): MockRedis {}),scan: vi.fn(async () => ['0', []] as [string, string[]]),...makeRedisRateLimitStubs(),+ ...makeSharedBlobRedisStubs(store),_store: store,_setCalls: setCalls,}}-const MANIFEST_BYTES_KEY = 'mcp:shared-blob:context-mill:manifest:bytes'-const MANIFEST_FRESH_KEY = 'mcp:shared-blob:context-mill:manifest:fresh'-const MANIFEST_LOCK_KEY = 'mcp:shared-blob:context-mill:manifest:lock'+const MANIFEST_CURRENT_KEY = 'mcp:shared-blob:context-mill:manifest:v2:current'+const MANIFEST_LOCK_KEY = 'mcp:shared-blob:context-mill:manifest:v2:lock'function bodyKey(uri: string): string {const hash = createHash('sha256').update(uri).digest('hex')@@ -117,8 +118,8 @@ describe('ContextMillResourceCache', () => {expect(slim.entries.map((e) => e.uri).sort()).toEqual(entries.map((e) => e.uri).sort())expect(slim.entries[0]).not.toHaveProperty('text')- // Body keys must land before the manifest bytes key in Redis writes.- const manifestIdx = redis._setCalls.indexOf(MANIFEST_BYTES_KEY)+ // Body keys must land before readers can discover the manifest.+ const manifestIdx = redis._setCalls.indexOf(MANIFEST_CURRENT_KEY)expect(manifestIdx).toBeGreaterThan(-1)for (const e of entries) {const bodyIdx = redis._setCalls.indexOf(bodyKey(e.uri))@@ -360,7 +361,7 @@ describe('ContextMillResourceCache', () => {expect(slim.entries[0]!.uri).toBe(entries[0]!.uri)expect(result).toBe('fallback')expect(upstream).toHaveBeenCalledTimes(1)- expect(redis._store.has(MANIFEST_BYTES_KEY)).toBe(false)+ expect(redis._store.has(MANIFEST_CURRENT_KEY)).toBe(false)expect(mockCacheEventsInc).toHaveBeenCalledWith({ event: 'wait_timeout' })})@@ -368,6 +369,6 @@ describe('ContextMillResourceCache', () => {const cache = new TestContextMillResourceCache(redis, async () => [makeEntry('a')])await cache.loadOrRefresh()expect(redis._store.has(MANIFEST_LOCK_KEY)).toBe(false)- expect(redis._store.has(MANIFEST_FRESH_KEY)).toBe(true)+ expect(redis._store.has(MANIFEST_CURRENT_KEY)).toBe(true)})})diff --git a/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts b/services/mcp/tests/hono/dispatcher-init-revalidation.test.tsindex 281efda93995..04521bb60550 100644--- a/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts+++ b/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const {mockBuildInstructions,@@ -6,6 +6,7 @@ const {mockInitTotalInc,mockRevalidateContextMillResources,mockResolveState,+ mockSkillCatalogService,mockTrackInitEvent,} = vi.hoisted(() => ({mockBuildInstructions: vi.fn(),@@ -13,9 +14,22 @@ const {mockInitTotalInc: vi.fn(),mockRevalidateContextMillResources: vi.fn(),mockResolveState: vi.fn(),+ mockSkillCatalogService: {+ getCatalog: vi.fn(),+ poll: vi.fn(),+ start: vi.fn(),+ stop: vi.fn(),+ warmup: vi.fn(),+ },mockTrackInitEvent: vi.fn(),}))+vi.mock('@/hono/skill-catalog-service', () => ({+ SkillCatalogService: vi.fn().mockImplementation(function () {+ return mockSkillCatalogService+ }),+}))+vi.mock('@/hono/analytics', () => ({trackInitEvent: mockTrackInitEvent,}))@@ -120,8 +134,11 @@ describe('McpDispatcher initialize resource revalidation', () => {mockResolveState.mockResolvedValue({ distinctId: 'test-distinct-id' })mockTrackInitEvent.mockResolvedValue(undefined)mockRevalidateContextMillResources.mockResolvedValue(undefined)+ mockSkillCatalogService.warmup.mockReset().mockResolvedValue(undefined)})+ afterEach(() => vi.unstubAllEnvs())+it('awaits context-mill resource revalidation before returning initialize', async () => {let resolveRevalidation: (() => void) | undefinedconst revalidationPromise = new Promise<void>((resolve) => {@@ -149,4 +166,43 @@ describe('McpDispatcher initialize resource revalidation', () => {expect(body.result.protocolVersion).toBe(LATEST_PROTOCOL_VERSION)expect(mockBuildInstructions).toHaveBeenCalled()})++ // The reverted skill discovery revalidated the skill archive on every handshake,+ // which re-read megabytes from Redis per session. The archive moves only at warmup+ // and on the service's own timer.+ it('does no skill archive work on initialize', async () => {+ const dispatcher = new McpDispatcher({} as any, createMockRedis())++ const response = await dispatcher.handleRequest(makeInitializeRequest(), makeProps())++ expect(response.status).toBe(200)+ for (const method of ['warmup', 'poll', 'start'] as const) {+ expect(mockSkillCatalogService[method]).not.toHaveBeenCalled()+ }+ })++ it.each([+ ['development', false, false],+ ['test', false, false],+ ['development', true, true],+ ['development', undefined, true],+ ['production', false, true],+ ] as const)('honors startup overrides only in dev/test (%s, flag %s)', async (nodeEnv, override, enabled) => {+ vi.stubEnv('NODE_ENV', nodeEnv)+ vi.stubEnv('FEATURE_FLAG_OVERRIDES', JSON.stringify({ 'mcp-exec-skills': override }))+ if (!enabled) {+ mockSkillCatalogService.warmup.mockRejectedValue(new Error('archive unavailable'))+ }+ const dispatcher = new McpDispatcher({ warmup: vi.fn(async () => {}) } as any, createMockRedis())++ await dispatcher.warmup()++ expect(mockSkillCatalogService.warmup).toHaveBeenCalledTimes(enabled ? 1 : 0)+ expect(mockSkillCatalogService.start).toHaveBeenCalledTimes(enabled ? 1 : 0)+ if (enabled) {+ expect(mockSkillCatalogService.start.mock.invocationCallOrder[0]).toBeGreaterThan(+ mockSkillCatalogService.warmup.mock.invocationCallOrder[0]!+ )+ }+ })})diff --git a/services/mcp/tests/hono/helpers/shared-blob-redis-stubs.ts b/services/mcp/tests/hono/helpers/shared-blob-redis-stubs.tsnew file mode 100644index 000000000000..b9fe5faa98a7--- /dev/null+++ b/services/mcp/tests/hono/helpers/shared-blob-redis-stubs.ts@@ -0,0 +1,22 @@+import { vi } from 'vitest'++import type { RedisLike } from '@/hono/cache/RedisCache'++export function makeSharedBlobRedisStubs(store: Map<string, string>): Pick<RedisLike, 'ttl' | 'expire' | 'eval'> {+ return {+ ttl: vi.fn(async (key: string) => (store.has(key) ? 60 : -2)),+ expire: vi.fn(async (key: string) => (store.has(key) ? 1 : 0)),+ eval: vi.fn(async (_script: string, numberOfKeys: number, ...args: (string | number)[]) => {+ if (numberOfKeys === 1) {+ const [key, token] = args.map(String)+ return store.get(key!) === token ? Number(store.delete(key!)) : 0+ }+ const [key, blobKey, expected, replacement] = args.map(String)+ if (store.get(key!) !== expected || !store.has(blobKey!)) {+ return 0+ }+ store.set(key!, replacement!)+ return 1+ }),+ }+}diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex a5968fee414f..c77128d74cfb 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -79,8 +79,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 { TASKS_CONTEXT_TOOL_NAMES } from '@/tools/tasksContext'import type { Env } from '@/tools/types'@@ -317,6 +318,19 @@ describe('RequestStateResolver MCP client contexts', () => {expect(props.mode).toBe('cli')})+ it('evaluates the exec skills flag even though no generated tool declares it', 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('honors a dev/test flag override even when evaluation returns nothing', async () => {// Evaluation stays empty (analytics client disabled, as in local dev/evals);// the override seam is what flips a tool flag on so it reaches the tool layer.diff --git a/services/mcp/tests/hono/resource-catalog.test.ts b/services/mcp/tests/hono/resource-catalog.test.tsindex 074bfb60a474..51b1f189e093 100644--- a/services/mcp/tests/hono/resource-catalog.test.ts+++ b/services/mcp/tests/hono/resource-catalog.test.ts@@ -45,6 +45,7 @@ import { fetchAndExtractEntries } from '@/resources/internals'import type { ContextMillResource } from '@/resources/manifest-types'import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'+import { makeSharedBlobRedisStubs } from './helpers/shared-blob-redis-stubs'const mockEnv = {MCP_APPS_BASE_URL: 'https://apps.test',@@ -78,6 +79,7 @@ function createMockRedis(): MockRedis {}),scan: vi.fn(async () => ['0', []] as [string, string[]]),...makeRedisRateLimitStubs(),+ ...makeSharedBlobRedisStubs(store),_store: store,}}@@ -95,8 +97,7 @@ function makeEntry(suffix: string): ContextMillResource {}}-const MANIFEST_BYTES_KEY = 'mcp:shared-blob:context-mill:manifest:bytes'-const MANIFEST_FRESH_KEY = 'mcp:shared-blob:context-mill:manifest:fresh'+const MANIFEST_CURRENT_KEY = 'mcp:shared-blob:context-mill:manifest:v2:current'describe('ResourceCatalog', () => {let redis: MockRedis@@ -161,8 +162,7 @@ describe('ResourceCatalog', () => {const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- redis._store.delete(MANIFEST_BYTES_KEY)- redis._store.delete(MANIFEST_FRESH_KEY)+ redis._store.delete(MANIFEST_CURRENT_KEY)vi.mocked(fetchAndExtractEntries).mockResolvedValueOnce([makeEntry('new')])await catalog.revalidateContextMillResources('initialize')@@ -186,8 +186,7 @@ describe('ResourceCatalog', () => {const catalog = new ResourceCatalog(mockEnv, redis)await catalog.warmup()- redis._store.delete(MANIFEST_BYTES_KEY)- redis._store.delete(MANIFEST_FRESH_KEY)+ redis._store.delete(MANIFEST_CURRENT_KEY)vi.mocked(fetchAndExtractEntries).mockRejectedValueOnce(new Error('network'))await catalog.revalidateContextMillResources('initialize')diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.tsindex 1b8124e8e053..17044d536182 100644--- a/services/mcp/tests/hono/setup.ts+++ b/services/mcp/tests/hono/setup.ts@@ -31,6 +31,20 @@ 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> {}+ start(): void {}+ stop(): void {}+ async poll(): 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..24e4c235ea40 100644--- a/services/mcp/tests/hono/shared-blob-cache.test.ts+++ b/services/mcp/tests/hono/shared-blob-cache.test.ts@@ -4,6 +4,7 @@ import type { RedisLike } from '@/hono/cache/RedisCache'import { SharedBlobCache, type SharedBlobCacheOptions } from '@/hono/cache/SharedBlobCache'import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'+import { makeSharedBlobRedisStubs } from './helpers/shared-blob-redis-stubs'class TestSharedBlobCache extends SharedBlobCache {constructor(redis: RedisLike, namespace: string, opts?: SharedBlobCacheOptions) {@@ -14,8 +15,8 @@ class TestSharedBlobCache extends SharedBlobCache {return this.readCache()}- write(bytes: Uint8Array): Promise<void> {- return this.writeCache(bytes)+ async write(bytes: Uint8Array, validator?: string): Promise<void> {+ await this.writeCache(bytes, validator)}acquire(token: string): Promise<boolean> {@@ -61,15 +62,15 @@ function createMockRedis(): MockRedis {}),scan: vi.fn(async () => ['0', []] as [string, string[]]),...makeRedisRateLimitStubs(),+ ...makeSharedBlobRedisStubs(store),_store: store,_setCalls: setCalls,}}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 CURRENT_KEY = `mcp:shared-blob:${NAMESPACE}:v2:current`+const LOCK_KEY = `mcp:shared-blob:${NAMESPACE}:v2:lock`describe('SharedBlobCache', () => {let redis: MockRedis@@ -85,9 +86,25 @@ describe('SharedBlobCache', () => {await cache.write(bytes)const cached = await cache.read()- expect(cached).toEqual({ bytes, fresh: true })- expect(redis._store.has(BYTES_KEY)).toBe(true)- expect(redis._store.has(FRESH_KEY)).toBe(true)+ expect(cached).toMatchObject({ bytes, fresh: true })+ expect(redis._store.has(CURRENT_KEY)).toBe(true)+ })++ it.each(['blob', 'pointer'])('keeps the previous generation when the %s write fails', async (failure) => {+ const cache = new TestSharedBlobCache(redis, NAMESPACE)+ const original = new Uint8Array([4, 5, 6])+ await cache.write(original, 'etag-old')+ const pointer = redis._store.get(CURRENT_KEY)+ redis.set = vi.fn(async (key: string, ...rest: (string | number)[]) => {+ if (failure === 'blob' ? key.includes(':blob:') : key === CURRENT_KEY) {+ throw new Error('write failed')+ }+ redis._store.set(key, String(rest[0]))+ return 'OK'+ })+ await expect(cache.write(new Uint8Array([1, 2, 3]), 'etag-new')).rejects.toThrow('write failed')+ expect(redis._store.get(CURRENT_KEY)).toBe(pointer)+ expect(await cache.read()).toMatchObject({ bytes: original, etag: 'etag-old' })})it('marks cached bytes stale after the freshness window', async () => {@@ -106,8 +123,8 @@ describe('SharedBlobCache', () => {await a.write(new Uint8Array([1]))await b.write(new Uint8Array([2]))- expect(redis._store.has('mcp:shared-blob:alpha:bytes')).toBe(true)- expect(redis._store.has('mcp:shared-blob:beta:bytes')).toBe(true)+ expect(redis._store.has(a.currentKey)).toBe(true)+ expect(redis._store.has(b.currentKey)).toBe(true)expect((await a.read())?.bytes).toEqual(new Uint8Array([1]))expect((await b.read())?.bytes).toEqual(new Uint8Array([2]))@@ -122,13 +139,16 @@ describe('SharedBlobCache', () => {expect(redis._store.get(LOCK_KEY)).toBe('first')})- it('releases the lock', async () => {+ it.each([false, true])('releases only its own lock (replaced: %s)', async (replaced) => {const cache = new TestSharedBlobCache(redis, NAMESPACE)await cache.acquire('token')+ if (replaced) {+ redis._store.set(LOCK_KEY, 'next-writer')+ }await cache.release('token')- expect(redis._store.has(LOCK_KEY)).toBe(false)+ expect(redis._store.get(LOCK_KEY)).toBe(replaced ? 'next-writer' : undefined)})it('waits for another writer to publish', async () => {diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex f44c8ed4a15e..6ab9026741e0 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -12,12 +12,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 { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'import { getToolDefinition } from '@/tools/toolDefinitions'import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'@@ -193,6 +195,209 @@ describe('ToolExecutor', () => {expect(result.tools[0]!.name).toBe('exec')})+ // The flag decides skill exposure per client; guides stay a Claude chat-host+ // feature; plugin and sandbox consumers get neither because they carry their+ // own skills. A regression in any row silently changes what an agent is told.+ 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: [makeSkillFile('SKILL.md', '# Sample skill')],+ },+ ])+ 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('learn <topic...>')).toBe(expectGuides)+ expect(listed.tools[0]!.description!.includes('SKILLS FIRST')).toBe(expectSkills)++ 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.',+ })+ }+ }+ )++ 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('tells the agent project skills need the read scope instead of failing silently', async () => {+ const state = makeState([], {+ useSingleExec: true,+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },+ apiKeyScopes: ['insight:read'],+ })++ const result = (await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'learn skills' } },+ state+ )) as { content: { text: string }[] }++ expect(JSON.parse(result.content[0]!.text).project).toEqual({+ available: false,+ reason: expect.stringContaining('llm_skill:read'),+ })+ })+// Active project metadata reaches the model on the exec `command` for every// single-exec client, including the ones that honor `instructions`: that payload is// capped at MCP_INSTRUCTIONS_CHAR_BUDGET and spends all of it on the tool-domaindiff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txtnew file mode 100644index 000000000000..d56b60ae236c--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt@@ -0,0 +1,178 @@+CLI-style command string. Supported commands:++```text+learn <topic...> - load one or more learning topics+tools — list available tool names+search <regex_pattern> — search tools by JavaScript regex (matches name, title, description)+info [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.+schema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)+call [--json] [--confirm] <tool_name> <json_input> — call a tool with JSON input (--json returns JSON instead of optimized output in supported tools. Informational responses remain tagged and escaped in both MCP and the agent CLI. --confirm is required by the CLI for destructive tools.)+```++**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.++- analytics: Query or analyze PostHog data; governed metrics, certified tables, and verified joins live in the catalog.+- visualizations: Create or render a visualization.+- urls: Load before writing any PostHog app link or URL.+- feedback: Send feedback about PostHog.++**Metrics & SQL trust**: for any metric question (business or operational), inspect the complete governed catalog with `metric-list` before insights, domain tools, or raw SQL. Use `metric-describe` for a candidate's definition, including HogQL or SQL, before adapting it. Run `learn analytics` before writing SQL or joins — it covers certified tables/views and verified joins. State the catalog outcome in query context.++**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.++If `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.++If `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.++**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.++For query tools, you will typically need:++- `schema <tool> series` — to see EventsNode/ActionsNode structure+- `schema <tool> series.properties` — to see property filter structure of series++**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.++**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,+`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via+`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary+per team. If the event isn't in the schema, tell the user instead of querying a guessed name.++Always run `info read-data-schema` first — the recipes below are common cases, not the full schema.++- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed). Actions come from `actions-get-all` instead.+- Event properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`+- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session`, or a group type name)+- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`++**CORRECT usage pattern:**++<example>+User: create pageviews visualization+Assistant: This needs analytics and visualization guidance, so I'll load both first.+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]+</example>++<example>+User: How many weekly active users do we have?+Assistant: This needs analytics and visualization guidance, so I'll load both before any other command.+[Runs `posthog:exec({"command":"learn analytics visualizations"})`]+Assistant: I need the query and data schema tools.+[Runs `posthog:exec({"command":"search query-trends"})` and `posthog:exec({"command":"search read-data"})` in parallel]+Assistant: I'll inspect both schemas.+[Runs `posthog:exec({"command":"info query-trends"})` and `posthog:exec({"command":"info read-data-schema"})` in parallel]+Assistant: The hinted series needs its full schema, and I need the team's events.+[Runs `posthog:exec({"command":"schema query-trends series"})` and `posthog:exec({"command":"call read-data-schema {\"query\":{\"kind\":\"events\"}}"})` in parallel]+Assistant: I now have the inputs for the query.+[Runs `posthog:exec({"command":"call query-trends {...}"})`]+Assistant: [Briefly summarizes the weekly active user trend.] I'll render it so you can verify the result.+[Runs `render-ui({ "tool_name": "query-trends", "tool_input": {...} })` with the same query input]+</example>++<example>+User: Create a dashboard for our key revenue metrics+Assistant: Analytics applies. I'll load it before any other command.+[Runs `posthog:exec({"command":"learn analytics"})`]+Assistant: I need dashboard and query tools.+[Runs `posthog:exec({"command":"search dashboard"})` and `posthog:exec({"command":"search execute-sql"})` in parallel]+Assistant: I'll inspect both schemas.+[Runs `posthog:exec({"command":"info dashboard-create"})` and `posthog:exec({"command":"info execute-sql"})` in parallel]+Assistant: I have the inputs to create the dashboard.+[Makes call commands with correct parameters]+</example>++**INCORRECT usage patterns: NEVER do this**++<bad-example>+User: Show me our feature flags+Assistant: [Calls `feature-flag-get-all` with guessed parameters]+WRONG: Run `info feature-flag-get-all` first.+</bad-example>++<bad-example>+User: Query our events+Assistant: [Loads analytics, then calls three tools without inspecting them]+WRONG: Run `info` for all tools before any `call` commands.+</bad-example>++<bad-example>+User: Show me a trends chart of signups+Assistant: [Runs `learn analytics visualizations`, then runs `info query-trends` and guesses the hinted series structure]+WRONG: Run `schema query-trends series` before populating a field with a drill-down hint.+</bad-example>++<bad-example>+User: query pageviews for the last 7 days+Assistant: [Runs `learn analytics`, then queries the guessed `$pageview` event]+WRONG: Confirm the event with `call read-data-schema {"query":{"kind":"events"}}` first.+</bad-example>++**Handling errors:**++- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.+- If a tool name doesn't exist, run `tools` again to find the correct name.+- If no tool covers a capability the user asks about, don't conclude it doesn't exist — PostHog ships changes daily. Check what's new via the `docs-search` tool or the changelog (https://posthog.com/changelog.md).++### Basic functionality++PostHog makes the user's product self-driving: it reads their product data and ships changes with them, never without them — read freely, but make changes only with the user's direction. You work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.++Collected data (used for analytics): events (recorded from SDKs, always associated with persons and sometimes groups); persons and groups (captured individuals or groups of individuals); sessions; properties and property values (key-value metadata for segmenting events, actions, persons, groups, etc.); session recordings (captured web/mobile interactions).++Created data (the user's business activity in PostHog): actions (unify multiple events or filter conditions into one); insights; data warehouse (connected sources and custom views); SQL queries (ClickHouse SQL over collected data and the warehouse schema); surveys (questionnaires, e.g. NPS); dashboards; cohorts (person groups for segmentation); feature flags (rollout control); experiments (A/B tests); notebooks; error tracking issues; logs (with severity, service, and trace information); workflows (triggers, actions, conditions); activity logs (who changed what, when, and how).++IMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.++If you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.++If you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.++### Tool search++**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need.++`search` understands two kinds of query:++- **Plain words** (including multiple words / natural language) — ranked by relevance across tool name, title, and description, with name matches weighted highest. `search create dashboard insight` surfaces `dashboard-create` / `insight-create` at the top. Results are capped to the top matches; narrow the query if you see a truncation note.+- **Regex** — a query containing regex metacharacters (`- | ( ) [ ] \ . * + ^ $ ?`) is treated as a single case-insensitive regular expression, matched against name/title/description. Use this for precise, narrow patterns.++**Good queries:**++- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first+- `search feature-flag` — regex (`-`): tools for feature flags+- `search query-` — regex (`-`): all insight query tools++**Avoid queries that are too broad** (match dozens of tools): `search data`, `search get list create` — they match almost everything.++Only fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.++PostHog tools have lowercase kebab-case naming. Tools are organized by category:++dashboard|execute-sql|feature-flag|query+Typical action names: list/retrieve/get/create/update/delete/query.+Example tool names: execute-sql, experiment-create, feature-flag-get-all.++Defined group types: organization, project++You 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]).\ No newline at end of filediff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex e239f444c947..2115cc8098a7 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -9,6 +9,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,@@ -20,7 +21,7 @@ import {formatInputValidationError,parseExecCallInnerToolName,} from '@/tools/exec'-import { ExecHelpCatalog } from '@/tools/exec-help'+import { ExecLearnCatalog } from '@/tools/exec-learn'import { GENERATED_TOOL_MAP } from '@/tools/generated'import { withInformationalResponse } from '@/tools/tool-utils'import { getToolDefinition } from '@/tools/toolDefinitions'@@ -74,76 +75,197 @@ function createExec(describe('exec tool', () => {describe('learn command', () => {- const helpCatalog = new ExecHelpCatalog([+ const guides = [{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.',+ id: 'visualizations',+ title: 'Visualizations',+ description: 'Rendering guidance.',+ content: '### Rendering\n\nRender the chart.',},- ])+ ]+ const learnCatalog = new ExecLearnCatalog(guides, { posthog: undefined })- it('lists topic metadata without loading topic content', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ 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([- {- id: 'analytics',- kind: 'guide',- title: 'Analytics',- description: 'Detailed analytics guidance.',- },- {- id: 'retention-analysis',- kind: 'skill',- title: 'Retention analysis',- description: 'A retention workflow.',+ expect(result).toEqual({+ guides: guides.map(({ content: _content, ...summary }) => summary),+ 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('loads multiple unique guides in the requested order', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })await expect(- exec.handler(mockContext, { command: 'learn retention-analysis analytics retention-analysis' })+ exec.handler(mockContext, { command: 'learn visualizations analytics visualizations' })).resolves.toBe(- '## Retention analysis\n\n### Retention analysis\n\nFollow the workflow.\n\n## Analytics\n\n### Retrieving data\n\nUse the analytics tools.'+ '## Visualizations\n\n### Rendering\n\nRender the chart.\n\n## Analytics\n\n### Retrieving data\n\nUse the analytics tools.')})- it('reports the available IDs when a topic is unknown', async () => {- const exec = createExec(undefined, undefined, { helpCatalog })+ it('reports every unknown guide as a typed learn error without partial content', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })- await expect(exec.handler(mockContext, { command: 'learn unknown' })).rejects.toThrow(- 'Unknown learning topic: "unknown". Available: analytics, retention-analysis'+ await expect(+ exec.handler(mockContext, { command: 'learn analytics unknown missing unknown' })+ ).rejects.toMatchObject({+ name: 'ExecCommandError',+ reason: 'unknown_learn_topic',+ message: 'Unknown learning topics: "unknown", "missing". Available: analytics, visualizations',+ })+ })++ it('keeps core exec usable and reports each unavailable skill source', async () => {+ const exec = createExec(undefined, undefined, { learnCatalog })++ 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)+ // A source outage is an operational error, not an agent mistake, so it must+ // keep its own class rather than be typed as a usage error.+ await expect(exec.handler(mockContext, { command: 'learn posthog:missing' })).rejects.toMatchObject({+ name: 'SkillsUnavailableError',+ message: expect.stringContaining('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(): NonNullable<ExecToolOptions['skillsSession']> {+ const state: { learnedAt?: number; ackAt?: number } = {}+ return {+ hasLearned: async () => state.learnedAt !== undefined,+ markLearned: async () => {+ state.learnedAt = Date.now()+ },+ hasAcknowledgedNoSkills: async () => state.ackAt !== undefined,+ markAcknowledgedNoSkills: async () => {+ state.ackAt = Date.now()+ },+ }+ }++ it('rejects an un-learned call with a typed reason and passes it after a skill load', async () => {+ const exec = createExec(undefined, undefined, {+ learnCatalog: guideCatalog(),+ skillsSession: makeSkillsSession(),+ })++ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toMatchObject({+ name: 'ExecCommandError',+ reason: 'skills_gate',+ message: expect.stringContaining('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 })+ // Each of these is a way an agent can touch `learn` without loading a skill; none+ // may open the gate, and the quoting cases fail a naive whitespace split.+ it.each([+ { label: 'a generic guide read', command: 'learn analytics' },+ { label: 'a bare search', command: 'learn -s bot traffic' },+ { label: 'a quoted search flag', command: "learn '-s' bot traffic" },+ { label: 'a listing', command: 'learn skills' },+ ])('does not open the gate for $label', async ({ command }) => {+ const exec = createExec(undefined, undefined, {+ learnCatalog: guideCatalog(),+ skillsSession: makeSkillsSession(),+ })- 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 })++ 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 exec = createExec(undefined, undefined, {+ learnCatalog: guideCatalog(),+ skillsSession: makeSkillsSession(),+ })++ // 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 exec = createExec(undefined, undefined, {+ learnCatalog: guideCatalog(),+ skillsSession: makeSkillsSession(),+ })++ 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 down = async (): Promise<never> => {+ throw new Error('redis down')+ }+ const failing: NonNullable<ExecToolOptions['skillsSession']> = {+ hasLearned: down,+ markLearned: down,+ hasAcknowledgedNoSkills: down,+ markAcknowledgedNoSkills: 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()})})@@ -253,14 +375,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 8596c210183d..0921d9744497 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'@@ -102,32 +103,42 @@ describe('InstructionsFormatter prompt snapshots', () => {await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-full.txt'))})- it('matches the exec command reference for Claude web/desktop', async () => {- const state = {+ function claudeChatState(toolFeatureFlags: Record<string, boolean> = {}): ResolvedState {+ return {allTools: STATIC_TOOLS.map(({ name }) => ({ name })),clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI' }),- toolFeatureFlags: {},+ toolFeatureFlags,renderUiEnabled: STATIC_CTX.renderUiEnabled,metadata: STATIC_CTX.metadata,groupTypes: STATIC_CTX.groupTypes,+ requestContext: { mcpConsumer: undefined },+ sessionContext: null,} as unknown as ResolvedState- const rendered = new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(state)+ }++ // Skills off is what every client sees until the flag is on for them; this snapshot+ // must not move when skill discovery ships dark.+ it('matches the exec command reference for Claude web/desktop', async () => {+ const rendered = new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(claudeChatState())await expect(rendered).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, 'exec-command-reference-claude-chat.txt'))})+ it('matches the exec command reference for Claude web/desktop with skills enabled', async () => {+ const rendered = new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(+ claudeChatState({ [MCP_EXEC_SKILLS_FEATURE_FLAG]: true })+ )++ await expect(rendered).toMatchFileSnapshot(+ path.join(SNAPSHOT_DIR, 'exec-command-reference-claude-chat-skills.txt')+ )+ })+// claude.ai never surfaces server `instructions`, so the exec command reference is the// only always-visible catalog-steering surface: without the compact metrics/trust// one-liner, skill-less claude.ai clients get zero catalog routing.it('renders the compact metrics/trust one-liner for claude.ai', () => {- const state = {- allTools: STATIC_TOOLS.map(({ name }) => ({ name })),- clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI' }),- toolFeatureFlags: {},- renderUiEnabled: STATIC_CTX.renderUiEnabled,- metadata: STATIC_CTX.metadata,- groupTypes: STATIC_CTX.groupTypes,- } as unknown as ResolvedState+ const state = claudeChatState()expect(new InstructionsBuilder(STATIC_CTX.guidelines).buildExecCommandReference(state)).toContain('Metrics & SQL trust'@@ -216,11 +227,15 @@ describe('InstructionsFormatter prompt snapshots', () => {const state = {allTools: Object.keys(getToolDefinitions()).map((name) => ({ name })),clientProfile: new MCPClientProfile({ vendorClient: 'ClaudeAI', userAgent: 'Claude-User' }),- toolFeatureFlags: {},+ // Skills on is the worst case: the compact skills-first section joins the+ // capped command reference.+ toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },renderUiEnabled: true,metadata: worstCaseMetadata,metadataCompact: worstCaseMetadataCompact,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 364dcea01fd3..16d8e1abe848 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -250,6 +250,10 @@ describe('InstructionsFormatter', () => {const formatter = new InstructionsFormatter()const result = formatter.buildClaudeExecCommandReference(fullCtx)+ // Skills off is the shipped default: the reference must carry no skill syntax.+ expect(result).not.toContain('(posthog|project):<skill>')+ expect(result).not.toContain('SKILLS FIRST')+expect(result).toContain('**LEARN FIRST: HARD REQUIREMENT**')expect(result).toContain('learn <topic...> - load one or more learning topics')expect(result).toContain('Topics are cumulative.')@@ -287,17 +291,46 @@ describe('InstructionsFormatter', () => {expect(result).not.toMatch(/\{help_topics\}|\{query_tools\}|\{metadata\}|\{defined_groups\}|\{guidelines\}/)})+ it('advertises skill syntax inside the schema budget only when skills are enabled', () => {+ const formatter = new InstructionsFormatter()+ const result = formatter.buildClaudeExecCommandReference(fullCtx, { skillsEnabled: true })++ expect(result).toContain('**SKILLS FIRST: HARD REQUIREMENT**')+ expect(result).toContain('(posthog|project):<skill> [path...]')+ // The compact variant, not the full routing paragraph, which belongs to the uncapped reference.+ expect(result).not.toContain('never clone, grep, or web-search PostHog internals')+ expect(result).toContain('- analytics:')+ expect(result).toContain('learn <topic...> - load one or more learning topics')+ })++ 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:')+ expect(result).not.toContain('learn <topic...>')+ })++ it('adds the full skills-first routing to the uncapped reference only when enabled', () => {+ const formatter = new InstructionsFormatter()+ const off = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false })+ const on = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: false, learnEnabled: true })++ expect(off).not.toContain('SKILLS FIRST')+ expect(on).toContain('**SKILLS FIRST: HARD REQUIREMENT**')+ expect(on).toContain('never clone, grep, or web-search PostHog internals')+ })+it('builds optional learning topics from their full guidance', () => {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: 'urls', 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')@@ -317,7 +350,7 @@ 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',@@ -344,7 +377,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'],},{@@ -370,7 +403,7 @@ describe('InstructionsFormatter', () => {it('advertises governed metrics in the analytics topic description', () => {const formatter = new InstructionsFormatter()const analyticsEntry = formatter- .buildClaudeExecHelpEntries(fullCtx)+ .buildClaudeExecLearnGuides(fullCtx).find((entry) => entry.id === 'analytics')!expect(analyticsEntry.description).toContain('governed metrics')})@@ -388,7 +421,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,},{name: 'buildExecCommandReference',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..215e976e7d2e--- /dev/null+++ b/services/mcp/tests/unit/project-skill-catalog.test.ts@@ -0,0 +1,283 @@+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_BODY = '# Retention\nHow to analyze retention.'+const SKILL_PAYLOAD = {+ body: SKILL_BODY,+ description: 'Find where users stop returning.',+ files: [],+ version: 7,+ body_total_length: SKILL_BODY.length,+ body_next_offset: null,+}++describe('ProjectSkillCatalog', () => {+ it.each([+ { lineCount: 600, expectedRead: 'TAILMARKER: compare like cohorts.' },+ { lineCount: 1800, expectedRead: 'too large to return in full' },+ ])(+ 'fetches the complete body in one request before formatting $lineCount lines',+ async ({ lineCount, expectedRead }) => {+ const body =+ '# 🦔 Retention\n' ++ 'Keep cohort definitions stable.\n'.repeat(lineCount) ++ 'TAILMARKER: compare like cohorts.'+ const request = vi.fn<RequestFn>(async ({ query }) => {+ const params = query as { body_length?: number } | undefined+ const length = params?.body_length ?? 8000+ const characters = Array.from(body)+ return {+ ...SKILL_PAYLOAD,+ body: characters.slice(0, length).join(''),+ body_total_length: characters.length,+ body_next_offset: length < characters.length ? length : null,+ }+ })+ const catalog = new ProjectSkillCatalog(makeContext(request))++ const read = await catalog.read('retention-analysis')+ const search = await catalog.searchFile('retention-analysis', 'SKILL.md', 'TAILMARKER')+ const lines = await catalog.readLines('retention-analysis', 'SKILL.md', lineCount + 2, lineCount + 2)++ expect(read).toContain(`${body.length} chars`)+ expect(read).toContain(expectedRead)+ expect(search).toContain('TAILMARKER: compare like cohorts.')+ expect(lines).toContain('TAILMARKER: compare like cohorts.')+ expect(request).toHaveBeenCalledTimes(1)+ }+ )++ 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.each(['a', '🦔'])('reads the tail of a body at the byte limit with %s characters', async (character) => {+ const tail = '\nTAILMARKER: compare like cohorts.'+ const remainingBytes = 1_000_000 - new TextEncoder().encode(tail).length+ const characterBytes = new TextEncoder().encode(character).length+ const body =+ character.repeat(Math.floor(remainingBytes / characterBytes)) ++ ' '.repeat(remainingBytes % characterBytes) ++ tail+ const request = vi.fn(async () => ({+ ...SKILL_PAYLOAD,+ body,+ body_total_length: Array.from(body).length,+ }))+ const catalog = new ProjectSkillCatalog(makeContext(request))++ expect(await catalog.readLines('retention-analysis', 'SKILL.md', 2, 2)).toContain(tail.trim())+ })++ it.each([+ {+ label: 'ASCII over the byte limit',+ body: 'a'.repeat(1_000_001),+ nextOffset: null,+ totalLength: 1_000_001,+ error: 'exceeds the 1 MB limit',+ },+ {+ label: 'Unicode over the byte limit',+ body: '🦔'.repeat(250_001),+ nextOffset: null,+ totalLength: 250_001,+ error: 'exceeds the 1 MB limit',+ },+ {+ label: 'a continuation offset',+ body: 'First page',+ nextOffset: 10,+ totalLength: 20,+ error: 'incomplete skill body',+ },+ {+ label: 'a missing tail without a continuation offset',+ body: 'First page',+ nextOffset: null,+ totalLength: 20,+ error: 'incomplete skill body',+ },+ ])('rejects $label without caching a partial skill', async ({ body, nextOffset, totalLength, error }) => {+ const request = vi+ .fn()+ .mockResolvedValueOnce({+ ...SKILL_PAYLOAD,+ body,+ body_next_offset: nextOffset,+ body_total_length: totalLength,+ })+ .mockResolvedValueOnce(SKILL_PAYLOAD)+ const catalog = new ProjectSkillCatalog(makeContext(request))++ await expect(catalog.read('retention-analysis')).rejects.toThrow(error)+ expect(await catalog.read('retention-analysis')).toContain(SKILL_BODY)+ 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 { ...SKILL_PAYLOAD, name: 'deep-skill', description: 'Past the list cap.' }+ }+ 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..9b671b0dc85e--- /dev/null+++ b/services/mcp/tests/unit/skill-archive-cache.test.ts@@ -0,0 +1,458 @@+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 { skillArchiveLastValidatedTimestampSeconds } from '@/hono/metrics'+import { SkillCatalogService } from '@/hono/skill-catalog-service'++import { makeSharedBlobRedisStubs } from '../hono/helpers/shared-blob-redis-stubs'++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),+ ...makeSharedBlobRedisStubs(store),+ }+}++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}.`+ ),+ },+ { mtime: new Date('2026-01-01T00:00:00Z') }+ )+}++function downloaded(bytes: Uint8Array = makeArchive(), etag?: string): SkillArchiveFetchResult {+ return { status: 'downloaded', bytes, etag }+}++const CURRENT_KEY = 'mcp:shared-blob:product-skills:v2:current'+const LOCK_KEY = 'mcp:shared-blob:product-skills:v2:lock'++function current(redis: MockRedis): { sha: string; etag?: string; validatedAt: number } {+ return JSON.parse(redis.store.get(CURRENT_KEY)!)+}++function bytesKey(redis: MockRedis): string {+ return `mcp:shared-blob:product-skills:v2:blob:${current(redis).sha}`+}++function expireSharedCopy(redis: MockRedis): void {+ redis.store.set(CURRENT_KEY, JSON.stringify({ ...current(redis), validatedAt: Date.now() - 600_001 }))+}++describe('SkillArchiveCache', () => {+ it('downloads once for a fleet and serves the shared copy to every later pod', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const first = new SkillArchiveCache(redis, { fetchArchive })+ const second = new SkillArchiveCache(redis, { fetchArchive })++ const cold = await first.loadOrRefresh()+ const warm = await second.loadOrRefresh()++ expect(cold.result).toBe('cold_refresh')+ expect(warm).toMatchObject({ result: 'fresh_hit', sha: cold.sha })+ expect(fetchArchive).toHaveBeenCalledTimes(1)+ expect(current(redis).sha).toBe(cold.sha)+ })++ it('serves a stale shared copy at startup without touching the source', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ await cache.loadOrRefresh()+ expireSharedCopy(redis)++ await expect(cache.loadOrRefresh()).resolves.toMatchObject({ result: 'stale_hit' })+ expect(fetchArchive).toHaveBeenCalledTimes(1)+ })++ it('starts a separate cache without trusting legacy split-key metadata', async () => {+ const redis = makeRedis()+ redis.store.set('mcp:shared-blob:product-skills:bytes', Buffer.from('old bytes').toString('base64'))+ redis.store.set('mcp:shared-blob:product-skills:sha', 'mismatched-sha')+ const cache = new SkillArchiveCache(redis, { fetchArchive: vi.fn(async () => downloaded()) })+ const loaded = await cache.loadOrRefresh()++ expect(loaded.result).toBe('cold_refresh')+ expect(current(redis).sha).toBe(loaded.sha)+ expect(redis.store.get('mcp:shared-blob:product-skills:sha')).toBe('mismatched-sha')+ })++ 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.currentKey).not.toBe(second.currentKey)+ expect(fetchArchive).toHaveBeenCalledTimes(2)+ })++ // The July incident: every handshake pulled the whole archive out of Redis. A pod+ // that already holds the current sha must read only the small keys.+ it('reads no archive bytes when the shared sha matches what the pod holds', async () => {+ const redis = makeRedis()+ const cache = new SkillArchiveCache(redis, { fetchArchive: vi.fn(async () => downloaded()) })+ const { sha } = await cache.loadOrRefresh()+ vi.mocked(redis.get).mockClear()++ await expect(cache.readIfChanged(sha)).resolves.toBeNull()+ expect(redis.get).not.toHaveBeenCalledWith(bytesKey(redis))+ })++ it('returns the new bytes when another pod published a different sha', async () => {+ const redis = makeRedis()+ const cache = new SkillArchiveCache(redis, {+ fetchArchive: vi.fn(async () => downloaded(makeArchive('first'))),+ })+ const { sha } = await cache.loadOrRefresh()+ const publisher = new SkillArchiveCache(redis, {+ fetchArchive: vi.fn(async () => downloaded(makeArchive('second'), 'etag-v2')),+ })+ expireSharedCopy(redis)+ await expect(publisher.refreshIfStale()).resolves.toBe('downloaded')++ const changed = await cache.readIfChanged(sha)++ expect(changed?.sha).not.toBe(sha)+ expect(changed?.bytes).toEqual(makeArchive('second'))+ })++ it('keeps a read consistent when a writer publishes between the pointer and blob reads', async () => {+ const redis = makeRedis()+ const firstBytes = makeArchive('first')+ const secondBytes = makeArchive('second')+ const reader = new SkillArchiveCache(redis, { fetchArchive: vi.fn(async () => downloaded(firstBytes)) })+ const first = await reader.loadOrRefresh()+ const publisher = new SkillArchiveCache(redis, { fetchArchive: vi.fn(async () => downloaded(secondBytes)) })+ expireSharedCopy(redis)+ let publishDuringRead = true+ vi.mocked(redis.get).mockImplementation(async (key) => {+ const value = redis.store.get(key) ?? null+ if (key === CURRENT_KEY && publishDuringRead) {+ publishDuringRead = false+ await publisher.refreshIfStale()+ }+ return value+ })++ expect(await reader.readIfChanged(undefined)).toEqual({ bytes: firstBytes, sha: first.sha })+ expect(await reader.readIfChanged(first.sha)).toEqual({ bytes: secondBytes, sha: current(redis).sha })+ })++ describe('refreshIfStale', () => {+ it('does nothing while the shared copy is fresh', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ await cache.loadOrRefresh()++ await expect(cache.refreshIfStale()).resolves.toBe('fresh')+ expect(fetchArchive).toHaveBeenCalledTimes(1)+ })++ it('revalidates a stale copy with If-None-Match and only bumps freshness 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 })+ const { sha } = await cache.loadOrRefresh()+ const originalBytes = redis.store.get(bytesKey(redis))+ expireSharedCopy(redis)++ await expect(cache.refreshIfStale()).resolves.toBe('not_modified')++ expect(fetchArchive).toHaveBeenLastCalledWith(expect.any(String), 'etag-v1')+ expect(current(redis).validatedAt).toBeGreaterThan(Date.now() - 1000)+ expect(redis.store.get(bytesKey(redis))).toBe(originalBytes)+ expect(current(redis).sha).toBe(sha)+ })++ it('replaces bytes, etag and sha when the source has a new archive', async () => {+ const redis = makeRedis()+ const second = makeArchive('second')+ const fetchArchive = vi.fn(+ async (_url: string, etag?: string): Promise<SkillArchiveFetchResult> =>+ etag ? downloaded(second, 'etag-v2') : downloaded(makeArchive('first'), 'etag-v1')+ )+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ const { sha } = await cache.loadOrRefresh()+ expireSharedCopy(redis)++ await expect(cache.refreshIfStale()).resolves.toBe('downloaded')++ expect(current(redis).etag).toBe('etag-v2')+ expect(redis.store.get(bytesKey(redis))).toBe(Buffer.from(second).toString('base64'))+ expect(current(redis).sha).not.toBe(sha)+ })++ it('never sends If-None-Match when the server stored no validator', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async (_url: string, _etag?: string) => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ await cache.loadOrRefresh()+ expect(current(redis).etag).toBeUndefined()+ expireSharedCopy(redis)++ await cache.refreshIfStale()++ expect(fetchArchive).toHaveBeenCalledTimes(2)+ for (const [, sentEtag] of fetchArchive.mock.calls) {+ expect(sentEtag).toBeUndefined()+ }+ })++ it('leaves the network to the pod holding the writer lock', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ await cache.loadOrRefresh()+ expireSharedCopy(redis)+ redis.store.set(LOCK_KEY, 'another-pod')++ await expect(cache.refreshIfStale()).resolves.toBe('lock_busy')+ expect(fetchArchive).toHaveBeenCalledTimes(1)+ })++ it('reports a missing shared copy instead of downloading outside the startup path', async () => {+ const cache = new SkillArchiveCache(makeRedis(), { fetchArchive: vi.fn(async () => downloaded()) })++ await expect(cache.refreshIfStale()).resolves.toBe('missing')+ })++ it.each(['before revalidation', 'during revalidation'])('repairs bytes evicted %s', async (when) => {+ const redis = makeRedis()+ const archive = makeArchive()+ const fetchArchive = vi.fn(async (_url: string, etag?: string): Promise<SkillArchiveFetchResult> => {+ if (etag) {+ redis.store.delete(bytesKey(redis))+ return { status: 'not_modified' }+ }+ return downloaded(archive, 'etag-v1')+ })+ const cache = new SkillArchiveCache(redis, { fetchArchive })+ await cache.loadOrRefresh()+ expireSharedCopy(redis)+ const pointer = redis.store.get(CURRENT_KEY)+ if (when === 'before revalidation') {+ redis.store.delete(bytesKey(redis))+ }++ await expect(cache.refreshIfStale()).resolves.toBe('missing')+ expect(redis.store.get(CURRENT_KEY)).toBe(pointer)+ await expect(cache.loadOrRefresh()).resolves.toMatchObject({ bytes: archive, result: 'cold_refresh' })+ expect(fetchArchive).toHaveBeenLastCalledWith(expect.any(String), undefined)+ })++ it('does not let a delayed 304 replace a newer pointer after the writer lock expires', async () => {+ const redis = makeRedis()+ let signalStarted!: () => void+ const started = new Promise<void>((resolve) => {+ signalStarted = resolve+ })+ let signalFinished!: () => void+ const finish = new Promise<void>((resolve) => {+ signalFinished = resolve+ })+ const first = new SkillArchiveCache(redis, {+ fetchArchive: async (_url, etag) => {+ if (etag) {+ signalStarted()+ await finish+ return { status: 'not_modified' }+ }+ return downloaded(makeArchive('first'), 'etag-v1')+ },+ })+ await first.loadOrRefresh()+ expireSharedCopy(redis)+ const pending = first.refreshIfStale()+ await started+ redis.store.delete(LOCK_KEY)+ const second = new SkillArchiveCache(redis, {+ fetchArchive: async () => downloaded(makeArchive('second'), 'etag-v2'),+ })+ await second.refreshIfStale()+ const pointer = redis.store.get(CURRENT_KEY)+ signalFinished()++ await expect(pending).resolves.toBe('missing')+ expect(redis.store.get(CURRENT_KEY)).toBe(pointer)+ expect((await first.loadOrRefresh()).bytes).toEqual(makeArchive('second'))+ })+ })++ it('keeps the previous shared copy when a downloaded archive fails validation', async () => {+ const redis = makeRedis()+ let release = 'good'+ const fetchArchive = vi.fn(async (): Promise<SkillArchiveFetchResult> => {+ return release === 'good' ? downloaded(makeArchive('good'), 'etag-good') : downloaded(strToU8('not a zip'))+ })+ const cache = new SkillArchiveCache(redis, {+ fetchArchive,+ validateArchive: (bytes) => {+ if (bytes.length < 100) {+ throw new Error('corrupt archive')+ }+ },+ })+ const { sha } = await cache.loadOrRefresh()+ release = 'bad'+ expireSharedCopy(redis)++ await expect(cache.refreshIfStale()).rejects.toThrow('corrupt archive')++ expect(current(redis).sha).toBe(sha)+ expect(current(redis).etag).toBe('etag-good')+ // The lock is released, so the next stale poll can try the source again.+ expect(redis.store.has(LOCK_KEY)).toBe(false)+ })+})++describe('SkillCatalogService', () => {+ function quietConsole(): ReturnType<typeof vi.spyOn> {+ return vi.spyOn(console, 'error').mockImplementation(() => undefined)+ }++ it('reports upstream validation time across restarts, unchanged releases and refresh failures', async () => {+ vi.useFakeTimers()+ const timestamp = vi.spyOn(skillArchiveLastValidatedTimestampSeconds, 'set')+ const consoleError = quietConsole()+ try {+ const redis = makeRedis()+ const fetchArchive = vi.fn(+ async (_url: string, etag?: string): Promise<SkillArchiveFetchResult> =>+ etag ? { status: 'not_modified' } : downloaded(makeArchive(), 'etag-v1')+ )+ const first = new SkillCatalogService(redis, { fetchArchive })+ await first.warmup()+ const validatedAt = Date.now()+ vi.setSystemTime(validatedAt + 20 * 60_000)+ const second = new SkillCatalogService(redis, { fetchArchive })+ await second.warmup()+ expect(timestamp).toHaveBeenLastCalledWith(validatedAt / 1000)+ const catalog = second.getCatalog()++ await second.poll()+ expect(timestamp).toHaveBeenLastCalledWith(Date.now() / 1000)+ expect(second.getCatalog()).toBe(catalog)+ const revalidatedAt = Date.now()+ vi.setSystemTime(revalidatedAt + 31 * 60_000)+ fetchArchive.mockRejectedValue(new Error('offline'))++ await second.poll()+ expect(timestamp).toHaveBeenLastCalledWith(revalidatedAt / 1000)+ expect(Date.now() / 1000 - Number(timestamp.mock.lastCall![0])).toBeGreaterThan(1800)+ } finally {+ timestamp.mockRestore()+ consoleError.mockRestore()+ vi.useRealTimers()+ }+ })++ it('retries warmup inside its budget and starts without skills when the source stays down', async () => {+ const fetchArchive = vi.fn(async () => {+ throw new Error('offline')+ })+ const service = new SkillCatalogService(makeRedis(), { fetchArchive, warmupTimeoutMs: 50, warmupRetryMs: 10 })+ const consoleError = quietConsole()++ await expect(service.warmup()).resolves.toBeUndefined()++ expect(service.getCatalog()).toBeUndefined()+ expect(fetchArchive.mock.calls.length).toBeGreaterThan(1)+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('starting without product skills'),+ expect.any(Error)+ )+ consoleError.mockRestore()+ })++ it('loads the catalog at warmup and adopts a newer archive another pod published', async () => {+ const redis = makeRedis()+ const first = new SkillCatalogService(redis, {+ fetchArchive: vi.fn(async () => downloaded(makeArchive('first'), 'etag-v1')),+ })+ await first.warmup()+ expect(first.getCatalog()?.listNames()).toEqual(['first'])++ const second = new SkillCatalogService(redis, {+ fetchArchive: vi.fn(async () => downloaded(makeArchive('second'), 'etag-v2')),+ })+ await second.warmup()+ expect(second.getCatalog()?.listNames()).toEqual(['first'])+ expireSharedCopy(redis)++ // The second pod wins the refresh and adopts its own download; the first pod+ // sees the new sha on its next poll and reparses without touching the source.+ await second.poll()+ await first.poll()++ expect(second.getCatalog()?.listNames()).toEqual(['second'])+ expect(first.getCatalog()?.listNames()).toEqual(['second'])+ })++ it('keeps the last catalog when the shared copy turns corrupt', async () => {+ const redis = makeRedis()+ const service = new SkillCatalogService(redis, { fetchArchive: vi.fn(async () => downloaded()) })+ await service.warmup()+ const original = service.getCatalog()+ const sha = 'a'.repeat(64)+ redis.store.set(CURRENT_KEY, JSON.stringify({ sha, validatedAt: Date.now() }))+ redis.store.set(bytesKey(redis), Buffer.from('not a zip').toString('base64'))+ const consoleError = quietConsole()++ await service.poll()++ expect(service.getCatalog()).toBe(original)+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('keeping the current catalog'),+ expect.any(Error)+ )+ await service.poll()+ expect(service.getCatalog()?.listNames()).toEqual(['sample'])+ expect(current(redis).sha).not.toBe(sha)+ consoleError.mockRestore()+ })++ it('repairs a shared copy that Redis lost', async () => {+ const redis = makeRedis()+ const fetchArchive = vi.fn(async () => downloaded())+ const service = new SkillCatalogService(redis, { fetchArchive })+ await service.warmup()+ redis.store.clear()++ await service.poll()++ expect(fetchArchive).toHaveBeenCalledTimes(2)+ expect(redis.store.has(bytesKey(redis))).toBe(true)+ expect(service.getCatalog()?.listNames()).toEqual(['sample'])+ })+})diff --git a/services/mcp/tests/unit/skill-catalog.test.ts b/services/mcp/tests/unit/skill-catalog.test.tsnew file mode 100644index 000000000000..5e7dd3577853--- /dev/null+++ b/services/mcp/tests/unit/skill-catalog.test.ts@@ -0,0 +1,445 @@+import { strToU8, zipSync } from 'fflate'+import { describe, expect, it, vi } from 'vitest'++import type { ProjectSkillCatalog } from '@/skills/project-skill-catalog'+import {+ formatLearnFile,+ LEARN_OUTPUT_CHAR_LIMIT,+ makeSkillFile,+ readLearnLines,+ searchLearnFile,+ 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.each([+ ['needle\na\nb\nc', '1: needle\n2: a\n3: b'],+ ['a\nb\nc\nneedle', '2: b\n3: c\n4: needle'],+ ['a\nneedle\nneedle\nb\n', '1: a\n2: needle\n3: needle\n4: b\n\n1: a\n2: needle\n3: needle\n4: b\n5: '],+ ['\n\nneedle 日本語 🦔\n', '1: \n2: \n3: needle 日本語 🦔\n4: '],+ ])('preserves line numbers and overlapping search context for %j', (content, context) => {+ const file = makeSkillFile('notes.md', content)+ expect(searchLearnFile('example', file, 'needle')).toBe(`Matches in example/notes.md:\n\n${context}`)+ })++ it('caps file search at 50 matches while including the final match context', () => {+ const file = makeSkillFile(+ 'notes.md',+ Array.from({ length: 60 }, (_, index) => `needle ${index}\nbefore\nmiddle\nafter`).join('\n')+ )+ const output = searchLearnFile('example', file, 'needle')+ expect(output.split('\n\n')).toHaveLength(51)+ expect(output).toContain('197: needle 49\n198: before\n199: middle')+ expect(output).not.toContain('needle 50')+ })++ it.each(['# ' + 'x'.repeat(100_000), '# Heading\n'.repeat(10_000)])(+ 'bounds oversized outlines and search output for long lines and many headings (%#)',+ (content) => {+ const file = makeSkillFile('notes.md', content)+ const outline = formatLearnFile('example', file)+ expect(outline).toHaveLength(LEARN_OUTPUT_CHAR_LIMIT)+ expect(outline).toContain('[Output truncated.')+ const search = searchLearnFile('example', file, file.lineCount === 1 ? 'x' : 'heading')+ expect(search.length).toBeLessThanOrEqual(LEARN_OUTPUT_CHAR_LIMIT)+ if (file.lineCount === 1) {+ expect(search).toContain('[Output truncated.')+ } else {+ expect(search.split('\n\n')).toHaveLength(51)+ }+ }+ )++ it('reads and searches a newline-heavy file, including its last and empty lines', () => {+ const file = makeSkillFile('notes.md', `x${'\n'.repeat(999_998)}x`)+ expect(file.lineCount).toBe(999_999)+ expect(formatLearnFile('example', file)).toContain('(No Markdown headings found.)')+ expect(searchLearnFile('example', file, 'missing')).toContain('No matches for "missing"')+ expect(readLearnLines('example', file, 999_998, 999_999)).toBe(+ 'File: example/notes.md lines 999998:999999\n\n999998: \n999999: x'+ )+ expect(() => readLearnLines('example', file, 1, file.lineCount)).toThrow('Requested line range exceeds')+ expect(() => readLearnLines('example', file, 1, file.lineCount + 1)).toThrow('Invalid line range')+ const empty = makeSkillFile('empty.md', '')+ expect(empty.lineCount).toBe(1)+ expect(readLearnLines('example', empty, 1, 1)).toBe('File: example/empty.md lines 1:1\n\n1: ')+ })++ 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('missing.md')+ 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(+ 'Unknown skill: "missing"'+ )+ 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.')+ })+ })+})