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(posthog-ai): split skill build script by concern (#99665)

Paul D'Ambra264588d50fd1
diff --git a/.agents/skills/debugging-mcp-analytics/references/wizard-and-onboarding.md b/.agents/skills/debugging-mcp-analytics/references/wizard-and-onboarding.md
index bfbba5346962..d2a895dcc957 100644
--- a/.agents/skills/debugging-mcp-analytics/references/wizard-and-onboarding.md
+++ b/.agents/skills/debugging-mcp-analytics/references/wizard-and-onboarding.md
@@ -109,7 +109,7 @@ Do not confuse these; they have different audiences and different release mechan
including the `mcp-analytics` codemod, served by `services/mcp`'s `ResourceCatalog`
(`src/hono/resource-catalog.ts`) as MCP prompts and resources. This is **also the sole
backend for `posthog-cli api skill list|install`** (`services/mcp/src/cli/skills.ts`).
-3. **`posthog_ai` `build_skills`** — `products/posthog_ai/scripts/build_skills.py` scans
+3. **`posthog_ai` `build_skills`** — `products/posthog_ai/scripts/build_skills/` scans
`products/*/skills/` into `dist/skills.zip`, which `ci-agent-skills.yml` publishes as a
GitHub release. This is the channel that carries the customer-facing **analysis** skills
(`querying-posthog-data`, the `exploring-mcp-*` set, `improving-mcp-tools`) and this skill.
diff --git a/.agents/skills/writing-skills/SKILL.md b/.agents/skills/writing-skills/SKILL.md
index 20f396811f0c..af215763effa 100644
--- a/.agents/skills/writing-skills/SKILL.md
+++ b/.agents/skills/writing-skills/SKILL.md
@@ -40,7 +40,7 @@ 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.
+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`, `instrument-metrics` — 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
@@ -87,7 +87,7 @@ Only `references/` and `scripts/` subdirectories are collected. Others are ignor
## Template functions
Files ending in `.j2` are rendered with Jinja2 at build time
-by [`products/posthog_ai/scripts/build_skills.py`](../../../products/posthog_ai/scripts/build_skills.py).
+by [`products/posthog_ai/scripts/build_skills/`](../../../products/posthog_ai/scripts/build_skills/).
Extend the build pipeline so the monorepo stays the source of truth —
when domain knowledge lives in code (Pydantic models, query runners, function registries),
add a template function rather than duplicating it as static markdown that drifts.
diff --git a/docs/published/handbook/engineering/ai/writing-skills.md b/docs/published/handbook/engineering/ai/writing-skills.md
index 765925897841..37f29b65c7cf 100644
--- a/docs/published/handbook/engineering/ai/writing-skills.md
+++ b/docs/published/handbook/engineering/ai/writing-skills.md
@@ -360,7 +360,7 @@ To add a new template function:
## Build pipeline
The pipeline discovers, renders, and packages skills.
-Source of truth: [`products/posthog_ai/scripts/build_skills.py`](https://github.com/PostHog/posthog/blob/master/products/posthog_ai/scripts/build_skills.py).
+Source of truth: [`products/posthog_ai/scripts/build_skills/`](https://github.com/PostHog/posthog/tree/master/products/posthog_ai/scripts/build_skills/).
### Pipeline steps
@@ -424,7 +424,7 @@ 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`.
+`instrument-error-tracking`, `instrument-llm-analytics`, `instrument-logs`, and `instrument-metrics`.
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,
diff --git a/hogli.yaml b/hogli.yaml
index 914c65dff3ca..31f61e275719 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -611,17 +611,17 @@ build:
cmd: pnpm --filter=@posthog/frontend run build:products
description: Build products manifest from TypeScript/JSX files
build:skills:
- cmd: python products/posthog_ai/scripts/build_skills.py
+ cmd: python -m products.posthog_ai.scripts.build_skills
description: Build agent skills from products/*/skills/ into dist/skills/ and
dist/skills.zip
init:skill:
- cmd: python products/posthog_ai/scripts/build_skills.py --init
+ cmd: python -m products.posthog_ai.scripts.build_skills --init
description: Scaffold a new agent skill directory with SKILL.md boilerplate
sync:skill:
- cmd: python products/posthog_ai/scripts/build_skills.py --sync
+ cmd: python -m products.posthog_ai.scripts.build_skills --sync
description: Build a product skill and sync to .agents/skills/ for local testing
unsync:skill:
- cmd: python products/posthog_ai/scripts/build_skills.py --sync --clean
+ cmd: python -m products.posthog_ai.scripts.build_skills --sync --clean
description: Remove a previously synced skill from .agents/skills/
docker:
docker:services:up:
@@ -865,7 +865,7 @@ quality:
cmd: ./bin/ruff.sh format
description: Format Python files
lint:skills:
- cmd: python products/posthog_ai/scripts/build_skills.py --lint
+ cmd: python -m products.posthog_ai.scripts.build_skills --lint
description: Validate agent skill sources (syntax, frontmatter, depth constraints)
lint:python:fix:
cmd: ./bin/ruff.sh check --fix
diff --git a/products/ai_observability/skills/README.md b/products/ai_observability/skills/README.md
index 1161982bfa80..4ad793fd90f5 100644
--- a/products/ai_observability/skills/README.md
+++ b/products/ai_observability/skills/README.md
@@ -30,7 +30,7 @@ the standalone Skills product — see `products/skills/skills/`.
hogli init:skill -- --product ai_observability --name my-new-skill
```
-See `products/posthog_ai/scripts/build_skills.py` for the build pipeline
+See `products/posthog_ai/scripts/build_skills/` for the build pipeline
and `AGENTS.md` for conventions.
## Local testing
diff --git a/products/desktop/scripts/dev-with-skills.mjs b/products/desktop/scripts/dev-with-skills.mjs
index bcd6e27cbfc8..a9fedfd630a3 100644
--- a/products/desktop/scripts/dev-with-skills.mjs
+++ b/products/desktop/scripts/dev-with-skills.mjs
@@ -45,7 +45,7 @@ async function buildSkills(signal) {
console.log("[skills] Building skills from this checkout...");
await run(
"uv",
- ["run", "python", "products/posthog_ai/scripts/build_skills.py"],
+ ["run", "python", "-m", "products.posthog_ai.scripts.build_skills"],
{
cwd: REPOSITORY_DIR,
signal,
diff --git a/products/desktop/scripts/sync-local-skills.test.mjs b/products/desktop/scripts/sync-local-skills.test.mjs
index d754d1a26aae..573163d11b5a 100644
--- a/products/desktop/scripts/sync-local-skills.test.mjs
+++ b/products/desktop/scripts/sync-local-skills.test.mjs
@@ -112,7 +112,13 @@ test("detects skill edits, additions, renames, removals and renderer changes but
temporaryDirectories.push(root);
await mkdir(join(root, "products"));
const skillDir = join(root, "products", "example", "skills", "example");
- const rendererDir = join(root, "products", "posthog_ai", "scripts");
+ const rendererDir = join(
+ root,
+ "products",
+ "posthog_ai",
+ "scripts",
+ "build_skills",
+ );
const outputDir = join(root, "products", "posthog_ai", "dist", "skills");
let fingerprint = await skillSourceFingerprint(root);
const changes = [
@@ -125,7 +131,7 @@ test("detects skill edits, additions, renames, removals and renderer changes but
() => rm(join(skillDir, "SKILL.md.j2")),
async () => {
await mkdir(rendererDir, { recursive: true });
- await writeFile(join(rendererDir, "build_skills.py"), "renderer");
+ await writeFile(join(rendererDir, "skill_builder.py"), "renderer");
},
];
for (const change of changes) {
diff --git a/products/error_tracking/backend/test/test_import_cycles.py b/products/error_tracking/backend/test/test_import_cycles.py
index 154daf467ff9..40d6209dc699 100644
--- a/products/error_tracking/backend/test/test_import_cycles.py
+++ b/products/error_tracking/backend/test/test_import_cycles.py
@@ -7,7 +7,7 @@ from pathlib import Path
# find the posthog package.
_REPO_ROOT = Path(__file__).parents[4]
-# The skills build (products/posthog_ai/scripts/build_skills.py) imports the query runners
+# The skills build (products/posthog_ai/scripts/build_skills/) imports the query runners
# in a cold interpreter, before anything has touched the error_tracking api package. If a
# runner imports from api.*, that executes api/__init__.py, whose viewsets import the
# runners right back (api/query.py -> ErrorTrackingQueryRunner) and the import blows up
diff --git a/products/feature_flags/skills/README.md b/products/feature_flags/skills/README.md
index d63e01ba7af6..206b940d7da2 100644
--- a/products/feature_flags/skills/README.md
+++ b/products/feature_flags/skills/README.md
@@ -38,9 +38,9 @@ So:
- **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`.
+- The same applies to the other six omnibus skills: `instrument-integration`, `instrument-product-analytics`, `instrument-error-tracking`, `instrument-llm-analytics`, `instrument-logs`, and `instrument-metrics`.
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.
+`hogli lint:skills` fails when any of the seven omnibus names appears under `products/*/skills/`, so the rule above is enforced rather than trusted.
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
deleted file mode 100755
index 963af708fd7f..000000000000
--- a/products/posthog_ai/scripts/build_skills.py
+++ /dev/null
@@ -1,1046 +0,0 @@
-#!/usr/bin/env python3
-# ruff: noqa: T201 allow print statements
-"""
-Build coding agent skills from products/*/skills/ into rendered files and a ZIP
-archive for distribution.
-
-Skills can be:
-- Plain markdown (SKILL.md) — copied as-is
-- Jinja2 templates (SKILL.md.j2) — rendered with Python context including Pydantic schema helpers
-
-Each skill must have YAML frontmatter with at least ``name`` and ``description`` fields.
-The build renders skills to dist/skills/{skill_name}/ (gitignored, human-readable)
-and optionally packages them into dist/skills.zip (published as a GitHub release by CI).
-
-Requires the project's Python environment (managed by uv) for template rendering
-that imports Pydantic models from product code.
-
-Usage:
- hogli build:skills # Build all product skills to dist/skills/ and dist/skills.zip
- hogli build:skills --list # List discovered skills without building
- hogli lint:skills # Validate skill sources without rendering
-"""
-
-from __future__ import annotations
-
-import os
-import re
-import sys
-import json
-import shutil
-import zipfile
-import argparse
-import textwrap
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Literal, cast
-
-import yaml
-from jinja2 import Environment, StrictUndefined, TemplateSyntaxError
-from pydantic import BaseModel, Field, ValidationError
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-sys.path.insert(0, str(REPO_ROOT))
-
-# After the sys.path line above, because this module also runs as a script, where the repo root is
-# not importable until then. The skills store reads the same set to refuse a store skill that takes
-# a bundled name, so both sides read one definition.
-from products.skills.backend.bundled_skills import OMNIBUS_SKILL_NAMES # noqa: E402
-
-MANIFEST_VERSION = "1.0.0"
-_ZIP_FIXED_TIME = (2025, 1, 1, 0, 0, 0)
-
-_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"}
-
-# 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
-# sources by the schema drift check in ci-mcp.yml). Mirrors lint-tool-names.ts in services/mcp.
-_MCP_SCHEMA_FILES = (
- "services/mcp/schema/tool-definitions.json",
- "services/mcp/schema/generated-tool-definitions.json",
-)
-# The reference check is heuristic and advisory: a candidate is only treated as a (stale) reference
-# when it *resembles* a real name — within this many edits of a real tool/skill, or an exact
-# casing miss. Real renames/typos sit at distance 1-2 from the intended name; ordinary hyphenated
-# prose ("highest-error", "per-file") is far from every name. Backticks are not treated as intent
-# (prose uses them for emphasis and field names too), so prose that does not resemble a real name is
-# simply ignored — no name-level allowlist is needed for it. Findings are reported, never blocking.
-_NEAR_MISS_MAX_EDITS = 2
-# SDK / HogQL function names that legitimately appear as code in skills (e.g. `emit_signal(...)`,
-# `get_feature_flag(...)`). They are real identifiers, not stale references, but collide with a
-# tool-name suffix/near-miss, so they are held out of the reference check.
-_SDK_FUNCTION_NAMES = {
- "feature_enabled",
- "get_feature_flag",
- "get_feature_flag_payload",
- "get_feature_flag_result",
- "get_all_flags",
- "get_all_flags_and_payloads",
- "apply_path_cleaning",
- "emit_signal",
-}
-# "use the X tool", "load the `X` skill" — kebab or snake candidate followed by tool/skill.
-_PHRASE_REFERENCE_RE = re.compile(r"(?<![A-Za-z0-9_`-])`?([a-z0-9]+(?:[_-][a-z0-9]+)+)`?\s+(tools?|skills?)\b")
-# "via `X`", "use `X`" — kebab-only (snake here is usually a field/SDK name, not a tool).
-_INVOCATION_REFERENCE_RE = re.compile(
- r"\b(?:via|use|using|call|calling)\s+(?:the\s+)?`([a-z0-9]+(?:-[a-z0-9]+)+)`(?!\s*(?:tools?|skills?)\b)"
-)
-# A noun right after the backticked name means it's not a tool reference ("via the `x` feature flag").
-_ENTITY_NOUN_RE = re.compile(r"\s+(?:feature|flag|event|property|properties|column|field|table|key|filter)s?\b")
-# Backticked call syntax, e.g. `read_data("experiments", id)` — tool invocations written as calls.
-# Deliberately skills-only (no equivalent in tool-references.ts): call-style references occur only
-# in skill prose. The near-miss gate keeps SDK/HogQL examples (e.g. `get_feature_flag(...)`) quiet,
-# since those names do not resemble any MCP tool.
-_CALL_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:[_-][a-z0-9]+)+)\(")
-# Backticked snake_case whose kebab form is a real tool — wrong casing.
-_SNAKE_CASE_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:_[a-z0-9]+)+)`")
-
-
-def _load_mcp_tool_names(repo_root: Path) -> set[str] | None:
- """Load valid MCP tool names from the checked-in schema registries.
-
- Returns None if no registry is available so the reference check can be skipped
- (keeps the lint runnable in checkouts without the MCP service).
- """
- names: set[str] = set()
- found = False
- for rel_path in _MCP_SCHEMA_FILES:
- schema_file = repo_root / rel_path
- if not schema_file.is_file():
- continue
- found = True
- names.update(json.loads(schema_file.read_text()).keys())
- return names if found else None
-
-
-# The kinds produced by the phrase regex alternation `(tools?|skills?)`.
-ReferenceKind = Literal["tool", "tools", "skill", "skills"]
-
-
-@dataclass(frozen=True)
-class ReferenceFinding:
- source_label: str
- line: int
- col: int
- name: str
- message: str
-
-
-def _is_valid_reference(name: str, kind: ReferenceKind, tool_names: set[str], skill_names: set[str]) -> bool:
- if name in _SDK_FUNCTION_NAMES:
- return True
- registry = skill_names if kind in ("skill", "skills") else tool_names
- if name in registry:
- return True
- # Shorthand suffix, e.g. "the partial-update tool" for external-data-schemas-partial-update.
- if any(known.endswith(f"-{name}") for known in registry):
- return True
- # Plural family reference, e.g. "the feature-flag tools".
- if kind in ("tools", "skills") and any(known.startswith(f"{name}-") for known in registry):
- return True
- return False
-
-
-def _edit_distance(a: str, b: str) -> int:
- prev = list(range(len(b) + 1))
- for i, ca in enumerate(a, 1):
- cur = [i]
- for j, cb in enumerate(b, 1):
- cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
- prev = cur
- return prev[-1]
-
-
-def _reference_suggestions(name: str, registry: set[str]) -> list[str]:
- """Real names this candidate plausibly meant: exact/suffix matches, else near-misses by edit distance."""
- kebab = name.replace("_", "-")
- suffix = sorted(t for t in registry if t == kebab or t.endswith(f"-{kebab}"))
- if suffix:
- return suffix
- near = sorted((_edit_distance(kebab, known), known) for known in registry)
- return [known for distance, known in near if distance <= _NEAR_MISS_MAX_EDITS]
-
-
-def _did_you_mean(suggestions: list[str]) -> str:
- return f" — did you mean {' or '.join(suggestions)}?" if suggestions else ""
-
-
-def _line_col(text: str, offset: int) -> tuple[int, int]:
- return text.count("\n", 0, offset) + 1, offset - text.rfind("\n", 0, offset)
-
-
-def _check_tool_references(
- text: str, source_label: str, tool_names: set[str], skill_names: set[str]
-) -> list[ReferenceFinding]:
- # Dedupe by name within this text only: one name tripping two rules (e.g. wrong casing inside
- # a phrase) is one finding, but the same stale name in another skill file needs its own.
- findings: list[ReferenceFinding] = []
- reported: set[str] = set()
-
- def report(offset: int, name: str, message: str) -> None:
- if name in reported:
- return
- reported.add(name)
- line, col = _line_col(text, offset)
- findings.append(ReferenceFinding(source_label, line, col, name, message))
-
- # "X tool/skill". Resemblance to a real name is the only signal we trust — backticks in prose
- # mean emphasis or a field name as often as a reference, so they are not treated as intent.
- for m in _PHRASE_REFERENCE_RE.finditer(text):
- name, kind = m.group(1), cast("ReferenceKind", m.group(2))
- if _is_valid_reference(name, kind, tool_names, skill_names):
- continue
- suggestions = _reference_suggestions(name, skill_names if kind in ("skill", "skills") else tool_names)
- if suggestions:
- report(
- m.start(1),
- name,
- f"'{name}' looks like a {kind.rstrip('s')} but none exists{_did_you_mean(suggestions)}",
- )
- # "via `X`": one concrete thing, but not whether tool or skill — check tools (a family prefix
- # like `feature-flag` is not invocable) plus exact skill names.
- for m in _INVOCATION_REFERENCE_RE.finditer(text):
- if _ENTITY_NOUN_RE.match(text, m.end()):
- continue
- name = m.group(1)
- if _is_valid_reference(name, "tool", tool_names, skill_names) or name in skill_names:
- continue
- suggestions = _reference_suggestions(name, tool_names)
- if suggestions:
- report(m.start(1), name, f"'{name}' looks like a tool but none exists{_did_you_mean(suggestions)}")
- for m in _CALL_REFERENCE_RE.finditer(text):
- name = m.group(1)
- if _is_valid_reference(name, "tool", tool_names, skill_names):
- continue
- suggestions = _reference_suggestions(name, tool_names)
- if suggestions:
- report(m.start(1), name, f"'{name}' looks like a tool but none exists{_did_you_mean(suggestions)}")
- for m in _SNAKE_CASE_REFERENCE_RE.finditer(text):
- name = m.group(1)
- if name not in tool_names and name.replace("_", "-") in tool_names:
- report(m.start(1), name, f"'{name}' has wrong casing — the tool is named {name.replace('_', '-')}")
- return findings
-
-
-def _emit_reference_findings(findings: list[ReferenceFinding]) -> None:
- """Surface advisory reference findings without failing the lint.
-
- In GitHub Actions, emit a workflow warning command so each finding renders as an annotation on
- the offending line in the PR diff; locally, print a plain ``file:line:col`` warning.
- """
- if not findings:
- return
- in_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
- for f in findings:
- if in_github_actions:
- print(
- f"::warning file={f.source_label},line={f.line},col={f.col},title=Possible stale reference::{f.message}"
- )
- else:
- print(f"{f.source_label}:{f.line}:{f.col}: warning: {f.message}", file=sys.stderr)
- print(
- f"\nNote: {len(findings)} possible stale tool/skill reference(s) flagged above (advisory, not blocking).",
- file=sys.stderr,
- )
-
-
-def _create_jinja_env(**extra_globals: object) -> Environment:
- """Create a Jinja2 Environment with the standard skill rendering settings."""
- env = Environment(
- # nosemgrep: python.jinja2.security.audit.autoescape-disabled-false.incorrect-autoescape-disabled -- output is Markdown for a JSON manifest, not HTML
- autoescape=False,
- undefined=StrictUndefined,
- keep_trailing_newline=True,
- lstrip_blocks=True,
- trim_blocks=True,
- )
- env.globals.update(extra_globals)
- return env
-
-
-def _assert_text_file(file_path: Path) -> None:
- """Raise ValueError if file appears to be binary (contains null bytes)."""
- with open(file_path, "rb") as f:
- chunk = f.read(_BINARY_CHECK_SIZE)
- if b"\x00" in chunk:
- raise ValueError(
- f"Binary file not supported in skill directory: {file_path.name}. Only text-based files are allowed."
- )
-
-
-_MARKDOWN_LINK_RE = re.compile(r"\]\(([^)\s]+)\)")
-
-
-def _check_reference_links(entry: Path, repo_root: Path) -> list[str]:
- """Find markdown links to references/ or scripts/ files that will not exist in the built bundle.
-
- A skill ships its SKILL.md, references/, and scripts/ files, and the build strips the .j2 suffix
- from every rendered template. So a link to `references/x.md` resolves when the source holds either
- `references/x.md` or `references/x.md.j2`, but a link to `references/x.md.j2` never resolves,
- because the bundle only has the stripped `references/x.md`.
- """
- skill_dir = entry.parent
- bundle: set[str] = set()
- for subdir_name in sorted(_ALLOWED_SUBDIRS):
- subdir = skill_dir / subdir_name
- if not subdir.is_dir():
- continue
- for root, dirs, filenames in os.walk(subdir):
- dirs[:] = sorted(dirs)
- for filename in sorted(filenames):
- # The build strips .j2 when it renders a template, so record the shipped path.
- rel = str((Path(root) / filename).relative_to(skill_dir))
- bundle.add(rel.removesuffix(".j2"))
-
- # Only the SKILL.md entry point is scanned. Reference files link to each other with paths
- # relative to the skill root, which do not resolve from inside references/, and their code
- # snippets hold `](...)` fragments that are not links.
- errors: list[str] = []
- text = entry.read_text()
- source_label = str(entry.relative_to(repo_root))
- for match in _MARKDOWN_LINK_RE.finditer(text):
- target = match.group(1).split("#", 1)[0].split("?", 1)[0]
- if not target or "://" in target or target.startswith("mailto:"):
- continue
- resolved = (skill_dir / target).resolve()
- try:
- rel_to_skill = resolved.relative_to(skill_dir.resolve())
- except ValueError:
- continue # Link points outside the skill; not part of the bundle.
- if not rel_to_skill.parts or rel_to_skill.parts[0] not in _ALLOWED_SUBDIRS:
- continue # Only references/ and scripts/ files ship in the bundle.
- if resolved.is_dir():
- continue # A directory ships through its files.
- if str(rel_to_skill) not in bundle:
- line, _col = _line_col(text, match.start(1))
- hint = (
- "Link to the built '.md' path, not the '.md.j2' template."
- if target.endswith(".j2")
- else "No file of that name ships in the skill."
- )
- errors.append(
- f"Broken reference link in {source_label}:{line}: '{target}' does not resolve to a bundled file. {hint}"
- )
- return errors
-
-
-class SkillFrontmatter(BaseModel):
- name: str
- description: str = Field(max_length=_MAX_SKILL_DESCRIPTION_LENGTH)
-
-
-class DiscoveredSkill(BaseModel):
- name: str
- source_file: Path
- product_dir: Path
- depth: int
-
-
-class SkillFile(BaseModel):
- path: str
- content: str
-
-
-class SkillResource(BaseModel):
- name: str
- description: str
- files: list[SkillFile]
- source: str
-
-
-class SkillManifest(BaseModel):
- version: str = MANIFEST_VERSION
- resources: list[SkillResource] = Field(default_factory=list)
-
-
-def validate_frontmatter(text: str, source_label: str = "<unknown>") -> SkillFrontmatter:
- """Parse and validate frontmatter from rendered skill text.
-
- Raises ``ValueError`` if frontmatter is missing or invalid.
- """
- match = _FRONTMATTER_RE.match(text)
- if not match:
- raise ValueError(f"Missing YAML frontmatter in {source_label}")
- raw_yaml = match.group(1)
- try:
- parsed = yaml.safe_load(raw_yaml)
- except yaml.YAMLError as e:
- raise ValueError(f"Invalid YAML frontmatter in {source_label}: {e}") from e
- if not isinstance(parsed, dict):
- raise ValueError(f"Frontmatter must be a YAML mapping in {source_label}")
- try:
- return SkillFrontmatter.model_validate(parsed)
- except ValidationError as e:
- raise ValueError(f"Invalid frontmatter in {source_label}: {e}") from e
-
-
-def parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
- """Extract YAML frontmatter and body from a skill file.
-
- Returns (metadata_dict, body_without_frontmatter).
- """
- match = _FRONTMATTER_RE.match(text)
- if not match:
- return {}, text
-
- raw_yaml = match.group(1)
- body = text[match.end() :]
- parsed = yaml.safe_load(raw_yaml)
- if not isinstance(parsed, dict):
- return {}, text
-
- metadata: dict[str, str] = {str(k): str(v) for k, v in parsed.items()}
- 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/."""
-
- def __init__(self, products_dir: Path) -> None:
- self.products_dir = products_dir
-
- def discover(self) -> list[DiscoveredSkill]:
- """Discover skill sources from products/*/skills/.
-
- Supports two depth levels relative to products/*/skills/:
- - Depth 0: Loose files directly in skills/ (e.g., my-skill.md or my-skill.md.j2).
- Skill name = filename stem (without .md or .md.j2 extension).
- - Depth 1: Directories containing SKILL.md(.j2) (e.g., my-skill/SKILL.md).
- Skill name = directory name.
-
- For both depths, .j2 files take priority over plain .md when both exist.
- """
- skills: list[DiscoveredSkill] = []
-
- if not self.products_dir.exists():
- return skills
-
- for product_dir in sorted(self.products_dir.iterdir()):
- if not product_dir.is_dir():
- continue
- skills_dir = product_dir / "skills"
- if not skills_dir.exists():
- continue
-
- for entry in sorted(skills_dir.iterdir()):
- if entry.is_dir():
- j2_file = entry / "SKILL.md.j2"
- md_file = entry / "SKILL.md"
- if j2_file.exists():
- skills.append(
- DiscoveredSkill(name=entry.name, source_file=j2_file, product_dir=product_dir, depth=1)
- )
- elif md_file.exists():
- skills.append(
- DiscoveredSkill(name=entry.name, source_file=md_file, product_dir=product_dir, depth=1)
- )
- elif (
- entry.is_file()
- # Convention docs that can live alongside skills — not skills themselves.
- and entry.name not in ("README.md", "AGENTS.md", "CLAUDE.md")
- and (entry.name.endswith(".md.j2") or entry.name.endswith(".md"))
- ):
- if entry.name.endswith(".md") and (entry.parent / (entry.name + ".j2")).exists():
- continue
- skill_name = entry.name.removesuffix(".j2").removesuffix(".md")
- skills.append(DiscoveredSkill(name=skill_name, source_file=entry, product_dir=product_dir, depth=0))
-
- return skills
-
-
-class SkillRenderer:
- """Renders skill source files to final markdown via Jinja2."""
-
- def __init__(self) -> None:
- from products.posthog_ai.scripts.audit_constants import audit_constants
- from products.posthog_ai.scripts.hogql_example import render_hogql_example
- from products.posthog_ai.scripts.hogql_functions import hogql_functions
- from products.posthog_ai.scripts.pydantic_schema import pydantic_schema
- from products.posthog_ai.scripts.schema_columns import schema_columns
-
- self.env = _create_jinja_env(
- pydantic_schema=pydantic_schema,
- render_hogql_example=render_hogql_example,
- hogql_functions=hogql_functions,
- audit_constants=audit_constants,
- schema_columns=schema_columns,
- )
-
- def render(self, source_file: Path) -> str:
- """Render a skill source file to its final markdown content."""
- raw = source_file.read_text()
- if source_file.suffix == ".j2":
- template = self.env.from_string(raw)
- return template.render()
- return raw
-
-
-class SkillBuilder:
- """Orchestrates skill discovery, rendering, and manifest generation."""
-
- def __init__(self, repo_root: Path, products_dir: Path, output_dir: Path) -> None:
- self.repo_root = repo_root
- self.products_dir = products_dir
- self.output_dir = output_dir
- self.dist_dir = output_dir / "dist"
- self.skills_dist_dir = self.dist_dir / "skills"
- self.discoverer = SkillDiscoverer(products_dir)
-
- def collect_skill_files(self, skill_dir: Path, renderer: SkillRenderer) -> list[SkillFile]:
- """Collect and render files from a skill directory using an explicit allowlist.
-
- Only collects from three sources:
- 1. Entry point: SKILL.md.j2 (preferred) or SKILL.md
- 2. references/ directory (recursive)
- 3. scripts/ directory (recursive)
-
- .j2 files are rendered through Jinja2 and have the .j2 extension stripped.
- Returns a list of SkillFile with SKILL.md always first.
- """
- j2_entry = skill_dir / "SKILL.md.j2"
- md_entry = skill_dir / "SKILL.md"
- if j2_entry.exists():
- entry_path = j2_entry
- elif md_entry.exists():
- entry_path = md_entry
- else:
- raise ValueError(f"Missing SKILL.md entry point in {skill_dir.name}")
-
- _assert_text_file(entry_path)
- entry_content = renderer.render(entry_path)
- entry_point = SkillFile(path="SKILL.md", content=entry_content)
-
- files: list[SkillFile] = []
- for subdir_name in sorted(_ALLOWED_SUBDIRS):
- subdir = skill_dir / subdir_name
- if not subdir.is_dir():
- continue
- for root, dirs, filenames in os.walk(subdir):
- dirs[:] = sorted(dirs)
- for filename in sorted(filenames):
- file_path = Path(root) / filename
- _assert_text_file(file_path)
- content = renderer.render(file_path)
- rel_path = str(file_path.relative_to(skill_dir))
- if rel_path.endswith(".j2"):
- rel_path = rel_path.removesuffix(".j2")
- files.append(SkillFile(path=rel_path, content=content))
-
- return [entry_point, *files]
-
- def build_skill(self, skill: DiscoveredSkill, renderer: SkillRenderer) -> SkillResource:
- """Build a single skill and return a SkillResource."""
- if skill.depth == 1:
- skill_dir = skill.source_file.parent
- skill_files = self.collect_skill_files(skill_dir, renderer)
- rendered_entry_content = skill_files[0].content
- metadata, _body = parse_frontmatter(rendered_entry_content)
- source = str(skill_dir.relative_to(self.repo_root))
- else:
- rendered_entry_content = renderer.render(skill.source_file)
- metadata, _body = parse_frontmatter(rendered_entry_content)
- out_name = skill.source_file.name
- if out_name.endswith(".j2"):
- out_name = out_name.removesuffix(".j2")
- skill_files = [SkillFile(path=out_name, content=rendered_entry_content.strip())]
- source = str(skill.source_file.relative_to(self.repo_root))
-
- if metadata:
- validated_metadata = validate_frontmatter(rendered_entry_content, source)
- display_name = validated_metadata.name
- description = validated_metadata.description
- else:
- 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,
- files=skill_files,
- source=source,
- )
-
- def build_manifest(self, skills: list[DiscoveredSkill], renderer: SkillRenderer) -> SkillManifest:
- """Build the full SkillManifest from discovered skills."""
- resources = [self.build_skill(skill, renderer) for skill in skills]
- return SkillManifest(resources=resources)
-
- def build_all(self, *, dry_run: bool = False) -> SkillManifest:
- """Build all product skills and write rendered files to skills_dist/."""
- skills = self.discoverer.discover()
- renderer = SkillRenderer()
- manifest = self.build_manifest(skills, renderer)
-
- if not dry_run and manifest.resources:
- if self.skills_dist_dir.exists():
- shutil.rmtree(self.skills_dist_dir)
- for resource in manifest.resources:
- for skill_file in resource.files:
- file_path = self.skills_dist_dir / resource.name / skill_file.path
- file_path.parent.mkdir(parents=True, exist_ok=True)
- file_path.write_text(skill_file.content)
-
- return manifest
-
- def pack(self) -> Path:
- """Build skills and package skills_dist/ into dist/skills.zip."""
- self.build_all()
- return self._zip_skills_dist()
-
- def _zip_skills_dist(self) -> Path:
- """Create dist/skills.zip from the dist/skills/ directory."""
- zip_path = self.dist_dir / "skills.zip"
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
- for file_path in sorted(self.skills_dist_dir.rglob("*")):
- if file_path.is_file():
- arcname = str(file_path.relative_to(self.skills_dist_dir))
- info = zipfile.ZipInfo(arcname, date_time=_ZIP_FIXED_TIME)
- zf.writestr(info, file_path.read_text())
- return zip_path
-
- def _collect_lint_files(self, skill: DiscoveredSkill) -> list[Path]:
- """Collect all files for linting from a skill using the allowlist.
-
- Only collects SKILL.md(.j2), references/, and scripts/.
- """
- if skill.depth == 0:
- return [skill.source_file]
-
- skill_dir = skill.source_file.parent
- result: list[Path] = [skill.source_file]
- for subdir_name in sorted(_ALLOWED_SUBDIRS):
- subdir = skill_dir / subdir_name
- if not subdir.is_dir():
- continue
- for root, dirs, filenames in os.walk(subdir):
- dirs[:] = sorted(dirs)
- for filename in sorted(filenames):
- result.append(Path(root) / filename)
- return result
-
- def lint_all(self) -> bool:
- """Validate skill sources without rendering (no Django needed).
-
- Checks:
- - Binary file detection (only text files allowed)
- - Duplicate skill name detection (across products)
- - Jinja2 syntax validation via parse-only (all .j2 files)
- - Frontmatter validation for product and project skill entry points
- - Tool/skill reference validation in markdown (against the MCP schema registries)
-
- Returns True if all checks pass, False otherwise.
- """
- skills = self.discoverer.discover()
- errors: list[str] = []
- reference_findings: list[ReferenceFinding] = []
-
- seen: dict[str, DiscoveredSkill] = {}
- for skill in skills:
- if skill.name in seen:
- first = seen[skill.name]
- errors.append(
- f"Duplicate skill name '{skill.name}': "
- f"{first.source_file.relative_to(self.repo_root)} and "
- f"{skill.source_file.relative_to(self.repo_root)}"
- )
- 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)
- skill_names = set(seen)
- agents_skills_dir = self.repo_root / ".agents" / "skills"
- project_skill_files: list[Path] = []
- if agents_skills_dir.is_dir():
- for entry in sorted(agents_skills_dir.iterdir()):
- if entry.is_dir():
- skill_names.add(entry.name)
- skill_file = entry / "SKILL.md"
- if skill_file.is_file():
- project_skill_files.append(skill_file)
-
- for skill_file in project_skill_files:
- source_label = str(skill_file.relative_to(self.repo_root))
- try:
- validate_frontmatter(skill_file.read_text(), source_label)
- except ValueError as e:
- errors.append(str(e))
-
- jinja_env = _create_jinja_env()
-
- for skill in skills:
- lint_files = self._collect_lint_files(skill)
-
- if skill.depth == 1:
- errors.extend(_check_reference_links(skill.source_file, self.repo_root))
-
- for file_path in lint_files:
- source_label = str(file_path.relative_to(self.repo_root))
-
- try:
- _assert_text_file(file_path)
- except ValueError as e:
- errors.append(str(e))
- continue
-
- if file_path.suffix == ".j2":
- raw = file_path.read_text()
- try:
- jinja_env.parse(raw)
- except TemplateSyntaxError as e:
- errors.append(f"Jinja2 syntax error in {source_label}: {e}")
-
- if tool_names is not None and (file_path.name.endswith(".md") or file_path.name.endswith(".md.j2")):
- reference_findings.extend(
- _check_tool_references(file_path.read_text(), source_label, tool_names, skill_names)
- )
-
- if skill.source_file.suffix != ".j2":
- raw = skill.source_file.read_text()
- source_label = str(skill.source_file.relative_to(self.repo_root))
- try:
- validate_frontmatter(raw, source_label)
- except ValueError as e:
- errors.append(str(e))
-
- # Tool/skill reference findings are advisory: they are surfaced (as CI annotations on the
- # offending line, or plain warnings locally) but never fail the lint, because the check is a
- # heuristic that can misfire on prose.
- _emit_reference_findings(reference_findings)
-
- if errors:
- for err in errors:
- print(f"ERROR: {err}", file=sys.stderr)
- return False
-
- print(f"OK: {len(skills)} product skill(s) and {len(project_skill_files)} project skill(s) passed lint checks.")
- return True
-
- def init_skill(self, product_name: str, skill_name: str, *, template: bool = False) -> Path:
- """Scaffold a new skill directory with SKILL.md boilerplate.
-
- Creates products/{product}/skills/{skill-name}/ with a SKILL.md (or .md.j2)
- stub and a references/ subdirectory.
-
- Returns the path to the created skill file.
- """
- product_dir = self.products_dir / product_name
- if not product_dir.is_dir():
- raise FileNotFoundError(f"Product directory does not exist: products/{product_name}")
-
- skill_dir = product_dir / "skills" / skill_name
- if skill_dir.exists():
- raise FileExistsError(f"Skill directory already exists: {skill_dir.relative_to(self.repo_root)}")
-
- skill_dir.mkdir(parents=True)
- (skill_dir / "references").mkdir()
-
- display_name = skill_name.replace("-", " ").capitalize()
- filename = "SKILL.md.j2" if template else "SKILL.md"
- content = textwrap.dedent(f"""\
- ---
- name: {skill_name}
- description: TODO
- ---
-
- # {display_name}
-
- TODO: Describe when and how to use this skill.
- """)
-
- skill_file = skill_dir / filename
- skill_file.write_text(content)
- return skill_file
-
- # ------------------------------------------------------------------
- # Sync / unsync: copy built skills to .agents/skills/ for local testing
- # ------------------------------------------------------------------
-
- _SYNCED_SKILLS_MARKER = "# Synced product skills (managed by hogli sync:skill)"
-
- def sync_skill(self, skill_name: str) -> Path:
- """Build a skill and copy it to .agents/skills/ for local Claude Code testing.
-
- Returns the path to the synced skill directory.
- """
- skills = self.discoverer.discover()
- match = next((s for s in skills if s.name == skill_name), None)
- if match is None:
- available = ", ".join(s.name for s in skills)
- raise ValueError(f"Skill '{skill_name}' not found. Available: {available}")
-
- manifest = self.build_all()
-
- # Find the built resource — build order matches discovery order
- resource = next((r for s, r in zip(skills, manifest.resources) if s.name == skill_name), None)
- if resource is None:
- raise ValueError(f"Skill '{skill_name}' was discovered but not built")
-
- agents_skills_dir = self.repo_root / ".agents" / "skills"
- target_dir = agents_skills_dir / resource.name
-
- if target_dir.exists():
- shutil.rmtree(target_dir)
-
- source_dir = self.skills_dist_dir / resource.name
- shutil.copytree(source_dir, target_dir)
-
- self._ensure_gitignored(resource.name)
- return target_dir
-
- def unsync_skill(self, skill_name: str) -> None:
- """Remove a previously synced skill from .agents/skills/."""
- agents_skills_dir = self.repo_root / ".agents" / "skills"
-
- # Try the name directly, and also resolve via discovery for frontmatter name
- names_to_try = [skill_name]
- skills = self.discoverer.discover()
- match = next((s for s in skills if s.name == skill_name), None)
- if match is not None and match.source_file.suffix != ".j2":
- try:
- metadata, _ = parse_frontmatter(match.source_file.read_text())
- fm_name = metadata.get("name", skill_name)
- if fm_name != skill_name and fm_name not in names_to_try:
- names_to_try.append(fm_name)
- except Exception:
- pass
-
- for name in names_to_try:
- target_dir = agents_skills_dir / name
- if target_dir.exists():
- shutil.rmtree(target_dir)
- self._remove_gitignore_entry(name)
- print(f"Removed synced skill: .agents/skills/{name}")
- return
-
- print(f"No synced skill found for '{skill_name}'", file=sys.stderr)
- sys.exit(1)
-
- def _ensure_gitignored(self, skill_name: str) -> None:
- """Add skill to .agents/skills/.gitignore if not already present."""
- gitignore_path = self.repo_root / ".agents" / "skills" / ".gitignore"
- entry = f"/{skill_name}"
-
- if gitignore_path.exists():
- content = gitignore_path.read_text()
- if entry in content.splitlines():
- return
- else:
- content = ""
-
- if not content:
- content = f"{self._SYNCED_SKILLS_MARKER}\n"
-
- if not content.endswith("\n"):
- content += "\n"
-
- content += f"{entry}\n"
- gitignore_path.write_text(content)
-
- def _remove_gitignore_entry(self, skill_name: str) -> None:
- """Remove skill from .agents/skills/.gitignore."""
- gitignore_path = self.repo_root / ".agents" / "skills" / ".gitignore"
- if not gitignore_path.exists():
- return
- entry = f"/{skill_name}"
- lines = gitignore_path.read_text().splitlines()
- lines = [line for line in lines if line != entry]
- remaining = [line for line in lines if line.strip() and not line.startswith("#")]
- if not remaining:
- gitignore_path.unlink()
- else:
- gitignore_path.write_text("\n".join(lines) + "\n")
-
- def list_skills(self) -> None:
- """List all discovered product skills."""
- skills = self.discoverer.discover()
-
- if not skills:
- print("No product skills found in products/*/skills/.")
- return
-
- print(f"Found {len(skills)} product skill(s):\n")
- for skill in skills:
- product = skill.product_dir.name
- is_template = skill.source_file.suffix == ".j2"
- kind = "template" if is_template else "static"
- depth_label = f"depth={skill.depth}"
- print(f" {skill.name:<40} product={product:<20} ({kind}, {depth_label})")
-
-
-def _setup_django() -> None:
- """Set up Django (needed for importing product models during build/check).
-
- Sets dummy values for infrastructure env vars (Redis, etc.) that the settings
- module requires at import time. The build script never connects to these services
- — it only needs the Django ORM metadata and model imports to work.
- """
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
- # A build must not depend on reaching the flags endpoint. Rendering a HogQL example walks
- # `Database.create_for`, which asks posthoganalytics whether a flag is on; that call has no
- # timeout, so on a machine without egress the build sits in connect() forever with no output
- # and no error. Opting out makes `feature_enabled` answer locally instead.
- os.environ.setdefault("OPT_OUT_CAPTURE", "1")
- try:
- import django
-
- django.setup()
- except SystemExit as e:
- print(
- f"ERROR: Django setup called sys.exit({e.code}). "
- "This usually means a required setting (e.g. SECRET_KEY) is missing. "
- "Skill building requires a working Django environment because Jinja2 "
- "templates import Pydantic models from product code.\n"
- "Hint: set SECRET_KEY in your environment or .env file.",
- file=sys.stderr,
- )
- raise SystemExit(1) from e
- except Exception as e:
- print(
- f"WARNING: Django setup failed ({e}). Template functions that import models will not work.",
- file=sys.stderr,
- )
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(
- description=textwrap.dedent(__doc__),
- formatter_class=argparse.RawDescriptionHelpFormatter,
- )
- parser.add_argument(
- "--list",
- action="store_true",
- help="List discovered product skills without building",
- )
- parser.add_argument(
- "--lint",
- action="store_true",
- help="Validate skill sources without rendering (no Django needed)",
- )
- parser.add_argument(
- "--init",
- action="store_true",
- help="Scaffold a new skill directory with SKILL.md boilerplate",
- )
- parser.add_argument(
- "--product",
- help="Product name for --init (e.g. feature_flags)",
- )
- parser.add_argument(
- "--name",
- help="Skill name for --init (e.g. my-new-skill)",
- )
- parser.add_argument(
- "--j2",
- action="store_true",
- help="Create SKILL.md.j2 instead of SKILL.md (use with --init)",
- )
- parser.add_argument(
- "--sync",
- action="store_true",
- help="Build a skill and sync it to .agents/skills/ for local testing",
- )
- parser.add_argument(
- "--clean",
- action="store_true",
- help="Remove a previously synced skill from .agents/skills/ (use with --sync)",
- )
- args = parser.parse_args()
-
- products_dir = REPO_ROOT / "products"
- output_dir = REPO_ROOT / "products" / "posthog_ai"
- builder = SkillBuilder(REPO_ROOT, products_dir, output_dir)
-
- if args.init:
- if not args.product or not args.name:
- parser.error("--init requires --product and --name")
- try:
- skill_file = builder.init_skill(args.product, args.name, template=args.j2)
- print(f"Created {skill_file.relative_to(REPO_ROOT)}")
- except (FileNotFoundError, FileExistsError) as e:
- print(f"ERROR: {e}", file=sys.stderr)
- sys.exit(1)
- return
-
- if args.lint:
- if not builder.lint_all():
- sys.exit(1)
- return
-
- if args.sync:
- if not args.name:
- builder.list_skills()
- print("\nUsage: hogli sync:skill -- --name <skill-name>")
- return
- if args.clean:
- builder.unsync_skill(args.name)
- return
- _setup_django()
- try:
- target = builder.sync_skill(args.name)
- print(f"Synced skill to {target.relative_to(REPO_ROOT)}")
- print(f" Available via .claude/skills/{target.name}/ for Claude Code")
- except ValueError as e:
- print(f"ERROR: {e}", file=sys.stderr)
- sys.exit(1)
- return
-
- if args.list:
- builder.list_skills()
- return
-
- _setup_django()
-
- manifest = builder.build_all()
- if not manifest.resources:
- print("No product skills found in products/*/skills/.")
- return
- zip_path = builder._zip_skills_dist()
- print(f"Built {len(manifest.resources)} skill(s) → {zip_path.relative_to(REPO_ROOT)}")
- for r in manifest.resources:
- print(f" {r.name:<40} source={r.source}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/products/posthog_ai/scripts/build_skills/__init__.py b/products/posthog_ai/scripts/build_skills/__init__.py
new file mode 100644
index 000000000000..be8a3e643711
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/__init__.py
@@ -0,0 +1,21 @@
+"""Build coding agent skills from products/*/skills/ into rendered files and a ZIP
+archive for distribution.
+
+Skills can be:
+- Plain markdown (SKILL.md) — copied as-is
+- Jinja2 templates (SKILL.md.j2) — rendered with Python context including Pydantic schema helpers
+
+Each skill must have YAML frontmatter with at least ``name`` and ``description`` fields.
+The build renders skills to dist/skills/{skill_name}/ (gitignored, human-readable)
+and optionally packages them into dist/skills.zip (published as a GitHub release by CI).
+
+Requires the project's Python environment (managed by uv) for template rendering
+that imports Pydantic models from product code.
+
+Usage:
+ hogli build:skills # Build all product skills to dist/skills/ and dist/skills.zip
+ hogli build:skills --list # List discovered skills without building
+ hogli lint:skills # Validate skill sources without rendering
+"""
+
+# One module per concern; import the module you need, never this package.
diff --git a/products/posthog_ai/scripts/build_skills/__main__.py b/products/posthog_ai/scripts/build_skills/__main__.py
new file mode 100644
index 000000000000..f2abf4a2bb92
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/__main__.py
@@ -0,0 +1,8 @@
+"""Entry point for ``python -m products.posthog_ai.scripts.build_skills``."""
+
+from __future__ import annotations
+
+from products.posthog_ai.scripts.build_skills.cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/products/posthog_ai/scripts/build_skills/cli.py b/products/posthog_ai/scripts/build_skills/cli.py
new file mode 100644
index 000000000000..2c3af5d6dcd3
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/cli.py
@@ -0,0 +1,160 @@
+# ruff: noqa: T201 allow print statements
+"""Command line entry point."""
+
+from __future__ import annotations
+
+import os
+import sys
+import argparse
+from pathlib import Path
+
+from . import (
+ __doc__ as PACKAGE_DOC,
+ skill_builder,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+sys.path.insert(0, str(REPO_ROOT))
+
+
+def _setup_django() -> None:
+ """Set up Django (needed for importing product models during build/check).
+
+ Sets dummy values for infrastructure env vars (Redis, etc.) that the settings
+ module requires at import time. The build script never connects to these services
+ — it only needs the Django ORM metadata and model imports to work.
+ """
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+ # A build must not depend on reaching the flags endpoint. Rendering a HogQL example walks
+ # `Database.create_for`, which asks posthoganalytics whether a flag is on; that call has no
+ # timeout, so on a machine without egress the build sits in connect() forever with no output
+ # and no error. Opting out makes `feature_enabled` answer locally instead.
+ os.environ.setdefault("OPT_OUT_CAPTURE", "1")
+ try:
+ import django
+
+ django.setup()
+ except SystemExit as e:
+ print(
+ f"ERROR: Django setup called sys.exit({e.code}). "
+ "This usually means a required setting (e.g. SECRET_KEY) is missing. "
+ "Skill building requires a working Django environment because Jinja2 "
+ "templates import Pydantic models from product code.\n"
+ "Hint: set SECRET_KEY in your environment or .env file.",
+ file=sys.stderr,
+ )
+ raise SystemExit(1) from e
+ except Exception as e:
+ print(
+ f"WARNING: Django setup failed ({e}). Template functions that import models will not work.",
+ file=sys.stderr,
+ )
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="python -m products.posthog_ai.scripts.build_skills",
+ description=PACKAGE_DOC or "",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument(
+ "--list",
+ action="store_true",
+ help="List discovered product skills without building",
+ )
+ parser.add_argument(
+ "--lint",
+ action="store_true",
+ help="Validate skill sources without rendering (no Django needed)",
+ )
+ parser.add_argument(
+ "--init",
+ action="store_true",
+ help="Scaffold a new skill directory with SKILL.md boilerplate",
+ )
+ parser.add_argument(
+ "--product",
+ help="Product name for --init (e.g. feature_flags)",
+ )
+ parser.add_argument(
+ "--name",
+ help="Skill name for --init (e.g. my-new-skill)",
+ )
+ parser.add_argument(
+ "--j2",
+ action="store_true",
+ help="Create SKILL.md.j2 instead of SKILL.md (use with --init)",
+ )
+ parser.add_argument(
+ "--sync",
+ action="store_true",
+ help="Build a skill and sync it to .agents/skills/ for local testing",
+ )
+ parser.add_argument(
+ "--clean",
+ action="store_true",
+ help="Remove a previously synced skill from .agents/skills/ (use with --sync)",
+ )
+ return parser
+
+
+def _run_init(builder: skill_builder.SkillBuilder, args: argparse.Namespace, parser: argparse.ArgumentParser) -> None:
+ if not args.product or not args.name:
+ parser.error("--init requires --product and --name")
+ try:
+ skill_file = builder.init_skill(args.product, args.name, template=args.j2)
+ print(f"Created {skill_file.relative_to(REPO_ROOT)}")
+ except (FileNotFoundError, FileExistsError) as e:
+ print(f"ERROR: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+def _run_sync(builder: skill_builder.SkillBuilder, args: argparse.Namespace) -> None:
+ if not args.name:
+ builder.list_skills()
+ print("\nUsage: hogli sync:skill -- --name <skill-name>")
+ return
+ if args.clean:
+ builder.unsync_skill(args.name)
+ return
+ _setup_django()
+ try:
+ target = builder.sync_skill(args.name)
+ print(f"Synced skill to {target.relative_to(REPO_ROOT)}")
+ print(f" Available via .claude/skills/{target.name}/ for Claude Code")
+ except ValueError as e:
+ print(f"ERROR: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+def _run_build(builder: skill_builder.SkillBuilder) -> None:
+ _setup_django()
+ manifest = builder.build_all()
+ if not manifest.resources:
+ print("No product skills found in products/*/skills/.")
+ return
+ zip_path = builder._zip_skills_dist()
+ print(f"Built {len(manifest.resources)} skill(s) → {zip_path.relative_to(REPO_ROOT)}")
+ for r in manifest.resources:
+ print(f" {r.name:<40} source={r.source}")
+
+
+def main() -> None:
+ parser = _build_parser()
+ args = parser.parse_args()
+
+ products_dir = REPO_ROOT / "products"
+ output_dir = REPO_ROOT / "products" / "posthog_ai"
+ builder = skill_builder.SkillBuilder(REPO_ROOT, products_dir, output_dir)
+
+ if args.init:
+ _run_init(builder, args, parser)
+ elif args.lint:
+ if not builder.lint_all():
+ sys.exit(1)
+ elif args.sync:
+ _run_sync(builder, args)
+ elif args.list:
+ builder.list_skills()
+ else:
+ _run_build(builder)
diff --git a/products/posthog_ai/scripts/build_skills/discovery.py b/products/posthog_ai/scripts/build_skills/discovery.py
new file mode 100644
index 000000000000..c02ea65f5416
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/discovery.py
@@ -0,0 +1,87 @@
+"""Finding skill sources under products/*/skills/."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import yaml
+
+from . import frontmatter, skill_manifest
+
+
+def _unrendered_skill_name(skill: skill_manifest.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, _ = frontmatter.parse_frontmatter(skill.source_file.read_text())
+ except (OSError, yaml.YAMLError):
+ return skill.name
+ return metadata.get("name") or skill.name
+
+
+def _directory_skill(entry: Path, product_dir: Path) -> skill_manifest.DiscoveredSkill | None:
+ """A depth-1 skill: a directory holding SKILL.md.j2 (preferred) or SKILL.md."""
+ for filename in ("SKILL.md.j2", "SKILL.md"):
+ source_file = entry / filename
+ if source_file.exists():
+ return skill_manifest.DiscoveredSkill(
+ name=entry.name, source_file=source_file, product_dir=product_dir, depth=1
+ )
+ return None
+
+
+def _loose_file_skill(entry: Path, product_dir: Path) -> skill_manifest.DiscoveredSkill | None:
+ """A depth-0 skill: a loose my-skill.md(.j2) directly in skills/."""
+ # Convention docs that can live alongside skills — not skills themselves.
+ if entry.name in ("README.md", "AGENTS.md", "CLAUDE.md") or not entry.name.endswith((".md", ".md.j2")):
+ return None
+ if entry.name.endswith(".md") and (entry.parent / (entry.name + ".j2")).exists():
+ return None
+ skill_name = entry.name.removesuffix(".j2").removesuffix(".md")
+ return skill_manifest.DiscoveredSkill(name=skill_name, source_file=entry, product_dir=product_dir, depth=0)
+
+
+class SkillDiscoverer:
+ """Discovers skill source files from products/*/skills/."""
+
+ def __init__(self, products_dir: Path) -> None:
+ self.products_dir = products_dir
+
+ def discover(self) -> list[skill_manifest.DiscoveredSkill]:
+ """Discover skill sources from products/*/skills/.
+
+ Supports two depth levels relative to products/*/skills/:
+ - Depth 0: Loose files directly in skills/ (e.g., my-skill.md or my-skill.md.j2).
+ Skill name = filename stem (without .md or .md.j2 extension).
+ - Depth 1: Directories containing SKILL.md(.j2) (e.g., my-skill/SKILL.md).
+ Skill name = directory name.
+
+ For both depths, .j2 files take priority over plain .md when both exist.
+ """
+ skills: list[skill_manifest.DiscoveredSkill] = []
+ if not self.products_dir.exists():
+ return skills
+
+ for product_dir in sorted(self.products_dir.iterdir()):
+ skills_dir = product_dir / "skills"
+ if not product_dir.is_dir() or not skills_dir.exists():
+ continue
+ for entry in sorted(skills_dir.iterdir()):
+ if entry.is_dir():
+ skill = _directory_skill(entry, product_dir)
+ elif entry.is_file():
+ skill = _loose_file_skill(entry, product_dir)
+ else:
+ continue
+ if skill is not None:
+ skills.append(skill)
+
+ return skills
diff --git a/products/posthog_ai/scripts/build_skills/frontmatter.py b/products/posthog_ai/scripts/build_skills/frontmatter.py
new file mode 100644
index 000000000000..cdec2cfa2035
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/frontmatter.py
@@ -0,0 +1,57 @@
+"""Parsing and validating the YAML frontmatter of a skill entry point."""
+
+from __future__ import annotations
+
+import re
+
+import yaml
+from pydantic import BaseModel, Field, ValidationError
+
+_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
+
+_MAX_SKILL_DESCRIPTION_LENGTH = 1024
+
+
+class SkillFrontmatter(BaseModel):
+ name: str
+ description: str = Field(max_length=_MAX_SKILL_DESCRIPTION_LENGTH)
+
+
+def validate_frontmatter(text: str, source_label: str = "<unknown>") -> SkillFrontmatter:
+ """Parse and validate frontmatter from rendered skill text.
+
+ Raises ``ValueError`` if frontmatter is missing or invalid.
+ """
+ match = _FRONTMATTER_RE.match(text)
+ if not match:
+ raise ValueError(f"Missing YAML frontmatter in {source_label}")
+ raw_yaml = match.group(1)
+ try:
+ parsed = yaml.safe_load(raw_yaml)
+ except yaml.YAMLError as e:
+ raise ValueError(f"Invalid YAML frontmatter in {source_label}: {e}") from e
+ if not isinstance(parsed, dict):
+ raise ValueError(f"Frontmatter must be a YAML mapping in {source_label}")
+ try:
+ return SkillFrontmatter.model_validate(parsed)
+ except ValidationError as e:
+ raise ValueError(f"Invalid frontmatter in {source_label}: {e}") from e
+
+
+def parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
+ """Extract YAML frontmatter and body from a skill file.
+
+ Returns (metadata_dict, body_without_frontmatter).
+ """
+ match = _FRONTMATTER_RE.match(text)
+ if not match:
+ return {}, text
+
+ raw_yaml = match.group(1)
+ body = text[match.end() :]
+ parsed = yaml.safe_load(raw_yaml)
+ if not isinstance(parsed, dict):
+ return {}, text
+
+ metadata: dict[str, str] = {str(k): str(v) for k, v in parsed.items()}
+ return metadata, body
diff --git a/products/posthog_ai/scripts/build_skills/linting.py b/products/posthog_ai/scripts/build_skills/linting.py
new file mode 100644
index 000000000000..373f5ac4fb0c
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/linting.py
@@ -0,0 +1,156 @@
+# ruff: noqa: T201 allow print statements
+"""Validating skill sources without rendering them."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from jinja2 import Environment, TemplateSyntaxError
+
+from . import (
+ discovery,
+ frontmatter,
+ reference_links,
+ rendering,
+ reserved_names,
+ skill_manifest,
+ source_files,
+ tool_references,
+)
+
+
+class SkillLinter:
+ """Validates skill sources without rendering (no Django needed).
+
+ Checks:
+ - Binary file detection (only text files allowed)
+ - Duplicate skill name detection (across products)
+ - Jinja2 syntax validation via parse-only (all .j2 files)
+ - Frontmatter validation for product and project skill entry points
+ - Tool/skill reference validation in markdown (against the MCP schema registries)
+ """
+
+ def __init__(self, repo_root: Path, skills: list[skill_manifest.DiscoveredSkill]) -> None:
+ self.repo_root = repo_root
+ self.skills = skills
+ self.errors: list[str] = []
+ self.findings: list[tool_references.ReferenceFinding] = []
+ self.skill_names: set[str] = set()
+ self.project_skill_files: list[Path] = []
+
+ def run(self) -> bool:
+ """Run every check and report. Returns True if all checks pass."""
+ self._check_names()
+ tool_names = tool_references._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)
+ self._collect_project_skills()
+ self._check_project_skill_frontmatter()
+
+ jinja_env = rendering._create_jinja_env()
+ for skill in self.skills:
+ self._check_skill(skill, jinja_env, tool_names)
+
+ # Tool/skill reference findings are advisory: they are surfaced (as CI annotations on the
+ # offending line, or plain warnings locally) but never fail the lint, because the check is a
+ # heuristic that can misfire on prose.
+ tool_references._emit_reference_findings(self.findings)
+ return self._report()
+
+ def _label(self, path: Path) -> str:
+ return str(path.relative_to(self.repo_root))
+
+ def _check_names(self) -> None:
+ """Flag duplicate skill names and names context-mill owns."""
+ seen: dict[str, skill_manifest.DiscoveredSkill] = {}
+ for skill in self.skills:
+ if skill.name in seen:
+ self.errors.append(
+ f"Duplicate skill name '{skill.name}': "
+ f"{self._label(seen[skill.name].source_file)} and {self._label(skill.source_file)}"
+ )
+ else:
+ seen[skill.name] = skill
+
+ unrendered_name = discovery._unrendered_skill_name(skill)
+ if unrendered_name in reserved_names.OMNIBUS_SKILL_NAMES:
+ self.errors.append(
+ reserved_names.reserved_name_message(unrendered_name, self._label(skill.source_file))
+ )
+ self.skill_names = set(seen)
+
+ def _collect_project_skills(self) -> None:
+ """Record the .agents/skills/ names and entry points alongside the product skills."""
+ agents_skills_dir = self.repo_root / ".agents" / "skills"
+ if not agents_skills_dir.is_dir():
+ return
+ for entry in sorted(agents_skills_dir.iterdir()):
+ if not entry.is_dir():
+ continue
+ self.skill_names.add(entry.name)
+ skill_file = entry / "SKILL.md"
+ if skill_file.is_file():
+ self.project_skill_files.append(skill_file)
+
+ def _check_project_skill_frontmatter(self) -> None:
+ for skill_file in self.project_skill_files:
+ try:
+ frontmatter.validate_frontmatter(skill_file.read_text(), self._label(skill_file))
+ except ValueError as e:
+ self.errors.append(str(e))
+
+ def _check_skill(
+ self, skill: skill_manifest.DiscoveredSkill, jinja_env: Environment, tool_names: set[str] | None
+ ) -> None:
+ if skill.depth == 1:
+ self.errors.extend(reference_links._check_reference_links(skill.source_file, self.repo_root))
+
+ for file_path in _lint_files(skill):
+ self._check_file(file_path, jinja_env, tool_names)
+
+ if skill.source_file.suffix != ".j2":
+ try:
+ frontmatter.validate_frontmatter(skill.source_file.read_text(), self._label(skill.source_file))
+ except ValueError as e:
+ self.errors.append(str(e))
+
+ def _check_file(self, file_path: Path, jinja_env: Environment, tool_names: set[str] | None) -> None:
+ source_label = self._label(file_path)
+ try:
+ source_files._assert_text_file(file_path)
+ except ValueError as e:
+ self.errors.append(str(e))
+ return
+
+ if file_path.suffix == ".j2":
+ try:
+ jinja_env.parse(file_path.read_text())
+ except TemplateSyntaxError as e:
+ self.errors.append(f"Jinja2 syntax error in {source_label}: {e}")
+
+ if tool_names is not None and file_path.name.endswith((".md", ".md.j2")):
+ self.findings.extend(
+ tool_references._check_tool_references(
+ file_path.read_text(), source_label, tool_names, self.skill_names
+ )
+ )
+
+ def _report(self) -> bool:
+ if self.errors:
+ for err in self.errors:
+ print(f"ERROR: {err}", file=sys.stderr)
+ return False
+ print(
+ f"OK: {len(self.skills)} product skill(s) and "
+ f"{len(self.project_skill_files)} project skill(s) passed lint checks."
+ )
+ return True
+
+
+def _lint_files(skill: skill_manifest.DiscoveredSkill) -> list[Path]:
+ """Collect the files to lint for a skill: SKILL.md(.j2), references/ and scripts/."""
+ if skill.depth == 0:
+ return [skill.source_file]
+
+ return [skill.source_file, *source_files._bundle_files(skill.source_file.parent)]
diff --git a/products/posthog_ai/scripts/build_skills/reference_links.py b/products/posthog_ai/scripts/build_skills/reference_links.py
new file mode 100644
index 000000000000..c88750276a4f
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/reference_links.py
@@ -0,0 +1,69 @@
+"""Lint for markdown links that will not resolve in the built bundle."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from . import source_files
+
+_MARKDOWN_LINK_RE = re.compile(r"\]\(([^)\s]+)\)")
+
+
+def _bundled_paths(skill_dir: Path) -> set[str]:
+ """The references/ and scripts/ paths a skill ships, as they appear in the built bundle."""
+ # The build strips .j2 when it renders a template, so record the shipped path.
+ return {
+ str(file_path.relative_to(skill_dir)).removesuffix(".j2") for file_path in source_files._bundle_files(skill_dir)
+ }
+
+
+def _bundled_link_target(target: str, skill_dir: Path) -> str | None:
+ """The bundle-relative path a markdown link points at, or None if the bundle does not carry it."""
+ if not target or "://" in target or target.startswith("mailto:"):
+ return None
+ resolved = (skill_dir / target).resolve()
+ try:
+ rel_to_skill = resolved.relative_to(skill_dir.resolve())
+ except ValueError:
+ return None # Link points outside the skill; not part of the bundle.
+ if not rel_to_skill.parts or rel_to_skill.parts[0] not in source_files._ALLOWED_SUBDIRS:
+ return None # Only references/ and scripts/ files ship in the bundle.
+ if resolved.is_dir():
+ return None # A directory ships through its files.
+ return str(rel_to_skill)
+
+
+def _check_reference_links(entry: Path, repo_root: Path) -> list[str]:
+ """Find markdown links to references/ or scripts/ files that will not exist in the built bundle.
+
+ A skill ships its SKILL.md, references/, and scripts/ files, and the build strips the .j2 suffix
+ from every rendered template. So a link to `references/x.md` resolves when the source holds either
+ `references/x.md` or `references/x.md.j2`, but a link to `references/x.md.j2` never resolves,
+ because the bundle only has the stripped `references/x.md`.
+ """
+ skill_dir = entry.parent
+ bundle = _bundled_paths(skill_dir)
+
+ # Only the SKILL.md entry point is scanned. Reference files link to each other with paths
+ # relative to the skill root, which do not resolve from inside references/, and their code
+ # snippets hold `](...)` fragments that are not links.
+ errors: list[str] = []
+ text = entry.read_text()
+ source_label = str(entry.relative_to(repo_root))
+ for match in _MARKDOWN_LINK_RE.finditer(text):
+ target = match.group(1).split("#", 1)[0].split("?", 1)[0]
+ rel_to_skill = _bundled_link_target(target, skill_dir)
+ if rel_to_skill is None or rel_to_skill in bundle:
+ continue
+ position = source_files._line_col(text, match.start(1))
+ hint = (
+ "Link to the built '.md' path, not the '.md.j2' template."
+ if target.endswith(".j2")
+ else "No file of that name ships in the skill."
+ )
+ errors.append(
+ f"Broken reference link in {source_label}:{position.line}: "
+ f"'{target}' does not resolve to a bundled file. {hint}"
+ )
+ return errors
diff --git a/products/posthog_ai/scripts/build_skills/rendering.py b/products/posthog_ai/scripts/build_skills/rendering.py
new file mode 100644
index 000000000000..b0d046c9a610
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/rendering.py
@@ -0,0 +1,48 @@
+"""Rendering a skill source file through Jinja2."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from jinja2 import Environment, StrictUndefined
+
+
+def _create_jinja_env(**extra_globals: object) -> Environment:
+ """Create a Jinja2 Environment with the standard skill rendering settings."""
+ env = Environment(
+ # nosemgrep: python.jinja2.security.audit.autoescape-disabled-false.incorrect-autoescape-disabled -- output is Markdown for a JSON manifest, not HTML
+ autoescape=False,
+ undefined=StrictUndefined,
+ keep_trailing_newline=True,
+ lstrip_blocks=True,
+ trim_blocks=True,
+ )
+ env.globals.update(extra_globals)
+ return env
+
+
+class SkillRenderer:
+ """Renders skill source files to final markdown via Jinja2."""
+
+ def __init__(self) -> None:
+ from products.posthog_ai.scripts.audit_constants import audit_constants
+ from products.posthog_ai.scripts.hogql_example import render_hogql_example
+ from products.posthog_ai.scripts.hogql_functions import hogql_functions
+ from products.posthog_ai.scripts.pydantic_schema import pydantic_schema
+ from products.posthog_ai.scripts.schema_columns import schema_columns
+
+ self.env = _create_jinja_env(
+ pydantic_schema=pydantic_schema,
+ render_hogql_example=render_hogql_example,
+ hogql_functions=hogql_functions,
+ audit_constants=audit_constants,
+ schema_columns=schema_columns,
+ )
+
+ def render(self, source_file: Path) -> str:
+ """Render a skill source file to its final markdown content."""
+ raw = source_file.read_text()
+ if source_file.suffix == ".j2":
+ template = self.env.from_string(raw)
+ return template.render()
+ return raw
diff --git a/products/posthog_ai/scripts/build_skills/reserved_names.py b/products/posthog_ai/scripts/build_skills/reserved_names.py
new file mode 100644
index 000000000000..8c3ec219254c
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/reserved_names.py
@@ -0,0 +1,28 @@
+"""Skill names this repo must not ship, because context-mill owns them."""
+
+from __future__ import annotations
+
+# 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",
+ "instrument-metrics",
+ }
+)
+
+
+def reserved_name_message(name: str, source: str) -> str:
+ """The error text for a skill that reuses a context-mill name."""
+ return (
+ f"'{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."
+ )
diff --git a/products/posthog_ai/scripts/build_skills/skill_builder.py b/products/posthog_ai/scripts/build_skills/skill_builder.py
new file mode 100644
index 000000000000..dc82069f40a3
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/skill_builder.py
@@ -0,0 +1,295 @@
+# ruff: noqa: T201 allow print statements
+"""Building, packing, scaffolding and syncing skills."""
+
+from __future__ import annotations
+
+import sys
+import shutil
+import zipfile
+import textwrap
+from pathlib import Path
+
+from . import discovery, frontmatter, linting, rendering, reserved_names, skill_manifest, source_files
+
+_ZIP_FIXED_TIME = (2025, 1, 1, 0, 0, 0)
+
+
+class SkillBuilder:
+ """Orchestrates skill discovery, rendering, and manifest generation."""
+
+ def __init__(self, repo_root: Path, products_dir: Path, output_dir: Path) -> None:
+ self.repo_root = repo_root
+ self.products_dir = products_dir
+ self.output_dir = output_dir
+ self.dist_dir = output_dir / "dist"
+ self.skills_dist_dir = self.dist_dir / "skills"
+ self.discoverer = discovery.SkillDiscoverer(products_dir)
+
+ def collect_skill_files(self, skill_dir: Path, renderer: rendering.SkillRenderer) -> list[skill_manifest.SkillFile]:
+ """Collect and render files from a skill directory using an explicit allowlist.
+
+ Only collects from three sources:
+ 1. Entry point: SKILL.md.j2 (preferred) or SKILL.md
+ 2. references/ directory (recursive)
+ 3. scripts/ directory (recursive)
+
+ .j2 files are rendered through Jinja2 and have the .j2 extension stripped.
+ Returns a list of SkillFile with SKILL.md always first.
+ """
+ j2_entry = skill_dir / "SKILL.md.j2"
+ md_entry = skill_dir / "SKILL.md"
+ if j2_entry.exists():
+ entry_path = j2_entry
+ elif md_entry.exists():
+ entry_path = md_entry
+ else:
+ raise ValueError(f"Missing SKILL.md entry point in {skill_dir.name}")
+
+ source_files._assert_text_file(entry_path)
+ entry_content = renderer.render(entry_path)
+ entry_point = skill_manifest.SkillFile(path="SKILL.md", content=entry_content)
+
+ files: list[skill_manifest.SkillFile] = []
+ for file_path in source_files._bundle_files(skill_dir):
+ source_files._assert_text_file(file_path)
+ content = renderer.render(file_path)
+ rel_path = str(file_path.relative_to(skill_dir)).removesuffix(".j2")
+ files.append(skill_manifest.SkillFile(path=rel_path, content=content))
+
+ return [entry_point, *files]
+
+ def build_skill(
+ self, skill: skill_manifest.DiscoveredSkill, renderer: rendering.SkillRenderer
+ ) -> skill_manifest.SkillResource:
+ """Build a single skill and return a SkillResource."""
+ if skill.depth == 1:
+ skill_dir = skill.source_file.parent
+ skill_files = self.collect_skill_files(skill_dir, renderer)
+ rendered_entry_content = skill_files[0].content
+ metadata, _body = frontmatter.parse_frontmatter(rendered_entry_content)
+ source = str(skill_dir.relative_to(self.repo_root))
+ else:
+ rendered_entry_content = renderer.render(skill.source_file)
+ metadata, _body = frontmatter.parse_frontmatter(rendered_entry_content)
+ # Consumers read <skill>/SKILL.md, so a loose source file must ship under that
+ # name however it is called at the source.
+ skill_files = [skill_manifest.SkillFile(path="SKILL.md", content=rendered_entry_content.strip())]
+ source = str(skill.source_file.relative_to(self.repo_root))
+
+ if metadata:
+ validated_metadata = frontmatter.validate_frontmatter(rendered_entry_content, source)
+ display_name = validated_metadata.name
+ description = validated_metadata.description
+ else:
+ 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 reserved_names.OMNIBUS_SKILL_NAMES:
+ raise ValueError(reserved_names.reserved_name_message(display_name, source))
+
+ return skill_manifest.SkillResource(
+ name=display_name,
+ description=description,
+ files=skill_files,
+ source=source,
+ )
+
+ def build_manifest(
+ self, skills: list[skill_manifest.DiscoveredSkill], renderer: rendering.SkillRenderer
+ ) -> skill_manifest.SkillManifest:
+ """Build the full SkillManifest from discovered skills."""
+ resources = [self.build_skill(skill, renderer) for skill in skills]
+ return skill_manifest.SkillManifest(resources=resources)
+
+ def build_all(self, *, dry_run: bool = False) -> skill_manifest.SkillManifest:
+ """Build all product skills and write rendered files to skills_dist/."""
+ skills = self.discoverer.discover()
+ renderer = rendering.SkillRenderer()
+ manifest = self.build_manifest(skills, renderer)
+
+ if not dry_run and manifest.resources:
+ if self.skills_dist_dir.exists():
+ shutil.rmtree(self.skills_dist_dir)
+ for resource in manifest.resources:
+ for skill_file in resource.files:
+ file_path = self.skills_dist_dir / resource.name / skill_file.path
+ file_path.parent.mkdir(parents=True, exist_ok=True)
+ file_path.write_text(skill_file.content)
+
+ return manifest
+
+ def pack(self) -> Path:
+ """Build skills and package skills_dist/ into dist/skills.zip."""
+ self.build_all()
+ return self._zip_skills_dist()
+
+ def _zip_skills_dist(self) -> Path:
+ """Create dist/skills.zip from the dist/skills/ directory."""
+ zip_path = self.dist_dir / "skills.zip"
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
+ for file_path in sorted(self.skills_dist_dir.rglob("*")):
+ if file_path.is_file():
+ arcname = str(file_path.relative_to(self.skills_dist_dir))
+ info = zipfile.ZipInfo(arcname, date_time=_ZIP_FIXED_TIME)
+ # A bare ZipInfo carries ZIP_STORED, which wins over the archive's default.
+ info.compress_type = zipfile.ZIP_DEFLATED
+ zf.writestr(info, file_path.read_text())
+ return zip_path
+
+ def lint_all(self) -> bool:
+ """Validate skill sources without rendering (no Django needed)."""
+ return linting.SkillLinter(self.repo_root, self.discoverer.discover()).run()
+
+ def init_skill(self, product_name: str, skill_name: str, *, template: bool = False) -> Path:
+ """Scaffold a new skill directory with SKILL.md boilerplate.
+
+ Creates products/{product}/skills/{skill-name}/ with a SKILL.md (or .md.j2)
+ stub and a references/ subdirectory.
+
+ Returns the path to the created skill file.
+ """
+ product_dir = self.products_dir / product_name
+ if not product_dir.is_dir():
+ raise FileNotFoundError(f"Product directory does not exist: products/{product_name}")
+
+ skill_dir = product_dir / "skills" / skill_name
+ if skill_dir.exists():
+ raise FileExistsError(f"Skill directory already exists: {skill_dir.relative_to(self.repo_root)}")
+
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "references").mkdir()
+
+ display_name = skill_name.replace("-", " ").capitalize()
+ filename = "SKILL.md.j2" if template else "SKILL.md"
+ content = textwrap.dedent(f"""\
+ ---
+ name: {skill_name}
+ description: TODO
+ ---
+
+ # {display_name}
+
+ TODO: Describe when and how to use this skill.
+ """)
+
+ skill_file = skill_dir / filename
+ skill_file.write_text(content)
+ return skill_file
+
+ # ------------------------------------------------------------------
+ # Sync / unsync: copy built skills to .agents/skills/ for local testing
+ # ------------------------------------------------------------------
+
+ _SYNCED_SKILLS_MARKER = "# Synced product skills (managed by hogli sync:skill)"
+
+ def sync_skill(self, skill_name: str) -> Path:
+ """Build a skill and copy it to .agents/skills/ for local Claude Code testing.
+
+ Returns the path to the synced skill directory.
+ """
+ skills = self.discoverer.discover()
+ match = next((s for s in skills if s.name == skill_name), None)
+ if match is None:
+ available = ", ".join(s.name for s in skills)
+ raise ValueError(f"Skill '{skill_name}' not found. Available: {available}")
+
+ manifest = self.build_all()
+
+ # Find the built resource — build order matches discovery order
+ resource = next((r for s, r in zip(skills, manifest.resources) if s.name == skill_name), None)
+ if resource is None:
+ raise ValueError(f"Skill '{skill_name}' was discovered but not built")
+
+ agents_skills_dir = self.repo_root / ".agents" / "skills"
+ target_dir = agents_skills_dir / resource.name
+
+ if target_dir.exists():
+ shutil.rmtree(target_dir)
+
+ source_dir = self.skills_dist_dir / resource.name
+ shutil.copytree(source_dir, target_dir)
+
+ self._ensure_gitignored(resource.name)
+ return target_dir
+
+ def unsync_skill(self, skill_name: str) -> None:
+ """Remove a previously synced skill from .agents/skills/."""
+ agents_skills_dir = self.repo_root / ".agents" / "skills"
+
+ # Try the name directly, and also resolve via discovery for frontmatter name
+ names_to_try = [skill_name]
+ skills = self.discoverer.discover()
+ match = next((s for s in skills if s.name == skill_name), None)
+ if match is not None and match.source_file.suffix != ".j2":
+ try:
+ metadata, _ = frontmatter.parse_frontmatter(match.source_file.read_text())
+ fm_name = metadata.get("name", skill_name)
+ if fm_name != skill_name and fm_name not in names_to_try:
+ names_to_try.append(fm_name)
+ except Exception:
+ pass
+
+ for name in names_to_try:
+ target_dir = agents_skills_dir / name
+ if target_dir.exists():
+ shutil.rmtree(target_dir)
+ self._remove_gitignore_entry(name)
+ print(f"Removed synced skill: .agents/skills/{name}")
+ return
+
+ print(f"No synced skill found for '{skill_name}'", file=sys.stderr)
+ sys.exit(1)
+
+ def _ensure_gitignored(self, skill_name: str) -> None:
+ """Add skill to .agents/skills/.gitignore if not already present."""
+ gitignore_path = self.repo_root / ".agents" / "skills" / ".gitignore"
+ entry = f"/{skill_name}"
+
+ if gitignore_path.exists():
+ content = gitignore_path.read_text()
+ if entry in content.splitlines():
+ return
+ else:
+ content = ""
+
+ if not content:
+ content = f"{self._SYNCED_SKILLS_MARKER}\n"
+
+ if not content.endswith("\n"):
+ content += "\n"
+
+ content += f"{entry}\n"
+ gitignore_path.write_text(content)
+
+ def _remove_gitignore_entry(self, skill_name: str) -> None:
+ """Remove skill from .agents/skills/.gitignore."""
+ gitignore_path = self.repo_root / ".agents" / "skills" / ".gitignore"
+ if not gitignore_path.exists():
+ return
+ entry = f"/{skill_name}"
+ lines = gitignore_path.read_text().splitlines()
+ lines = [line for line in lines if line != entry]
+ remaining = [line for line in lines if line.strip() and not line.startswith("#")]
+ if not remaining:
+ gitignore_path.unlink()
+ else:
+ gitignore_path.write_text("\n".join(lines) + "\n")
+
+ def list_skills(self) -> None:
+ """List all discovered product skills."""
+ skills = self.discoverer.discover()
+
+ if not skills:
+ print("No product skills found in products/*/skills/.")
+ return
+
+ print(f"Found {len(skills)} product skill(s):\n")
+ for skill in skills:
+ product = skill.product_dir.name
+ is_template = skill.source_file.suffix == ".j2"
+ kind = "template" if is_template else "static"
+ depth_label = f"depth={skill.depth}"
+ print(f" {skill.name:<40} product={product:<20} ({kind}, {depth_label})")
diff --git a/products/posthog_ai/scripts/build_skills/skill_manifest.py b/products/posthog_ai/scripts/build_skills/skill_manifest.py
new file mode 100644
index 000000000000..df96e0c4364f
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/skill_manifest.py
@@ -0,0 +1,47 @@
+"""The manifest models that describe a built skill bundle."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from pydantic import BaseModel, Field, model_validator
+
+MANIFEST_VERSION = "1.0.0"
+
+
+class DiscoveredSkill(BaseModel):
+ name: str
+ source_file: Path
+ product_dir: Path
+ depth: int
+
+
+class SkillFile(BaseModel):
+ path: str
+ content: str
+
+
+class SkillResource(BaseModel):
+ name: str
+ description: str
+ files: list[SkillFile]
+ source: str
+
+
+class SkillManifest(BaseModel):
+ version: str = MANIFEST_VERSION
+ resources: list[SkillResource] = Field(default_factory=list)
+
+ @model_validator(mode="after")
+ def _reject_duplicate_names(self) -> SkillManifest:
+ """Every resource writes to ``dist/skills/<name>``, so two resources sharing a
+ name merge into one directory and the later entry point overwrites the earlier
+ one. The lint deduplicates the source names, which the rendered frontmatter name
+ can differ from, so the collision is only visible here.
+ """
+ seen: dict[str, str] = {}
+ for resource in self.resources:
+ if resource.name in seen:
+ raise ValueError(f"Duplicate skill name '{resource.name}': {seen[resource.name]} and {resource.source}")
+ seen[resource.name] = resource.source
+ return self
diff --git a/products/posthog_ai/scripts/build_skills/source_files.py b/products/posthog_ai/scripts/build_skills/source_files.py
new file mode 100644
index 000000000000..3377b381f644
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/source_files.py
@@ -0,0 +1,50 @@
+"""Reading skill source files: the text-file guard and offset-to-line mapping."""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Iterator
+from dataclasses import dataclass
+from pathlib import Path
+
+_BINARY_CHECK_SIZE = 8192
+
+_ALLOWED_SUBDIRS = {"references", "scripts"}
+
+
+@dataclass(frozen=True)
+class TextPosition:
+ line: int
+ col: int
+
+
+def _line_col(text: str, offset: int) -> TextPosition:
+ return TextPosition(
+ line=text.count("\n", 0, offset) + 1,
+ col=offset - text.rfind("\n", 0, offset),
+ )
+
+
+def _bundle_files(skill_dir: Path) -> Iterator[Path]:
+ """Every file under the skill's references/ and scripts/ directories.
+
+ Sorted at each level, so the built ZIP is reproducible.
+ """
+ for subdir_name in sorted(_ALLOWED_SUBDIRS):
+ subdir = skill_dir / subdir_name
+ if not subdir.is_dir():
+ continue
+ for root, dirs, filenames in os.walk(subdir):
+ dirs[:] = sorted(dirs)
+ for filename in sorted(filenames):
+ yield Path(root) / filename
+
+
+def _assert_text_file(file_path: Path) -> None:
+ """Raise ValueError if file appears to be binary (contains null bytes)."""
+ with open(file_path, "rb") as f:
+ chunk = f.read(_BINARY_CHECK_SIZE)
+ if b"\x00" in chunk:
+ raise ValueError(
+ f"Binary file not supported in skill directory: {file_path.name}. Only text-based files are allowed."
+ )
diff --git a/products/posthog_ai/scripts/build_skills/tool_references.py b/products/posthog_ai/scripts/build_skills/tool_references.py
new file mode 100644
index 000000000000..20931ab67aa2
--- /dev/null
+++ b/products/posthog_ai/scripts/build_skills/tool_references.py
@@ -0,0 +1,235 @@
+# ruff: noqa: T201 allow print statements
+"""Advisory lint for stale MCP tool and skill references in skill markdown."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+import json
+from collections.abc import Iterator
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal, cast
+
+from . import source_files
+
+# 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
+# sources by the schema drift check in ci-mcp.yml). Mirrors lint-tool-names.ts in services/mcp.
+_MCP_SCHEMA_FILES = (
+ "services/mcp/schema/tool-definitions.json",
+ "services/mcp/schema/generated-tool-definitions.json",
+)
+
+# The reference check is heuristic and advisory: a candidate is only treated as a (stale) reference
+# when it *resembles* a real name — within this many edits of a real tool/skill, or an exact
+# casing miss. Real renames/typos sit at distance 1-2 from the intended name; ordinary hyphenated
+# prose ("highest-error", "per-file") is far from every name. Backticks are not treated as intent
+# (prose uses them for emphasis and field names too), so prose that does not resemble a real name is
+# simply ignored — no name-level allowlist is needed for it. Findings are reported, never blocking.
+_NEAR_MISS_MAX_EDITS = 2
+
+# SDK / HogQL function names that legitimately appear as code in skills (e.g. `emit_signal(...)`,
+# `get_feature_flag(...)`). They are real identifiers, not stale references, but collide with a
+# tool-name suffix/near-miss, so they are held out of the reference check.
+_SDK_FUNCTION_NAMES = {
+ "feature_enabled",
+ "get_feature_flag",
+ "get_feature_flag_payload",
+ "get_feature_flag_result",
+ "get_all_flags",
+ "get_all_flags_and_payloads",
+ "apply_path_cleaning",
+ "emit_signal",
+}
+
+# "use the X tool", "load the `X` skill" — kebab or snake candidate followed by tool/skill.
+_PHRASE_REFERENCE_RE = re.compile(r"(?<![A-Za-z0-9_`-])`?([a-z0-9]+(?:[_-][a-z0-9]+)+)`?\s+(tools?|skills?)\b")
+
+# "via `X`", "use `X`" — kebab-only (snake here is usually a field/SDK name, not a tool).
+_INVOCATION_REFERENCE_RE = re.compile(
+ r"\b(?:via|use|using|call|calling)\s+(?:the\s+)?`([a-z0-9]+(?:-[a-z0-9]+)+)`(?!\s*(?:tools?|skills?)\b)"
+)
+
+# A noun right after the backticked name means it's not a tool reference ("via the `x` feature flag").
+_ENTITY_NOUN_RE = re.compile(r"\s+(?:feature|flag|event|property|properties|column|field|table|key|filter)s?\b")
+
+# Backticked call syntax, e.g. `read_data("experiments", id)` — tool invocations written as calls.
+# Deliberately skills-only (no equivalent in tool-references.ts): call-style references occur only
+# in skill prose. The near-miss gate keeps SDK/HogQL examples (e.g. `get_feature_flag(...)`) quiet,
+# since those names do not resemble any MCP tool.
+_CALL_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:[_-][a-z0-9]+)+)\(")
+
+# Backticked snake_case whose kebab form is a real tool — wrong casing.
+_SNAKE_CASE_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:_[a-z0-9]+)+)`")
+
+
+def _load_mcp_tool_names(repo_root: Path) -> set[str] | None:
+ """Load valid MCP tool names from the checked-in schema registries.
+
+ Returns None if no registry is available so the reference check can be skipped
+ (keeps the lint runnable in checkouts without the MCP service).
+ """
+ names: set[str] = set()
+ found = False
+ for rel_path in _MCP_SCHEMA_FILES:
+ schema_file = repo_root / rel_path
+ if not schema_file.is_file():
+ continue
+ found = True
+ names.update(json.loads(schema_file.read_text()).keys())
+ return names if found else None
+
+
+# The kinds produced by the phrase regex alternation `(tools?|skills?)`.
+ReferenceKind = Literal["tool", "tools", "skill", "skills"]
+
+
+@dataclass(frozen=True)
+class ReferenceFinding:
+ source_label: str
+ line: int
+ col: int
+ name: str
+ message: str
+
+
+def _is_valid_reference(name: str, kind: ReferenceKind, tool_names: set[str], skill_names: set[str]) -> bool:
+ if name in _SDK_FUNCTION_NAMES:
+ return True
+ registry = skill_names if kind in ("skill", "skills") else tool_names
+ if name in registry:
+ return True
+ # Shorthand suffix, e.g. "the partial-update tool" for external-data-schemas-partial-update.
+ if any(known.endswith(f"-{name}") for known in registry):
+ return True
+ # Plural family reference, e.g. "the feature-flag tools".
+ if kind in ("tools", "skills") and any(known.startswith(f"{name}-") for known in registry):
+ return True
+ return False
+
+
+def _edit_distance(a: str, b: str) -> int:
+ prev = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ cur = [i]
+ for j, cb in enumerate(b, 1):
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
+ prev = cur
+ return prev[-1]
+
+
+def _reference_suggestions(name: str, registry: set[str]) -> list[str]:
+ """Real names this candidate plausibly meant: exact/suffix matches, else near-misses by edit distance."""
+ kebab = name.replace("_", "-")
+ suffix = sorted(t for t in registry if t == kebab or t.endswith(f"-{kebab}"))
+ if suffix:
+ return suffix
+ near = sorted((_edit_distance(kebab, known), known) for known in registry)
+ return [known for distance, known in near if distance <= _NEAR_MISS_MAX_EDITS]
+
+
+def _did_you_mean(suggestions: list[str]) -> str:
+ return f" — did you mean {' or '.join(suggestions)}?" if suggestions else ""
+
+
+@dataclass(frozen=True)
+class _Candidate:
+ """A name a rule believes was meant as a tool or skill reference."""
+
+ offset: int
+ name: str
+ message: str
+
+
+def _candidate(offset: int, name: str, noun: str, registry: set[str]) -> Iterator[_Candidate]:
+ """One candidate, but only when the name resembles something in the registry."""
+ suggestions = _reference_suggestions(name, registry)
+ if suggestions:
+ yield _Candidate(offset, name, f"'{name}' looks like a {noun} but none exists{_did_you_mean(suggestions)}")
+
+
+def _phrase_candidates(text: str, tool_names: set[str], skill_names: set[str]) -> Iterator[_Candidate]:
+ """ "X tool/skill". Resemblance to a real name is the only signal we trust — backticks in prose
+ mean emphasis or a field name as often as a reference, so they are not treated as intent.
+ """
+ for m in _PHRASE_REFERENCE_RE.finditer(text):
+ name, kind = m.group(1), cast("ReferenceKind", m.group(2))
+ if _is_valid_reference(name, kind, tool_names, skill_names):
+ continue
+ registry = skill_names if kind in ("skill", "skills") else tool_names
+ yield from _candidate(m.start(1), name, kind.rstrip("s"), registry)
+
+
+def _invocation_candidates(text: str, tool_names: set[str], skill_names: set[str]) -> Iterator[_Candidate]:
+ """ "via `X`": one concrete thing, but not whether tool or skill — check tools (a family prefix
+ like `feature-flag` is not invocable) plus exact skill names.
+ """
+ for m in _INVOCATION_REFERENCE_RE.finditer(text):
+ if _ENTITY_NOUN_RE.match(text, m.end()):
+ continue
+ name = m.group(1)
+ if _is_valid_reference(name, "tool", tool_names, skill_names) or name in skill_names:
+ continue
+ yield from _candidate(m.start(1), name, "tool", tool_names)
+
+
+def _call_candidates(text: str, tool_names: set[str], skill_names: set[str]) -> Iterator[_Candidate]:
+ for m in _CALL_REFERENCE_RE.finditer(text):
+ name = m.group(1)
+ if _is_valid_reference(name, "tool", tool_names, skill_names):
+ continue
+ yield from _candidate(m.start(1), name, "tool", tool_names)
+
+
+def _casing_candidates(text: str, tool_names: set[str], _skill_names: set[str]) -> Iterator[_Candidate]:
+ for m in _SNAKE_CASE_REFERENCE_RE.finditer(text):
+ name = m.group(1)
+ kebab = name.replace("_", "-")
+ if name not in tool_names and kebab in tool_names:
+ yield _Candidate(m.start(1), name, f"'{name}' has wrong casing — the tool is named {kebab}")
+
+
+_REFERENCE_RULES = (_phrase_candidates, _invocation_candidates, _call_candidates, _casing_candidates)
+
+
+def _check_tool_references(
+ text: str, source_label: str, tool_names: set[str], skill_names: set[str]
+) -> list[ReferenceFinding]:
+ # Dedupe by name within this text only: one name tripping two rules (e.g. wrong casing inside
+ # a phrase) is one finding, but the same stale name in another skill file needs its own.
+ findings: list[ReferenceFinding] = []
+ reported: set[str] = set()
+ for rule in _REFERENCE_RULES:
+ for candidate in rule(text, tool_names, skill_names):
+ if candidate.name in reported:
+ continue
+ reported.add(candidate.name)
+ position = source_files._line_col(text, candidate.offset)
+ findings.append(
+ ReferenceFinding(source_label, position.line, position.col, candidate.name, candidate.message)
+ )
+ return findings
+
+
+def _emit_reference_findings(findings: list[ReferenceFinding]) -> None:
+ """Surface advisory reference findings without failing the lint.
+
+ In GitHub Actions, emit a workflow warning command so each finding renders as an annotation on
+ the offending line in the PR diff; locally, print a plain ``file:line:col`` warning.
+ """
+ if not findings:
+ return
+ in_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
+ for f in findings:
+ if in_github_actions:
+ print(
+ f"::warning file={f.source_label},line={f.line},col={f.col},title=Possible stale reference::{f.message}"
+ )
+ else:
+ print(f"{f.source_label}:{f.line}:{f.col}: warning: {f.message}", file=sys.stderr)
+ print(
+ f"\nNote: {len(findings)} possible stale tool/skill reference(s) flagged above (advisory, not blocking).",
+ file=sys.stderr,
+ )
diff --git a/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py b/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py
index f2245a320ece..492f35c805f6 100644
--- a/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py
+++ b/products/posthog_ai/scripts/schema_columns/test/test_schema_columns.py
@@ -5,7 +5,7 @@ from pathlib import Path
import pytest
-from products.posthog_ai.scripts.build_skills import SkillRenderer
+from products.posthog_ai.scripts.build_skills.rendering import SkillRenderer
from products.posthog_ai.scripts.schema_columns import schema_columns
REPO_ROOT = Path(__file__).resolve().parents[5]
diff --git a/products/posthog_ai/scripts/test/test_build_skills.py b/products/posthog_ai/scripts/test/test_build_skills.py
index 67688f5c556c..ec45071b4930 100644
--- a/products/posthog_ai/scripts/test/test_build_skills.py
+++ b/products/posthog_ai/scripts/test/test_build_skills.py
@@ -11,15 +11,12 @@ from typing import Any, cast
import pytest
-from products.posthog_ai.scripts.build_skills import (
- DiscoveredSkill,
- SkillBuilder,
- SkillDiscoverer,
- SkillRenderer,
- _check_tool_references,
- parse_frontmatter,
- validate_frontmatter,
-)
+from products.posthog_ai.scripts.build_skills.discovery import SkillDiscoverer
+from products.posthog_ai.scripts.build_skills.frontmatter import parse_frontmatter, validate_frontmatter
+from products.posthog_ai.scripts.build_skills.rendering import SkillRenderer
+from products.posthog_ai.scripts.build_skills.skill_builder import SkillBuilder
+from products.posthog_ai.scripts.build_skills.skill_manifest import DiscoveredSkill
+from products.posthog_ai.scripts.build_skills.tool_references import _check_tool_references
@pytest.mark.parametrize(
@@ -339,6 +336,21 @@ def test_build_skill_entry_point_first(tmp_path: Path) -> None:
assert len(result.files) == 3
[email protected]("filename", ["my-skill.md", "my-skill.md.j2"], ids=["static", "template"])
+def test_build_all_ships_a_loose_skill_as_skill_md(tmp_path: Path, filename: str) -> None:
+ # Every consumer reads <skill>/SKILL.md, so a loose source file named anything
+ # else would build and publish but never load.
+ skills_dir = tmp_path / "products" / "alpha" / "skills"
+ skills_dir.mkdir(parents=True)
+ (skills_dir / filename).write_text("---\nname: my-skill\ndescription: Loose\n---\n# Body\n")
+
+ builder = SkillBuilder(repo_root=tmp_path, products_dir=tmp_path / "products", output_dir=tmp_path / "output")
+ manifest = builder.build_all()
+
+ assert [f.path for f in manifest.resources[0].files] == ["SKILL.md"]
+ assert (tmp_path / "output" / "dist" / "skills" / "my-skill" / "SKILL.md").exists()
+
+
def test_build_manifest_produces_valid_structure(tmp_path: Path) -> None:
products = tmp_path / "products"
for skill_name in ("skill-a", "skill-b"):
@@ -360,6 +372,23 @@ def test_build_manifest_produces_valid_structure(tmp_path: Path) -> None:
assert manifest.resources[0].description == "desc"
+def test_build_manifest_rejects_duplicate_rendered_names(tmp_path: Path) -> None:
+ # Distinct source directories, one frontmatter name: the lint deduplicates the
+ # source names, so only the manifest can catch this collision.
+ products = tmp_path / "products"
+ for product, dir_name in (("alpha", "first-copy"), ("beta", "second-copy")):
+ skill_dir = products / product / "skills" / dir_name
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text("---\nname: shared-name\ndescription: desc\n---\n# Body\n")
+
+ discoverer = SkillDiscoverer(products_dir=products)
+ builder = SkillBuilder(repo_root=tmp_path, products_dir=products, output_dir=tmp_path / "output")
+
+ assert builder.lint_all() is True
+ with pytest.raises(ValueError, match="Duplicate skill name 'shared-name'"):
+ builder.build_manifest(discoverer.discover(), SkillRenderer())
+
+
def test_end_to_end_template_with_pydantic(tmp_path: Path) -> None:
from pydantic import BaseModel, Field
@@ -411,6 +440,7 @@ def test_end_to_end_template_with_pydantic(tmp_path: Path) -> None:
with zipfile.ZipFile(zip_path) as zf:
assert "e2e-skill/SKILL.md" in zf.namelist()
assert '"title"' in zf.read("e2e-skill/SKILL.md").decode()
+ assert zf.getinfo("e2e-skill/SKILL.md").compress_type == zipfile.ZIP_DEFLATED
finally:
del sys.modules["_test_e2e_models"]
@@ -560,8 +590,13 @@ def test_lint_all_catches_duplicate_skill_names(tmp_path: Path) -> None:
"instrument-error-tracking",
"---\nname: instrument-error-tracking\ndescription: Copy\n---\n# {{ 'x' }}\n",
),
+ (
+ "local-copy/SKILL.md",
+ "instrument-metrics",
+ "---\nname: instrument-metrics\ndescription: Copy\n---\nBody\n",
+ ),
],
- ids=["loose-file", "renamed-dir", "j2-entry"],
+ ids=["loose-file", "renamed-dir", "j2-entry", "metrics"],
)
def test_lint_all_catches_reserved_name_in_frontmatter(
tmp_path: Path, capsys: pytest.CaptureFixture[str], relpath: str, reserved_name: str, content: str
diff --git a/products/posthog_ai/skills/README.md b/products/posthog_ai/skills/README.md
index b62356d74972..7131237c5db1 100644
--- a/products/posthog_ai/skills/README.md
+++ b/products/posthog_ai/skills/README.md
@@ -54,4 +54,4 @@ hogli unsync:skill -- --name <skill-name> # Remove it again
2. Run `hogli lint:skills`, then `hogli sync:skill` to try it in a real agent session
3. Push to master — CI builds the ZIP and creates a GitHub release (`agent-skills-latest` + versioned)
-The pipeline itself lives in [`products/posthog_ai/scripts/build_skills.py`](../scripts/build_skills.py).
+The pipeline itself lives in [`products/posthog_ai/scripts/build_skills/`](../scripts/build_skills/).
diff --git a/products/review_hog/backend/reviewer/lazy_seed.py b/products/review_hog/backend/reviewer/lazy_seed.py
index 9e1728265924..ce62d6c3dec0 100644
--- a/products/review_hog/backend/reviewer/lazy_seed.py
+++ b/products/review_hog/backend/reviewer/lazy_seed.py
@@ -48,7 +48,7 @@ logger = logging.getLogger(__name__)
# Canonical review-hog-perspective-* skills live on disk under `products/review_hog/skills/`.
_SKILLS_DIR = Path(__file__).resolve().parent.parent.parent / "skills"
-# Mirrors the frontmatter regex used by the scout sync + `build_skills.py` so parsing stays
+# Mirrors the frontmatter regex used by the scout sync + `build_skills/frontmatter.py` so parsing stays
# consistent across consumers.
_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
# Bundled subdirs walked recursively, in lockstep with the scout sync's `_ALLOWED_BUNDLE_SUBDIRS`.
diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.py
index 266a658a928d..a21fe9ec9056 100644
--- a/products/signals/backend/scout_harness/lazy_seed.py
+++ b/products/signals/backend/scout_harness/lazy_seed.py
@@ -50,11 +50,11 @@ _COMPANION_SKILL_DIRS = ("authoring-scouts",)
_PRODUCTS_DIR = Path(__file__).resolve().parents[3]
_EXTERNAL_COMPANION_SKILL_DIRS = (_PRODUCTS_DIR / "replay_vision" / "skills" / "exploring-replay-vision-observations",)
-# Mirrors the regex in `products/posthog_ai/scripts/build_skills.py` so frontmatter parsing
+# Mirrors the regex in `products/posthog_ai/scripts/build_skills/frontmatter.py` so frontmatter parsing
# stays consistent across the two consumers. Keep these in sync if the skill spec evolves.
_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
# Bundled subdirs walked recursively. Kept in lockstep with `_ALLOWED_SUBDIRS` in
-# `products/posthog_ai/scripts/build_skills.py` — diverging here means a file format
+# `products/posthog_ai/scripts/build_skills/source_files.py` — diverging here means a file format
# `hogli build:skills` ignores would silently land in the team's `LLMSkillFile` rows
# (or vice versa). The agentskills.io spec also defines `assets/`; if we ever want to
# support binary attachments, add to both consumers in the same change.
diff --git a/products/skills/skills/README.md b/products/skills/skills/README.md
index 02c04a450c09..ffb48e86bc98 100644
--- a/products/skills/skills/README.md
+++ b/products/skills/skills/README.md
@@ -18,7 +18,7 @@ Also available to Claude Code / Codex via `hogli sync:skill`.
hogli init:skill -- --product skills --name my-new-skill
```
-See `products/posthog_ai/scripts/build_skills.py` for the build pipeline.
+See `products/posthog_ai/scripts/build_skills/` for the build pipeline.
## Local testing
diff --git a/products/tasks/backend/logic/services/local_skills.py b/products/tasks/backend/logic/services/local_skills.py
index 2c98b3a44927..94c7fc795e8f 100644
--- a/products/tasks/backend/logic/services/local_skills.py
+++ b/products/tasks/backend/logic/services/local_skills.py
@@ -165,7 +165,7 @@ class LocalSkillsCache:
return False
def _build(self, source_hash: str) -> None:
- from products.posthog_ai.scripts.build_skills import SkillBuilder
+ from products.posthog_ai.scripts.build_skills.skill_builder import SkillBuilder
builder = SkillBuilder(self.base_dir, self.base_dir / "products", self.output_dir)
manifest = builder.build_all()
diff --git a/products/tasks/backend/logic/services/test_local_skills.py b/products/tasks/backend/logic/services/test_local_skills.py
index 0695e18b3e16..b21e4281e781 100644
--- a/products/tasks/backend/logic/services/test_local_skills.py
+++ b/products/tasks/backend/logic/services/test_local_skills.py
@@ -21,7 +21,7 @@ from products.tasks.backend.logic.services.local_skills import (
)
from products.tasks.backend.models import SandboxEnvironment
-PATCH_TARGET = "products.posthog_ai.scripts.build_skills.SkillBuilder"
+PATCH_TARGET = "products.posthog_ai.scripts.build_skills.skill_builder.SkillBuilder"
def _mock_builder(cache: LocalSkillsCache, *, produce_files: bool = True):
@@ -69,9 +69,9 @@ class TestLocalSkills(BaseTest):
skill_dir.mkdir(parents=True)
(skill_dir / "SKILL.md").write_text("# skill body\n")
- scripts_dir = self.base_dir / "products" / "posthog_ai" / "scripts"
+ scripts_dir = self.base_dir / "products" / "posthog_ai" / "scripts" / "build_skills"
scripts_dir.mkdir(parents=True)
- (scripts_dir / "build_skills.py").write_text("# stub renderer\n")
+ (scripts_dir / "skill_builder.py").write_text("# stub renderer\n")
def _seed_dist(self, filename: str = "placeholder.md") -> Path:
self.cache.dist_dir.mkdir(parents=True, exist_ok=True)
@@ -139,7 +139,7 @@ class TestLocalSkills(BaseTest):
def test_hash_reacts_to_relevant_changes_only(self) -> None:
skill_file = self.base_dir / "products" / "alpha" / "skills" / "my-skill" / "SKILL.md"
- builder_script = self.base_dir / "products" / "posthog_ai" / "scripts" / "build_skills.py"
+ builder_script = self.base_dir / "products" / "posthog_ai" / "scripts" / "build_skills" / "skill_builder.py"
baseline = self.cache._compute_source_hash()
diff --git a/products/tasks/backend/management/commands/setup_background_agents.py b/products/tasks/backend/management/commands/setup_background_agents.py
index 4261c78e33a8..5df57b592266 100644
--- a/products/tasks/backend/management/commands/setup_background_agents.py
+++ b/products/tasks/backend/management/commands/setup_background_agents.py
@@ -161,7 +161,7 @@ class Command(BaseCommand):
self.stdout.write(self.style.MIGRATE_HEADING("Building agent skills (this can take a minute)..."))
process = subprocess.Popen(
- [sys.executable, "products/posthog_ai/scripts/build_skills.py"],
+ [sys.executable, "-m", "products.posthog_ai.scripts.build_skills"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
diff --git a/products/tasks/scripts/build_model_catalog.py b/products/tasks/scripts/build_model_catalog.py
index e228b27df0e8..55044a9996e0 100755
--- a/products/tasks/scripts/build_model_catalog.py
+++ b/products/tasks/scripts/build_model_catalog.py
@@ -5,7 +5,7 @@ Same pattern as ``bin/build-mcp-oauth-scopes.py``: a codegen script that reads a
Python module and writes a checked-in ``*.generated.ts``, so the Python module stays the
single authority and the TypeScript sides are projections of it. It lives beside the
catalog it projects rather than in ``bin/``, since only this product reads or writes it —
-the same placement as ``products/posthog_ai/scripts/build_skills.py``.
+the same placement as ``products/posthog_ai/scripts/build_skills/``.
Two files come out of one template because the two workspaces run different formatters —
the web app runs oxfmt (four spaces, single quotes, no semicolons, 120 columns) and the
diff --git a/services/mcp/scripts/lib/tool-references.ts b/services/mcp/scripts/lib/tool-references.ts
index d593f9e0159e..7e77b9f8fb14 100644
--- a/services/mcp/scripts/lib/tool-references.ts
+++ b/services/mcp/scripts/lib/tool-references.ts
@@ -9,8 +9,9 @@
* too), so anything that doesn't resemble a real name is ignored and no name-level allowlist is
* needed.
*
- * Used by scripts/lint-tool-names.ts. The skills lint (products/posthog_ai/scripts/
- * build_skills.py) implements the same rules for skill markdown, plus one deliberately
+ * Used by scripts/lint-tool-names.ts. The skills lint
+ * (products/posthog_ai/scripts/build_skills/tool_references.py) implements the same rules
+ * for skill markdown, plus one deliberately
* skills-only rule: call-syntax references like `read_data("experiments", id)` occur
* only in skill prose, and detecting them here would false-positive on SDK/HogQL code
* examples in tool descriptions.