Skip to content

: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.

chore(flags): record the instrumentation skill source of truth (#90943)

James Gill68b7fa30feee
diff --git a/.agents/skills/writing-skills/SKILL.md b/.agents/skills/writing-skills/SKILL.md
index 24ac57191f23..0d8383aa526f 100644
--- a/.agents/skills/writing-skills/SKILL.md
+++ b/.agents/skills/writing-skills/SKILL.md
@@ -30,6 +30,8 @@ hogli unsync:skill -- --name <skill-name>
Distribution is automatic after merge — CI publishes to [PostHog/skills](https://github.com/PostHog/skills).
+This repo is not the only source. [`PostHog/context-mill`](https://github.com/PostHog/context-mill) publishes the omnibus skills — `instrument-integration`, `instrument-product-analytics`, `instrument-feature-flags`, `instrument-error-tracking`, `instrument-llm-analytics`, `instrument-logs` — and **every shipping consumer overlays them on top of this repo's**, so context-mill wins on a same-named skill. `hogli lint:skills` fails if you add one of those names under `products/*/skills/`; change the context-mill source instead. Local builds are the opposite case: they carry no omnibus skills at all, so anything that depends on one has to overlay it or fail loudly. See [Context-mill skills override this repo's](../../../docs/published/handbook/engineering/ai/writing-skills.md#context-mill-skills-override-this-repos) for the merge sites.
+
## When to write a skill
When new functionality is added to a product and agents need to know how to work with it.
diff --git a/docs/published/handbook/engineering/ai/writing-skills.md b/docs/published/handbook/engineering/ai/writing-skills.md
index f1b9a0d27c34..2765c8c22a59 100644
--- a/docs/published/handbook/engineering/ai/writing-skills.md
+++ b/docs/published/handbook/engineering/ai/writing-skills.md
@@ -386,6 +386,43 @@ Because both repositories are updated from the same `dist/skills.zip` on every m
you don't need to handle distribution yourself –
merge your skill and it shows up in both places on the next CI run.
+### Context-mill skills override this repo's
+
+This repo is not the only source of shipped skills.
+[`PostHog/context-mill`](https://github.com/PostHog/context-mill) assembles the "omnibus" skills
+from posthog.com docs and publishes them as `skills-mcp-resources.zip`:
+`instrument-integration`, `instrument-product-analytics`, `instrument-feature-flags`,
+`instrument-error-tracking`, `instrument-llm-analytics`, and `instrument-logs`.
+These are the skills behind PostHog Desktop's setup buttons and the wizard.
+
+Every consumer below unzips `dist/skills.zip` first and then unzips context-mill on top,
+so **context-mill wins on any skill they both define**.
+A same-named skill added here would have its `SKILL.md` overwritten
+while its extra reference files survived as orphans in the other source's directory.
+The Desktop harness bundle is the exception: it packages context-mill alone,
+so a skill from this repo is absent there rather than overwritten.
+
+| Consumer | Merge site |
+| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
+| PostHog Desktop build | `products/desktop/apps/code/vite-main-plugins.mts` (`copyPosthogPlugin`) |
+| PostHog Desktop runtime, every 30 min | `products/desktop/packages/workspace-server/src/services/posthog-plugin/update-skills-saga.ts` |
+| Desktop harness bundle | `products/desktop/packages/harness/tsup.config.ts` – context-mill only, this repo's skills are absent rather than overwritten |
+| Tasks sandbox base image | `.github/workflows/cd-sandbox-base-image.yml` |
+| Tasks golden snapshot | `.github/workflows/cd-tasks-golden-snapshot.yml` |
+| `PostHog/skills` mirror | that repo's `.github/workflows/sync-omnibus.yml` |
+| `PostHog/ai-plugin` plugin | that repo's `.github/workflows/sync-skills.yml` |
+
+Note what is missing from that list: local builds.
+`LocalSkillsCache.ensure_built()` renders only `products/*/skills/` and wipes the dist dir first,
+so a locally built sandbox has no omnibus skills at all.
+An eval or manual run that depends on one has to overlay context-mill itself,
+or check for the skill and fail loudly – see `products/feature_flags/evals/eval_instrument_flags.py`.
+
+So before you write a skill, check the omnibus names above.
+If your job is one of them, change the context-mill source.
+Product teams take ownership of a skill tree there with a CODEOWNERS entry;
+several already have.
+
## Testing
To test a product skill locally with Claude Code, sync it to `.agents/skills/`:
diff --git a/products/feature_flags/evals/__init__.py b/products/feature_flags/evals/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/feature_flags/evals/eval_instrument_flags.py b/products/feature_flags/evals/eval_instrument_flags.py
new file mode 100644
index 000000000000..6088bb021ebc
--- /dev/null
+++ b/products/feature_flags/evals/eval_instrument_flags.py
@@ -0,0 +1,157 @@
+"""Baseline trigger evals for the ``instrument-feature-flags`` skill.
+
+The skill is authored in `PostHog/context-mill`, not here — see
+``products/feature_flags/skills/README.md`` for the source-of-truth record. This
+suite grades whether its description fires on an explicit "put this behind a
+feature flag" request and stays quiet on a pure refactor.
+
+**The skill is not in a locally built sandbox, so the suite guards for it.**
+``hogli evals`` builds skills through ``LocalSkillsCache.ensure_built()``, which
+renders only this repo's ``products/*/skills/`` trees into
+``products/posthog_ai/dist/skills/`` and wipes whatever was there. The
+context-mill overlay runs in ``.github/workflows/cd-sandbox-base-image.yml``, not
+on any local path, so a plain local run has no ``instrument-feature-flags``
+installed at all. Without a guard the positive case would score 0 for a missing
+skill and the negative case would score 1 for the wrong reason — a suite mean of
+0.5 indistinguishable from a real trigger regression. ``require_instrument_skill``
+raises instead, which the harness reports as an infra error and excludes from the
+score averages.
+
+Two cases share one deterministic scorer — no LLM judge, so the signal is binary
+and cheap to rerun while iterating on the skill's description. The scorer grades
+each case against the direction it expects, so the suite mean is trigger
+accuracy:
+
+* ``explicit_flag_request`` — an explicit "put this behind a feature flag" ask
+ about a real surface in the seeded `posthog/hedgebox` checkout. The skill must
+ load.
+* ``pure_refactor_no_flag`` — a rewrite with no behavior change, the canonical
+ non-trigger. The skill must not load.
+
+Prompts describe their target rather than naming a path, because hedgebox is an
+external repo cloned at its default branch: a file move there would otherwise
+score as a trigger regression here. The trigger wording is what is graded.
+
+The pair is a baseline, not a quality bar: it measures whether the description
+fires on the right request, not whether the workflow the skill teaches is good.
+Both cases are ``SandboxedPrivateEval`` so they run without a Braintrust key.
+
+**Claude runtime only.** Under ``--agent-runtime codex`` the guard refuses the
+cases rather than scoring them. See ``_CODEX_UNSUPPORTED`` for the two reasons and
+where each fix belongs.
+
+To run, invoke the command below once. It builds the local skill cache, then the
+guard prints the overlay command. Apply that overlay and run the command again: the
+second run reuses the cache, so the overlay survives.
+ flox activate -- bash -c "hogli evals eval_instrument_flags"
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from django.conf import settings
+
+from products.posthog_ai.eval_harness.base import SandboxedPrivateEval
+from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.scorers import RequiredToolCall
+from products.posthog_ai.evals.retrieval.scorers import SkillTriggered
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
+
+SKILL_NAME = "instrument-feature-flags"
+SCORER_NAME = "instrument_flags_skill_triggered"
+
+_BUILT_SKILLS_DIR = Path("products/posthog_ai/dist/skills")
+
+_OVERLAY_HINT = f"""\
+'{SKILL_NAME}' is not in {_BUILT_SKILLS_DIR}, so the sandbox would run without the
+skill this suite grades. It ships from PostHog/context-mill, and only CI overlays it
+(.github/workflows/cd-sandbox-base-image.yml). The eval rebuilds the local skill
+cache at startup when it is stale or unbuilt, which wipes an overlay applied before
+it. The cache is up to date now, so apply the overlay and re-run. Startup then
+reuses the cache and the overlay survives:
+
+ curl -fsSL -o /tmp/cm.zip \\
+ https://github.com/PostHog/context-mill/releases/latest/download/skills-mcp-resources.zip
+ unzip -q -o /tmp/cm.zip -d /tmp/cm
+ unzip -q -o /tmp/cm/omnibus-{SKILL_NAME}.zip -d {_BUILT_SKILLS_DIR}/{SKILL_NAME}
+ perl -pi -e 's/^(name: *)omnibus-/$1/' {_BUILT_SKILLS_DIR}/{SKILL_NAME}/SKILL.md
+
+Editing any products/*/skills/ file invalidates the cache, so the next run rebuilds
+and wipes the overlay again. Re-apply it after that run, not before."""
+
+
+_CODEX_UNSUPPORTED = f"""\
+This suite measures the claude runtime only, so it refuses to run under codex.
+
+Two gaps make a codex run report a number that looks like a trigger result but is not:
+
+1. The local overlay reaches the bind-mounted plugin directory, but codex discovers
+ skills from $HOME/.agents/skills, which only install-skills.sh populates when the
+ base image is baked. A reused docker image therefore serves stale or missing
+ skills while this guard, which stats the host copy, still passes.
+2. `RequiredToolCall` matches Edit, Write and MultiEdit. Codex carries no named file
+ tools, so `edited_a_file` scores 0 even when the agent edits a file.
+
+Both fixes land outside this product, in sandbox provisioning and in the shared
+scorers, and need a live docker plus codex run to validate. Until then, measuring
+claude and refusing codex beats reporting a corrupt mean. Run without
+`--agent-runtime codex`."""
+
+
+def require_instrument_skill(context: CustomPromptSandboxContext) -> dict[str, Any]:
+ """Fail the case as infra error when it cannot be measured in this sandbox.
+
+ A seeder exception is an infra error the harness excludes from score averages,
+ which is what both refusals want: no measurement rather than a wrong one.
+ """
+ if context.runtime_adapter == "codex":
+ raise RuntimeError(_CODEX_UNSUPPORTED)
+
+ skill_file = Path(settings.BASE_DIR) / _BUILT_SKILLS_DIR / SKILL_NAME / "SKILL.md"
+ if not skill_file.is_file():
+ raise RuntimeError(_OVERLAY_HINT)
+ return {"skill_source": "context-mill overlay", "skill_file": str(skill_file)}
+
+
+async def eval_instrument_flags(ctx: EvalContext) -> None:
+ cases: list[SandboxedEvalCase] = [
+ SandboxedEvalCase(
+ name="explicit_flag_request",
+ prompt=(
+ "In this repo, the pricing page marks one of the plans with a "
+ "'Most Popular' badge. Put that badge behind a PostHog feature "
+ "flag so we can roll it out gradually."
+ ),
+ setup=require_instrument_skill,
+ expected={SCORER_NAME: {"should_load": True}},
+ metadata={"trigger": "positive", "skill": SKILL_NAME},
+ ),
+ SandboxedEvalCase(
+ name="pure_refactor_no_flag",
+ prompt=(
+ "In this repo, the helper that picks a file-type emoji does it "
+ "with a chain of if statements. Rewrite it as a lookup table. "
+ "Keep the returned emoji for every input the same."
+ ),
+ setup=require_instrument_skill,
+ expected={SCORER_NAME: {"should_load": False}},
+ metadata={"trigger": "negative", "skill": SKILL_NAME},
+ ),
+ ]
+
+ await SandboxedPrivateEval(
+ experiment_name="sandboxed-feature-flags-instrument-trigger-cli",
+ cases=cases,
+ scorers=[
+ SkillTriggered(SKILL_NAME, name=SCORER_NAME),
+ # Both prompts assert something about the cloned checkout. If hedgebox
+ # drifts, the agent finds nothing to change and the negative case still
+ # scores 1.0 for not loading the skill — a hollow pass. This row drops
+ # to 0 instead, so a stale premise is visible rather than silent.
+ RequiredToolCall({"Edit", "Write", "MultiEdit"}, name="edited_a_file"),
+ ],
+ ctx=ctx,
+ )
diff --git a/products/feature_flags/skills/README.md b/products/feature_flags/skills/README.md
new file mode 100644
index 000000000000..d63e01ba7af6
--- /dev/null
+++ b/products/feature_flags/skills/README.md
@@ -0,0 +1,46 @@
+# Feature flag skills
+
+Agent skills owned by team-feature-flags.
+Built by `hogli build:skills` and shipped in `dist/skills.zip` — see [products/posthog_ai/skills/README.md](../../posthog_ai/skills/README.md) for the pipeline.
+
+| Skill | Job |
+| --------------------------------- | ------------------------------------------------------------------------- |
+| `cleaning-up-stale-feature-flags` | Find flags that no longer serve a purpose and remove them safely. |
+| `copying-flags-across-projects` | Duplicate a flag into other projects in the same organization. |
+| `finding-deleted-feature-flags` | List flags soft-deleted in a time window, with who deleted each and when. |
+
+## `instrument-feature-flags` is not ours, and must not be added here
+
+The skill that teaches an agent to put code behind a PostHog flag is authored in [PostHog/context-mill](https://github.com/PostHog/context-mill), not in this repository.
+It is the skill a person gets from "put this behind a feature flag", from the **Add feature flag** button in PostHog Desktop, and from `/instrument-feature-flags`.
+
+- **Source:** `context/skills/omnibus/instrument-feature-flags/{config.yaml,description.md}`.
+ `description.md` is the hand-written SKILL.md body.
+ The per-platform `references/` are generated at build time from the `docs_urls` in `config.yaml`, so the SDK guidance tracks posthog.com instead of being maintained by hand.
+ The per-platform variants live beside it in `context/skills/feature-flags/`.
+- **Owner:** `@PostHog/team-wizard-docs`, via the default entry in context-mill's CODEOWNERS.
+ A product team takes over a skill tree there by adding a path entry, the way team-error-tracking and team-self-driving already have.
+- **Distribution:** a context-mill release publishes `skills-mcp-resources.zip`, a zip of zips.
+ Consumers pull `omnibus-instrument-feature-flags.zip` out of it and strip the `omnibus-` prefix from both the directory name and the `name:` frontmatter, which is why the installed skill is called `instrument-feature-flags`.
+
+Every shipping consumer overlays context-mill on top of this repository's skills, not under it — the [handbook lists the merge sites](../../../docs/published/handbook/engineering/ai/writing-skills.md#context-mill-skills-override-this-repos).
+So a `products/feature_flags/skills/instrument-feature-flags/` directory would not replace the shipping skill.
+Its `SKILL.md` would be overwritten, any extra reference file would survive as an orphan inside someone else's skill, and the two sources would drift with no signal.
+The only place the monorepo copy would win is `hogli sync:skill`, which is local development.
+
+Local builds are the mirror image: they carry no omnibus skills at all, because `LocalSkillsCache.ensure_built()` renders only `products/*/skills/` and wipes the dist dir first.
+That is why the eval below guards for the skill instead of assuming it is installed.
+
+So:
+
+- **Do not add `instrument-feature-flags` under `products/*/skills/`.**
+ Change the context-mill source instead.
+- **Do not add a second skill covering the same trigger**, for example `wrapping-code-in-feature-flags`.
+ Two entry points for one job means agents pick one at random and the two drift.
+ A rename needs an atomic rename and migration agreed with the skills-distribution owner.
+- The same applies to the other five omnibus skills: `instrument-integration`, `instrument-product-analytics`, `instrument-error-tracking`, `instrument-llm-analytics`, and `instrument-logs`.
+
+Baseline trigger coverage lives in [`products/feature_flags/evals/eval_instrument_flags.py`](../evals/eval_instrument_flags.py).
+It grades the context-mill skill itself, so it needs that skill present in the sandbox and refuses to run without it — read its module docstring before running it.
+
+`hogli lint:skills` fails when any of the six omnibus names appears under `products/*/skills/`, so the rule above is enforced rather than trusted.
diff --git a/products/posthog_ai/eval_harness/test/test_eval_scorers.py b/products/posthog_ai/eval_harness/test/test_eval_scorers.py
index b893c2299256..57434fe0d4aa 100644
--- a/products/posthog_ai/eval_harness/test/test_eval_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_eval_scorers.py
@@ -1,8 +1,12 @@
from __future__ import annotations
import json
+from collections.abc import Sequence
from typing import Any
+import pytest
+
+from products.posthog_ai.eval_harness.log_parser import SKILL_TOOL_NAME
from products.posthog_ai.evals.error_tracking.scorers import (
ERROR_TRACKING_WRITE_TOOLS,
QUERY_ISSUE_EVENTS_TOOL,
@@ -12,11 +16,19 @@ from products.posthog_ai.evals.error_tracking.scorers import (
IssuesListToolUsed,
_recordings_text_has_results,
)
+from products.posthog_ai.evals.retrieval.scorers import SkillTriggered
+
+def _raw_tool_log(calls: Sequence[tuple[Any, ...]]) -> str:
+ """Build an ACP log. A fourth tuple element overrides the result status.
-def _raw_tool_log(calls: list[tuple[str, dict[str, Any], object]]) -> str:
+ ``"failed"`` is what makes ``ToolCall.is_error`` true, which every scorer here
+ uses to ignore an attempt the agent made and lost.
+ """
lines = []
- for index, (name, raw_input, raw_output) in enumerate(calls, start=1):
+ for index, call in enumerate(calls, start=1):
+ name, raw_input, raw_output = call[0], call[1], call[2]
+ result_status = call[3] if len(call) > 3 else "completed"
call_id = f"call-{index}"
lines.append(
{
@@ -44,7 +56,7 @@ def _raw_tool_log(calls: list[tuple[str, dict[str, Any], object]]) -> str:
"update": {
"sessionUpdate": "tool_call_update",
"toolCallId": call_id,
- "status": "completed",
+ "status": result_status,
"rawOutput": raw_output,
}
},
@@ -142,3 +154,61 @@ def test_issue_drilldown_order_accepts_non_empty_events() -> None:
)
assert score.score == 1.0
+
+
+_SKILL = "instrument-feature-flags"
+
+
+ "load_call,should_load,expected_score",
+ [
+ ((SKILL_TOOL_NAME, {"skill": _SKILL}), True, 1.0),
+ (("Read", {"file_path": f"/root/.claude/skills/{_SKILL}/SKILL.md"}), True, 1.0),
+ (("Bash", {"command": f"cat /scripts/plugins/posthog/skills/{_SKILL}/SKILL.md"}), True, 1.0),
+ (None, False, 1.0),
+ (None, True, 0.0),
+ ((SKILL_TOOL_NAME, {"skill": _SKILL}), False, 0.0),
+ ],
+)
+def test_skill_triggered_grades_against_the_expected_direction(
+ load_call: tuple[str, dict[str, Any]] | None, should_load: bool, expected_score: float
+) -> None:
+ calls: list[tuple[str, dict[str, Any], object]] = [("Read", {"file_path": "src/app/page.tsx"}, "ok")]
+ if load_call is not None:
+ calls.append((*load_call, "loaded"))
+
+ score = SkillTriggered(_SKILL, name="trigger")._run_eval_sync(
+ {"raw_log": _raw_tool_log(calls)},
+ {"trigger": {"should_load": should_load}},
+ )
+
+ assert score.score == expected_score
+ assert score.metadata["loaded"] is (load_call is not None)
+
+
+ "load_call",
+ [
+ (SKILL_TOOL_NAME, {"skill": _SKILL}),
+ ("Read", {"file_path": f"/root/.claude/skills/{_SKILL}/SKILL.md"}),
+ ("Bash", {"command": f"cat /scripts/plugins/posthog/skills/{_SKILL}/SKILL.md"}),
+ ],
+)
+def test_skill_triggered_ignores_a_failed_load_attempt(load_call: tuple[str, dict[str, Any]]) -> None:
+ score = SkillTriggered(_SKILL, name="trigger")._run_eval_sync(
+ {"raw_log": _raw_tool_log([(*load_call, "boom", "failed")])},
+ {"trigger": {"should_load": False}},
+ )
+
+ assert score.score == 1.0
+ assert score.metadata["loaded"] is False
+
+
[email protected]("expected", [None, {}, {"trigger": {}}, {"trigger": None}])
+def test_skill_triggered_skips_when_the_case_declares_no_direction(expected: dict | None) -> None:
+ score = SkillTriggered(_SKILL, name="trigger")._run_eval_sync(
+ {"raw_log": _raw_tool_log([(SKILL_TOOL_NAME, {"skill": _SKILL}, "loaded")])},
+ expected,
+ )
+
+ assert score.score is None
diff --git a/products/posthog_ai/eval_harness/test/test_instrument_flags_guard.py b/products/posthog_ai/eval_harness/test/test_instrument_flags_guard.py
new file mode 100644
index 000000000000..15d78b6c44b5
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_instrument_flags_guard.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import TYPE_CHECKING, cast
+
+import pytest
+
+from products.feature_flags.evals.eval_instrument_flags import SKILL_NAME, require_instrument_skill
+
+if TYPE_CHECKING:
+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext
+
+
+def _context(runtime_adapter: str | None) -> CustomPromptSandboxContext:
+ # The guard reads only runtime_adapter; a namespace stands in for the real
+ # sandbox context here.
+ return cast(
+ "CustomPromptSandboxContext",
+ SimpleNamespace(team_id=1, user_id=1, runtime_adapter=runtime_adapter),
+ )
+
+
+def _install_skill(base_dir, name: str = SKILL_NAME) -> None:
+ skill_file = base_dir / "products" / "posthog_ai" / "dist" / "skills" / name / "SKILL.md"
+ skill_file.parent.mkdir(parents=True)
+ skill_file.write_text(f"---\nname: {name}\ndescription: Stand-in\n---\nBody\n")
+
+
+def test_guard_refuses_codex_before_looking_for_the_skill(tmp_path, settings) -> None:
+ settings.BASE_DIR = tmp_path
+ _install_skill(tmp_path)
+
+ with pytest.raises(RuntimeError, match="claude runtime only"):
+ require_instrument_skill(_context("codex"))
+
+
[email protected]("runtime_adapter", [None, "claude"])
+def test_guard_refuses_when_the_graded_skill_is_absent(tmp_path, settings, runtime_adapter: str | None) -> None:
+ settings.BASE_DIR = tmp_path
+
+ with pytest.raises(RuntimeError, match="is not in products/posthog_ai/dist/skills"):
+ require_instrument_skill(_context(runtime_adapter))
+
+
[email protected]("runtime_adapter", [None, "claude"])
+def test_guard_returns_the_overlay_path_when_the_skill_is_present(
+ tmp_path, settings, runtime_adapter: str | None
+) -> None:
+ settings.BASE_DIR = tmp_path
+ _install_skill(tmp_path)
+
+ seed = require_instrument_skill(_context(runtime_adapter))
+
+ assert seed["skill_source"] == "context-mill overlay"
+ assert seed["skill_file"].endswith(f"{SKILL_NAME}/SKILL.md")
diff --git a/products/posthog_ai/evals/retrieval/scorers.py b/products/posthog_ai/evals/retrieval/scorers.py
index 68e5bbb70594..222dc2136fee 100644
--- a/products/posthog_ai/evals/retrieval/scorers.py
+++ b/products/posthog_ai/evals/retrieval/scorers.py
@@ -1,9 +1,12 @@
"""Deterministic scorers for the retrieval evals.
-Four binary scorers grade the retrieval flow:
+Five binary scorers grade the retrieval flow:
* ``SkillLoaded`` — did the agent load the named skill (e.g.
``querying-posthog-data``) before producing its answer?
+* ``SkillTriggered`` — the same detection, but graded against the
+ direction the case expects, for suites that pair positive and negative
+ trigger cases.
* ``LookupIdInOutput`` — does the agent's final assistant message contain
the seeded lookup insight's ID, proving it actually queried PostHog
rather than hallucinating?
@@ -22,10 +25,12 @@ Four binary scorers grade the retrieval flow:
(skipped) outside CLI mode, where tool schemas come bundled with the
tool registration.
-The first two scorers walk ``output["messages"]`` (Anthropic-format) and
-``output["seed"]`` (set by the seeder hook in ``base.py:task()``), so
-nothing has to be threaded through ``expected``. The third opts in via
-``expected = {"information_schema_before_sql": {}}``.
+``SkillLoaded`` and ``LookupIdInOutput`` walk ``output["messages"]``
+(Anthropic-format) and ``output["seed"]`` (set by the seeder hook in
+``base.py:task()``), so nothing has to be threaded through ``expected``.
+``InformationSchemaBeforeSql`` opts in via
+``expected = {"information_schema_before_sql": {}}``, and ``SkillTriggered``
+requires ``expected = {<scorer name>: {"should_load": <bool>}}`` on every case.
"""
from __future__ import annotations
@@ -37,11 +42,27 @@ from typing import Any
from products.posthog_ai.eval_harness.log_parser import INFO_SYNTHETIC_PREFIX, LogParser
from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
-__all__ = ["InfoCalledBeforeTool", "InformationSchemaBeforeSql", "LookupIdInOutput", "SkillLoaded"]
+__all__ = [
+ "InfoCalledBeforeTool",
+ "InformationSchemaBeforeSql",
+ "LookupIdInOutput",
+ "SkillLoaded",
+ "SkillTriggered",
+]
-class SkillLoaded(Scorer):
- """Binary: did the agent load a specific skill?
+def _matches_skill_file(skill_name: str, file_path: str) -> bool:
+ """Heuristic match: a Read of `<...>/<skill_name>/SKILL.md` counts as load.
+
+ The sandbox bind-mounts the local skills directory, so the exact path
+ depends on how skills are laid out in the cache — guard with a
+ substring check on both the skill name and the SKILL.md filename.
+ """
+ return skill_name in file_path and file_path.endswith("SKILL.md")
+
+
+def _find_skill_load(parser: LogParser, skill_name: str) -> dict[str, Any] | None:
+ """Return metadata for the first evidence that ``skill_name`` was loaded, else None.
Recognized as any of:
* a successful ``Skill`` tool call (``input.skill == skill_name``),
@@ -52,6 +73,29 @@ class SkillLoaded(Scorer):
path in its name or input — the codex runtime has no ``Skill``/``Read``
tools and reads skills through shell commands instead.
"""
+ for skill_call in parser.get_skill_calls(skill_name):
+ if not skill_call.is_error:
+ return {"matched_via": "skill_tool", "skill": skill_name}
+
+ for read_call in parser.get_tool_calls("Read"):
+ if read_call.is_error:
+ continue
+ file_path = read_call.input.get("file_path", "")
+ if isinstance(file_path, str) and _matches_skill_file(skill_name, file_path):
+ return {"matched_via": "read_skill_md", "file_path": file_path}
+
+ skill_file_ref = f"{skill_name}/SKILL.md"
+ for call in parser.get_tool_calls():
+ if call.is_error:
+ continue
+ if skill_file_ref in call.name or skill_file_ref in json.dumps(call.input, default=str):
+ return {"matched_via": "tool_reference", "tool": call.name[:120]}
+
+ return None
+
+
+class SkillLoaded(Scorer):
+ """Binary: did the agent load a specific skill? See ``_find_skill_load`` for what counts."""
def __init__(self, skill_name: str, *, name: str | None = None):
self.skill_name = skill_name
@@ -60,7 +104,7 @@ class SkillLoaded(Scorer):
def _name(self) -> str:
return self._label
- def _run_eval_sync(self, output: dict | None, expected=None, **kwargs) -> Score:
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
if not output:
return Score(name=self._name(), score=None, metadata={"reason": "No output"})
raw_log = output.get("raw_log")
@@ -68,36 +112,9 @@ class SkillLoaded(Scorer):
return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")
-
- for skill_call in parser.get_skill_calls(self.skill_name):
- if not skill_call.is_error:
- return Score(
- name=self._name(),
- score=1.0,
- metadata={"matched_via": "skill_tool", "skill": self.skill_name},
- )
-
- for read_call in parser.get_tool_calls("Read"):
- if read_call.is_error:
- continue
- file_path = read_call.input.get("file_path", "")
- if isinstance(file_path, str) and self._matches_skill_file(file_path):
- return Score(
- name=self._name(),
- score=1.0,
- metadata={"matched_via": "read_skill_md", "file_path": file_path},
- )
-
- skill_file_ref = f"{self.skill_name}/SKILL.md"
- for call in parser.get_tool_calls():
- if call.is_error:
- continue
- if skill_file_ref in call.name or skill_file_ref in json.dumps(call.input, default=str):
- return Score(
- name=self._name(),
- score=1.0,
- metadata={"matched_via": "tool_reference", "tool": call.name[:120]},
- )
+ match = _find_skill_load(parser, self.skill_name)
+ if match is not None:
+ return Score(name=self._name(), score=1.0, metadata=match)
return Score(
name=self._name(),
@@ -105,14 +122,54 @@ class SkillLoaded(Scorer):
metadata={"reason": f"Skill '{self.skill_name}' was never loaded"},
)
- def _matches_skill_file(self, file_path: str) -> bool:
- """Heuristic match: a Read of `<...>/<skill_name>/SKILL.md` counts as load.
- The sandbox bind-mounts the local skills directory, so the exact path
- depends on how skills are laid out in the cache — guard with a
- substring check on both the skill name and the SKILL.md filename.
- """
- return self.skill_name in file_path and file_path.endswith("SKILL.md")
+class SkillTriggered(Scorer):
+ """Binary: did a skill's trigger fire when it should, and stay quiet when it shouldn't?
+
+ Shares ``SkillLoaded``'s detection, so the two can never disagree about what
+ counts as a load, but takes the expected direction from the case:
+ ``expected[<scorer name>] = {"should_load": <bool>}``. Every case must declare
+ it; an undeclared direction skips (``score=None``) rather than assuming a
+ positive, so a case that forgets the key reads as unconfigured instead of as
+ the agent over-triggering.
+
+ Use this instead of ``SkillLoaded`` in a suite that pairs positive and
+ negative trigger cases. ``SkillLoaded`` scores a correct non-load as 0, which
+ reads as a regression on the scorecard; here one row spans both directions
+ and the mean is trigger accuracy.
+ """
+
+ def __init__(self, skill_name: str, *, name: str | None = None):
+ self.skill_name = skill_name
+ self._label = name or "skill_triggered"
+
+ def _name(self) -> str:
+ return self._label
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs) -> Score:
+ if not output:
+ return Score(name=self._name(), score=None, metadata={"reason": "No output"})
+ raw_log = output.get("raw_log")
+ if not raw_log:
+ return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})
+
+ direction = (expected or {}).get(self._name())
+ if not isinstance(direction, dict) or "should_load" not in direction:
+ return Score(
+ name=self._name(),
+ score=None,
+ metadata={"reason": f"Case declared no should_load for '{self._name()}'"},
+ )
+ should_load = bool(direction["should_load"])
+
+ parser = LogParser.cached(raw_log, initial_prompt=output.get("prompt", "") or "")
+ match = _find_skill_load(parser, self.skill_name)
+ loaded = match is not None
+
+ metadata: dict[str, Any] = {"skill": self.skill_name, "should_load": should_load, "loaded": loaded}
+ if match is not None:
+ metadata |= match
+ return Score(name=self._name(), score=1.0 if loaded == should_load else 0.0, metadata=metadata)
_NORMALIZE_RE = re.compile(r"[^a-z0-9 ]+")
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
index ea29a31bd6ea..aaf9c5af119a 100755
--- a/products/posthog_ai/scripts/build_skills.py
+++ b/products/posthog_ai/scripts/build_skills.py
@@ -49,6 +49,20 @@ _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
_BINARY_CHECK_SIZE = 8192
_MAX_SKILL_DESCRIPTION_LENGTH = 1024
_ALLOWED_SUBDIRS = {"references", "scripts"}
+# Skills authored in PostHog/context-mill. Every shipping consumer unzips this
+# repo's skills first and then unzips the context-mill release on top, so a
+# same-named skill here is overwritten instead of shipped — a failure that is
+# silent without this check, because the copy still builds and still publishes.
+OMNIBUS_SKILL_NAMES = frozenset(
+ {
+ "instrument-integration",
+ "instrument-product-analytics",
+ "instrument-feature-flags",
+ "instrument-error-tracking",
+ "instrument-llm-analytics",
+ "instrument-logs",
+ }
+)
# Tool/skill reference linting: skills must only reference MCP tools and skills that exist.
# The valid tool names come from the checked-in MCP schema registries (kept in sync with the
@@ -391,6 +405,24 @@ def parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
return metadata, body
+def _unrendered_skill_name(skill: DiscoveredSkill) -> str:
+ """Return the entry point's raw frontmatter ``name``, or the path name.
+
+ Not the shipped name. ``SkillBuilder.build_skill`` writes each skill to
+ ``dist/skills/<name>`` using the *rendered* frontmatter ``name``, and the lint
+ runs without rendering, so a Jinja name such as ``instrument-{{ 'logs' }}``
+ comes back here verbatim. ``build_skill`` checks the rendered name against
+ ``OMNIBUS_SKILL_NAMES`` (see ``display_name`` there), which is what catches a
+ templated reserved name; this function only gives the lint an earlier, cheaper
+ shot at the plain case.
+ """
+ try:
+ metadata, _ = parse_frontmatter(skill.source_file.read_text())
+ except (OSError, yaml.YAMLError):
+ return skill.name
+ return metadata.get("name") or skill.name
+
+
class SkillDiscoverer:
"""Discovers skill source files from products/*/skills/."""
@@ -551,6 +583,16 @@ class SkillBuilder:
display_name = skill.name
description = f"Skill: {skill.name}"
+ # lint_all reads the raw frontmatter, so a name that only becomes an
+ # omnibus name after rendering slips past it. Here the name is rendered,
+ # so catch that case before it builds into a context-mill-owned directory.
+ if display_name in OMNIBUS_SKILL_NAMES:
+ raise ValueError(
+ f"'{display_name}' is owned by PostHog/context-mill, which every consumer "
+ f"overlays on top of this repo's skills, so a copy here is overwritten "
+ f"rather than shipped. Remove {source} and change the context-mill source instead."
+ )
+
return SkillResource(
name=display_name,
description=description,
@@ -644,6 +686,15 @@ class SkillBuilder:
else:
seen[skill.name] = skill
+ unrendered_name = _unrendered_skill_name(skill)
+ if unrendered_name in OMNIBUS_SKILL_NAMES:
+ errors.append(
+ f"'{unrendered_name}' is owned by PostHog/context-mill, which every consumer "
+ f"overlays on top of this repo's skills, so a copy here is overwritten "
+ f"rather than shipped. Remove {skill.source_file.relative_to(self.repo_root)} "
+ f"and change the context-mill source instead."
+ )
+
tool_names = _load_mcp_tool_names(self.repo_root)
if tool_names is None:
print("WARNING: MCP schema registries not found; skipping tool reference checks.", file=sys.stderr)
diff --git a/products/posthog_ai/scripts/test/test_build_skills.py b/products/posthog_ai/scripts/test/test_build_skills.py
index 8211f1b2b566..67688f5c556c 100644
--- a/products/posthog_ai/scripts/test/test_build_skills.py
+++ b/products/posthog_ai/scripts/test/test_build_skills.py
@@ -542,6 +542,64 @@ def test_lint_all_catches_duplicate_skill_names(tmp_path: Path) -> None:
assert builder.lint_all() is False
+ "relpath,reserved_name,content",
+ [
+ (
+ "local-copy.md",
+ "instrument-feature-flags",
+ "---\nname: instrument-feature-flags\ndescription: Copy\n---\nBody\n",
+ ),
+ (
+ "local-copy/SKILL.md",
+ "instrument-logs",
+ "---\nname: instrument-logs\ndescription: Copy\n---\nBody\n",
+ ),
+ (
+ "local-copy/SKILL.md.j2",
+ "instrument-error-tracking",
+ "---\nname: instrument-error-tracking\ndescription: Copy\n---\n# {{ 'x' }}\n",
+ ),
+ ],
+ ids=["loose-file", "renamed-dir", "j2-entry"],
+)
+def test_lint_all_catches_reserved_name_in_frontmatter(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str], relpath: str, reserved_name: str, content: str
+) -> None:
+ skill_file = tmp_path / "products" / "alpha" / "skills" / relpath
+ skill_file.parent.mkdir(parents=True)
+ skill_file.write_text(content)
+
+ builder = SkillBuilder(
+ repo_root=tmp_path,
+ products_dir=tmp_path / "products",
+ output_dir=tmp_path / "output",
+ )
+ assert builder.lint_all() is False
+ stderr = capsys.readouterr().err
+ assert f"'{reserved_name}' is owned by PostHog/context-mill" in stderr
+ # The path is the only part that tells an author which file to delete.
+ assert str(skill_file.relative_to(tmp_path)) in stderr
+
+
+def test_build_skill_rejects_reserved_name_after_rendering(tmp_path: Path) -> None:
+ # A templated name that only becomes an omnibus name once rendered slips past
+ # lint_all, which reads the raw frontmatter. build_skill sees the rendered
+ # name, so it must still refuse it.
+ skill_dir = tmp_path / "products" / "alpha" / "skills" / "local-copy"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md.j2").write_text("---\nname: instrument-{{ 'logs' }}\ndescription: Copy\n---\n# Body\n")
+
+ renderer = SkillRenderer()
+ skill = DiscoveredSkill(
+ name="local-copy", source_file=skill_dir / "SKILL.md.j2", product_dir=tmp_path / "products" / "alpha", depth=1
+ )
+ builder = SkillBuilder(repo_root=tmp_path, products_dir=tmp_path / "products", output_dir=tmp_path / "output")
+
+ with pytest.raises(ValueError, match="owned by PostHog/context-mill"):
+ builder.build_skill(skill, renderer)
+
+
def test_build_skill_rejects_binary_file(tmp_path: Path) -> None:
skill_dir = tmp_path / "products" / "alpha" / "skills" / "has-binary"
skill_dir.mkdir(parents=True)