:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): unbreak the MCP build and cover the trees it compiles (#94179)
Georges-Antoine Assi28bef1932a03
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex 90fdb0b7b0c3..1092dfa7cc8e 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -28,7 +28,7 @@ The linters own the mechanical rules (below); this skill is the **judgment calls## What the linters already enforceRun `bin/hogli lint:workflows` and `actionlint` before pushing — they gate CI, and they (not this list) are the source of truth for what's enforced.-Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, required-check gate hygiene, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).+Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).Third-party action digests are bumped by Renovate.## The dispatch budget (500 runs / 10s / repo)@@ -65,6 +65,12 @@ GitHub caps _workflow-run dispatch_ at 500 runs per 10s per repo; overflow failsHeavy matrices (`ci-backend`, `ci-nodejs`) do exactly this — deliberate.- Delete dead dispatchers outright.A disabled-but-still-triggered workflow keeps dispatching no-op runs against the cap — remove the trigger, don't just disable it.+- **A filter has to cover what the job actually compiles, not just where the code lives.**+ A build that reaches out of its own tree — through a tsconfig `paths` alias, a workspace dependency, a generated file — breaks when a filter lists only the service directory.+ The PR touching the imported tree skips the job, the merge-queue run skips it too, and the break lands on master, where it then fails every later PR whose diff does match.+ Cover the _enclosing directory_, not the imported file: the module drags its own relative imports along.+ When the imported tree is busy, give it a second filter output and gate only the jobs it can actually break, rather than widening the one that also fires an expensive suite.+ `WF009` derives the MCP filters' required trees from the MCP sources and fails when one is uncovered; a build with the same shape wants the same treatment.## Concurrencydiff --git a/.github/workflows/ci-mcp-ui-apps.yml b/.github/workflows/ci-mcp-ui-apps.ymlindex 6568586ad03c..1b02dcc8ea88 100644--- a/.github/workflows/ci-mcp-ui-apps.yml+++ b/.github/workflows/ci-mcp-ui-apps.yml@@ -52,6 +52,12 @@ jobs:- 'products/*/mcp/**'- 'services/mcp/definitions/*.yaml'- 'common/mosaic/**'+ # Compiled into the UI apps: the quill packages they render with, the+ # product-analytics chart transforms they import, and the generated+ # API types their views are typed against.+ - 'packages/quill/**'+ - 'products/product_analytics/frontend/insights/**'+ - 'products/*/frontend/generated/**'- '.github/workflows/ci-mcp-ui-apps.yml'build-and-report:diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.ymlindex 8a686a47d66f..602690fd7273 100644--- a/.github/workflows/ci-mcp.yml+++ b/.github/workflows/ci-mcp.yml@@ -52,6 +52,7 @@ jobs:name: Determine need to run MCP checksoutputs:mcp: ${{ steps.filter.outputs.mcp || 'true' }}+ mcp-typescript: ${{ steps.filter.outputs.mcp-typescript || 'true' }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -90,6 +91,8 @@ jobs:- 'products/*/backend/**/*.py'# Query schemas used by MCP analytics tools- 'frontend/src/queries/schema.json'+ # Widget catalog the notebook cell tools validate against+ - 'products/notebooks/notebook-widget-catalog.json'# Shared UI component library (used by MCP UI apps)- 'common/mosaic/**'# Code generation tooling@@ -154,13 +157,31 @@ jobs:- '!products/*/backend/**/test_*.py'- '!products/*/backend/**/*_test.py'- '!products/*/backend/**/conftest.py'+ # Source outside services/mcp/ that the MCP build compiles: the quill+ # packages the UI apps render with, the chart transforms and generated+ # API types those UI apps import, and the insight fixtures the tests+ # load. Directory-wide on purpose, so a relative import inside the+ # tree comes along.+ #+ # Its own filter because it reaches a different set of jobs: `build`+ # (whose tsgo pass is stricter than the frontend tsconfig, so the+ # frontend lane can be green while this one is red) and `unit-tests`+ # (UI app snapshots), but never the integration tests, which drive the+ # Python backend. WF009 keeps the list in step with what MCP imports.+ mcp-typescript:+ - 'packages/quill/**'+ - 'products/product_analytics/frontend/insights/**'+ - 'products/*/frontend/generated/**'+ - 'frontend/src/mocks/fixtures/**'build:name: Build Packageruns-on: ubuntu-latesttimeout-minutes: 10needs: changes# Not on master push — master coverage comes from the hourly run (see `schedule`).- if: needs.changes.outputs.mcp == 'true' && github.event_name != 'push'+ if: >-+ (needs.changes.outputs.mcp == 'true' || needs.changes.outputs.mcp-typescript == 'true')+ && github.event_name != 'push'steps:- name: Checkout code@@ -242,7 +263,9 @@ jobs:timeout-minutes: 10needs: changes# Not on master push — master coverage comes from the hourly run (see `schedule`).- if: needs.changes.outputs.mcp == 'true' && github.event_name != 'push'+ if: >-+ (needs.changes.outputs.mcp == 'true' || needs.changes.outputs.mcp-typescript == 'true')+ && github.event_name != 'push'steps:- name: Checkout codeuses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -771,7 +794,7 @@ jobs:# A status function is required to commit regenerated snapshots even when unit-tests# failed (a snapshot mismatch fails that job). !cancelled() rather than always() so a# superseded run does not push a stale snapshot commit to the branch.- if: ${{ !cancelled() && needs.changes.outputs.mcp == 'true' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && !contains(github.actor, '[bot]') && github.actor != 'posthog-bot' && !contains(github.actor, 'github-actions') }}+ if: ${{ !cancelled() && (needs.changes.outputs.mcp == 'true' || needs.changes.outputs.mcp-typescript == 'true') && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && !contains(github.actor, '[bot]') && github.actor != 'posthog-bot' && !contains(github.actor, 'github-actions') }}permissions:contents: writepull-requests: write@@ -849,7 +872,7 @@ jobs:fi# Pass if no MCP changes detected (jobs were skipped)- if [[ "${{ needs.changes.outputs.mcp }}" != "true" ]]; then+ if [[ "${{ needs.changes.outputs.mcp }}" != "true" && "${{ needs.changes.outputs.mcp-typescript }}" != "true" ]]; thenecho "MCP checks were skipped (no relevant changes)."exit 0fidiff --git a/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.ts b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.tsindex b5a66c5e0ac5..1465da70b03c 100644--- a/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.ts+++ b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.ts@@ -23,10 +23,17 @@ export function computeMagnitudeAxisIds(datasets: readonly (readonly number[])[].flatMap((magnitude, seriesIndex) => (magnitude === null ? [] : [{ magnitude, seriesIndex }])).sort((a, b) => a.magnitude - b.magnitude)+ const gaps: { pos: number; gap: number }[] = []+ let previousMagnitude: number | null = null+ measured.forEach(({ magnitude }, pos) => {+ if (previousMagnitude !== null) {+ gaps.push({ pos, gap: magnitude - previousMagnitude })+ }+ previousMagnitude = magnitude+ })+const splitPositions = new Set(- measured- .slice(1)- .map((entry, k) => ({ pos: k + 1, gap: entry.magnitude - measured[k].magnitude }))+ gaps.filter(({ gap }) => gap >= MAGNITUDE_GAP).sort((a, b) => b.gap - a.gap).slice(0, MAX_Y_AXES - 1)@@ -43,7 +50,8 @@ export function computeMagnitudeAxisIds(datasets: readonly (readonly number[])[]groupOf[seriesIndex] = group})- const idOf = new Map<number, string>(datasets.length ? [[groupOf[0], DEFAULT_Y_AXIS_ID]] : [])+ const firstGroup = groupOf[0]+ const idOf = new Map<number, string>(firstGroup === undefined ? [] : [[firstGroup, DEFAULT_Y_AXIS_ID]])return groupOf.map((g) => {let id = idOf.get(g)if (!id) {diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.pyindex e31599f0bc61..1836b79fa65e 100644--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py@@ -27,6 +27,7 @@ from hogli_commands.workflow_lint.checks.cache_writes import (from hogli_commands.workflow_lint.checks.checkout_full_depth import CheckoutFullDepthCheckfrom hogli_commands.workflow_lint.checks.dorny_negation import DornyNegationCheckfrom hogli_commands.workflow_lint.checks.job_timeouts import JobTimeoutsCheck+from hogli_commands.workflow_lint.checks.mcp_filter_coverage import McpFilterCoverageCheck, _resolvefrom hogli_commands.workflow_lint.checks.pr_concurrency import PrConcurrencyCheckfrom hogli_commands.workflow_lint.checks.pr_event_fanout import PrEventFanoutCheckfrom hogli_commands.workflow_lint.checks.required_gates import RequiredGateCheck@@ -1559,6 +1560,209 @@ class TestRequiredGateCheck:assert [issue.message.split("'")[1] for issue in issues] == ["changes"]+# ---------------------------------------------------------------------------+# McpFilterCoverageCheck+# ---------------------------------------------------------------------------++_MCP_TSCONFIG = """+{+ "compilerOptions": {+ "paths": {+ "products/*": ["../../products/*"],+ "@posthog/quill-charts": ["../../packages/quill/packages/charts/dist/index.d.ts"]+ }+ }+}+"""++_UI_APP_SOURCE = (+ "import { Chart } from '@posthog/quill-charts'\n"+ "import { transform } from 'products/product_analytics/frontend/insights/trends/transforms'\n"+)++_INSIGHTS = "products/product_analytics/frontend/insights"+_INSIGHTS_TRENDS = f"{_INSIGHTS}/trends"+_INSIGHTS_SHARED = f"{_INSIGHTS}/shared"+_COVERING_PATTERNS = ["services/mcp/**", "packages/quill/**", f"{_INSIGHTS}/**"]+++def _write_file(path: Path, content: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content)+++def _filter_workflow(patterns: list[str]) -> str:+ return "\n".join(+ [+ "name: x",+ "on: [pull_request]",+ "jobs:",+ " changes:",+ " runs-on: ubuntu-latest",+ " timeout-minutes: 5",+ " steps:",+ " - uses: ./.github/actions/paths-filter",+ " with:",+ " filters: |",+ " mcp:",+ *(f" - '{pattern}'" for pattern in patterns),+ "",+ ]+ )+++def _mcp_repo(+ repo_root: Path,+ *,+ mcp_patterns: list[str],+ ui_apps_patterns: list[str],+ tool_source: str = "",+) -> Path:+ """Fixture repo: an MCP tsconfig, MCP sources, the trees they import, both workflows.++ The UI app imports a product transform through an alias, and that transform+ relatively imports a sibling tree, so the fixture exercises both hops.+ """+ _write_file(repo_root / "services" / "mcp" / "tsconfig.json", _MCP_TSCONFIG)+ _write_file(repo_root / "services" / "mcp" / "src" / "ui-apps" / "Chart.tsx", _UI_APP_SOURCE)+ _write_file(repo_root / "services" / "mcp" / "src" / "tools" / "tool.ts", tool_source)+ insights = repo_root / "products" / "product_analytics" / "frontend" / "insights"+ _write_file(insights / "trends" / "transforms.ts", "import { helper } from '../shared/helper'\n")+ _write_file(insights / "shared" / "helper.ts", "export const helper = 1\n")+ _write_file(repo_root / "products" / "notebooks" / "catalog.json", "{}\n")+ workflows_dir = repo_root / ".github" / "workflows"+ workflows_dir.mkdir(parents=True)+ _write(workflows_dir, "ci-mcp.yml", _filter_workflow(mcp_patterns))+ _write(workflows_dir, "ci-mcp-ui-apps.yml", _filter_workflow(ui_apps_patterns))+ return workflows_dir+++def _coverage_issues(repo_root: Path, workflows_dir: Path, workflow: str) -> list[str]:+ result = McpFilterCoverageCheck(repo_root=repo_root).run(_read_all(workflows_dir))+ return [issue.message for issue in result.issues if issue.workflow == workflow]+++class TestMcpAliasResolution:+ @pytest.mark.parametrize(+ "alias, specifier, target",+ [+ ("products/*", "products/pa/frontend/x", "products/pa/frontend/x"),+ ("@app/*/index", "@app/charts/index", "products/charts"),+ ("@app/*/index", "@app//index", "products/"),+ # The tail is empty and the end index is 0, which must not read as+ # "slice to the end" and substitute the suffix for the wildcard.+ ("*/index", "/index", "products/"),+ ],+ )+ def test_substitutes_the_wildcard_tail(self, alias: str, specifier: str, target: str) -> None:+ assert _resolve(specifier, {alias: ["products/*"]}) == [target]++ def test_an_alias_without_a_wildcard_matches_whole(self) -> None:+ aliases = {"@posthog/quill": ["packages/quill/dist/index.d.ts"]}+ assert _resolve("@posthog/quill", aliases) == ["packages/quill/dist/index.d.ts"]+ assert _resolve("@posthog/quill/extra", aliases) == []+++class TestMcpFilterCoverageCheck:+ def test_passes_when_directory_patterns_cover_every_import(self, tmp_path: Path) -> None:+ # quill's alias target is a built `dist` file absent from a fresh checkout;+ # the check must still demand coverage of it, and 'packages/quill/**' gives it.+ workflows_dir = _mcp_repo(tmp_path, mcp_patterns=_COVERING_PATTERNS, ui_apps_patterns=_COVERING_PATTERNS)+ assert McpFilterCoverageCheck(repo_root=tmp_path).run(_read_all(workflows_dir)).issues == []++ @pytest.mark.parametrize(+ "patterns, uncovered",+ [+ pytest.param([], [_INSIGHTS_SHARED, _INSIGHTS_TRENDS], id="no-pattern"),+ # A module reaches its own relative imports, so covering the directly+ # imported directory alone still leaves the sibling tree uncovered.+ pytest.param([f"{_INSIGHTS_TRENDS}/**"], [_INSIGHTS_SHARED], id="only-the-imported-directory"),+ pytest.param(+ [f"{_INSIGHTS_TRENDS}/transforms.ts", f"{_INSIGHTS_SHARED}/helper.ts"],+ [_INSIGHTS_SHARED, _INSIGHTS_TRENDS],+ id="patterns-naming-the-files",+ ),+ ],+ )+ def test_flags_a_tree_no_directory_pattern_covers(+ self, tmp_path: Path, patterns: list[str], uncovered: list[str]+ ) -> None:+ product_patterns = ["services/mcp/**", "packages/quill/**", *patterns]+ workflows_dir = _mcp_repo(tmp_path, mcp_patterns=product_patterns, ui_apps_patterns=product_patterns)+ messages = _coverage_issues(tmp_path, workflows_dir, "ci-mcp.yml")+ assert sorted(message.split("'")[1] for message in messages) == uncovered++ @pytest.mark.parametrize(+ "tsconfig, reported",+ [+ pytest.param("{ not json", True, id="unparseable"),+ pytest.param('{"compilerOptions": {}}', True, id="no-paths-key"),+ pytest.param(None, False, id="no-mcp-service-in-this-checkout"),+ ],+ )+ def test_an_unusable_tsconfig_is_reported_rather_than_passed(+ self, tmp_path: Path, tsconfig: str | None, reported: bool+ ) -> None:+ # Deriving no aliases means reading no imports, which clears every filter+ # by not looking. Only an absent MCP service is a legitimate pass.+ workflows_dir = _mcp_repo(tmp_path, mcp_patterns=_COVERING_PATTERNS, ui_apps_patterns=_COVERING_PATTERNS)+ path = tmp_path / "services" / "mcp" / "tsconfig.json"+ path.unlink()+ if tsconfig is not None:+ path.write_text(tsconfig)+ messages = _coverage_issues(tmp_path, workflows_dir, "ci-mcp.yml")+ assert bool(messages) is reported+ assert not reported or "compilerOptions.paths" in messages[0]++ def test_a_relative_import_out_of_the_mcp_tree_needs_coverage(self, tmp_path: Path) -> None:+ # The MCP tests reach the frontend insight fixtures this way, so a relative+ # specifier that leaves services/mcp/ counts like an aliased one.+ _mcp_repo(tmp_path, mcp_patterns=_COVERING_PATTERNS, ui_apps_patterns=_COVERING_PATTERNS)+ _write_file(tmp_path / "frontend" / "fixtures" / "trends.json", "{}\n")+ _write_file(+ tmp_path / "services" / "mcp" / "tests" / "fixtures.ts",+ "import trends from '../../../frontend/fixtures/trends.json'\n",+ )+ workflows_dir = tmp_path / ".github" / "workflows"+ messages = _coverage_issues(tmp_path, workflows_dir, "ci-mcp.yml")+ assert [message.split("'")[1] for message in messages] == ["frontend/fixtures/trends.json"]++ def test_a_relative_specifier_that_resolves_to_nothing_is_ignored(self, tmp_path: Path) -> None:+ # generate-ui-apps.ts holds import statements inside the code it emits, and+ # from services/mcp/scripts/ those climb clear of the MCP tree. The regex+ # cannot tell them from real imports, so the missing file is the signal.+ workflows_dir = _mcp_repo(tmp_path, mcp_patterns=_COVERING_PATTERNS, ui_apps_patterns=_COVERING_PATTERNS)+ _write_file(+ tmp_path / "services" / "mcp" / "scripts" / "generate.ts",+ "const template = `import { App } from '../../components/App'`\n",+ )+ assert McpFilterCoverageCheck(repo_root=tmp_path).run(_read_all(workflows_dir)).issues == []++ def test_a_data_import_is_covered_by_a_pattern_naming_it(self, tmp_path: Path) -> None:+ # A JSON import has no relative imports of its own, so naming the file is enough.+ workflows_dir = _mcp_repo(+ tmp_path,+ mcp_patterns=[*_COVERING_PATTERNS, "products/notebooks/catalog.json"],+ ui_apps_patterns=_COVERING_PATTERNS,+ tool_source="import catalog from 'products/notebooks/catalog.json'\n",+ )+ assert McpFilterCoverageCheck(repo_root=tmp_path).run(_read_all(workflows_dir)).issues == []++ def test_ui_apps_workflow_ignores_imports_it_does_not_compile(self, tmp_path: Path) -> None:+ # ci-mcp-ui-apps.yml builds only the UI apps, so an import reachable only+ # from services/mcp/src/tools is not its filter's problem.+ workflows_dir = _mcp_repo(+ tmp_path,+ mcp_patterns=_COVERING_PATTERNS,+ ui_apps_patterns=_COVERING_PATTERNS,+ tool_source="import catalog from 'products/notebooks/catalog.json'\n",+ )+ assert _coverage_issues(tmp_path, workflows_dir, "ci-mcp-ui-apps.yml") == []+ assert [message.split("'")[1] for message in _coverage_issues(tmp_path, workflows_dir, "ci-mcp.yml")] == [+ "products/notebooks/catalog.json"+ ]++class TestLiveTreeSmoke:"""Smoke test against the live ``.github/workflows/`` tree.diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.pyindex d6a588d2022e..49e3f9614324 100644--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py@@ -16,6 +16,7 @@ from .cache_writes import CacheWriteGateCheckfrom .checkout_full_depth import CheckoutFullDepthCheckfrom .dorny_negation import DornyNegationCheckfrom .job_timeouts import JobTimeoutsCheck+from .mcp_filter_coverage import McpFilterCoverageCheckfrom .pr_concurrency import PrConcurrencyCheckfrom .pr_event_fanout import PrEventFanoutCheckfrom .required_gates import RequiredGateCheck@@ -30,6 +31,7 @@ CHECKS: list[WorkflowCheck] = [CacheWriteGateCheck(),RequiredGateCheck(),PrEventFanoutCheck(),+ McpFilterCoverageCheck(),]diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/mcp_filter_coverage.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/mcp_filter_coverage.pynew file mode 100644index 000000000000..8720e0056670--- /dev/null+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/mcp_filter_coverage.py@@ -0,0 +1,319 @@+"""The MCP path filters must cover every tree the MCP build compiles.++``services/mcp`` and ``products/*/mcp`` import source out of other trees through+the ``paths`` aliases in ``services/mcp/tsconfig.json``: the quill packages,+shared product frontend code, product data files. That code is compiled by+``tsgo`` under a stricter tsconfig than the frontend's+(``noUncheckedIndexedAccess``, among others), so the frontend lane can be green+on a file the MCP lane rejects.++When a filter misses one of those trees, a PR touching only that tree skips the+MCP jobs, the merge queue's ``trunk-merge/**`` run skips them for the same+reason, and the break lands on master, where it then fails every later PR whose+own diff does trigger the filter.++Imports are read from source rather than from a hand-kept list. A TypeScript+import must be covered by a **directory** pattern (``.../**``), because the+imported module pulls in its own relative imports and only a pattern covering+the enclosing tree brings those along. A data import (JSON) has no such tail, so+a pattern naming the file is enough.++``ci-mcp.yml`` compiles the whole service and ``ci-mcp-ui-apps.yml`` only the UI+apps, so each is judged against the imports of the sources it actually builds.+"""++from __future__ import annotations++import re+import json+import subprocess+from pathlib import Path++from hogli.manifest import REPO_ROOT++from ..check import CheckResult, Issue, WorkflowCheck+from ..model import Workflow, parse_filters++MCP_TSCONFIG = Path("services/mcp/tsconfig.json")++# workflow file -> the MCP source roots that workflow compiles+COMPILED_SOURCES: dict[str, tuple[str, ...]] = {+ "ci-mcp.yml": ("services/mcp", "products/*/mcp"),+ "ci-mcp-ui-apps.yml": ("services/mcp/src/ui-apps", "products/*/mcp"),+}++# Where a problem with the tsconfig itself is reported, rather than at a filter.+PRIMARY_WORKFLOW = "ci-mcp.yml"++IMPORT = re.compile(r"""(?:from|import)\s*\(?\s*['"](?P<specifier>[^'"]+)['"]""")+JSON_LINE_COMMENT = re.compile(r"^\s*//.*$", re.MULTILINE)+OWN_MCP_TREE = re.compile(r"^(?:services/mcp/|products/[^/]+/mcp/)")+DATA_SUFFIXES = (".json", ".css", ".svg")+++class McpFilterCoverageCheck(WorkflowCheck):+ id = "WF009-mcp-filter-coverage"+ label = "MCP filter covers compiled trees"+ description = "every tree the MCP build imports is covered by the MCP workflows' path filters"++ def __init__(self, repo_root: Path | None = None) -> None:+ # Injected so tests can point at a fixture tree without monkeypatching env vars.+ self._repo_root = repo_root or REPO_ROOT++ @property+ def fix_hint(self) -> str | None:+ return (+ "Add a pattern covering each listed path to the named workflow's path filters. For a "+ "TypeScript import, widen to the enclosing directory ('packages/quill/**') rather than "+ "naming the file, so the module's own relative imports come along."+ )++ def run(self, workflows: list[Workflow]) -> CheckResult:+ result = CheckResult()+ # A checkout without the MCP service has no filters to keep honest. Any+ # other unusable tsconfig is reported, because reading no aliases means+ # reading no imports, which would pass every filter by not looking.+ if not (self._repo_root / MCP_TSCONFIG).is_file():+ return result+ aliases = _read_path_aliases(self._repo_root)+ if not aliases:+ result.issues.append(+ Issue(+ workflow=PRIMARY_WORKFLOW,+ message=(+ f"{MCP_TSCONFIG} has no readable compilerOptions.paths, so the trees MCP "+ "compiles cannot be derived and this check would pass without verifying anything"+ ),+ file=str(MCP_TSCONFIG),+ )+ )+ return result++ for workflow_name, source_roots in COMPILED_SOURCES.items():+ wf = next((w for w in workflows if w.path.name == workflow_name), None)+ if wf is None:+ result.issues.append(+ Issue(+ workflow=workflow_name,+ message="workflow not found; cannot verify that its path filters cover MCP's imports",+ )+ )+ continue+ patterns = _positive_patterns(wf)+ for target, needs_directory in sorted(_imported(self._repo_root, source_roots, aliases).items()):+ if any(_covers(pattern, target, needs_directory) for pattern in patterns):+ continue+ result.issues.append(+ Issue(+ workflow=workflow_name,+ message=(+ f"MCP imports '{target}', which no path filter in this workflow "+ "covers, so a change there skips the MCP jobs"+ ),+ file=str(wf.path),+ )+ )+ return result+++def _read_path_aliases(repo_root: Path) -> dict[str, list[str]]:+ """``compilerOptions.paths`` from the MCP tsconfig, as repo-relative targets."""+ try:+ raw = (repo_root / MCP_TSCONFIG).read_text(encoding="utf-8")+ except OSError:+ return {}+ try:+ parsed = json.loads(JSON_LINE_COMMENT.sub("", raw))+ except json.JSONDecodeError:+ return {}+ paths = parsed.get("compilerOptions", {}).get("paths") if isinstance(parsed, dict) else None+ if not isinstance(paths, dict):+ return {}++ base = MCP_TSCONFIG.parent+ aliases: dict[str, list[str]] = {}+ for alias, targets in paths.items():+ if not isinstance(alias, str) or not isinstance(targets, list):+ continue+ resolved = [_repo_relative(base, target) for target in targets if isinstance(target, str)]+ aliases[alias] = [target for target in resolved if target is not None]+ return aliases+++def _repo_relative(base: Path, target: str) -> str | None:+ """Resolve a tsconfig target against the tsconfig's dir. None if it escapes the repo."""+ parts: list[str] = []+ for part in Path(base, target).parts:+ if part == "..":+ if not parts:+ return None+ parts.pop()+ elif part != ".":+ parts.append(part)+ return "/".join(parts)+++def _imported(repo_root: Path, source_roots: tuple[str, ...], aliases: dict[str, list[str]]) -> dict[str, bool]:+ """Paths outside MCP's own trees that these sources import, each with whether a+ directory pattern is required to cover it."""+ required: dict[str, bool] = {}+ for source in _mcp_sources(repo_root, source_roots):+ try:+ text = (repo_root / source).read_text(encoding="utf-8")+ except OSError:+ continue+ for match in IMPORT.finditer(text):+ for resolved in _resolve_from(repo_root, match.group("specifier"), source, aliases):+ if OWN_MCP_TREE.match(resolved) or "node_modules" in resolved.split("/"):+ continue+ # A data file is a leaf. A module drags its own relative imports+ # along, so every tree the walk reaches has to be covered too.+ if resolved.endswith(DATA_SUFFIXES):+ required.setdefault(resolved, False)+ continue+ for module in _relative_closure(repo_root, resolved):+ required[_enclosing_directory(module)] = True+ return required+++def _relative_closure(repo_root: Path, entry: str) -> set[str]:+ """``entry`` plus every module reachable from it through relative imports.++ A module that does not resolve on disk still counts, because a generated or+ built target (quill's ``dist``) is absent from a fresh checkout and dropping it+ would quietly stop requiring coverage of the tree that produces it.+ """+ reached: set[str] = set()+ queue = [entry]+ while queue:+ current = queue.pop()+ if current in reached:+ continue+ reached.add(current)+ module = _resolve_on_disk(repo_root, current)+ if module is None:+ continue+ reached.add(module)+ for match in IMPORT.finditer((repo_root / module).read_text(encoding="utf-8")):+ specifier = match.group("specifier")+ if not specifier.startswith("."):+ continue+ neighbor = _repo_relative(Path(_enclosing_directory(module)), specifier)+ if neighbor is not None and not neighbor.endswith(DATA_SUFFIXES):+ queue.append(neighbor)+ return reached+++def _resolve_on_disk(repo_root: Path, module: str) -> str | None:+ """The file a TypeScript module specifier names, extension and index forms included."""+ for candidate in (module, f"{module}.ts", f"{module}.tsx", f"{module}/index.ts", f"{module}/index.tsx"):+ if (repo_root / candidate).is_file():+ return candidate+ return None+++def _mcp_sources(repo_root: Path, source_roots: tuple[str, ...]) -> list[str]:+ """TypeScript under the given roots, which may hold ``*`` path segments."""+ return [source for source in _tracked_typescript(repo_root) if _under_any(source, source_roots)]+++def _tracked_typescript(repo_root: Path) -> list[str]:+ """Git-tracked TypeScript under the MCP trees, falling back to the filesystem.++ Only tracked files count: CI sees nothing else, and a working tree can carry+ build residue from another branch.+ """+ command = ["git", "ls-files", "-z", "--", "services/mcp", "products"]+ try:+ listing = subprocess.run(command, cwd=repo_root, check=True, capture_output=True, text=True)+ except (OSError, subprocess.CalledProcessError):+ return sorted(+ path.relative_to(repo_root).as_posix()+ for root in ("services/mcp", "products")+ for path in repo_root.glob(f"{root}/**/*.ts*")+ if "node_modules" not in path.parts+ )+ return [entry for entry in listing.stdout.split("\0") if entry.endswith((".ts", ".tsx"))]+++def _under_any(path: str, roots: tuple[str, ...]) -> bool:+ return any(re.fullmatch(rf"{_to_regex(root)}/.*", path) for root in roots)+++def _resolve_from(repo_root: Path, specifier: str, source: str, aliases: dict[str, list[str]]) -> list[str]:+ """Repo-relative targets one import in ``source`` resolves to.++ A relative specifier can leave the MCP tree just as an alias can, and the MCP+ tests reach the frontend insight fixtures that way, so both forms resolve+ here. The caller drops whatever lands back inside MCP's own trees.++ A relative specifier must also name a file that exists. Unlike an alias+ target, which can be a build artifact absent from a fresh checkout, a+ relative path that resolves to nothing is either dead or, more often, an+ import statement inside a generated-code template string, which the regex+ cannot tell from a real one.+ """+ if specifier.startswith("."):+ target = _repo_relative(Path(_enclosing_directory(source)), specifier)+ if target is None or _resolve_on_disk(repo_root, target) is None:+ return []+ return [target]+ return _resolve(specifier, aliases)+++def _resolve(specifier: str, aliases: dict[str, list[str]]) -> list[str]:+ """Repo-relative targets a bare import specifier resolves to, via tsconfig aliases."""+ for alias, targets in aliases.items():+ prefix, star, suffix = alias.partition("*")+ if not star:+ if specifier == alias:+ return targets+ continue+ if specifier.startswith(prefix) and specifier.endswith(suffix):+ # endswith already bounds len(suffix), so the end index cannot go negative.+ tail = specifier[len(prefix) : len(specifier) - len(suffix)]+ return [target.replace("*", tail) for target in targets]+ return []+++def _enclosing_directory(target: str) -> str:+ """The imported module's directory, which is the unit a filter has to cover."""+ return target.rsplit("/", 1)[0] if "/" in target else target+++def _positive_patterns(wf: Workflow) -> list[str]:+ """Every non-negated glob across the workflow's paths-filters."""+ patterns: list[str] = []+ for job in wf.jobs:+ for step in job.steps:+ if step.with_ is None:+ continue+ filters = parse_filters(step.with_.get("filters"))+ if filters is None:+ continue+ for entries in filters.values():+ if not isinstance(entries, list):+ continue+ for entry in entries:+ values = entry.values() if isinstance(entry, dict) else [entry]+ patterns.extend(v for v in values if isinstance(v, str) and not v.startswith("!"))+ return patterns+++def _covers(pattern: str, target: str, needs_directory: bool) -> bool:+ """Does one filter glob cover ``target``?++ A directory glob covers the tree it names; anything else has to name the+ target exactly, and only where a whole tree is not required.+ """+ if pattern.endswith("/**"):+ regex = _to_regex(pattern.removesuffix("/**"))+ return re.fullmatch(regex, target) is not None or re.fullmatch(rf"{regex}/.*", target) is not None+ return not needs_directory and re.fullmatch(_to_regex(pattern), target) is not None+++def _to_regex(pattern: str) -> str:+ return re.escape(pattern).replace(r"\*\*", ".*").replace(r"\*", "[^/]*")+++__all__ = ["McpFilterCoverageCheck"]