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.

145 KB
Raw Blame
"""Tests for product lint checks — focused on PackageJsonScriptsCheck."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from hogli_commands.product import (
    checks as checks_module,
    gh as gh_module,
    isolation as isolation_module,
)
from hogli_commands.product.checks import (
    BackendPackageMarkerCheck,
    CheckContext,
    FacadeShapeCheck,
    FileFolderConflictsCheck,
    ImportSurfaceCheck,
    IsolationChainCheck,
    OrphanedTestFilesCheck,
    PackageJsonScriptsCheck,
    ProductYamlCheck,
    ProductYamlOwnersCheck,
    SystemChecksCheck,
    WiringInterfaceCheck,
    _has_test_files,
    _is_noop_script,
    _names_from_pattern,
    _parse_pytest_paths,
    has_legacy_interface_leaks,
    validate_facade_alternation,
    validate_interface_blocks,
    validate_tach_references,
)
from hogli_commands.product.crossings import facade_shape_use
from hogli_commands.product.isolation import (
    MODEL_SURFACE_PREFIXES,
    IsolationRung,
    facade_carveout_modules,
    facade_class_imports,
    facade_function_names,
    facade_model_crossings,
    facade_shape_findings,
    facade_unapproved_wiring,
    has_narrowed_turbo_inputs,
    has_real_facade,
    has_tach_interface,
    permanent_interface_modules,
    routes_in_turbo_inputs,
    uncovered_carveout_modules,
    uncovered_permanent_modules,
    unqualified_permanent_modules,
    unwatched_garages,
    unwatched_model_surface,
)

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _make_product(
    tmp_path: Path,
    *,
    scripts: dict[str, str] | None = None,
    has_backend: bool = True,
    strict: bool = False,
    test_files: list[str] | None = None,
    extra_dirs: list[str] | None = None,
) -> CheckContext:
    """Build a minimal product directory and return a CheckContext for it."""
    product_dir = tmp_path / "my_product"
    product_dir.mkdir()
    backend_dir = product_dir / "backend"

    if has_backend:
        backend_dir.mkdir()

    if strict:
        (backend_dir / "facade").mkdir(parents=True, exist_ok=True)
        (backend_dir / "facade" / "contracts.py").write_text("")
        (backend_dir / "facade" / "api.py").write_text("def get_thing():\n    pass\n")

    if scripts is not None:
        (product_dir / "package.json").write_text(json.dumps({"scripts": scripts}))

    if test_files:
        for tf in test_files:
            p = backend_dir / tf
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text("")

    if extra_dirs:
        for d in extra_dirs:
            (product_dir / d).mkdir(parents=True, exist_ok=True)

    return CheckContext(
        name="my_product",
        product_dir=product_dir,
        backend_dir=backend_dir,
        has_facade_contracts=strict,
        structure={},
        detailed=False,
    )


def _write_facade_product(
    tmp_path: Path,
    *,
    name: str = "my_product",
    facade_files: dict[str, str] | None = None,
    sources: dict[str, str] | None = None,
    turbo_inputs: list[str] | None = None,
) -> tuple[Path, Path]:
    """Build a product with a facade/ package plus arbitrary internal source files.

    `facade_files` are written under backend/facade/; `sources` are backend-relative paths
    (parents created), used both for the modules a facade re-exports from and for making a
    garage directory exist. Returns (product_dir, backend_dir)."""
    product_dir = tmp_path / name
    backend_dir = product_dir / "backend"
    facade = backend_dir / "facade"
    facade.mkdir(parents=True)
    (facade / "contracts.py").write_text("")
    for fname, content in (facade_files or {}).items():
        (facade / fname).parent.mkdir(parents=True, exist_ok=True)
        (facade / fname).write_text(content)
    for rel, content in (sources or {}).items():
        path = backend_dir / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content)
    if turbo_inputs is not None:
        (product_dir / "turbo.json").write_text(
            json.dumps({"tasks": {"backend:contract-check": {"inputs": turbo_inputs}}})
        )
    return product_dir, backend_dir


check = PackageJsonScriptsCheck()


# ---------------------------------------------------------------------------
# Unit tests for helpers
# ---------------------------------------------------------------------------


class TestParseHelpers:
    @pytest.mark.parametrize(
        "script, expected",
        [
            ("pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short", ["backend/tests"]),
            ("pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short", ["backend/"]),
            (
                "pytest -c ../../pytest.ini --rootdir ../.. backend/ stats/tests -v --tb=short",
                ["backend/", "stats/tests"],
            ),
            ("pytest backend/test_max_tools.py", ["backend/test_max_tools.py"]),
            ("echo 'No backend tests'", []),
            ("pytest -v", []),
            ("pytest -c ../../pytest.ini --rootdir ../.. -k 'not slow' backend/tests", ["backend/tests"]),
        ],
    )
    def test_parse_pytest_paths(self, script: str, expected: list[str]) -> None:
        assert _parse_pytest_paths(script) == expected

    @pytest.mark.parametrize(
        "script, expected",
        [
            ("echo 'No backend tests'", True),
            ("echo skip", True),
            ("true", True),
            ("exit 0", True),
            (":", True),
            ("pytest backend/tests", False),
            ("pytest -v", False),
        ],
    )
    def test_is_noop_script(self, script: str, expected: bool) -> None:
        assert _is_noop_script(script) == expected

    def test_has_test_files_true(self, tmp_path: Path) -> None:
        (tmp_path / "test_foo.py").write_text("")
        assert _has_test_files(tmp_path) is True

    def test_has_test_files_nested(self, tmp_path: Path) -> None:
        (tmp_path / "tests").mkdir()
        (tmp_path / "tests" / "test_bar.py").write_text("")
        assert _has_test_files(tmp_path) is True

    def test_has_test_files_suffix_convention(self, tmp_path: Path) -> None:
        (tmp_path / "foo_test.py").write_text("")
        assert _has_test_files(tmp_path) is True

    def test_has_test_files_false(self, tmp_path: Path) -> None:
        (tmp_path / "models.py").write_text("")
        assert _has_test_files(tmp_path) is False

    def test_has_test_files_empty_dir(self, tmp_path: Path) -> None:
        assert _has_test_files(tmp_path) is False


# ---------------------------------------------------------------------------
# Presence checks
# ---------------------------------------------------------------------------


class TestPresenceChecks:
    def test_skip_when_no_backend_dir(self, tmp_path: Path) -> None:
        ctx = _make_product(tmp_path, has_backend=False)
        result = check.run(ctx)
        assert result.skip is True

    def test_backend_test_required_when_backend_exists(self, tmp_path: Path) -> None:
        ctx = _make_product(tmp_path, scripts={})
        result = check.run(ctx)
        assert any("missing 'backend:test'" in i for i in result.issues)

    def test_backend_test_present_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert not result.issues

    def test_contract_check_required_for_strict(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            strict=True,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert any("missing 'backend:contract-check'" in i for i in result.issues)

    def test_contract_check_present_for_strict_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
                "backend:contract-check": "echo 'Contract files unchanged'",
            },
            strict=True,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert not result.issues

    def test_invalid_json_returns_issue(self, tmp_path: Path) -> None:
        ctx = _make_product(tmp_path, has_backend=True)
        (ctx.product_dir / "package.json").write_text("{invalid json")
        result = check.run(ctx)
        assert any("not valid JSON" in i for i in result.issues)


# ---------------------------------------------------------------------------
# Absence checks
# ---------------------------------------------------------------------------


class TestAbsenceChecks:
    def test_contract_check_forbidden_for_lenient(self, tmp_path: Path) -> None:
        """Non-isolated product with contract-check causes turbo-discover misclassification."""
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
                "backend:contract-check": "echo 'Contract files unchanged'",
            },
            strict=False,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert result.issues
        assert any("turbo-discover" in i for i in result.issues)

    def test_no_contract_check_for_lenient_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            strict=False,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert not result.issues

    def test_contract_check_forbidden_with_deferred_presentation_entries(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """An isolated product still owing presentation-wave work can't opt into the skip."""
        import hogli_commands.product.isolation as isolation_module

        monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: ["e1", "e2"])
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
                "backend:contract-check": "echo 'Contract files unchanged'",
            },
            strict=True,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert any("presentation-wave ignore_imports" in i for i in result.issues)
        # and it must not nag the same product to *add* the script it can't have yet
        assert not any("missing 'backend:contract-check'" in i for i in result.issues)


# ---------------------------------------------------------------------------
# Isolation chain: earned-but-not-turned-on enforcement
# ---------------------------------------------------------------------------


_NARROWED_TURBO = {
    "extends": ["//"],
    "tasks": {
        "backend:contract-check": {
            "inputs": ["backend/facade/**", "backend/presentation/**", "backend/migrations/**"],
            "outputs": [],
            "cache": True,
        }
    },
}

_NARROWED_TURBO_WITH_ROUTES = {
    "extends": ["//"],
    "tasks": {
        "backend:contract-check": {
            "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py", "backend/migrations/**"],
            "outputs": [],
            "cache": True,
        }
    },
}

_NARROWED_TURBO_WITH_CONSUMERS = {
    "extends": ["//"],
    "tasks": {
        "backend:contract-check": {
            "inputs": [
                "backend/facade/**",
                "backend/presentation/**",
                "backend/webhook_consumers.py",
                "backend/migrations/**",
            ],
            "outputs": [],
            "cache": True,
        }
    },
}


def _narrowed_turbo(inputs: list[str]) -> dict:
    """A turbo.json body whose backend:contract-check watches exactly `inputs`."""
    return {
        "extends": ["//"],
        "tasks": {"backend:contract-check": {"inputs": inputs, "outputs": [], "cache": True}},
    }


chain_check = IsolationChainCheck()


_WITH_SCRIPT = {
    "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
    "backend:contract-check": "echo 'Contract files unchanged'",
}


def _seal_externally(monkeypatch: pytest.MonkeyPatch) -> None:
    # The tmp fixture product isn't declared in the repo's real tach.toml/pyproject.toml,
    # so force compute_isolation_status to see an externally sealed, internally clean product.
    import hogli_commands.product.isolation as isolation_module

    monkeypatch.setattr(isolation_module, "has_tach_interface", lambda *_a, **_k: True)
    monkeypatch.setattr(isolation_module, "has_legacy_interface_leaks", lambda *_a, **_k: False)
    monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: [])


class TestIsolationChainTurnOn:
    def test_eligible_with_script_but_no_narrowed_turbo_fails(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        result = chain_check.run(ctx)
        assert any("inert" in i for i in result.issues)
        assert result.file == "products/my_product/turbo.json"

    def test_eligible_with_narrowed_turbo_passes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        assert not result.issues

    def test_eligible_without_script_is_not_nagged_to_narrow_turbo(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # Eligible + sealed but the contract-check script isn't added yet: PackageJsonScriptsCheck
        # owns nagging for the script, so IsolationChainCheck must not raise the turn-on issue
        # (which would falsely claim the product "carries 'backend:contract-check'").
        _seal_externally(monkeypatch)
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            strict=True,
        )
        result = chain_check.run(ctx)
        assert not any("inert" in i for i in result.issues)

    def test_not_externally_sealed_does_not_demand_turbo(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        # Without the tach interface the product isn't externally sealed — TachCheck owns that
        # failure, so the chain check must not pile on a turbo-narrowing demand.
        import hogli_commands.product.isolation as isolation_module

        monkeypatch.setattr(isolation_module, "has_tach_interface", lambda *_a, **_k: False)
        monkeypatch.setattr(isolation_module, "has_legacy_interface_leaks", lambda *_a, **_k: False)
        monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: [])
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        result = chain_check.run(ctx)
        assert not any("inert" in i for i in result.issues)


class TestHasRealFacade:
    @pytest.mark.parametrize(
        "facade_files, expected_names",
        [
            pytest.param({"api.py": "def list_items() -> list[int]:\n    return []\n"}, ["list_items"], id="api_py"),
            pytest.param(
                {
                    "api.py": "from .writes import create_item as create_item\n",
                    "writes.py": "def create_item() -> None:\n    pass\n",
                },
                ["create_item"],
                id="submodule_with_reexport_only_api",
            ),
            pytest.param(
                {"nested/reads.py": "def get_item() -> None:\n    pass\n"}, ["get_item"], id="nested_submodule"
            ),
            pytest.param({"api.py": "from .writes import create_item\n"}, [], id="reexport_only"),
            pytest.param(
                {"enums.py": "def label() -> str:\n    return ''\n", "testing.py": "def fake() -> None:\n    pass\n"},
                [],
                id="only_contracts_enums_testing",
            ),
            pytest.param(
                {"contracts/widgets.py": "def build_widget() -> None:\n    pass\n"}, [], id="contracts_package"
            ),
            pytest.param({"test_api.py": "def test_it() -> None:\n    pass\n"}, [], id="test_module_ignored"),
        ],
    )
    def test_functions_in_any_facade_module(
        self, tmp_path: Path, facade_files: dict[str, str], expected_names: list[str]
    ) -> None:
        _, backend_dir = _write_facade_product(tmp_path, facade_files=facade_files)

        assert facade_function_names(backend_dir) == expected_names
        assert has_real_facade(backend_dir) is bool(expected_names)

    @pytest.mark.parametrize(
        "api_source",
        [
            pytest.param("from ..logic import run as run\n", id="relative_logic_reexport"),
            pytest.param("from products.my_product.backend.logic import run as run\n", id="absolute_logic_reexport"),
            pytest.param(
                "from products.my_product.backend.facade_legacy import run as run\n", id="facade_prefix_is_not_facade"
            ),
        ],
    )
    def test_logic_reexport_api_is_a_shim_despite_sibling_helpers(self, tmp_path: Path, api_source: str) -> None:
        _, backend_dir = _write_facade_product(
            tmp_path,
            facade_files={"api.py": api_source, "activity.py": "def model_activity() -> None:\n    pass\n"},
            sources={"logic.py": "def run() -> None:\n    pass\n"},
        )

        assert has_real_facade(backend_dir) is False

    def test_type_checking_import_does_not_make_a_shim(self, tmp_path: Path) -> None:
        api_source = (
            "from typing import TYPE_CHECKING\n"
            "if TYPE_CHECKING:\n"
            "    from ..logic import Thing\n"
            "from .reads import get_thing as get_thing\n"
        )
        _, backend_dir = _write_facade_product(
            tmp_path,
            facade_files={"api.py": api_source, "reads.py": "def get_thing() -> None:\n    pass\n"},
        )

        assert has_real_facade(backend_dir) is True


class TestIsolationRung:
    @pytest.mark.parametrize(
        "strict, real_facade, tach_interface, skip_configured, expected",
        [
            pytest.param(False, False, False, False, IsolationRung.LENIENT, id="no_contracts"),
            pytest.param(True, True, False, False, IsolationRung.STRICT, id="contracts_without_tach_interface"),
            pytest.param(True, False, True, False, IsolationRung.STRICT, id="empty_facade_is_not_sealed"),
            pytest.param(True, True, True, False, IsolationRung.SEALED, id="sealed_without_test_skip"),
            pytest.param(True, True, False, True, IsolationRung.STRICT, id="test_skip_without_seals_is_not_isolated"),
            pytest.param(True, True, True, True, IsolationRung.ISOLATED, id="sealed_with_test_skip"),
        ],
    )
    def test_rung(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
        strict: bool,
        real_facade: bool,
        tach_interface: bool,
        skip_configured: bool,
        expected: IsolationRung,
    ) -> None:
        monkeypatch.setattr(isolation_module, "has_tach_interface", lambda *_a, **_k: tach_interface)
        monkeypatch.setattr(isolation_module, "has_legacy_interface_leaks", lambda *_a, **_k: False)
        monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: [])
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=strict)
        if strict and not real_facade:
            (ctx.backend_dir / "facade" / "api.py").write_text("")
        if skip_configured:
            (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        assert ctx.isolation_status().rung == expected


_WIRING_FACADE = "from ..temporal.flows import Handed\n\n__all__ = ['Handed']\n"
_WIRING_SOURCES: dict[str, dict[str, str]] = {
    "decorated_workflow": {
        "temporal/flows.py": "from temporalio import workflow\n\n\n@workflow.defn\nclass Handed:\n    pass\n",
    },
    "approved_base_through_product_class": {
        "temporal/base.py": "from posthog.hogql_queries.query_runner import QueryRunner\n\n\nclass Base(QueryRunner):\n    pass\n",
        "temporal/flows.py": "from .base import Base\n\n\nclass Handed(Base):\n    pass\n",
    },
    "approved_library_base": {
        "temporal/flows.py": "from temporalio.worker import Interceptor\n\n\nclass Handed(Interceptor):\n    pass\n",
    },
    "plain_client": {"temporal/flows.py": "class Handed:\n    pass\n"},
    "unreadable_base": {"temporal/flows.py": "class Handed(Mystery):\n    pass\n"},
    "decorator_on_the_base_only": {
        "temporal/base.py": "from temporalio import workflow\n\n\n@workflow.defn\nclass Base:\n    pass\n",
        "temporal/flows.py": "from .base import Base\n\n\nclass Handed(Base):\n    pass\n",
    },
    "import_shadowed_by_a_local_class": {
        "temporal/flows.py": (
            "from posthog.hogql_queries.query_runner import QueryRunner\n\n\nclass QueryRunner:\n    pass\n\n\n"
            "class Handed(QueryRunner):\n    pass\n"
        ),
    },
    "import_rebound_by_an_assignment": {
        "temporal/flows.py": (
            "from posthog.hogql_queries.query_runner import QueryRunner\n\nQueryRunner = object\n\n\n"
            "class Handed(QueryRunner):\n    pass\n"
        ),
    },
    "collection_of_classes": {"temporal/flows.py": "class Plain:\n    pass\n\n\nHanded = [Plain]\n"},
    "concatenated_collections": {
        "temporal/flows.py": "from .impl import FLOWS as IMPL_FLOWS\n\n\nclass Plain:\n    pass\n\n\nHanded = [Plain] + IMPL_FLOWS\n",
        "temporal/impl.py": "class Other:\n    pass\n\n\nFLOWS = [Other]\n",
    },
    "starred_collection": {
        "temporal/flows.py": "from .impl import FLOWS\n\n\nHanded = [*FLOWS]\n",
        "temporal/impl.py": "class Other:\n    pass\n\n\nFLOWS = [Other]\n",
    },
    "reassigned_collection": {
        "temporal/flows.py": "class Plain:\n    pass\n\n\nHanded = []\nHanded = [Plain]\n",
    },
    "absolute_reexport": {
        "temporal/flows.py": "from products.my_product.backend.temporal.impl import Handed\n",
        "temporal/impl.py": "class Handed:\n    pass\n",
    },
    "class_alias": {"temporal/flows.py": "class Plain:\n    pass\n\n\nHanded = Plain\n"},
    "approved_class_alias": {
        "temporal/flows.py": "from temporalio.worker import Interceptor\n\n\nclass Plain(Interceptor):\n    pass\n\n\nHanded = Plain\n",
    },
    "mutated_collection": {
        "temporal/flows.py": (
            "from temporalio import workflow\n\n\n@workflow.defn\nclass Approved:\n    pass\n\n\n"
            "class Plain:\n    pass\n\n\nclass Other:\n    pass\n\n\n"
            "Handed = [Approved]\nHanded.append(Plain)\nHanded += [Other]\n"
        ),
    },
}


class TestWiringInterfaces:
    @pytest.mark.parametrize(
        "case, expected",
        [
            ("decorated_workflow", set()),
            ("approved_base_through_product_class", set()),
            ("approved_library_base", set()),
            ("plain_client", {("Handed", "unapproved")}),
            ("unreadable_base", {("Handed", "unresolved")}),
            ("decorator_on_the_base_only", {("Handed", "unapproved")}),
            ("import_shadowed_by_a_local_class", {("Handed", "unresolved")}),
            ("import_rebound_by_an_assignment", {("Handed", "unresolved")}),
            ("collection_of_classes", {("Plain", "unapproved")}),
            ("concatenated_collections", {("Plain", "unapproved"), ("Other", "unapproved")}),
            ("starred_collection", {("Other", "unapproved")}),
            ("reassigned_collection", {("Plain", "unapproved")}),
            ("absolute_reexport", {("Handed", "unapproved")}),
            ("class_alias", {("Handed", "unapproved")}),
            ("approved_class_alias", set()),
            ("mutated_collection", {("Handed", "unresolved")}),
        ],
    )
    def test_scan_reads_the_class_not_the_folder(
        self, tmp_path: Path, case: str, expected: set[tuple[str, str]]
    ) -> None:
        _, backend = _write_facade_product(
            tmp_path, facade_files={"wiring.py": _WIRING_FACADE}, sources=_WIRING_SOURCES[case]
        )
        assert {(f.class_name, str(f.verdict)) for f in facade_unapproved_wiring(backend, "my_product")} == expected

    def test_same_named_classes_keep_their_exported_names(self, tmp_path: Path) -> None:
        facade = "from ..temporal.a import Worker as AWorker\nfrom ..temporal.b import Worker\n\n__all__ = ['AWorker', 'Worker']\n"
        sources = {"temporal/a.py": "class Worker:\n    pass\n", "temporal/b.py": "class Worker:\n    pass\n"}
        _, backend = _write_facade_product(tmp_path, facade_files={"wiring.py": facade}, sources=sources)
        assert {f.class_name for f in facade_unapproved_wiring(backend, "my_product")} == {"AWorker", "Worker"}

    @pytest.mark.parametrize(
        "isolated, recorded, blocks",
        [
            pytest.param(False, False, False, id="information_below_isolated"),
            pytest.param(True, False, True, id="isolated_blocks_an_unrecorded_class"),
            pytest.param(True, True, False, id="isolated_passes_a_grandfathered_row"),
        ],
    )
    def test_only_isolated_products_are_held_to_it(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, isolated: bool, recorded: bool, blocks: bool
    ) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "facade" / "wiring.py").write_text(_WIRING_FACADE)
        (ctx.backend_dir / "temporal").mkdir()
        (ctx.backend_dir / "temporal" / "flows.py").write_text(_WIRING_SOURCES["plain_client"]["temporal/flows.py"])
        if isolated:
            (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        row = "my_product.Handed products.my_product.backend.facade.wiring facade-wiring 1"
        monkeypatch.setattr(checks_module, "recorded_facade_shape_rows", lambda _name: {row} if recorded else set())
        assert bool(WiringInterfaceCheck().run(ctx).issues) == blocks

    def test_a_sealed_product_is_not_steered_into_isolation_it_cannot_pass(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "facade" / "wiring.py").write_text(_WIRING_FACADE)
        (ctx.backend_dir / "temporal").mkdir()
        (ctx.backend_dir / "temporal" / "flows.py").write_text(_WIRING_SOURCES["plain_client"]["temporal/flows.py"])
        assert not any("inert" in issue for issue in chain_check.run(ctx).issues)


class TestIsolationChainRoutes:
    def test_narrowed_with_routes_not_in_inputs_fails(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "routes.py").write_text("")
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        assert any("routes.py" in i for i in result.issues)
        assert result.file == "products/my_product/turbo.json"

    def test_narrowed_with_routes_in_inputs_passes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "routes.py").write_text("")
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO_WITH_ROUTES))
        result = chain_check.run(ctx)
        assert not result.issues

    def test_narrowed_with_routes_package_dir_not_in_inputs_fails(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # routes/ as a package directory (not a routes.py file) is the other form has_routes_module
        # accepts — it must be demanded in the inputs the same way.
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "routes").mkdir()
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        # the message must point at the package glob, not backend/routes.py
        assert any("backend/routes/**" in i for i in result.issues)

    def test_narrowed_without_routes_module_is_not_demanded(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # No routes.py at all — nothing to watch, so the routes demand must not fire.
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        assert not any("routes.py" in i for i in result.issues)

    def test_unnarrowed_with_routes_is_not_demanded(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        # Not narrowed (no turbo.json) — contract-check still watches all of backend/, so routes.py
        # is already covered and the routes demand must not fire.
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "routes.py").write_text("")
        result = chain_check.run(ctx)
        assert not any("routes.py" in i for i in result.issues)


class TestIsolationChainWebhookConsumers:
    @pytest.mark.parametrize(
        "turbo, reported",
        [
            pytest.param(_NARROWED_TURBO, True, id="narrowed_without_the_consumer_input"),
            pytest.param(_NARROWED_TURBO_WITH_CONSUMERS, False, id="narrowed_with_the_consumer_input"),
            pytest.param(None, False, id="unnarrowed_still_watches_all_of_backend"),
            # a negation that covers the module leaves it out of the task hash, so listing it and
            # then excluding it is still an unwatched consumer
            pytest.param(
                _narrowed_turbo(
                    [
                        "backend/facade/**",
                        "backend/webhook_consumers.py",
                        "backend/migrations/**",
                        "!backend/webhook_consumers.py",
                    ]
                ),
                True,
                id="negation_cancels_the_consumer_input",
            ),
            pytest.param(
                _narrowed_turbo(
                    [
                        "backend/facade/**",
                        "backend/webhook_consumers.py",
                        "backend/migrations/**",
                        "!backend/**",
                    ]
                ),
                True,
                id="negation_glob_cancels_the_consumer_input",
            ),
            # a negation whose shape the matcher can't evaluate is read as reaching the module
            pytest.param(
                _narrowed_turbo(
                    [
                        "backend/facade/**",
                        "backend/webhook_consumers.py",
                        "backend/migrations/**",
                        "!backend/**/webhook_consumers.py",
                    ]
                ),
                True,
                id="deep_negation_glob_cancels_the_consumer_input",
            ),
            pytest.param(
                _narrowed_turbo(
                    [
                        "backend/facade/**",
                        "backend/webhook_consumers.py",
                        "backend/migrations/**",
                        "!backend/webhook_*.py",
                    ]
                ),
                True,
                id="stem_negation_glob_cancels_the_consumer_input",
            ),
            pytest.param(
                _narrowed_turbo(
                    [
                        "backend/facade/**",
                        "backend/webhook_consumers.py",
                        "backend/migrations/**",
                        "!backend/models/**",
                    ]
                ),
                False,
                id="negation_of_an_unrelated_path_leaves_the_consumer_watched",
            ),
        ],
    )
    def test_unwatched_consumer_module_is_reported_when_not_eligible(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, turbo: dict | None, reported: bool
    ) -> None:
        # No tach interface, so the product is not externally sealed and not eligible for isolated
        # tests — needs_turn_on stays silent. An unwatched consumer module is also what makes
        # has_narrowed False, so every other turbo-omission issue is silent too. The consumer
        # omission must still be reported, or the narrowing that skips the Django suite on a
        # consumer change goes unmentioned by the whole check.
        import hogli_commands.product.isolation as isolation_module

        monkeypatch.setattr(isolation_module, "has_tach_interface", lambda *_a, **_k: False)
        monkeypatch.setattr(isolation_module, "has_legacy_interface_leaks", lambda *_a, **_k: False)
        monkeypatch.setattr(isolation_module, "presentation_bypass_entries", lambda *_a, **_k: [])
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "webhook_consumers.py").write_text("")
        if turbo is not None:
            (ctx.product_dir / "turbo.json").write_text(json.dumps(turbo))

        result = chain_check.run(ctx)

        assert any("webhook_consumers.py" in i for i in result.issues) is reported
        assert not any("inert" in i for i in result.issues)
        if reported:
            assert result.file == "products/my_product/turbo.json"


class TestNarrowedTurboDetection:
    @pytest.mark.parametrize(
        "inputs, expected",
        [
            (["backend/facade/**", "backend/presentation/**"], True),
            (["backend/facade/**", "backend/presentation/**", "backend/routes.py"], True),
            (["backend/presentation/**"], True),
            (["backend/facade/**", "!backend/facade/**/__pycache__/**"], True),
            # a broad glob alongside a surface glob keeps the skip inert — must not count as narrowed
            (["backend/**", "backend/facade/**"], False),
            (["backend/**"], False),
            (["**/*.py"], False),
            ([], False),
            # near-misses must not pass as surface (anchored on the path separator)
            (["backend/facade_legacy/**"], False),
            (["backend/routesmap/**"], False),
            # a routes input whose path merely contains "presentation" is not a facade/presentation surface
            (["backend/routes/presentation_router.py"], False),
        ],
    )
    def test_has_narrowed_turbo_inputs(self, tmp_path: Path, inputs: list[str], expected: bool) -> None:
        (tmp_path / "turbo.json").write_text(json.dumps({"tasks": {"backend:contract-check": {"inputs": inputs}}}))
        assert has_narrowed_turbo_inputs(tmp_path) is expected


class TestRoutesInTurboInputs:
    @pytest.mark.parametrize(
        "inputs, expected",
        [
            (["backend/facade/**", "backend/routes.py"], True),
            (["backend/routes/**"], True),
            (["backend/facade/**", "backend/presentation/**"], False),
            # 'routes' substring in an unrelated glob must NOT count as watching the routes module
            (["backend/presentation/routes_views.py"], False),
            (["backend/logic/routes_helpers/**"], False),
            # a negated routes exclusion must NOT count as watched
            (["backend/facade/**", "!backend/routes.py"], False),
        ],
    )
    def test_routes_in_turbo_inputs(self, tmp_path: Path, inputs: list[str], expected: bool) -> None:
        (tmp_path / "turbo.json").write_text(json.dumps({"tasks": {"backend:contract-check": {"inputs": inputs}}}))
        assert routes_in_turbo_inputs(tmp_path) is expected


# ---------------------------------------------------------------------------
# Content checks: pytest path validation
# ---------------------------------------------------------------------------


class TestPytestPathValidation:
    def test_valid_path_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"},
            test_files=["tests/test_foo.py"],
        )
        result = check.run(ctx)
        assert not result.issues

    def test_nonexistent_path_fails(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/typo_tests -v --tb=short"},
        )
        result = check.run(ctx)
        assert any("does not exist" in i for i in result.issues)
        assert any("typo_tests" in i for i in result.issues)

    def test_multiple_paths_one_missing(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ stats/tests -v --tb=short"},
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        # backend/ exists, stats/tests does not
        assert any("stats/tests" in i for i in result.issues)
        assert not any("backend/" in i for i in result.issues)

    def test_file_path_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test_max_tools.py -v --tb=short"
            },
            test_files=["test_max_tools.py"],
        )
        result = check.run(ctx)
        assert not result.issues


# ---------------------------------------------------------------------------
# Content checks: no-op detection
# ---------------------------------------------------------------------------


class TestNoopDetection:
    def test_noop_without_test_files_passes(self, tmp_path: Path) -> None:
        """echo 'No backend tests' is fine when there are genuinely no test files."""
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "echo 'No backend tests'"},
        )
        result = check.run(ctx)
        assert not result.issues

    def test_noop_with_test_files_fails(self, tmp_path: Path) -> None:
        """echo 'No backend tests' is wrong when test files actually exist."""
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "echo 'No backend tests'"},
            test_files=["tests/test_something.py"],
        )
        result = check.run(ctx)
        assert any("no-op" in i for i in result.issues)
        assert any("test files" in i for i in result.issues)


# ---------------------------------------------------------------------------
# Content checks: || true detection
# ---------------------------------------------------------------------------


class TestPipeTrueDetection:
    def test_pipe_true_fails(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short || true"},
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert any("|| true" in i for i in result.issues)
        assert any("swallows" in i for i in result.issues)

    def test_pipe_exit_0_fails(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short || exit 0"},
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert any("|| exit 0" in i for i in result.issues)
        assert any("swallows" in i for i in result.issues)

    def test_no_pipe_true_passes(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert not result.issues


# ---------------------------------------------------------------------------
# Combined scenario: isolated product, all good
# ---------------------------------------------------------------------------


class TestCombinedScenarios:
    def test_fully_valid_isolated_product(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
                "backend:contract-check": "echo 'Contract files unchanged'",
            },
            strict=True,
            test_files=["tests/test_api.py"],
        )
        result = check.run(ctx)
        assert not result.issues
        assert any("✓ ok" in line for line in result.lines)

    def test_fully_valid_legacy_product(self, tmp_path: Path) -> None:
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            strict=False,
            extra_dirs=["backend"],
        )
        result = check.run(ctx)
        assert not result.issues
        assert any("✓ ok" in line for line in result.lines)

    def test_multiple_issues_reported(self, tmp_path: Path) -> None:
        """A product with several problems reports all of them."""
        ctx = _make_product(
            tmp_path,
            scripts={
                "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/nonexistent -v --tb=short || true",
                "backend:contract-check": "echo 'Contract files unchanged'",
            },
            strict=False,
        )
        result = check.run(ctx)
        # Should report: contract-check forbidden, || true, nonexistent path
        assert len(result.issues) >= 3


# ---------------------------------------------------------------------------
# has_legacy_interface_leaks
# ---------------------------------------------------------------------------

_TACH_SAMPLE = """\
[[modules]]
path = "products.visual_review"
depends_on = ["posthog"]
layer = "modules"

[[modules]]
path = "products.experiments"
depends_on = ["ee", "posthog"]
layer = "modules"

[[modules]]
path = "products.mcp_store"
depends_on = ["ee", "posthog"]
layer = "modules"

# Facade + views: canonical public surface
[[interfaces]]
expose = [
    "backend\\.facade.*",
    "backend\\.presentation\\.views.*",
]
from = [
    "products\\.(experiments|mcp_store|visual_review)",
]

# Legacy leaks — experiments
[[interfaces]]
expose = [
    "backend\\.models.*",
    "stats\\..*",
]
from = [
    "products.experiments",
]

# Legacy leaks — mcp_store
[[interfaces]]
expose = [
    "backend\\.models.*",
    "backend\\.oauth.*",
]
from = [
    "products.mcp_store",
]
"""


class TestLegacyInterfaceLeaks:
    @pytest.mark.parametrize(
        "module_path, expected",
        [
            ("products.visual_review", False),
            ("products.experiments", True),
            ("products.mcp_store", True),
            ("products.nonexistent", False),
        ],
    )
    def test_detection(self, module_path: str, expected: bool) -> None:
        assert has_legacy_interface_leaks(_TACH_SAMPLE, module_path) == expected

    def test_empty_tach(self) -> None:
        assert has_legacy_interface_leaks("", "products.anything") is False

    def test_only_facade_block(self) -> None:
        tach = """\
[[interfaces]]
expose = [
    "backend\\.facade.*",
    "backend\\.presentation\\.views.*",
]
from = [
    "products.clean_product",
]
"""
        assert has_legacy_interface_leaks(tach, "products.clean_product") is False

    def test_regex_from_does_not_false_positive(self) -> None:
        assert has_legacy_interface_leaks(_TACH_SAMPLE, "products.mcp") is False


# ---------------------------------------------------------------------------
# has_tach_interface
# ---------------------------------------------------------------------------

_TACH_INTERFACE_MENTIONS = r"""
[[modules]]
path = "products.review_hog"
depends_on = [
    # Facade-only (enforced by stamphog's [[interfaces]] block)
    "products.stamphog",
]
layer = "modules"

[[modules]]
path = "products.field_notes"
depends_on = ["posthog"]
layer = "modules"

[[interfaces]]
expose = [
    "backend\\.models\\.Task",
]
from = [
    "products.tasks",
]

[[interfaces]]
expose = [
    "backend\\.facade.*",
]
from = [
    "products\\.(stamphog|visual_review)",
]
"""


class TestHasTachInterface:
    @pytest.mark.parametrize(
        "name, expected",
        [
            pytest.param("review_hog", False, id="comment_mentions_interfaces"),
            pytest.param("field_notes", False, id="next_product_interfaces_block_follows"),
            pytest.param("tasks", True, id="named_in_from"),
            pytest.param("stamphog", True, id="named_in_from_regex"),
        ],
    )
    def test_detection(self, name: str, expected: bool) -> None:
        assert has_tach_interface(name, _TACH_INTERFACE_MENTIONS) is expected


# ---------------------------------------------------------------------------
# permanent-interface marker
# ---------------------------------------------------------------------------

_TACH_PERMANENT = """\
# Facade + views: canonical public surface
[[interfaces]]
expose = [
    "backend\\.facade.*",
    "backend\\.presentation\\.views.*",
]
from = [
    "products\\.(error_tracking|experiments)",
]

# isolation:permanent-interface
# error_tracking exposes its ClickHouse DDL to core's schema registry + frozen migrations.
[[interfaces]]
expose = [
    "backend\\.embedding.*",
    "backend\\.indexed_embedding.*",
    "backend\\.sql.*",
]
from = [
    "products.error_tracking",
]

# Legacy leaks — experiments (unmarked, a real leak)
[[interfaces]]
expose = [
    "backend\\.models.*",
]
from = [
    "products.experiments",
]
"""


class TestPermanentInterface:
    def test_marked_block_is_not_a_leak(self) -> None:
        # The DDL exposure carries the marker, so it must not hold the external seal open.
        assert has_legacy_interface_leaks(_TACH_PERMANENT, "products.error_tracking") is False

    def test_unmarked_block_is_still_a_leak(self) -> None:
        # The experiments block exposes internals with no marker — a genuine leak.
        assert has_legacy_interface_leaks(_TACH_PERMANENT, "products.experiments") is True

    def test_marker_does_not_leak_across_blocks(self) -> None:
        # The marker sits above the error_tracking block; the previous block's body separates
        # it from the facade block, so the facade block is not mistaken for permanent (and the
        # experiments leak below stays a leak — already covered above).
        assert permanent_interface_modules(_TACH_PERMANENT, "products.experiments") == set()

    def test_exposed_modules_returned(self) -> None:
        assert permanent_interface_modules(_TACH_PERMANENT, "products.error_tracking") == {
            "backend.embedding",
            "backend.indexed_embedding",
            "backend.sql",
        }

    def test_unmarked_exposure_is_not_permanent(self) -> None:
        assert permanent_interface_modules(_TACH_SAMPLE, "products.experiments") == set()

    @pytest.mark.parametrize(
        "inputs, expected",
        [
            # the three DDL modules + facade satisfy the extended-surface narrowing
            (["backend/facade/**", "backend/sql.py", "backend/embedding.py", "backend/indexed_embedding.py"], True),
            # facade alone still narrows (permanent modules are allowed, not required, here)
            (["backend/facade/**"], True),
            # a broad glob alongside still keeps the skip inert
            (["backend/**", "backend/sql.py"], False),
            # a permanent module without any facade/presentation glob is not a real surface
            (["backend/sql.py"], False),
        ],
    )
    def test_permanent_modules_count_as_extended_surface(
        self, tmp_path: Path, inputs: list[str], expected: bool
    ) -> None:
        (tmp_path / "turbo.json").write_text(json.dumps({"tasks": {"backend:contract-check": {"inputs": inputs}}}))
        permanent = frozenset({"backend.sql", "backend.embedding", "backend.indexed_embedding"})
        assert has_narrowed_turbo_inputs(tmp_path, permanent) is expected

    def test_uncovered_permanent_modules_detected(self, tmp_path: Path) -> None:
        (tmp_path / "turbo.json").write_text(
            json.dumps({"tasks": {"backend:contract-check": {"inputs": ["backend/facade/**", "backend/sql.py"]}}})
        )
        permanent = frozenset({"backend.sql", "backend.embedding", "backend.indexed_embedding"})
        assert uncovered_permanent_modules(tmp_path, permanent) == {"backend.embedding", "backend.indexed_embedding"}

    def test_all_permanent_modules_covered(self, tmp_path: Path) -> None:
        (tmp_path / "turbo.json").write_text(
            json.dumps(
                {
                    "tasks": {
                        "backend:contract-check": {
                            "inputs": ["backend/facade/**", "backend/sql.py", "backend/embedding.py"]
                        }
                    }
                }
            )
        )
        assert uncovered_permanent_modules(tmp_path, frozenset({"backend.sql", "backend.embedding"})) == set()


def _make_ddl_repo(tmp_path: Path, *, migration_body: str = "", schema_body: str = "") -> Path:
    migrations = tmp_path / "posthog" / "clickhouse" / "migrations"
    migrations.mkdir(parents=True)
    (migrations / "0001_x.py").write_text(migration_body)
    (tmp_path / "posthog" / "clickhouse" / "schema.py").write_text(schema_body)
    return tmp_path


class TestPermanentInterfaceQualification:
    @pytest.mark.parametrize(
        "migration_body, schema_body, marked, expected",
        [
            # DDL module imported by a frozen migration qualifies.
            ("from products.foo.backend.sql import CREATE_X", "", {"backend.sql"}, set()),
            # A reference from the schema registry alone qualifies too.
            ("", "from products.foo.backend.sql import CREATE_X", {"backend.sql"}, set()),
            # A submodule import still counts as a reference to the root.
            ("from products.foo.backend.sql.tables import CREATE_X", "", {"backend.sql"}, set()),
            # The abuse case: an internal marked permanent with no DDL consumer is flagged.
            ("", "", {"backend.models"}, {"backend.models"}),
            # Word boundary: backend.sql_extra must not qualify backend.sql.
            ("from products.foo.backend.sql_extra import CREATE_X", "", {"backend.sql"}, {"backend.sql"}),
            # Leaf import form counts as a reference.
            ("from products.foo.backend import sql", "", {"backend.sql"}, set()),
            # An unrelated leaf-name token on a later line must not qualify the module.
            ("from products.foo.backend import models\nsql = 1", "", {"backend.sql"}, {"backend.sql"}),
            # A path mentioned only in a comment must not qualify — imports come from the AST.
            ("# depends on products.foo.backend.models\nimport datetime", "", {"backend.models"}, {"backend.models"}),
            # Same for a string literal (e.g. DDL text or a log message naming the module).
            ('TABLE_SQL = "see products.foo.backend.models"', "", {"backend.models"}, {"backend.models"}),
        ],
    )
    def test_qualification(
        self, tmp_path: Path, migration_body: str, schema_body: str, marked: set[str], expected: set[str]
    ) -> None:
        repo_root = _make_ddl_repo(tmp_path, migration_body=migration_body, schema_body=schema_body)
        assert unqualified_permanent_modules("products.foo", frozenset(marked), repo_root=repo_root) == expected

    def test_exempt_product_skips_qualification(self, tmp_path: Path) -> None:
        # warehouse_sources' marker is justified by a non-DDL channel; dropping the exemption
        # would turn product:lint --all red for it.
        repo_root = _make_ddl_repo(tmp_path)
        assert (
            unqualified_permanent_modules(
                "products.warehouse_sources", frozenset({"backend.models"}), repo_root=repo_root
            )
            == set()
        )

    def test_unqualified_exposure_blocks_isolation_chain(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        # A marked module that no migration/schema-registry imports must hard-block, and the issue
        # must point at tach.toml where the bogus marker lives.
        _seal_externally(monkeypatch)
        import hogli_commands.product.isolation as isolation_module

        monkeypatch.setattr(isolation_module, "permanent_interface_modules", lambda *_a, **_k: {"backend.models"})
        # Controlled corpus — don't let the assertion depend on the real repo's migrations.
        monkeypatch.setattr(isolation_module, "_clickhouse_ddl_imports", lambda _root: frozenset())
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        result = chain_check.run(ctx)
        assert any("don't qualify as a permanent interface" in i for i in result.issues)
        assert result.file == "tach.toml"


# ---------------------------------------------------------------------------
# ProductYamlCheck
# ---------------------------------------------------------------------------

yaml_check = ProductYamlCheck()
owners_check = ProductYamlOwnersCheck()


def _make_yaml_ctx(tmp_path: Path, yaml_content: str | None = None) -> CheckContext:
    product_dir = tmp_path / "test_product"
    product_dir.mkdir()
    backend_dir = product_dir / "backend"
    backend_dir.mkdir()
    if yaml_content is not None:
        (product_dir / "product.yaml").write_text(yaml_content)
    return CheckContext(
        name="test_product",
        product_dir=product_dir,
        backend_dir=backend_dir,
        has_facade_contracts=False,
        structure={},
        detailed=False,
    )


class TestProductYamlCheck:
    def test_missing_file(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path)
        result = yaml_check.run(ctx)
        assert any("Missing product.yaml" in i for i in result.issues)

    def test_valid_yaml(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n  - team-foo\n")
        result = yaml_check.run(ctx)
        assert not result.issues

    def test_invalid_yaml(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: [\ninvalid")
        result = yaml_check.run(ctx)
        assert any("invalid YAML" in i for i in result.issues)

    def test_non_dict_yaml(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "- just\n- a\n- list\n")
        result = yaml_check.run(ctx)
        assert any("must be a YAML mapping" in i for i in result.issues)

    def test_missing_name(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "owners:\n  - team-foo\n")
        result = yaml_check.run(ctx)
        assert any("missing 'name'" in i for i in result.issues)

    def test_missing_owners(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\n")
        result = yaml_check.run(ctx)
        assert any("missing 'owners'" in i for i in result.issues)

    def test_owners_must_be_list(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners: team-foo\n")
        result = yaml_check.run(ctx)
        assert any("list of strings" in i for i in result.issues)

    def test_owners_must_be_strings(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n  - 123\n")
        result = yaml_check.run(ctx)
        assert any("list of strings" in i for i in result.issues)

    def test_name_must_be_string(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: 42\nowners:\n  - team-foo\n")
        result = yaml_check.run(ctx)
        assert any("missing 'name'" in i for i in result.issues)

    @pytest.mark.parametrize("value,valid", [("true", True), ("false", True), ("'true'", False), ("yes please", False)])
    def test_sensitive_must_be_boolean(self, tmp_path: Path, value: str, valid: bool) -> None:
        ctx = _make_yaml_ctx(tmp_path, f"name: My product\nowners:\n  - team-foo\nsensitive: {value}\n")
        result = yaml_check.run(ctx)
        assert (not result.issues) is valid, result.issues


class TestProductYamlOwnersCheck:
    def test_skip_when_no_owners(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\n")
        result = owners_check.run(ctx)
        assert result.skip

    def test_skip_when_owners_wrong_type(self, tmp_path: Path) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners: team-foo\n")
        result = owners_check.run(ctx)
        assert result.skip

    def test_invalid_slug_reported(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n  - team-nonexistent\n")
        monkeypatch.setattr(gh_module, "get_team_slugs", lambda: ({"team-real"}, ""))
        result = owners_check.run(ctx)
        assert any("team-nonexistent" in i for i in result.issues)

    def test_valid_slug_passes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n  - team-real\n")
        monkeypatch.setattr(gh_module, "get_team_slugs", lambda: ({"team-real"}, ""))
        result = owners_check.run(ctx)
        assert not result.issues

    def test_gh_unavailable_is_error(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n  - team-foo\n")
        monkeypatch.setattr(gh_module, "get_team_slugs", lambda: (None, "gh CLI not found"))
        result = owners_check.run(ctx)
        assert result.issues
        assert any("gh CLI" in i for i in result.issues)


# ---------------------------------------------------------------------------
# FileFolderConflictsCheck — file vs package twin detection
# ---------------------------------------------------------------------------

# Structure mirrors product_structure.yaml: subdirs (logic/, tasks/, facade/)
# are packages regardless of whether they declare an __init__.py in the
# structure; models can be either a file or folder via can_be_folder.
_CONFLICT_STRUCTURE = {
    "backend_files": {
        "models.py": {"can_be_folder": True},
        "logic/": {"__init__.py": {}},
        "tasks/": {"tasks.py": {}},  # no __init__.py declared — namespace package
        "facade/": {"api.py": {}, "contracts.py": {}},
    },
}

conflict_check = FileFolderConflictsCheck()


def _make_backend(tmp_path: Path, files: list[str]) -> CheckContext:
    """Create a product with the given files/dirs under backend/. Trailing '/' = directory."""
    product_dir = tmp_path / "p"
    backend = product_dir / "backend"
    backend.mkdir(parents=True)
    for f in files:
        target = backend / f.rstrip("/")
        if f.endswith("/"):
            target.mkdir(parents=True, exist_ok=True)
        else:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text("")
    return CheckContext(
        name="p",
        product_dir=product_dir,
        backend_dir=backend,
        has_facade_contracts=False,
        structure=_CONFLICT_STRUCTURE,
        detailed=False,
    )


class TestImportSurfaceCheck:
    """The AST twin of the three import-linter contracts. Its reason to exist is the namespace
    package: grimp cannot see a module under a directory without __init__.py, so a routed
    view there passes the contract vacuously. None of the fixtures below carry a marker."""

    def _ctx(
        self,
        tmp_path: Path,
        files: dict[str, str],
        monkeypatch: pytest.MonkeyPatch,
        ignored=None,
        has_facade_contracts: bool = True,
    ) -> CheckContext:
        ctx = _make_backend(tmp_path, list(files))
        ctx.has_facade_contracts = has_facade_contracts
        for path, content in files.items():
            (ctx.backend_dir / path).write_text(content)
        monkeypatch.setattr(checks_module, "ignored_import_edges", lambda: set(ignored or ()))
        return ctx

    @pytest.mark.parametrize(
        "files, expected",
        [
            pytest.param(
                {"routes.py": "from products.p.backend.presentation.views import V\n", "presentation/views.py": ""},
                0,
                id="routes_from_presentation",
            ),
            pytest.param(
                {"routes.py": "from products.p.backend.services.views import V\n", "services/views.py": ""},
                1,
                id="routes_from_unmarked_package",
            ),
            pytest.param(
                {"routes.py": "import products.p.backend.api as api\n", "api/__init__.py": ""},
                1,
                id="routes_plain_import",
            ),
            pytest.param(
                {"presentation/views.py": "from products.p.backend.facade.api import f\n", "facade/api.py": ""},
                0,
                id="presentation_from_facade",
            ),
            pytest.param(
                {"presentation/views.py": "from products.p.backend.services import thing\n", "services/thing.py": ""},
                1,
                id="presentation_from_unmarked_package",
            ),
            pytest.param(
                {"presentation/views.py": "from products.p.backend import models\n", "models.py": ""},
                1,
                id="presentation_from_backend_root",
            ),
            pytest.param(
                {"presentation/views.py": "from products.other.backend.models import M\n"},
                0,
                id="cross_product_is_tachs_job",
            ),
            pytest.param(
                {"webhook_consumers.py": "from products.p.backend.facade.api import f\n", "facade/api.py": ""},
                0,
                id="webhook_consumers_from_facade",
            ),
            pytest.param(
                {
                    "webhook_consumers.py": "from products.p.backend.services.handlers import h\n",
                    "services/handlers.py": "",
                },
                1,
                id="webhook_consumers_from_unmarked_package",
            ),
            pytest.param(
                {
                    "webhook_consumers.py": "from products.p.backend.facade_legacy.handlers import h\n",
                    "facade_legacy/handlers.py": "",
                },
                1,
                id="webhook_consumers_from_facade_lookalike",
            ),
            # A relative import names the same module as the absolute one, so every surface
            # has to read both shapes alike.
            pytest.param(
                {
                    "webhook_consumers.py": "from .services.handlers import h\n",
                    "services/handlers.py": "",
                },
                1,
                id="webhook_consumers_from_internals_relatively",
            ),
            pytest.param(
                {"webhook_consumers.py": "from . import services\n", "services/__init__.py": ""},
                1,
                id="webhook_consumers_from_internals_bare_relative",
            ),
            pytest.param(
                {"webhook_consumers.py": "from .facade.api import f\n", "facade/api.py": ""},
                0,
                id="webhook_consumers_from_facade_relatively",
            ),
            pytest.param(
                {"presentation/views.py": "from ..services import thing\n", "services/thing.py": ""},
                1,
                id="presentation_from_internals_relatively",
            ),
            pytest.param(
                {"presentation/views.py": "from ..facade.api import f\n", "facade/api.py": ""},
                0,
                id="presentation_from_facade_relatively",
            ),
            pytest.param(
                {"routes.py": "from .presentation.views import V\n", "presentation/views.py": ""},
                0,
                id="routes_from_presentation_relatively",
            ),
            # Climbing out of backend/ leaves this check's tree, so the resolver must not
            # report a module built from the leftover parts.
            pytest.param(
                {"presentation/views.py": "from ....other.backend.models import M\n"},
                0,
                id="relative_import_above_the_product",
            ),
        ],
    )
    def test_surface(
        self, tmp_path: Path, files: dict[str, str], expected: int, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        result = ImportSurfaceCheck().run(self._ctx(tmp_path, files, monkeypatch))
        assert len(result.issues) == expected

    def test_deferral_in_pyproject_is_honored(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        files = {"routes.py": "from products.p.backend.api import V\n", "api/__init__.py": ""}
        edge = "products.p.backend.routes -> products.p.backend.api"
        ctx = self._ctx(tmp_path, files, monkeypatch, ignored={edge})
        assert ImportSurfaceCheck().run(ctx).issues == []

    @pytest.mark.parametrize(
        "files, should_run, expected",
        [
            # The ingress contract holds for any product that registers a consumer, sealed
            # or not.
            pytest.param(
                {
                    "webhook_consumers.py": "from .services.handlers import h\n",
                    "services/handlers.py": "",
                },
                True,
                1,
                id="unsealed_consumer_reaching_internals",
            ),
            pytest.param(
                {"webhook_consumers.py": "from .facade.api import f\n", "facade/api.py": ""},
                True,
                0,
                id="unsealed_consumer_reaching_facade",
            ),
            # The routes and presentation contracts name every product, so an unsealed product
            # without a consumer is held to them too.
            pytest.param(
                {"routes.py": "from .api.views import V\n", "api/views.py": ""},
                True,
                1,
                id="unsealed_routes_from_unmarked_package",
            ),
            pytest.param(
                {
                    "presentation/views.py": "from products.p.backend.summary.read import LIMIT\n",
                    "summary/read.py": "",
                },
                True,
                1,
                id="unsealed_presentation_from_unmarked_package",
            ),
        ],
    )
    def test_unsealed_product(
        self,
        tmp_path: Path,
        files: dict[str, str],
        should_run: bool,
        expected: int,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        ctx = self._ctx(tmp_path, files, monkeypatch, has_facade_contracts=False)
        check = ImportSurfaceCheck()
        assert check.should_run(ctx) is should_run
        assert len(check.run(ctx).issues) == expected


class TestFileFolderConflictsCheck:
    def test_skip_when_no_backend(self, tmp_path: Path) -> None:
        product_dir = tmp_path / "p"
        product_dir.mkdir()
        ctx = CheckContext(
            name="p",
            product_dir=product_dir,
            backend_dir=product_dir / "backend",
            has_facade_contracts=False,
            structure=_CONFLICT_STRUCTURE,
            detailed=False,
        )
        assert conflict_check.run(ctx).skip is True

    @pytest.mark.parametrize(
        "files, expect_conflicts",
        [
            # Pattern A (can_be_folder): models.py only / models/ only — both fine
            (["models.py"], []),
            (["models/"], []),
            (["models.py", "models/"], ["models.py"]),
            # Pattern B (package init): logic.py only / logic/ only — both fine
            (["logic/__init__.py"], []),
            (["logic.py"], []),
            (["logic/"], []),  # half-migrated package without __init__.py
            (["logic.py", "logic/__init__.py"], ["logic.py"]),
            (["logic.py", "logic/"], ["logic.py"]),  # __init__.py absent — still flagged
            # Pattern B also covers other canonical packages — stray tasks.py is a mistake
            (["tasks/__init__.py"], []),
            (["tasks.py", "tasks/__init__.py"], ["tasks.py"]),
            # Namespace-package subdir (no __init__.py declared in structure) — stem still detected
            (["facade/api.py"], []),
            (["facade.py", "facade/api.py"], ["facade.py"]),
            # Multiple conflicts at once
            (["logic.py", "logic/", "models.py", "models/"], ["logic.py", "models.py"]),
        ],
    )
    def test_conflict_detection(self, tmp_path: Path, files: list[str], expect_conflicts: list[str]) -> None:
        ctx = _make_backend(tmp_path, files)
        result = conflict_check.run(ctx)
        if not expect_conflicts:
            assert not result.issues, f"unexpected conflicts: {result.issues}"
            return
        assert len(result.issues) == len(expect_conflicts)
        for stem in expect_conflicts:
            assert any(f"backend/{stem}" in i and f"backend/{stem[:-3]}/" in i for i in result.issues), result.issues


# ---------------------------------------------------------------------------
# validate_facade_alternation — global tach.toml check
# ---------------------------------------------------------------------------


def _mkproduct(products_dir: Path, name: str, *, strict: bool) -> None:
    p = products_dir / name
    (p / "backend").mkdir(parents=True)
    (p / "__init__.py").write_text("")
    (p / "backend" / "__init__.py").write_text("")
    if strict:
        (p / "backend" / "facade").mkdir()
        (p / "backend" / "facade" / "contracts.py").write_text("")


_CANONICAL_BLOCK = """\
[[interfaces]]
expose = [
    "backend\\\\.facade.*",
    "backend\\\\.presentation\\\\.views.*",
]
from = [
    "products\\\\.(alpha|beta)",
]
"""


_LEGACY_ONLY_TACH = """\
[[interfaces]]
expose = ["backend\\\\.models.*"]
from = ["products.alpha"]
"""

# Real tach.toml on disk uses literal `\\.` (two backslashes + dot).
# `_CANONICAL_BLOCK` already encodes that form via escaped backslashes in
# the Python source — `\\\\` in source is two literal backslashes at runtime.
# This row uses a non-alternation single-name `from` so the parametrized
# test additionally exercises that branch of `_names_from_pattern`.
_CANONICAL_SINGLE_NAME_TACH = (
    "[[interfaces]]\n"
    'expose = [\n    "backend\\\\.facade.*",\n    "backend\\\\.presentation\\\\.views.*",\n]\n'
    'from = [\n    "products\\\\.alpha",\n]\n'
)


_FACADE_PLUS_LEGACY_TACH = (
    "[[interfaces]]\n"
    'expose = ["backend\\\\.facade.*"]\n'
    'from = ["products.alpha"]\n'
    "[[interfaces]]\n"
    'expose = ["backend\\\\.models.*"]\n'
    'from = ["products.alpha"]\n'
)


class TestValidateFacadeAlternation:
    @pytest.mark.parametrize(
        "products, tach, expected_substrings",
        [
            # Empty tach — nothing to validate.
            ([], "", []),
            # Only a legacy-leak block — TachCheck handles per-product, this
            # validator stays quiet.
            ([("alpha", True)], _LEGACY_ONLY_TACH, []),
            # Clean alternation: every listed product exists and is isolated.
            ([("alpha", True), ("beta", True)], _CANONICAL_BLOCK, []),
            # Stale entry: product listed but not on disk.
            ([("alpha", True)], _CANONICAL_BLOCK, [("beta", "does not exist")]),
            # Stale entry: product on disk but missing contracts.py.
            (
                [("alpha", True), ("beta", False)],
                _CANONICAL_BLOCK,
                [("beta", "contracts.py")],
            ),
            # On-disk single-name `from` (no alternation) parses.
            ([("alpha", True)], _CANONICAL_SINGLE_NAME_TACH, []),
            # A product still draining legacy leaks may expose its facade without contracts.py.
            ([("alpha", False)], _FACADE_PLUS_LEGACY_TACH, []),
            # Non-listed isolated products are tolerated — having
            # facade/contracts.py is just scaffolding, not a commitment to
            # canonical exposure.
            (
                [("alpha", True), ("beta", True), ("gamma", True)],
                _CANONICAL_BLOCK,
                [],
            ),
        ],
        ids=[
            "empty_tach",
            "legacy_only_block_silent",
            "clean_alternation",
            "stale_entry_missing_on_disk",
            "stale_entry_not_isolated",
            "on_disk_single_name_form_parses",
            "facade_block_with_legacy_leaks_needs_no_contracts",
            "isolated_but_not_in_alternation_is_tolerated",
        ],
    )
    def test_validate(
        self,
        tmp_path: Path,
        products: list[tuple[str, bool]],
        tach: str,
        expected_substrings: list[tuple[str, ...]],
    ) -> None:
        for name, strict in products:
            _mkproduct(tmp_path, name, strict=strict)
        issues = validate_facade_alternation(tach, tmp_path)
        if not expected_substrings:
            assert issues == []
            return
        for substrings in expected_substrings:
            assert any(all(s in issue for s in substrings) for issue in issues), (
                f"no issue matched all of {substrings!r}; got {issues!r}"
            )


class TestNamesFromPattern:
    @pytest.mark.parametrize(
        "pattern, expected",
        [
            ("products.experiments", {"experiments"}),
            ("products\\.experiments", {"experiments"}),
            ("products\\\\.experiments", {"experiments"}),
            ("products\\.(a|b|c)", {"a", "b", "c"}),
            ("products\\\\.(a|b|c)", {"a", "b", "c"}),
            ("products\\.(experiments|mcp_store|tracing)", {"experiments", "mcp_store", "tracing"}),
            ("posthog.api", set()),
            ("products.something.deeper", set()),
            ("", set()),
        ],
    )
    def test_extraction(self, pattern: str, expected: set[str]) -> None:
        assert _names_from_pattern(pattern) == expected


# ---------------------------------------------------------------------------
# validate_interface_blocks — per-block structural checks
# ---------------------------------------------------------------------------


def _iface(expose: list[str], frm: str = "products.x") -> str:
    expose_str = ", ".join(f'"{e}"' for e in expose)
    return f'[[interfaces]]\nexpose = [{expose_str}]\nfrom = ["{frm}"]\n'


class TestValidateInterfaceBlocks:
    @pytest.mark.parametrize(
        "expose, expected_issue",
        [
            # Pure facade — clean.
            (["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"], None),
            # Pure legacy — clean.
            (["backend\\\\.models.*", "backend\\\\.logic.*"], None),
            # Mixed facade + internal — error.
            (
                ["backend\\\\.facade.*", "backend\\\\.models.*"],
                "mixes facade/presentation",
            ),
            # Mixed presentation + internal — error.
            (
                ["backend\\\\.presentation\\\\.views.*", "backend\\\\.logic.*"],
                "mixes facade/presentation",
            ),
            # Overly broad: backend.* (raw).
            (["backend.*"], "overly broad"),
            # Overly broad: backend\\..*  (tach regex form).
            (["backend\\\\..*"], "overly broad"),
            # Overly broad: backend.** (globstar).
            (["backend\\\\.**"], "overly broad"),
            # Specific submodule — not broad.
            (["backend\\\\.models.*"], None),
            # Facade + routes — routes is public surface, not a mix.
            (["backend\\\\.facade.*", "backend\\\\.routes.*"], None),
        ],
        ids=[
            "pure_facade",
            "pure_legacy",
            "mixed_facade_internal",
            "mixed_presentation_internal",
            "broad_raw",
            "broad_tach_regex",
            "broad_globstar",
            "specific_submodule",
            "facade_plus_routes",
        ],
    )
    def test_blocks(self, expose: list[str], expected_issue: str | None) -> None:
        tach = _iface(expose)
        issues = validate_interface_blocks(tach)
        if expected_issue is None:
            assert issues == [], f"unexpected issues: {issues}"
        else:
            assert any(expected_issue in i for i in issues), (
                f"expected substring {expected_issue!r} in issues; got {issues!r}"
            )


# ---------------------------------------------------------------------------
# validate_tach_references — referential integrity
# ---------------------------------------------------------------------------


class TestValidateTachReferences:
    @pytest.mark.parametrize(
        "tach, expected_substrings",
        [
            # Clean: interface references existing module.
            (
                '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'
                '[[interfaces]]\nexpose = ["backend\\\\.models.*"]\nfrom = ["products.alpha"]\n',
                [],
            ),
            # Dangling interface: references nonexistent module.
            (
                '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'
                '[[interfaces]]\nexpose = ["backend\\\\.models.*"]\nfrom = ["products.ghost"]\n',
                [("products.ghost", "dangling interface")],
            ),
            # Dangling depends_on.
            (
                '[[modules]]\npath = "products.alpha"\ndepends_on = ["products.ghost"]\n',
                [("products.ghost", "dangling dependency")],
            ),
            # Clean depends_on.
            (
                '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'
                '[[modules]]\npath = "products.beta"\ndepends_on = ["products.alpha"]\n',
                [],
            ),
            # Both dangling.
            (
                '[[modules]]\npath = "products.a"\ndepends_on = ["products.missing_dep"]\n\n'
                '[[interfaces]]\nexpose = ["backend\\\\.x.*"]\nfrom = ["products.missing_iface"]\n',
                [("missing_dep", "dangling dependency"), ("missing_iface", "dangling interface")],
            ),
            # Dangling depends_on listed after a comment that names [[interfaces]].
            (
                '[[modules]]\npath = "products.alpha"\ndepends_on = [\n'
                "    # Facade-only (enforced by beta's [[interfaces]] block)\n"
                '    "products.ghost",\n]\n',
                [("products.ghost", "dangling dependency")],
            ),
        ],
        ids=[
            "clean_interface",
            "dangling_interface",
            "dangling_depends_on",
            "clean_depends_on",
            "both_dangling",
            "dangling_depends_on_after_interfaces_comment",
        ],
    )
    def test_references(self, tach: str, expected_substrings: list[tuple[str, str]]) -> None:
        issues = validate_tach_references(tach)
        if not expected_substrings:
            assert issues == []
            return
        for substrings in expected_substrings:
            assert any(all(s in issue for s in substrings) for issue in issues), (
                f"no issue matched all of {substrings!r}; got {issues!r}"
            )


# ---------------------------------------------------------------------------
# validate_facade_alternation — alphabetical sort check
# ---------------------------------------------------------------------------


class TestAlternationSorting:
    def test_sorted_passes(self, tmp_path: Path) -> None:
        _mkproduct(tmp_path, "alpha", strict=True)
        _mkproduct(tmp_path, "beta", strict=True)
        tach = _iface(
            ["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],
            "products\\\\.(alpha|beta)",
        )
        assert validate_facade_alternation(tach, tmp_path) == []

    def test_unsorted_fails(self, tmp_path: Path) -> None:
        _mkproduct(tmp_path, "alpha", strict=True)
        _mkproduct(tmp_path, "beta", strict=True)
        tach = _iface(
            ["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],
            "products\\\\.(beta|alpha)",
        )
        issues = validate_facade_alternation(tach, tmp_path)
        assert any("not sorted" in i for i in issues)


# ---------------------------------------------------------------------------
# OrphanedTestFilesCheck — ensures every product test file is reachable by
# either backend:test or a known external runner.
# ---------------------------------------------------------------------------


class TestOrphanedTestFilesCheck:
    """Verifies the lint catches test files left behind by misconfigured scripts."""

    _orphan_check = OrphanedTestFilesCheck()

    def _ctx(self, tmp_path: Path, *, scripts: dict[str, str] | None = None, name: str = "my_product") -> CheckContext:
        product_dir = tmp_path / name
        product_dir.mkdir()
        backend_dir = product_dir / "backend"
        backend_dir.mkdir()
        if scripts is not None:
            (product_dir / "package.json").write_text(json.dumps({"scripts": scripts}))
        return CheckContext(
            name=name,
            product_dir=product_dir,
            backend_dir=backend_dir,
            has_facade_contracts=False,
            structure={},
            detailed=False,
        )

    def test_skip_when_no_test_files(self, tmp_path: Path) -> None:
        ctx = self._ctx(tmp_path)
        result = self._orphan_check.run(ctx)
        assert result.skip is True

    def test_orphan_flagged_when_backend_test_missing(self, tmp_path: Path) -> None:
        ctx = self._ctx(tmp_path)
        (ctx.backend_dir / "api" / "test").mkdir(parents=True)
        (ctx.backend_dir / "api" / "test" / "test_thing.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert any("backend/api/test/test_thing.py" in line for line in result.lines)
        assert result.issues

    def test_no_orphans_when_backend_test_covers(self, tmp_path: Path) -> None:
        ctx = self._ctx(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
        )
        (ctx.backend_dir / "api" / "test").mkdir(parents=True)
        (ctx.backend_dir / "api" / "test" / "test_thing.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert not result.issues

    def test_specific_file_path_in_pytest_does_not_false_flag(self, tmp_path: Path) -> None:
        ctx = self._ctx(
            tmp_path,
            scripts={"backend:test": "pytest backend/test_max_tools.py -v"},
        )
        (ctx.backend_dir / "test_max_tools.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert not result.issues

    def test_directory_prefix_does_not_eat_unrelated_paths(self, tmp_path: Path) -> None:
        ctx = self._ctx(
            tmp_path,
            scripts={"backend:test": "pytest backend/api"},
        )
        (ctx.backend_dir / "api").mkdir()
        (ctx.backend_dir / "api" / "test_covered.py").write_text("")
        (ctx.backend_dir / "api_v2").mkdir()
        (ctx.backend_dir / "api_v2" / "test_uncovered.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert any("api_v2/test_uncovered.py" in i for i in result.issues)
        assert not any("api/test_covered.py" in i for i in result.issues)

    def test_dags_tests_exempted_via_external_runner(self, tmp_path: Path) -> None:
        # ci-dagster.yml runs `pytest products/**/dags`. The check should not
        # flag test files under `dags/` even when backend:test doesn't cover them.
        ctx = self._ctx(tmp_path, scripts={"backend:test": "pytest backend/"})
        (ctx.product_dir / "dags" / "tests").mkdir(parents=True)
        (ctx.product_dir / "dags" / "tests" / "test_thing.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert not result.issues

    def test_per_product_exemption_applied(self, tmp_path: Path) -> None:
        # products/tasks/backend/temporal/ is covered by ci-backend.yml Temporal
        # segment, not the product matrix.
        ctx = self._ctx(
            tmp_path,
            scripts={"backend:test": "pytest backend/tests backend/services"},
            name="tasks",
        )
        (ctx.backend_dir / "temporal" / "tests").mkdir(parents=True)
        (ctx.backend_dir / "temporal" / "tests" / "test_workflow.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert not result.issues

    def test_per_product_exemption_does_not_apply_to_other_products(self, tmp_path: Path) -> None:
        ctx = self._ctx(
            tmp_path,
            scripts={"backend:test": "pytest backend/tests"},
            name="not_tasks",
        )
        (ctx.backend_dir / "temporal" / "tests").mkdir(parents=True)
        (ctx.backend_dir / "temporal" / "tests" / "test_workflow.py").write_text("")
        result = self._orphan_check.run(ctx)
        assert any("backend/temporal/tests/test_workflow.py" in i for i in result.issues)


_IGNORE_IMPORTS_PYPROJECT = """
[tool.importlinter]
root_packages = ["products"]

[[tool.importlinter.contracts]]
name = "presentation must use facade"
type = "forbidden"
source_modules = ["products.*.backend.presentation"]
forbidden_modules = ["products.*.backend"]
ignore_imports = [
    "products.**.backend.presentation.** -> products.**.backend.facade.**",
    "products.logs.backend.presentation.views.api -> products.logs.backend.runner",
    "products.logs.backend.presentation.views.alerts_api -> products.logs.backend.models",
    "products.tracing.backend.presentation.views -> products.tracing.backend.logic",
]

[[tool.importlinter.contracts]]
name = "routes must only import presentation"
type = "forbidden"
source_modules = ["products.*.backend.routes"]
forbidden_modules = ["products.*.backend"]
ignore_imports = [
    "products.**.backend.routes -> products.**.backend.presentation.**",
    "products.tracing.backend.routes -> products.tracing.backend.api",
]
"""


@pytest.mark.parametrize(
    "name,expected",
    [
        ("logs", 2),
        ("tracing", 2),  # one presentation bypass + one routes -> backend/api/ deferral
        ("wizard", 0),
    ],
)
def test_presentation_bypass_entries(name: str, expected: int) -> None:
    from hogli_commands.product.isolation import presentation_bypass_entries

    assert len(presentation_bypass_entries(name, _IGNORE_IMPORTS_PYPROJECT)) == expected


def test_presentation_bypass_entries_handles_broken_toml() -> None:
    from hogli_commands.product.isolation import presentation_bypass_entries

    assert presentation_bypass_entries("logs", "not = [valid") == []


# ---------------------------------------------------------------------------
# Wiring couplings — facade class re-exports and garage coverage
# ---------------------------------------------------------------------------


class TestFacadeClassImports:
    @pytest.mark.parametrize(
        "facade_files, sources, expected",
        [
            # a pure re-export module hands out every class it imports from a non-garage module
            (
                {"queries.py": "from ..logic import Thing\n__all__ = ['Thing']\n"},
                {"logic.py": "class Thing:\n    pass\n"},
                {"Thing"},
            ),
            # a class re-exported from a garage is sanctioned wiring, never flagged
            (
                {"queries.py": "from ..hogql_queries.runner import Runner\n__all__ = ['Runner']\n"},
                {"hogql_queries/runner.py": "class Runner:\n    pass\n"},
                set(),
            ),
            # a re-exported function is the designed delegation pattern, never flagged
            (
                {"helpers.py": "from ..logic import do_it\n__all__ = ['do_it']\n"},
                {"logic.py": "def do_it():\n    pass\n"},
                set(),
            ),
            # a third-party / core source is not product-internal
            ({"queries.py": "from posthog.models import Team\n__all__ = ['Team']\n"}, {}, set()),
            # a TYPE_CHECKING import is type-only — nothing crosses at runtime
            (
                {
                    "queries.py": "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from ..logic import Thing\n"
                },
                {"logic.py": "class Thing:\n    pass\n"},
                set(),
            ),
            # a data-capability module (has functions) without __all__ imports an internal class for
            # its own use, not to hand out
            (
                {"api2.py": "from ..logic import Thing\n\n\ndef build():\n    return Thing()\n"},
                {"logic.py": "class Thing:\n    pass\n"},
                set(),
            ),
            # ...but the same module hands the class out once it advertises it in __all__
            (
                {
                    "api2.py": "from ..logic import Thing\n\n\ndef build():\n    return 1\n\n\n__all__ = ['Thing', 'build']\n"
                },
                {"logic.py": "class Thing:\n    pass\n"},
                {"Thing"},
            ),
            # ...or re-exports it with the explicit self-alias idiom (which also suppresses F401)
            (
                {"api2.py": "from ..logic import Thing as Thing\n\n\ndef build():\n    return 1\n"},
                {"logic.py": "class Thing:\n    pass\n"},
                {"Thing"},
            ),
            # a renaming alias is a private import for internal use, not the re-export idiom
            (
                {"api2.py": "from ..logic import Thing as _Thing\n\n\ndef build():\n    return _Thing()\n"},
                {"logic.py": "class Thing:\n    pass\n"},
                set(),
            ),
            # a PEP 562 lazy map hands out every class it maps
            (
                {
                    "api2.py": "_LAZY = {'Thing': 'logic'}\n\n\ndef __getattr__(name):\n    import importlib\n\n    return getattr(importlib.import_module('x'), name)\n"
                },
                {"logic.py": "class Thing:\n    pass\n"},
                {"Thing"},
            ),
            # a class surfaced through a package __init__ still resolves (one re-export hop)
            (
                {"queries.py": "from ..logic import Thing\n__all__ = ['Thing']\n"},
                {"logic/__init__.py": "from .impl import Thing\n", "logic/impl.py": "class Thing:\n    pass\n"},
                {"Thing"},
            ),
        ],
    )
    def test_detection(
        self, tmp_path: Path, facade_files: dict[str, str], sources: dict[str, str], expected: set[str]
    ) -> None:
        _, backend = _write_facade_product(tmp_path, facade_files=facade_files, sources=sources)
        assert {f.class_name for f in facade_class_imports(backend, "my_product")} == expected

    @pytest.mark.parametrize(
        "facade_files, expected_modules",
        [
            # a flat module keeps its bare file name as the key
            ({"api.py": "from ..logic import Thing\n__all__ = ['Thing']\n"}, {"api.py"}),
            # a module in a subfolder is read and keyed by its path inside facade/
            ({"destinations/s3.py": "from ...logic import Thing\n__all__ = ['Thing']\n"}, {"destinations/s3.py"}),
            # contracts.py and enums.py are exempt at the top level only
            ({"contracts.py": "from ..logic import Thing\n__all__ = ['Thing']\n"}, set()),
            (
                {"destinations/contracts.py": "from ...logic import Thing\n__all__ = ['Thing']\n"},
                {"destinations/contracts.py"},
            ),
            ({"destinations/enums.py": "from ...logic import Thing\n__all__ = ['Thing']\n"}, {"destinations/enums.py"}),
            # a tests/ folder is no hiding place: only test file names are skipped
            (
                {"destinations/tests/s3.py": "from ....logic import Thing\n__all__ = ['Thing']\n"},
                {"destinations/tests/s3.py"},
            ),
        ],
    )
    def test_leaks_are_keyed_by_path_inside_facade(
        self, tmp_path: Path, facade_files: dict[str, str], expected_modules: set[str]
    ) -> None:
        _, backend = _write_facade_product(
            tmp_path, facade_files=facade_files, sources={"logic.py": "class Thing:\n    pass\n"}
        )
        assert {f.facade_module for f in facade_class_imports(backend, "my_product")} == expected_modules

    def test_carveout_is_not_a_violation_but_is_tracked_for_coverage(self, tmp_path: Path) -> None:
        facade = {
            "team_extension.py": "from ..models.tcac import TeamCustomerAnalyticsConfig\n__all__ = ['TeamCustomerAnalyticsConfig']\n"
        }
        sources = {"models/tcac.py": "class TeamCustomerAnalyticsConfig:\n    pass\n"}
        _, backend = _write_facade_product(tmp_path, name="customer_analytics", facade_files=facade, sources=sources)
        assert facade_class_imports(backend, "customer_analytics") == []
        assert facade_carveout_modules(backend, "customer_analytics") == {"backend/models/tcac.py"}

    def test_carveout_class_is_an_ordinary_violation_for_a_product_that_does_not_own_it(self, tmp_path: Path) -> None:
        # the carve-out is keyed (product, class): another product re-exporting the same class name
        # gets no free pass.
        facade = {
            "team_extension.py": "from ..models.tcac import TeamCustomerAnalyticsConfig\n__all__ = ['TeamCustomerAnalyticsConfig']\n"
        }
        sources = {"models/tcac.py": "class TeamCustomerAnalyticsConfig:\n    pass\n"}
        _, backend = _write_facade_product(tmp_path, name="unrelated_product", facade_files=facade, sources=sources)
        assert {f.class_name for f in facade_class_imports(backend, "unrelated_product")} == {
            "TeamCustomerAnalyticsConfig"
        }


class TestWatchedModelsAllowance:
    _FACADE = {"models.py": "from ..models.table import DataWarehouseTable\n__all__ = ['DataWarehouseTable']\n"}
    _SOURCES = {"models/table.py": "class DataWarehouseTable:\n    pass\n"}

    def test_model_reexport_is_a_tracked_crossing_not_a_leak_for_an_allowance_product(self, tmp_path: Path) -> None:
        # if this classification breaks, warehouse_sources' model re-exports re-arm the leak block
        # and the restored narrowing silently forfeits (skip inert).
        _, backend = _write_facade_product(
            tmp_path, name="warehouse_sources", facade_files=self._FACADE, sources=self._SOURCES
        )
        assert facade_class_imports(backend, "warehouse_sources") == []
        assert {c.class_name for c in facade_model_crossings(backend, "warehouse_sources")} == {"DataWarehouseTable"}

    def test_model_reexport_stays_a_violation_for_a_product_not_on_the_allowance_list(self, tmp_path: Path) -> None:
        _, backend = _write_facade_product(
            tmp_path, name="unrelated_product", facade_files=self._FACADE, sources=self._SOURCES
        )
        assert {f.class_name for f in facade_class_imports(backend, "unrelated_product")} == {"DataWarehouseTable"}
        assert facade_model_crossings(backend, "unrelated_product") == []

    def test_unlisted_class_stays_a_violation_on_an_allowance_product(self, tmp_path: Path) -> None:
        # the allowance is keyed per class, so a listed product cannot grow a new crossing without a
        # doctrine amendment — the rot vector a product-keyed list left wide open
        facade = {"models.py": "from ..models.table import BrandNewModel\n__all__ = ['BrandNewModel']\n"}
        sources = {"models/table.py": "class BrandNewModel:\n    pass\n"}
        _, backend = _write_facade_product(tmp_path, name="warehouse_sources", facade_files=facade, sources=sources)
        assert {f.class_name for f in facade_class_imports(backend, "warehouse_sources")} == {"BrandNewModel"}
        assert facade_model_crossings(backend, "warehouse_sources") == []

    def test_allowance_is_scoped_to_the_model_package(self, tmp_path: Path) -> None:
        # a class defined outside backend/models/ gets no free pass even for an allowance product
        facade = {"models.py": "from ..logic.engine import Engine\n__all__ = ['Engine']\n"}
        sources = {"logic/engine.py": "class Engine:\n    pass\n"}
        _, backend = _write_facade_product(tmp_path, name="warehouse_sources", facade_files=facade, sources=sources)
        assert {f.class_name for f in facade_class_imports(backend, "warehouse_sources")} == {"Engine"}

    @pytest.mark.parametrize(
        "turbo_inputs, expected",
        [
            # models + migrations watched -> covered
            (["backend/facade/**", "backend/models/**", "backend/migrations/**"], set()),
            # migrations forgotten -> a data migration would skip the suite
            (["backend/facade/**", "backend/models/**"], {"backend/migrations/"}),
            # models forgotten entirely -> the crossing classes' definitions are unwatched
            (["backend/facade/**"], {"backend/migrations/", "backend/models/"}),
            # a single model file is not the whole surface -> every other model file is unwatched
            (["backend/facade/**", "backend/models/table.py", "backend/migrations/**"], {"backend/models/"}),
            # a negation carving files out of the surface breaks whole-surface coverage
            (
                ["backend/facade/**", "backend/models/**", "backend/migrations/**", "!backend/models/secret.py"],
                {"backend/models/"},
            ),
            # ./-prefixed negations normalize the same way — no bypass
            (
                ["backend/facade/**", "backend/models/**", "backend/migrations/**", "!./backend/models/secret.py"],
                {"backend/models/"},
            ),
            # a wildcard negation that could match inside the surface is rejected conservatively
            (
                ["backend/facade/**", "backend/models/**", "backend/migrations/**", "!backend/**/secret.py"],
                {"backend/migrations/", "backend/models/"},
            ),
            # a wildcard negation provably outside the surface stays allowed
            (
                [
                    "backend/facade/**",
                    "backend/models/**",
                    "backend/migrations/**",
                    "!backend/temporal/data_imports/sources/mysql/tests/**",
                ],
                set(),
            ),
        ],
    )
    def test_model_surface_coverage(self, tmp_path: Path, turbo_inputs: list[str], expected: set[str]) -> None:
        sources = {**self._SOURCES, "migrations/0001_initial.py": ""}
        product_dir, _ = _write_facade_product(
            tmp_path, name="warehouse_sources", facade_files=self._FACADE, sources=sources, turbo_inputs=turbo_inputs
        )
        assert unwatched_model_surface(product_dir) == expected

    def test_migrations_are_required_before_the_directory_exists(self, tmp_path: Path) -> None:
        # a product with models but no migrations yet must still watch the glob, otherwise its first
        # migration lands in an unwatched location and a data migration skips the suite
        product_dir, _ = _write_facade_product(
            tmp_path,
            name="warehouse_sources",
            facade_files=self._FACADE,
            sources=self._SOURCES,
            turbo_inputs=["backend/facade/**", "backend/models/**"],
        )
        assert not (product_dir / "backend/migrations").exists()
        assert unwatched_model_surface(product_dir) == {"backend/migrations/"}

    def test_model_surface_inputs_count_as_narrowing_only_when_passed(self, tmp_path: Path) -> None:
        # the restored warehouse_sources turbo.json must register as narrowed — otherwise the skip
        # is silently inert forever — but only via the allowance, never for arbitrary products.
        inputs = ["backend/facade/**", "backend/models/**", "backend/migrations/**"]
        product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)
        assert has_narrowed_turbo_inputs(product_dir) is False
        assert has_narrowed_turbo_inputs(product_dir, model_surface=MODEL_SURFACE_PREFIXES) is True

    def _allowance_ctx(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, turbo_inputs: list[str]) -> CheckContext:
        # end-to-end through IsolationChainCheck: guards the status wiring and the checks.py
        # branches, which the helper tests above cannot see
        import hogli_commands.product.isolation as isolation_module

        _seal_externally(monkeypatch)
        monkeypatch.setattr(isolation_module, "MODEL_CROSSINGS", frozenset({("my_product", "Table")}))
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "facade" / "models.py").write_text("from ..models.table import Table\n__all__ = ['Table']\n")
        (ctx.backend_dir / "models").mkdir()
        (ctx.backend_dir / "models" / "table.py").write_text("class Table:\n    pass\n")
        (ctx.backend_dir / "migrations").mkdir()
        (ctx.product_dir / "turbo.json").write_text(
            json.dumps({"tasks": {"backend:contract-check": {"inputs": turbo_inputs}}})
        )
        return ctx

    def test_chain_check_narrows_with_standing_warning_when_surface_watched(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        ctx = self._allowance_ctx(
            tmp_path, monkeypatch, ["backend/facade/**", "backend/models/**", "backend/migrations/**"]
        )
        result = chain_check.run(ctx)
        assert not result.issues
        assert any("watched-models allowance" in w for w in result.warnings)

    def test_chain_check_blocks_when_surface_omitted(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        ctx = self._allowance_ctx(tmp_path, monkeypatch, ["backend/facade/**", "backend/models/**"])
        result = chain_check.run(ctx)
        assert any("model surface" in i and "backend/migrations/" in i for i in result.issues)
        assert result.file == "products/my_product/turbo.json"

    def _narrowed_ctx(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, turbo_inputs: list[str]) -> CheckContext:
        # a narrowed product with models but no allowance entry: the surface must still be watched
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "models.py").write_text("class Table:\n    pass\n")
        (ctx.backend_dir / "migrations").mkdir()
        (ctx.product_dir / "turbo.json").write_text(
            json.dumps({"tasks": {"backend:contract-check": {"inputs": turbo_inputs}}})
        )
        return ctx

    @pytest.mark.parametrize(
        "turbo_inputs, expected_uncovered",
        [
            (["backend/facade/**"], ["backend/migrations/", "backend/models.py"]),
            (["backend/facade/**", "backend/models.py"], ["backend/migrations/"]),
            (["backend/facade/**", "backend/models.py", "backend/migrations/**"], []),
        ],
    )
    def test_chain_check_requires_the_model_surface_without_an_allowance(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, turbo_inputs: list[str], expected_uncovered: list[str]
    ) -> None:
        ctx = self._narrowed_ctx(tmp_path, monkeypatch, turbo_inputs)
        result = chain_check.run(ctx)
        surface_issues = [i for i in result.issues if "model surface" in i]
        if not expected_uncovered:
            assert surface_issues == []
            return
        assert len(surface_issues) == 1
        assert all(location in surface_issues[0] for location in expected_uncovered)


class TestUnwatchedGarages:
    @pytest.mark.parametrize(
        "garage_file, turbo_inputs, expected",
        [
            ("tasks/tasks.py", ["backend/facade/**"], {"backend/tasks/"}),  # garage present but not watched
            ("tasks/tasks.py", ["backend/facade/**", "backend/tasks/**"], set()),  # watched — satisfied
            # un-narrowed: contract-check watches everything, so nothing is "unwatched"
            ("tasks/tasks.py", None, set()),
            # the flat-file garage form is detected and satisfied the same way
            ("tasks.py", ["backend/facade/**"], {"backend/tasks.py"}),
            ("tasks.py", ["backend/facade/**", "backend/tasks.py"], set()),
            # near-miss prefixes must not count as covering the directory garage
            ("tasks/tasks.py", ["backend/facade/**", "backend/tasks.py"], {"backend/tasks/"}),
            ("tasks/tasks.py", ["backend/facade/**", "backend/tasks_extra/**"], {"backend/tasks/"}),
            # a flat-file garage needs an exact input, not a shared prefix
            ("tasks.py", ["backend/facade/**", "backend/tasks.py.bak"], {"backend/tasks.py"}),
        ],
    )
    def test_present_garage_coverage(
        self, tmp_path: Path, garage_file: str, turbo_inputs: list[str] | None, expected: set[str]
    ) -> None:
        product_dir, _ = _write_facade_product(tmp_path, sources={garage_file: ""}, turbo_inputs=turbo_inputs)
        assert unwatched_garages(product_dir) == expected

    @pytest.mark.parametrize(
        "garage_file, driven, expected",
        [
            # no evidence at all: every present garage must stay watched
            ("hogql_queries/paths.py", None, {"backend/hogql_queries/"}),
            # evidence says nothing outside drives the computed garage: it may leave the inputs
            ("hogql_queries/paths.py", frozenset(), set()),
            ("hogql_queries/paths.py", frozenset({"backend/hogql_queries/"}), {"backend/hogql_queries/"}),
            # a garage whose drive channel is not scanned stays presence-watched whatever the evidence says
            ("tasks/tasks.py", frozenset(), {"backend/tasks/"}),
        ],
    )
    def test_computed_garage_follows_the_evidence(
        self, tmp_path: Path, garage_file: str, driven: frozenset[str] | None, expected: set[str]
    ) -> None:
        product_dir, _ = _write_facade_product(tmp_path, sources={garage_file: ""}, turbo_inputs=["backend/facade/**"])
        assert unwatched_garages(product_dir, driven) == expected


class TestNarrowedTurboWiringSurface:
    @pytest.mark.parametrize(
        "inputs, expected",
        [
            (["backend/facade/**", "backend/hogql_queries/**"], True),  # a garage dir counts as narrowing surface
            (["backend/facade/**", "backend/max_tools.py"], True),  # a single-file garage counts too
            (["backend/facade/**", "backend/tasks.py"], True),  # the flat-file tasks garage form
            (["backend/hogql_queries/**"], False),  # garage alone isn't a real contract surface
            (["backend/facade/**", "backend/logic/**"], False),  # a non-wiring dir breaks the narrowing
        ],
    )
    def test_garage_inputs_count_as_narrowing(self, tmp_path: Path, inputs: list[str], expected: bool) -> None:
        product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)
        assert has_narrowed_turbo_inputs(product_dir) is expected

    @pytest.mark.parametrize(
        "inputs, expected",
        [
            (["backend/facade/**", "backend/webhook_consumers.py"], True),
            # present but unlisted: a consumer change would run no Django suite, so it isn't narrowed
            (["backend/facade/**"], False),
            # listed and then negated: turbo drops the file from the task hash, so it is unwatched
            (["backend/facade/**", "backend/webhook_consumers.py", "!backend/webhook_consumers.py"], False),
            (["backend/facade/**", "backend/webhook_consumers.py", "!backend/**"], False),
            # a negation shape the matcher can't evaluate is read as reaching the module
            (["backend/facade/**", "backend/webhook_consumers.py", "!backend/**/webhook_consumers.py"], False),
            (["backend/facade/**", "backend/webhook_consumers.py", "!backend/webhook_*.py"], False),
            # a negation of an unrelated path cannot reach the module, so it stays watched
            (["backend/facade/**", "backend/webhook_consumers.py", "!backend/models/**"], True),
        ],
    )
    def test_present_webhook_consumers_must_stay_watched(
        self, tmp_path: Path, inputs: list[str], expected: bool
    ) -> None:
        product_dir, _ = _write_facade_product(tmp_path, sources={"webhook_consumers.py": ""}, turbo_inputs=inputs)
        assert has_narrowed_turbo_inputs(product_dir) is expected

    def test_carveout_module_is_accepted_surface_only_when_declared(self, tmp_path: Path) -> None:
        # a carve-out defining module is an odd input (not facade/garage): it only counts as
        # narrowing when the caller passes it as a known carve-out module.
        product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=["backend/facade/**", "backend/models/tcac.py"])
        assert has_narrowed_turbo_inputs(product_dir) is False
        assert has_narrowed_turbo_inputs(product_dir, frozenset(), frozenset({"backend/models/tcac.py"})) is True

    @pytest.mark.parametrize(
        "inputs, expected",
        [
            (["backend/facade/**", "backend/models/tcac.py"], set()),  # covered
            (["backend/facade/**", "backend/models/**"], set()),  # a dir glob covers the file inside it
            (["backend/facade/**", "backend/models/**/*.py"], set()),  # the file-set form turbo inputs use
            (["backend/facade/**", "backend/models/*.py"], set()),  # single-level file set
            (["backend/facade/**", "backend/models/**/*.ts"], {"backend/models/tcac.py"}),  # other extension
            (["backend/facade/**", "backend/models_extra/**"], {"backend/models/tcac.py"}),  # sibling dir doesn't
            (["backend/facade/**"], {"backend/models/tcac.py"}),  # missing -> uncovered
        ],
    )
    def test_carveout_module_coverage(self, tmp_path: Path, inputs: list[str], expected: set[str]) -> None:
        product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)
        assert uncovered_carveout_modules(product_dir, frozenset({"backend/models/tcac.py"})) == expected


def _add_facade_reexport(ctx: CheckContext) -> None:
    """Give the fixture product a wiring violation: a pure re-export facade module handing out a
    non-garage internal class."""
    (ctx.backend_dir / "facade" / "queries.py").write_text("from ..logic import Thing\n__all__ = ['Thing']\n")
    (ctx.backend_dir / "logic.py").write_text("class Thing:\n    pass\n")


class TestIsolationChainWiringGate:
    def test_narrowed_facade_violation_blocks(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        _add_facade_reexport(ctx)
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        assert any("Thing" in i and "wiring location" in i for i in result.issues)

    def test_unnarrowed_facade_violation_warns_and_suppresses_the_narrowing_nag(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # Un-narrowed: the skip is inert, so the leak is a warning, not a block. And the "you're
        # eligible, narrow now" nag must be suppressed — the wiring gate would reject that narrowing.
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        _add_facade_reexport(ctx)
        result = chain_check.run(ctx)
        # the leak is a warning that also explains what blocks narrowing...
        assert any("Thing" in w and "narrowing is blocked" in w for w in result.warnings)
        assert not any("Thing" in i for i in result.issues)
        # ...and the "you're eligible, narrow now" nag is suppressed.
        assert not any("inert" in i for i in result.issues)

    def test_narrowed_unwatched_garage_blocks(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        (ctx.backend_dir / "tasks").mkdir()
        (ctx.backend_dir / "tasks" / "tasks.py").write_text("")
        (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))
        result = chain_check.run(ctx)
        assert any("backend/tasks/" in i and "wiring location" in i for i in result.issues)


class TestPackageJsonScriptsWiringWithheld:
    def test_eligible_facade_violation_is_not_nagged_to_add_the_script(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # A demoted product (facade hands out unsanctioned classes) that dropped its script must not
        # be told to add it back — it can't soundly narrow.
        _seal_externally(monkeypatch)
        ctx = _make_product(
            tmp_path,
            scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},
            strict=True,
        )
        _add_facade_reexport(ctx)
        result = check.run(ctx)
        assert not any("contract-check" in i for i in result.issues)

    def test_eligible_facade_violation_keeps_an_existing_script(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # The un-narrowed script+broad products carry a facade violation too; the absence check keys
        # on plain eligibility, so they must not be told to remove the script.
        _seal_externally(monkeypatch)
        ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, strict=True)
        _add_facade_reexport(ctx)
        result = check.run(ctx)
        assert not any("must not have" in i or "remove 'backend:contract-check'" in i for i in result.issues)


class TestBackendPackageMarker:
    check = BackendPackageMarkerCheck()

    def _product(self, tmp_path: Path, *, markers: list[str], trees: list[str]) -> CheckContext:
        ctx = _make_product(tmp_path, strict=True)
        for tree in trees:
            (ctx.backend_dir / tree).mkdir(parents=True, exist_ok=True)
            (ctx.backend_dir / tree / "views.py").write_text("x = 1\n")
        for marker in markers:
            (ctx.backend_dir / marker / "__init__.py").write_text("")
        return ctx

    @pytest.mark.parametrize(
        "markers, expected",
        [
            # every level marked -> grimp reaches the whole contract surface
            ([".", "facade", "presentation", "presentation/views"], set()),
            # backend/ alone is not enough: grimp stops at the first unmarked level, so
            # everything below is dropped and the contract passes for code it never saw
            ([".", "facade", "presentation"], {"backend/presentation/views/"}),
            ([".", "facade"], {"backend/presentation/", "backend/presentation/views/"}),
            # missing at the root hides the entire backend
            (["facade", "presentation", "presentation/views"], {"backend/"}),
        ],
    )
    def test_missing_markers_on_contract_paths(self, tmp_path: Path, markers: list[str], expected: set[str]) -> None:
        ctx = self._product(tmp_path, markers=markers, trees=["presentation", "presentation/views"])
        assert set(self.check._missing_markers(ctx)) == expected

    def test_directories_outside_the_contract_trees_are_left_alone(self, tmp_path: Path) -> None:
        # test dirs and generated trees are namespace packages on purpose — flagging them would
        # mean thousands of pointless files, and no contract targets them
        ctx = self._product(tmp_path, markers=[".", "facade"], trees=[])
        (ctx.backend_dir / "temporal" / "sources" / "stripe").mkdir(parents=True)
        (ctx.backend_dir / "temporal" / "sources" / "stripe" / "source.py").write_text("x = 1\n")
        (ctx.backend_dir / "tests").mkdir()
        (ctx.backend_dir / "tests" / "test_thing.py").write_text("x = 1\n")
        assert self.check._missing_markers(ctx) == []

    def test_empty_directories_need_no_marker(self, tmp_path: Path) -> None:
        ctx = self._product(tmp_path, markers=[".", "facade"], trees=[])
        (ctx.backend_dir / "facade" / "empty").mkdir()
        assert self.check._missing_markers(ctx) == []


_MODELS_PY = (
    "from django.db import models\n\n\n"
    "class Thing(models.Model):\n    pass\n\n\n"
    "class ThingKind(models.TextChoices):\n    RED = 'red'\n\n\n"
    "class ExternalDataSource(models.Model):\n    pass\n"
)


def _write_shape_product(
    tmp_path: Path,
    facade_files: dict[str, str],
    *,
    name: str = "my_product",
    sources: dict[str, str] | None = None,
) -> Path:
    """A product whose models module defines Thing, the ThingKind choices, and ExternalDataSource."""
    _, backend = _write_facade_product(
        tmp_path, name=name, facade_files=facade_files, sources={"models.py": _MODELS_PY, **(sources or {})}
    )
    return backend


class TestFacadeShape:
    @pytest.mark.parametrize(
        "facade_files, expected",
        [
            # a public function returning the product's own model hands the caller managers,
            # save()/delete(), and FK descriptors that query on attribute access
            (
                {"api.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n    return Thing()\n"},
                {("get_thing", "", "returns", "Thing")},
            ),
            # the facade's own models shim re-exports the same class, so it cannot be the spelling
            # that gets the model past the check
            (
                {"api.py": "from .models import Thing\n\n\ndef get_thing() -> Thing:\n    return Thing()\n"},
                {("get_thing", "", "returns", "Thing")},
            ),
            # a models module also holds choices and enums, which are values a contract may carry
            (
                {"api.py": "from ..models import ThingKind\n\n\ndef kind() -> ThingKind:\n    ...\n"},
                set(),
            ),
            # a QuerySet return lets the caller keep building the query outside the product
            (
                {
                    "api.py": "from django.db.models import QuerySet\n\n\ndef list_things() -> QuerySet[int]:\n    return []\n"
                },
                {("list_things", "", "returns", "QuerySet")},
            ),
            # a Prefetch is an ORM plan object, so the caller decides what the product loads
            (
                {"api.py": "from django.db.models import Prefetch\n\n\ndef tiles() -> Prefetch:\n    ...\n"},
                {("tiles", "", "returns", "Prefetch")},
            ),
            # the `models.QuerySet` spelling must resolve like the direct import
            (
                {"api.py": "from django.db import models\n\n\ndef things() -> models.QuerySet:\n    ...\n"},
                {("things", "", "returns", "QuerySet")},
            ),
            # a bare relative import binds the submodule too, so `models.Thing` after it names the
            # model, which is the spelling several facades already use for their own models shim
            (
                {"api.py": "from . import models\n\n\ndef get_thing() -> models.Thing:\n    ...\n"},
                {("get_thing", "", "returns", "Thing")},
            ),
            (
                {"api.py": "from .. import models\n\n\ndef get_thing() -> models.Thing:\n    ...\n"},
                {("get_thing", "", "returns", "Thing")},
            ),
            # ...but only the model surface binds that way: contracts are what the facade is for
            (
                {"api.py": "from . import contracts\n\n\ndef get_thing() -> contracts.Thing:\n    ...\n"},
                set(),
            ),
            # a nested class attribute carries no instance of the outer class, so `Thing.Status` is
            # a value a contract may hold
            (
                {"api.py": "from ..models import Thing\n\n\ndef status() -> Thing.Status:\n    ...\n"},
                set(),
            ),
            # an alias must report the type at the source, or the row cannot be matched to a class
            (
                {"api.py": "from django.db.models import QuerySet as QS\n\n\ndef things() -> QS:\n    ...\n"},
                {("things", "", "returns", "QuerySet")},
            ),
            # a module-level alias is a name for the same type, so the spelling a facade picks
            # cannot decide whether the model on it counts
            (
                {
                    "api.py": "from collections.abc import Callable\n\nfrom ..models import Thing\n\nHandler = Callable[[Thing], None]\n\n\ndef register(handler: Handler) -> None:\n    return None\n"
                },
                {("register", "handler", "accepts", "Thing")},
            ),
            # ...and the explicit TypeAlias spelling of the same alias
            (
                {
                    "api.py": "from typing import TypeAlias\n\nfrom ..models import Thing\n\nRows: TypeAlias = list[Thing]\n\n\ndef load() -> Rows:\n    ...\n"
                },
                {("load", "", "returns", "Thing")},
            ),
            # ...and the PEP 695 statement, which facades already write
            (
                {"api.py": "from ..models import Thing\n\ntype Rows = list[Thing]\n\n\ndef load() -> Rows:\n    ...\n"},
                {("load", "", "returns", "Thing")},
            ),
            # a dataclass field is a keyword of the constructor the decorator generates, so a model
            # on one is a model the caller hands the class
            (
                {
                    "api.py": "from dataclasses import dataclass\n\nfrom ..models import Thing\n\n\n@dataclass\nclass Row:\n    thing: Thing\n"
                },
                {("Row.__init__", "thing", "accepts", "Thing")},
            ),
            (
                {
                    "api.py": "from dataclasses import dataclass\n\nfrom ..models import Thing\n\n\n@dataclass(frozen=True)\nclass Row:\n    thing: Thing\n"
                },
                {("Row.__init__", "thing", "accepts", "Thing")},
            ),
            # a frozen contract is precisely what must never carry a model, so contracts.py is read
            # like every other facade module
            (
                {
                    "contracts.py": "from posthog.dataclasses import frozen\n\nfrom ..models import Thing\n\n\n@frozen\nclass ThingData:\n    thing: Thing\n"
                },
                {("ThingData.__init__", "thing", "accepts", "Thing")},
            ),
            # a bare `-> Any` promises nothing, which is the evasion the check exists to close
            (
                {"api.py": "from typing import Any\n\n\ndef serialize() -> Any:\n    ...\n"},
                {("serialize", "", "returns", "Any")},
            ),
            # ...and typing_extensions exports the same name, so it cannot be the import that gets
            # an `Any` past the check
            (
                {"api.py": "from typing_extensions import Any\n\n\ndef serialize() -> Any:\n    ...\n"},
                {("serialize", "", "returns", "Any")},
            ),
            # ...but data inside a container is still data
            (
                {"api.py": "from typing import Any\n\n\ndef serialize() -> dict[str, Any]:\n    ...\n"},
                set(),
            ),
            # `Any` on the tenant parameter is how a Team model crosses without naming itself
            (
                {"api.py": "from typing import Any\n\n\ndef digest(team: Any) -> None:\n    return None\n"},
                {("digest", "team", "accepts", "Any")},
            ),
            # ...but `Any` on an ordinary payload says nothing about a Django object
            (
                {"api.py": "from typing import Any\n\n\ndef digest(payload: Any) -> None:\n    return None\n"},
                set(),
            ),
            # product -> core is the sanctioned direction, so a core model is not a finding
            (
                {"api.py": "from posthog.models import Team\n\n\ndef digest(team: Team) -> None:\n    return None\n"},
                set(),
            ),
            # a DRF request in the facade means the facade knows the transport
            (
                {
                    "api.py": "from rest_framework.request import Request\n\n\ndef provenance(request: Request) -> None:\n    return None\n"
                },
                {("provenance", "request", "accepts", "Request")},
            ),
            # ...and importing the submodule instead binds a namespace, so `request.Request` names
            # the same class and cannot be the spelling that gets it past the check
            (
                {
                    "api.py": "from rest_framework import request\n\n\ndef provenance(req: request.Request) -> None:\n    return None\n"
                },
                {("provenance", "req", "accepts", "Request")},
            ),
            # a constructor takes what the caller hands the class, so it is part of the surface
            (
                {
                    "api.py": "from django.db.models import QuerySet\n\n\nclass Rows:\n    def __init__(self, queryset: QuerySet) -> None:\n        self._queryset = queryset\n"
                },
                {("Rows.__init__", "queryset", "accepts", "QuerySet")},
            ),
            # the arguments of a Literal are values, so a model name among them is data
            (
                {
                    "api.py": "from typing import Literal\n\nfrom ..models import Thing\n\n\ndef pick(kind: Literal['Thing', 'ExternalDataSource']) -> None:\n    return None\n"
                },
                set(),
            ),
            # Annotated is one type plus metadata: the type counts and the metadata does not
            (
                {
                    "api.py": "from typing import Annotated\n\nfrom ..models import Thing\n\n\ndef pick(row: Annotated[Thing, 'ExternalDataSource']) -> None:\n    return None\n"
                },
                {("pick", "row", "accepts", "Thing")},
            ),
            # a TYPE_CHECKING import plus a quoted annotation is the same promise, spelled to dodge
            # the import graph
            (
                {
                    "api.py": "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from ..models import Thing\n\n\ndef get_thing() -> 'Thing':\n    ...\n"
                },
                {("get_thing", "", "returns", "Thing")},
            ),
            # converting a model to a contract is what a private facade helper is for
            (
                {"api.py": "from ..models import Thing\n\n\ndef _to_contract(row: Thing) -> None:\n    return None\n"},
                set(),
            ),
            (
                {
                    "api.py": "from ..models import Thing\n\n\nclass Mapper:\n    def to_contract(self, row: Thing) -> None:\n        return None\n"
                },
                {("Mapper.to_contract", "row", "accepts", "Thing")},
            ),
        ],
    )
    def test_detection(
        self, tmp_path: Path, facade_files: dict[str, str], expected: set[tuple[str, str, str, str]]
    ) -> None:
        backend = _write_shape_product(tmp_path, facade_files)
        findings = facade_shape_findings(backend, "my_product")
        assert {(f.symbol, f.parameter, f.kind, f.type_name) for f in findings} == expected

    def test_a_model_routed_through_another_facade_is_still_a_model(self, tmp_path: Path) -> None:
        # The owner's facade.models shim is the sanctioned way to reach its models, so a foreign
        # model arrives spelled through it rather than through the models module directly.
        _write_shape_product(
            tmp_path, {"models.py": "from ..models import Thing\n\n__all__ = ['Thing']\n"}, name="owner"
        )
        backend = _write_shape_product(
            tmp_path,
            {
                "api.py": "from products.owner.backend.facade.models import Thing\n\n\n"
                "def get_thing() -> Thing:\n    ...\n"
            },
        )
        findings = facade_shape_findings(backend, "my_product")
        assert [(f.source, f.type_name, f.kind) for f in findings] == [("owner", "Thing", "returns")]

    def test_a_sanctioned_model_crossing_is_not_a_shape_finding(self, tmp_path: Path) -> None:
        # warehouse_sources holds the ExternalDataSource entry in MODEL_CROSSINGS, so its facade may
        # hand the class out. Without the exemption the sanctioned crossing would fail the lint the
        # day the check lands, and the allowance is keyed per product, so nobody else inherits it.
        facade = {
            "api.py": "from ..models import ExternalDataSource\n\n\ndef source() -> ExternalDataSource:\n    ...\n"
        }
        allowed = _write_shape_product(tmp_path / "a", facade, name="warehouse_sources")
        other = _write_shape_product(tmp_path / "b", facade, name="unrelated_product")
        assert facade_shape_findings(allowed, "warehouse_sources") == []
        assert [f.type_name for f in facade_shape_findings(other, "unrelated_product")] == ["ExternalDataSource"]

    def test_the_allowance_does_not_cover_a_same_named_class_from_another_product(self, tmp_path: Path) -> None:
        # warehouse_sources may hand out its own ExternalDataSource, and the identically named class
        # from another product is a crossing nobody sanctioned. Both sit in one annotation, so a
        # per-name key would collapse them and let the sanctioned one hide the other.
        _write_shape_product(tmp_path, {}, name="lookalike")
        backend = _write_shape_product(
            tmp_path,
            {
                "api.py": "from ..models import ExternalDataSource\n"
                "from products.lookalike.backend.models import ExternalDataSource as Other\n\n\n"
                "def sources() -> tuple[ExternalDataSource, Other]:\n    ...\n"
            },
            name="warehouse_sources",
        )
        findings = facade_shape_findings(backend, "warehouse_sources")
        assert [(f.source, f.type_name) for f in findings] == [("lookalike", "ExternalDataSource")]

    @pytest.mark.parametrize(
        "facade_api, extra_sources, symbol",
        [
            # a PEP 562 map: the consumer imports the name from the facade and the map decides
            # which module answers
            (
                '_B = "products.my_product.backend."\n'
                '_LAZY = {"get_thing": "logic.crud"}\n\n\n'
                "def __getattr__(name):\n    ...\n",
                {},
                "get_thing",
            ),
            # a module with no definitions of its own hands out everything it imports
            ("from ..logic.crud import get_thing\n", {}, "get_thing"),
            # the self-alias idiom, which also suppresses ruff's F401
            (
                "from ..logic.crud import get_thing as get_thing\n\n\ndef other() -> None:\n    return None\n",
                {},
                "get_thing",
            ),
            # a renamed re-export is read under the name the facade hands out
            ("from ..logic.crud import get_thing as fetch\n\n__all__ = ['fetch']\n", {}, "fetch"),
            # a facade reaches its logic through the package, whose __init__ commonly surfaces the
            # function from a submodule rather than defining it
            (
                "from ..logic import get_thing\n",
                {"logic/__init__.py": "from .crud import get_thing\n"},
                "get_thing",
            ),
        ],
    )
    def test_a_re_exported_function_is_read_under_the_facade_name(
        self, tmp_path: Path, facade_api: str, extra_sources: dict[str, str], symbol: str
    ) -> None:
        # A re-export is part of the facade's own call surface: the consumer imports the name from
        # the facade, so neither spelling can be what gets the model past the check.
        backend = _write_shape_product(
            tmp_path,
            {"api.py": facade_api},
            sources={
                "logic/crud.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n    ...\n",
                **extra_sources,
            },
        )
        findings = facade_shape_findings(backend, "my_product")
        assert [(f.dotted_module, f.symbol, f.kind, f.type_name) for f in findings] == [
            ("products.my_product.backend.facade.api", symbol, "returns", "Thing")
        ]

    @pytest.mark.parametrize(
        "facade_files, expected",
        [
            # a task body in facade/tasks.py is the implementation core registers, sitting in the one
            # package core imports instead of in backend/tasks/ where the inputs watch it
            (
                {"tasks.py": "from celery import shared_task\n\n\n@shared_task\ndef run_it() -> None:\n    print(1)\n"},
                ("run_it",),
            ),
            # the same module doing only what it is for stays clean
            (
                {"tasks.py": "from ..tasks import run_it\n\n__all__ = ['run_it']\n"},
                None,
            ),
            (
                {"temporal.py": "from temporalio import workflow\n\n\n@workflow.defn\nclass Flow:\n    x = 1\n"},
                ("Flow",),
            ),
            # one row per module, so the count says how many bodies are left to move
            (
                {"queries.py": "def one():\n    return 1\n\n\nclass Two:\n    x = 1\n"},
                ("one", "Two"),
            ),
            # api.py holds the data capabilities, so a body there is the designed shape
            (
                {"api.py": "def run_query():\n    return 1\n"},
                None,
            ),
            # the PEP 562 hook is the re-export mechanism, not logic of the module's own
            (
                {
                    "models.py": "_LAZY = {'Thing': 'models'}\n\n\ndef __getattr__(name):\n    import importlib\n\n    return getattr(importlib.import_module('x'), name)\n"
                },
                None,
            ),
        ],
    )
    def test_capability_submodule_logic(
        self, tmp_path: Path, facade_files: dict[str, str], expected: tuple[str, ...] | None
    ) -> None:
        backend = _write_shape_product(tmp_path, facade_files)
        logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]
        assert [f.bodies for f in logic] == ([expected] if expected else [])
        assert [f.count for f in logic] == ([len(expected)] if expected else [])

    @pytest.mark.parametrize(
        "reexport, expected",
        [
            # a module that hands out a Temporal definition is wiring whatever it is called, and
            # products already name such a module workflow_tasks.py or tools.py
            ("from ..temporal.flows import run_it\n\n__all__ = ['run_it']\n", ("helper",)),
            # a module that hands out logic is an ordinary facade module, where a body is allowed
            ("from ..logic.crud import run_it\n\n__all__ = ['run_it']\n", None),
            # an alias may name the wiring package itself rather than a name inside it, and then the
            # module the facade hands out is that package. Both spellings reach the same directory.
            ("from products.my_product.backend import tasks as tasks\n", ("helper",)),
            ("from .. import tasks\n\n__all__ = ['tasks']\n", ("helper",)),
        ],
    )
    def test_a_capability_module_is_recognized_by_what_it_hands_out(
        self, tmp_path: Path, reexport: str, expected: tuple[str, ...] | None
    ) -> None:
        backend = _write_shape_product(
            tmp_path,
            {"wiring.py": f"{reexport}\n\ndef helper():\n    return 1\n"},
            sources={
                "temporal/flows.py": "def run_it():\n    ...\n",
                "logic/crud.py": "def run_it():\n    ...\n",
                "tasks/__init__.py": "def run_it():\n    ...\n",
            },
        )
        logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]
        assert [f.bodies for f in logic] == ([expected] if expected else [])

    @pytest.mark.parametrize(
        "module_key, expected_dotted",
        [
            ("api.py", "products.my_product.backend.facade.api"),
            ("destinations/s3.py", "products.my_product.backend.facade.destinations.s3"),
            ("destinations/__init__.py", "products.my_product.backend.facade.destinations"),
        ],
    )
    def test_a_finding_carries_the_module_path_and_dotted_name(
        self, tmp_path: Path, module_key: str, expected_dotted: str
    ) -> None:
        # A nested module reaches the models with `...`, a flat one with `..`.
        dots = "." * (module_key.count("/") + 2)
        backend = _write_shape_product(
            tmp_path, {module_key: f"from {dots}models import Thing\n\n\ndef get_thing() -> Thing:\n    ...\n"}
        )
        findings = facade_shape_findings(backend, "my_product")
        assert [(f.facade_module, f.dotted_module) for f in findings] == [(module_key, expected_dotted)]

    @pytest.mark.parametrize(
        "module_key, expected",
        [
            ("testing.py", None),
            ("destinations/testing.py", ("helper",)),
        ],
    )
    def test_name_exemptions_apply_to_top_level_modules_only(
        self, tmp_path: Path, module_key: str, expected: tuple[str, ...] | None
    ) -> None:
        dots = "." * (module_key.count("/") + 2)
        backend = _write_shape_product(
            tmp_path,
            {
                module_key: f"from {dots}temporal.flows import run_it\n\n__all__ = ['run_it']\n\n\ndef helper():\n    return 1\n"
            },
            sources={"temporal/flows.py": "def run_it():\n    ...\n"},
        )
        logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]
        assert [f.bodies for f in logic] == ([expected] if expected else [])


class TestFacadeShapeLedgerRows:
    @pytest.mark.parametrize(
        "facade_files, expected",
        [
            # a product model keeps `<product>.<Class>` in the first column, like every other
            # crossing row, so one grep over the ledger finds every way the class leaves
            (
                {"api.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n    return Thing()\n"},
                "my_product.Thing products.my_product.backend.facade.api.get_thing facade-returns 1",
            ),
            # everything else names the library it comes from, so `QuerySet` cannot read as a class
            (
                {"api.py": "from django.db.models import QuerySet\n\n\ndef things() -> QuerySet:\n    ...\n"},
                "django.QuerySet products.my_product.backend.facade.api.things facade-returns 1",
            ),
            # the parameter rides in the kind, the way drives(...) and reverse-accessor(...) carry
            # their detail, so the row stays four fields wide
            (
                {"api.py": "from typing import Any\n\n\ndef digest(team: Any) -> None:\n    return None\n"},
                "typing.Any products.my_product.backend.facade.api.digest facade-accepts(team) 1",
            ),
            # a method keeps its class in the path, and the parameter never enters it
            (
                {
                    "api.py": "from ..models import Thing\n\n\nclass Mapper:\n    def to_contract(self, row: Thing) -> None:\n        return None\n"
                },
                "my_product.Thing products.my_product.backend.facade.api.Mapper.to_contract facade-accepts(row) 1",
            ),
            # a logic row has no type to name, so it is keyed by the module that holds the bodies —
            # the same location shape the drives(...) rows use — and counted in the count column
            (
                {
                    "tasks.py": "from celery import shared_task\n\n\n@shared_task\ndef run_it() -> None:\n    print(1)\n\n\ndef helper() -> None:\n    print(2)\n"
                },
                "my_product:backend/facade/tasks.py products.my_product.backend.facade.tasks facade-logic 2",
            ),
        ],
    )
    def test_a_finding_renders_one_ledger_row(
        self, tmp_path: Path, facade_files: dict[str, str], expected: str
    ) -> None:
        backend = _write_shape_product(tmp_path, facade_files)
        findings = facade_shape_findings(backend, "my_product")
        assert [facade_shape_use(f).as_baseline_line() for f in findings] == [expected]


class TestFacadeShapeBaseline:
    _ROW = "my_product.Thing products.my_product.backend.facade.api.get_thing facade-returns 1"

    def _leaking_product(self, tmp_path: Path) -> CheckContext:
        ctx = _make_product(tmp_path, strict=True)
        (ctx.backend_dir / "models.py").write_text(_MODELS_PY)
        (ctx.backend_dir / "facade" / "api.py").write_text(
            "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n    return Thing()\n"
        )
        return ctx

    def test_an_unrecorded_finding_fails_and_a_recorded_one_only_warns(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # Both directions of the same fixture: without the ratchet the debt would either block every
        # product on day one or never block anything.
        ctx = self._leaking_product(tmp_path)
        monkeypatch.setattr(checks_module, "recorded_facade_shape_rows", lambda name: frozenset())
        unrecorded = FacadeShapeCheck().run(ctx)
        assert any("returns my_product.Thing" in i and "frozen contract" in i for i in unrecorded.issues)

        monkeypatch.setattr(checks_module, "recorded_facade_shape_rows", lambda name: frozenset({self._ROW}))
        recorded = FacadeShapeCheck().run(ctx)
        assert recorded.issues == []
        assert recorded.lines == ["⚠ facade shape debt: 1 rows"]


# ---------------------------------------------------------------------------
# SystemChecksCheck — Django system checks live in backend/checks.py
# ---------------------------------------------------------------------------

_READY_IMPORTS_CHECKS = """
from django.apps import AppConfig


class PConfig(AppConfig):
    name = "products.p.backend"

    def ready(self):
        from products.p.backend import checks  # noqa: F401
"""

_READY_WITHOUT_CHECKS = """
from django.apps import AppConfig


class PConfig(AppConfig):
    name = "products.p.backend"
"""

_CHECKS_MODULE = """
from posthog.checks import register_check

P_CHECK = "{check_id}"


@register_check(P_CHECK)
def check_p(app_configs, **kwargs):
    return []
"""

_DJANGO_REGISTER_ELSEWHERE = """
from django.core import checks


@checks.register()
def check_p(app_configs, **kwargs):
    return []
"""


def _system_checks_ctx(tmp_path: Path, files: dict[str, str]) -> CheckContext:
    product_dir = tmp_path / "p"
    backend = product_dir / "backend"
    backend.mkdir(parents=True)
    for rel, content in files.items():
        (backend / rel).parent.mkdir(parents=True, exist_ok=True)
        (backend / rel).write_text(content)
    return CheckContext(
        name="p",
        product_dir=product_dir,
        backend_dir=backend,
        has_facade_contracts=False,
        structure={},
        detailed=False,
    )


class TestSystemChecksCheck:
    @pytest.mark.parametrize(
        "files, expected",
        [
            ({"apps.py": _READY_WITHOUT_CHECKS}, []),
            (
                {"apps.py": _READY_IMPORTS_CHECKS, "checks.py": _CHECKS_MODULE.format(check_id="posthog.p.E001")},
                [],
            ),
            (
                {
                    "apps.py": _READY_IMPORTS_CHECKS.replace(
                        "from products.p.backend import checks", "from . import checks"
                    ),
                    "checks.py": _CHECKS_MODULE.format(check_id="posthog.p.W001"),
                },
                [],
            ),
            (
                {"apps.py": _READY_WITHOUT_CHECKS, "logic/settings_guard.py": _DJANGO_REGISTER_ELSEWHERE},
                ["backend/logic/settings_guard.py registers a Django system check"],
            ),
            (
                {"apps.py": _READY_IMPORTS_CHECKS, "checks.py": _CHECKS_MODULE.format(check_id="p.E001")},
                ["check ID 'p.E001'"],
            ),
            (
                {"apps.py": _READY_IMPORTS_CHECKS, "checks.py": _CHECKS_MODULE.format(check_id="posthog.other.E001")},
                ["check ID 'posthog.other.E001'"],
            ),
            (
                {"apps.py": _READY_WITHOUT_CHECKS, "checks.py": _CHECKS_MODULE.format(check_id="posthog.p.E001")},
                ["never imported by apps.py ready()"],
            ),
            (
                {
                    "apps.py": _READY_WITHOUT_CHECKS,
                    "logic/guard.py": "import posthog.checks as checks\n\n\n@checks.register_check('posthog.p.W001')\n"
                    "def check_p(app_configs, **kwargs):\n    return []\n",
                },
                ["backend/logic/guard.py registers a Django system check"],
            ),
            (
                {
                    "apps.py": _READY_IMPORTS_CHECKS.replace(
                        "        from products.p.backend import checks",
                        "        from typing import TYPE_CHECKING\n\n        if TYPE_CHECKING:\n"
                        "            from products.p.backend import checks",
                    ),
                    "checks.py": _CHECKS_MODULE.format(check_id="posthog.p.E001"),
                },
                ["never imported by apps.py ready()"],
            ),
            (
                {
                    "apps.py": _READY_IMPORTS_CHECKS.replace(
                        "        from products.p.backend import checks",
                        "        import typing\n\n        if not typing.TYPE_CHECKING:\n"
                        "            from products.p.backend import checks",
                    ),
                    "checks.py": _CHECKS_MODULE.format(check_id="posthog.p.E001"),
                },
                [],
            ),
        ],
    )
    def test_system_check_placement_ids_and_registration(
        self, tmp_path: Path, files: dict[str, str], expected: list[str]
    ) -> None:
        issues = SystemChecksCheck().run(_system_checks_ctx(tmp_path, files)).issues
        assert len(issues) == len(expected), issues
        for fragment, issue in zip(expected, issues):
            assert fragment in issue