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.

32.6 KB
Raw Blame
"""Tests for deny-list pattern matching in gates.py."""

from pathlib import Path

import pytest

import yaml
import gates
from gates import (
    DEPENDENCY_ECOSYSTEMS,
    build_ownership,
    dependency_manifests_without_lockfile,
    detect_deny_categories,
    detect_ownership,
    detect_title_scrutiny_flags,
    has_dependency_changes,
    is_size_exempt,
    substantive_size,
)
from policy import OwnershipSource, bundled_defaults_dir, load_policy, merge_policy, repo_root

# ── False positives that should NOT trigger ──────────────────────


@pytest.mark.parametrize(
    "files",
    [
        pytest.param(
            [
                "frontend/src/queries/nodes/InsightViz/EditorFilters/SessionAnalysisWarning.tsx",
                "frontend/src/queries/nodes/InsightViz/EditorFilters/SuggestionBanner.tsx",
                "frontend/src/queries/nodes/InsightViz/EditorFilters/EditorFilterItems.tsx",
            ],
            id="session-analysis-warning-component",
        ),
        pytest.param(
            ["frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts"],
            id="localstorage-recents-logic",
        ),
        pytest.param(
            ["frontend/src/lib/utils/tokenizer.ts"],
            id="tokenizer-not-auth-token",
        ),
        pytest.param(
            ["frontend/src/scenes/session-recordings/SessionRecordingPlayer.tsx"],
            id="session-recording-not-auth",
        ),
        pytest.param(
            ["frontend/src/lib/components/KeyboardShortcut.tsx"],
            id="keyboard-not-crypto-key",
        ),
        pytest.param(
            ["frontend/src/lib/hooks/useRoutingLogic.ts"],
            id="routing-logic-not-infra",
        ),
        pytest.param(
            ["products/signals/backend/temporal/backfill_error_tracking.py"],
            id="temporal-backfill-workflow-not-migration",
        ),
        pytest.param(
            ["posthog/management/commands/backfill_distinct_id_overrides.py"],
            id="backfill-management-command-not-migration",
        ),
        pytest.param(
            ["posthog/dags/backfill_materialized_column.py"],
            id="dagster-backfill-dag-not-migration",
        ),
        pytest.param(
            ["posthog/management/commands/migrate_team.py"],
            id="migrate-operator-command-not-migration",
        ),
        pytest.param(
            ["ee/api/subscription.py", "ee/api/test/test_subscription.py"],
            id="insight-subscriptions-not-billing",
        ),
        pytest.param(
            ["posthog/api/routing.py"],
            id="drf-routers-not-infra",
        ),
        pytest.param(
            ["docs/internal/checking-deploy-timing.md"],
            id="deploy-timing-docs-not-infra",
        ),
        pytest.param(
            ["products/conversations/backend/api/tests/test_slack_message_routing.py"],
            id="message-routing-test-not-infra",
        ),
        pytest.param(
            ["products/web_analytics/backend/temporal/health_checks/authorized_urls.py"],
            id="authorized-urls-domain-config-not-auth",
        ),
        pytest.param(
            ["dustbin/deploy.py"],
            id="bin-deploy-needs-path-anchor",
        ),
        pytest.param(
            ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py"],
            id="stripe-connector-not-billing",
        ),
        pytest.param(
            ["frontend/package.json"],
            id="manifest-without-lockfile-not-deps",
        ),
        pytest.param(
            ["pyproject.toml"],
            id="pyproject-without-lockfile-not-deps",
        ),
        pytest.param(
            ["common/esbuilder/tsconfig.json"],
            id="tsconfig-not-deps",
        ),
        pytest.param(
            ["frontend/src/lib/api.ts"],
            id="busy-api-client-not-guardrail",
        ),
        pytest.param(
            ["tach.toml"],
            id="busy-tach-config-not-guardrail",
        ),
        pytest.param(
            ["products/model_crossing_uses_baseline.txt"],
            id="busy-crossings-baseline-not-guardrail",
        ),
        pytest.param(
            ["posthog/test/repo_invariants/setup_receivers_baseline.txt"],
            id="busy-receivers-baseline-not-guardrail",
        ),
        pytest.param(
            ["posthog/egress/slack/client.py"],
            id="egress-domain-not-guardrail",
        ),
        pytest.param(
            ["tools/release/feature-product.yaml"],
            id="product-yaml-suffix-not-manifest",
        ),
    ],
)
def test_no_false_positive(files: list[str]) -> None:
    assert detect_deny_categories(files) == []


# ── True positives that SHOULD trigger ───────────────────────────


@pytest.mark.parametrize(
    "files, expected_category",
    [
        pytest.param(
            ["posthog/api/authentication.py"],
            "auth",
            id="authentication-api-file",
        ),
        pytest.param(
            ["frontend/src/scenes/authentication/passwordResetLogic.ts"],
            "auth",
            id="authentication-scene-tree",
        ),
        pytest.param(
            ["posthog/api/login.py"],
            "auth",
            id="login-endpoint",
        ),
        pytest.param(
            ["posthog/models/oauth_config.py"],
            "auth",
            id="oauth-config",
        ),
        pytest.param(
            ["posthog/api/auth/session_token.py"],
            "auth",
            id="auth-session-token-path",
        ),
        pytest.param(
            ["posthog/crypto/encrypt.py"],
            "crypto_secrets",
            id="encryption-file",
        ),
        pytest.param(
            ["posthog/settings/.env.example"],
            "crypto_secrets",
            id="dot-env-file",
        ),
        pytest.param(
            ["posthog/api/api_key.py"],
            "crypto_secrets",
            id="api-key-file",
        ),
        pytest.param(
            ["posthog/models/secret_key_store.py"],
            "crypto_secrets",
            id="secret-key-file",
        ),
        pytest.param(
            ["posthog/migrations/0400_add_column.py"],
            "migrations",
            id="migration-file",
        ),
        pytest.param(
            ["rust/persons_migrations/20260206000001_add_last_seen_at.sql"],
            "migrations",
            id="rust-sqlx-migration",
        ),
        pytest.param(
            [".github/workflows/ci.yml"],
            "ci_workflows",
            id="github-workflow",
        ),
        pytest.param(
            [".depot/workflows/ci-backend.yml"],
            "ci_workflows",
            id="depot-workflow",
        ),
        pytest.param(
            [".github/workflows/ci-security.yaml"],
            "infra_cicd",
            id="security-owned-workflow",
        ),
        pytest.param(
            [".depot/workflows/ci-security.yaml"],
            "infra_cicd",
            id="security-owned-depot-workflow",
        ),
        pytest.param(
            ["bin/deploy-hobby"],
            "infra_cicd",
            id="deploy-hobby-script",
        ),
        pytest.param(
            ["livestream/deploy.sh"],
            "infra_cicd",
            id="deploy-sh-script",
        ),
        pytest.param(
            [".github/pr-deploy/values.yaml.tmpl"],
            "infra_cicd",
            id="pr-deploy-directory",
        ),
        pytest.param(
            ["posthog/models/two_factor_auth.py"],
            "auth",
            id="two-factor-auth-file",
        ),
        pytest.param(
            ["posthog/billing/stripe_webhook.py"],
            "billing",
            id="billing-file",
        ),
        pytest.param(
            ["pnpm-lock.yaml"],
            "deps_toolchain",
            id="pnpm-lockfile",
        ),
        pytest.param(
            ["rust/Cargo.lock"],
            "deps_toolchain",
            id="cargo-lockfile",
        ),
        pytest.param(
            ["composer.lock"],
            "deps_toolchain",
            id="composer-lockfile",
        ),
        pytest.param(
            ["requirements.txt"],
            "deps_toolchain",
            id="requirements-pins-directly",
        ),
        pytest.param(
            ["common/ingestion/requirements-dev.txt"],
            "deps_toolchain",
            id="requirements-variant-pins-too",
        ),
        pytest.param(
            ["frontend/package.json", "pnpm-lock.yaml"],
            "deps_toolchain",
            id="manifest-with-lockfile",
        ),
        pytest.param(
            [".semgrep/rules/devex/url-naming.yaml"],
            "devex_guardrails",
            id="devex-semgrep-rule",
        ),
        pytest.param(
            ["frontend/src/lib/api-ratchet-baseline.txt"],
            "devex_guardrails",
            id="api-ratchet-baseline",
        ),
        pytest.param(
            ["posthog/egress/AGENTS.md"],
            "devex_guardrails",
            id="egress-agents-md-matches-lowercased",
        ),
        pytest.param(
            [".agents/code-style.md"],
            "agent_steering",
            id="root-agents-topic-guide",
        ),
        pytest.param(
            ["posthog/ingress/verify/hmac.py"],
            "devex_guardrails",
            id="ingress-shared-verify",
        ),
        pytest.param(
            ["posthog/test/repo_invariants/test_startup_import_budget.py"],
            "devex_guardrails",
            id="startup-budget-invariant-test",
        ),
        pytest.param(
            ["tools/hogli-commands/hogli_commands/product/isolation.py"],
            "devex_guardrails",
            id="isolation-lint",
        ),
    ],
)
def test_true_positive(files: list[str], expected_category: str) -> None:
    result = detect_deny_categories(files)
    assert expected_category in result, f"Expected '{expected_category}' in {result}"


# ── Title scrutiny flags (titles never hard-deny) ────────────────


@pytest.mark.parametrize(
    "subject, expected_flags",
    [
        pytest.param("fix: oauth login redirect", ["auth"], id="auth-keywords"),
        pytest.param("fix: stripe invoice pagination", ["billing"], id="billing-keywords"),
        pytest.param("feat(subscriptions): raise hourly org cap", [], id="insight-subscription-not-billing"),
        pytest.param("chore: migrate helm chart to terraform", ["infra_cicd"], id="infra-keywords"),
        pytest.param("fix: authorized urls health check", ["auth"], id="title-only-past-participle"),
        pytest.param("fix(insights): trend legend overlap", [], id="neutral-title"),
        pytest.param("fix: authentication flow", ["auth"], id="authentication-long-form"),
        pytest.param("feat: stripe oauth billing sync", ["auth", "billing"], id="two-category-title"),
    ],
)
def test_title_scrutiny_flags(subject: str, expected_flags: list[str]) -> None:
    # Titles flag for LLM scrutiny but never deny — a title-only keyword
    # must not put the PR in T2-never (56-83% of those merged unchanged).
    assert detect_title_scrutiny_flags(subject) == expected_flags


@pytest.fixture
def deny_exceptions(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    raw = merge_policy(
        yaml.safe_load((bundled_defaults_dir() / "policy.yml").read_text()),
        yaml.safe_load((repo_root() / ".stamphog" / "policy.yml").read_text()),
    )
    raw["deny"]["billing"]["match"]["any"][0] = "Billing"
    raw["deny_exceptions"] = {
        "billing": [
            {
                "keyword": "BILLING",
                "path_prefixes": ["APPS/", "argocd/", "shared/", "state/", "charts/"],
                "extensions": [".YAML", ".yml"],
            },
            {"keyword": "billing", "path_prefixes": ["apps/billing.v2/"], "extensions": [".tar.gz"]},
        ],
        "infra_cicd": [{"path_prefixes": [".github/"]}],
        "auth": [{"keyword": "permission", "path_prefixes": ["apps/billing.v2/"], "extensions": [".yaml"]}],
    }
    policy_path = tmp_path / "policy.yml"
    policy_path.write_text(yaml.safe_dump(raw))
    policy = load_policy(
        policy_path, lockfile_names=gates._ALL_LOCKFILE_NAMES, ownership_formats=gates.OWNERSHIP_FORMAT_LOCATORS
    )
    monkeypatch.setattr(gates, "DENY_PATTERNS", gates._compile_patterns(policy.deny_pattern_defs()))
    monkeypatch.setattr(
        gates, "DENY_EXCEPTIONS", gates._compile_deny_exceptions(policy.deny_pattern_defs(), policy.deny_exceptions)
    )


@pytest.mark.parametrize(
    "files, expected",
    [
        pytest.param(["apps/billing/values.yaml"], [], id="billing-yaml"),
        pytest.param(["ARGocd/BILLING/VALUES.YML"], [], id="case-insensitive"),
        pytest.param(["shared/billing.yaml", "state/billing.yml", "charts/billing/values.yaml"], [], id="all-prefixes"),
        pytest.param(["apps/payment-billing/values.yaml"], ["billing"], id="payment-in-same-path"),
        pytest.param(["apps/stripe-billing/values.yaml"], ["billing"], id="stripe-in-same-path"),
        pytest.param(["apps/invoice-billing/values.yaml"], ["billing"], id="invoice-in-same-path"),
        pytest.param(["apps/pricing-billing/values.yaml"], ["billing"], id="pricing-in-same-path"),
        pytest.param(["apps/billing/values.json"], ["billing"], id="wrong-extension"),
        pytest.param(["apps/billing/values.yaml.py"], ["billing"], id="lookalike-extension"),
        pytest.param(["apps-other/billing/values.yaml"], ["billing"], id="lookalike-prefix"),
        pytest.param(["src/apps/billing/values.yaml"], ["billing"], id="nested-prefix"),
        pytest.param(["apps/billing.v2/values.tar.gz"], [], id="compound-suffix-and-literal-dot-prefix"),
        pytest.param(["apps/billing-v2/values.tar.gz"], ["billing"], id="dot-prefix-is-literal"),
        pytest.param(["apps/billing.v2/values.tar.gz.py"], ["billing"], id="compound-suffix-is-terminal"),
        pytest.param(["apps/billing.v2/permission.yaml"], [], id="path-only-keyword-exception"),
        pytest.param(["apps/billing.v2/permission-auth.yaml"], ["auth"], id="path-only-keeps-other-auth-pattern"),
        pytest.param(["apps/billing/permission.yaml"], ["auth"], id="path-only-keeps-other-scopes"),
        pytest.param(["apps/billing/values.yaml", "src/billing.py"], ["billing"], id="non-exempt-file"),
        pytest.param(["apps/billing/auth.yaml"], ["auth"], id="auth-stays-protected"),
        pytest.param(["apps/billing/secret.yaml"], ["crypto_secrets"], id="secrets-stay-protected"),
        pytest.param(["apps/billing/openapi.yaml"], ["public_api"], id="api-stays-protected"),
        pytest.param(["apps/billing/migrations/change.yaml"], ["migrations"], id="migrations-stay-protected"),
        pytest.param(["apps/billing/owners.yaml"], ["stamphog_policy"], id="policy-stays-protected"),
        pytest.param([".github/helm/check.py"], [], id="category-exception-without-extension"),
        pytest.param([".github/pr-deploy"], [], id="category-path-pattern"),
        pytest.param([".github-other/helm/check.py"], ["infra_cicd"], id="category-prefix-lookalike"),
        pytest.param([".github/helm/check.py", "terraform/main.tf"], ["infra_cicd"], id="category-mixed-files"),
        pytest.param([".github/workflows/codeql.yml"], ["ci_workflows"], id="other-category-same-file"),
    ],
)
def test_deny_exceptions_are_per_pattern_and_per_file(deny_exceptions, files: list[str], expected: list[str]) -> None:
    assert detect_deny_categories(files) == expected


def test_disabling_deny_exceptions_keeps_ignored_files(deny_exceptions) -> None:
    files = ["apps/billing/values.yaml", "posthog/migrations/0999_add_column.py"]
    ignored = {"posthog/migrations/0999_add_column.py"}

    assert detect_deny_categories(files, ignored_files=ignored) == []
    assert detect_deny_categories(files, ignored_files=ignored, apply_exceptions=False) == ["billing"]
    assert detect_title_scrutiny_flags("fix: billing helm auth") == ["auth", "billing", "infra_cicd"]


# ── Deny-list bypass via ignored_files ───────────────────────────


def test_ignored_files_bypass_deny_list() -> None:
    files = [
        "posthog/migrations/1117_alter_integration_kind.py",
        "posthog/migrations/max_migration.txt",
    ]
    ignored = set(files)

    assert detect_deny_categories(files, ignored_files=ignored) == []


def test_ignored_files_does_not_bypass_other_deny_list_files() -> None:
    files = [
        "posthog/migrations/1117_alter_integration_kind.py",
        "posthog/migrations/1118_add_column.py",
    ]
    ignored = {"posthog/migrations/1117_alter_integration_kind.py"}

    assert detect_deny_categories(files, ignored_files=ignored) == ["migrations"]


# ── Data warehouse connector exemption (auth + billing) ──────────


@pytest.mark.parametrize(
    "files, exempt_category",
    [
        pytest.param(
            ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/auth.py"],
            "auth",
            id="dwh-source-auth-file",
        ),
        pytest.param(
            [
                "products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.py",
                "products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/settings.py",
            ],
            "auth",
            id="dwh-source-multi-file",
        ),
        pytest.param(
            ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe_billing.py"],
            "billing",
            id="dwh-source-billing-file",
        ),
    ],
)
def test_dwh_source_exempt(files: list[str], exempt_category: str) -> None:
    assert exempt_category not in detect_deny_categories(files)


def test_dwh_source_still_denies_non_exempt_categories() -> None:
    # Only auth/billing are exempted — crypto/secrets still applies to
    # connector files that handle stored customer API keys.
    files = ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/api_key_store.py"]
    result = detect_deny_categories(files)
    assert "auth" not in result
    assert "crypto_secrets" in result


def test_dwh_source_mixed_still_denies() -> None:
    # The exemption is per-path, not per-PR: a real auth file alongside
    # connector files must still deny.
    files = [
        "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py",
        "posthog/api/authentication.py",
    ]
    assert "auth" in detect_deny_categories(files)


# ── Size-ceiling exemptions ──────────────────────────────────────


@pytest.mark.parametrize(
    "path, exempt",
    [
        pytest.param("docs/internal/monorepo-layout.md", True, id="markdown"),
        pytest.param(".agents/skills/foo/SKILL.md", True, id="skill-markdown"),
        pytest.param("docs/example-snippet.ts", True, id="docs-dir-artifact-extension"),
        pytest.param("posthog/api/test/__snapshots__/test_api.ambr", True, id="ambr-snapshot"),
        pytest.param("frontend/__snapshots__/scene.storyshot", True, id="storyshot-extension"),
        # Outside a test dir, an executable under a snapshots dir still counts
        # (extension-only snapshot exemption). Inside a test dir it is exempt
        # like any test file: test-only PRs already gate-trust the same content
        # via T0, and the LLM still reads it in the diff.
        pytest.param("frontend/__snapshots__/helper.py", False, id="executable-under-snapshots-counted"),
        pytest.param("posthog/test/__snapshots__/helper.py", True, id="snapshots-inside-test-dir-exempt"),
        pytest.param("frontend/src/generated/core/api.schemas.ts", True, id="generated-dir"),
        pytest.param("products/tasks/frontend/generated/api.ts", True, id="product-generated-dir"),
        pytest.param("services/mcp/src/api/generated.ts", True, id="mcp-client-generated-ts"),
        # Pinned to the one path CI regenerates and diffs. A file merely named generated.ts
        # elsewhere has no drift check behind it, so it stays reviewable.
        pytest.param("products/growth/frontend/generated.ts", False, id="generated-ts-off-the-checked-path"),
        pytest.param("frontend/src/scenes/generatedReport.ts", False, id="generated-prefix-counted"),
        pytest.param("services/mcp/src/api/generated_helpers.ts", False, id="generated-underscore-counted"),
        pytest.param("frontend/src/queries/schema/schema-general.ts", True, id="queries-schema"),
        pytest.param("frontend/src/types.gen.ts", True, id="dot-gen-suffix"),
        pytest.param(
            "products/desktop/packages/workspace-server/src/db/migrations/meta/0009_snapshot.json",
            True,
            id="drizzle-snapshot",
        ),
        pytest.param(
            "products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json",
            False,
            id="drizzle-journal-counted",
        ),
        pytest.param("frontend/src/meta/0001_snapshot.ts", False, id="snapshot-named-code-counted"),
        pytest.param("config/meta/0001_snapshot.json", False, id="snapshot-outside-migrations-counted"),
        pytest.param("pnpm-lock.yaml", False, id="lockfile-yaml-counted"),
        pytest.param("uv.lock", True, id="lockfile-lock-ext"),
        pytest.param("posthog/api/insight.py", False, id="python-code"),
        pytest.param("frontend/src/scenes/insights/Insight.tsx", False, id="frontend-code"),
        pytest.param("posthog/settings/web.py", False, id="settings-code"),
        pytest.param("docker-compose.dev.yml", False, id="yaml-config"),
        pytest.param("package.json", False, id="json-config"),
        pytest.param("regenerated_totals.py", False, id="generated-substring-not-dir"),
        pytest.param("frontend/src/generated/core/evil.py", False, id="generated-dir-executable-py"),
        pytest.param("frontend/src/generated/core/build.sh", False, id="generated-dir-executable-sh"),
        pytest.param("docs/generate_sidebar.py", False, id="docs-dir-executable-py"),
        pytest.param("posthog/api/test/test_insight.py", True, id="test-dir-exempt"),
        pytest.param("frontend/src/scenes/insights/Insight.test.tsx", True, id="dot-test-exempt"),
        pytest.param("posthog/personhog_client/test_interceptor.py", True, id="bare-pytest-file-exempt"),
        pytest.param(
            "common/ingestion/acceptance_tests/test_basic_capture.py", True, id="test-file-in-loose-test-tree-exempt"
        ),
        pytest.param("nodejs/src/cdp/_tests/helpers.ts", True, id="underscore-tests-dir-exempt"),
        pytest.param("posthog/tasks/protest.py", False, id="test-suffix-substring-counted"),
        pytest.param("posthog/latest/models.py", False, id="latest-dir-counted"),
        # Runtime packages that merely end in "_test(s)" must not classify as
        # tests: via the shared predicate that would open the T0 auto-approve
        # path, not just the size exemption.
        pytest.param(
            "products/batch_exports/backend/api/destination_tests/delta.py", False, id="runtime-dir-test-suffix-counted"
        ),
        pytest.param(
            "posthog/temporal/ingestion_acceptance_test/worker.py", False, id="runtime-worker-test-suffix-counted"
        ),
    ],
)
def test_is_size_exempt(path: str, exempt: bool) -> None:
    assert is_size_exempt(path) is exempt


def test_substantive_size_counts_only_non_exempt_files() -> None:
    # A docs- or test-heavy PR must not be size-denied for its prose or its
    # tests, and a code-heavy PR must not slip under the ceiling by padding
    # with either.
    files = [
        {"filename": "docs/big-rewrite.md", "additions": 2000, "deletions": 500},
        {"filename": "frontend/src/generated/core/api.ts", "additions": 900, "deletions": 900},
        {"filename": "posthog/api/insight.py", "additions": 30, "deletions": 10},
        {"filename": "posthog/api/test/test_insight.py", "additions": 50, "deletions": 0},
    ]

    lines, file_count = substantive_size(files)

    assert lines == 40
    assert file_count == 1


# ── Dependency manifests without a lockfile ──────────────────────


@pytest.mark.parametrize(
    "files, expected",
    [
        pytest.param(
            ["frontend/package.json", "frontend/src/app.ts"],
            ["frontend/package.json"],
            id="manifest-only-flagged",
        ),
        pytest.param(
            ["frontend/package.json", "pnpm-lock.yaml"],
            [],
            id="lockfile-present-hard-denies-instead",
        ),
        pytest.param(
            ["pnpm-workspace.yaml"],
            ["pnpm-workspace.yaml"],
            id="pnpm-workspace-manifest-flagged",
        ),
        pytest.param(
            ["common/esbuilder/tsconfig.json"],
            ["common/esbuilder/tsconfig.json"],
            id="tsconfig-flagged",
        ),
        pytest.param(
            ["posthog/api/insight.py"],
            [],
            id="no-manifests",
        ),
        pytest.param(
            ["frontend/package.json", "rust/Cargo.lock"],
            ["frontend/package.json"],
            id="unrelated-ecosystem-lockfile-does-not-suppress",
        ),
        pytest.param(
            ["common/esbuilder/tsconfig.json", "pnpm-lock.yaml"],
            ["common/esbuilder/tsconfig.json"],
            id="tsconfig-has-no-lockfile-always-flagged",
        ),
        pytest.param(
            ["composer.json"],
            ["composer.json"],
            id="composer-manifest-flagged",
        ),
        pytest.param(
            ["docs/some_tsconfig_notes.md"],
            [],
            id="tsconfig-substring-not-manifest",
        ),
    ],
)
def test_dependency_manifests_without_lockfile(files: list[str], expected: list[str]) -> None:
    # The deny-list no longer blocks manifest-only changes, so this helper is
    # what routes them to the reviewer's scripts/hooks guard — if it breaks,
    # a package.json scripts edit sails through with no scrutiny at all.
    assert dependency_manifests_without_lockfile(files) == expected


@pytest.mark.parametrize("ecosystem", list(DEPENDENCY_ECOSYSTEMS))
def test_dependency_ecosystem_names_are_lowercase(ecosystem: str) -> None:
    # Call sites match against Path(...).name.lower(); a mixed-case entry
    # here would silently never match and go unrecognized in a security gate.
    spec = DEPENDENCY_ECOSYSTEMS[ecosystem]
    for name in (*spec.manifests, *spec.lockfiles):
        assert name == name.lower()


@pytest.mark.parametrize(
    "path",
    [
        pytest.param("common/esbuilder/tsconfig.json", id="tsconfig"),
        pytest.param("setup.py", id="setup-py"),
        pytest.param("setup.cfg", id="setup-cfg"),
        pytest.param("pipfile", id="pipfile-manifest"),
        pytest.param("gemfile", id="gemfile-manifest"),
        pytest.param("composer.json", id="composer-manifest"),
        pytest.param("pipfile.lock", id="pipfile-lock"),
        pytest.param("gemfile.lock", id="gemfile-lock"),
        pytest.param("composer.lock", id="composer-lock"),
    ],
)
def test_has_dependency_changes_recognizes_uncurated_manifests_and_lockfiles(path: str) -> None:
    # Pins the members that DEPENDENCY_ECOSYSTEMS added beyond the old
    # curated set — a future narrowing of the table should fail here rather
    # than silently stop flagging these as dependency changes.
    assert has_dependency_changes([path]) is True


# ── Ownership sources ────────────────────────────────────────────

_HOGLI_RESOLVER = (OwnershipSource(format="hogli-resolver", path="."),)


@pytest.mark.parametrize(
    "owners_yaml, expected_teams, expected_individuals, expected_owned",
    [
        pytest.param("owners:\n  - team-devex\n", ["@PostHog/team-devex"], [], 1, id="plain-slug-prefixed"),
        # Individuals count as owned but stay out of `teams`, which feeds
        # team-membership checks and the cross-team calculus downstream.
        pytest.param("owners:\n  - '@handle'\n", [], ["@handle"], 1, id="individual-own-bucket"),
        pytest.param("name: foo\n", [], [], 0, id="ownerless"),
    ],
)
def test_resolver_owner_normalization(
    tmp_path: Path,
    owners_yaml: str,
    expected_teams: list[str],
    expected_individuals: list[str],
    expected_owned: int,
) -> None:
    (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
    product_dir = tmp_path / "products" / "foo"
    product_dir.mkdir(parents=True)
    (product_dir / "product.yaml").write_text(owners_yaml)

    resolvers = build_ownership(tmp_path, _HOGLI_RESOLVER)
    ownership = detect_ownership(["products/foo/backend/models.py"], resolvers)

    assert ownership["teams"] == expected_teams
    assert ownership["individuals"] == expected_individuals
    assert ownership["owned_files"] == expected_owned
    assert ownership["cross_team"] is False


def test_ownership_cross_team_and_unowned(tmp_path: Path) -> None:
    (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
    product_dir = tmp_path / "products" / "foo"
    product_dir.mkdir(parents=True)
    (product_dir / "product.yaml").write_text("owners:\n  - team-a\n  - team-b\n")

    resolvers = build_ownership(tmp_path, _HOGLI_RESOLVER)

    owned = detect_ownership(["products/foo/sub/x.py"], resolvers)
    assert owned["teams"] == ["@PostHog/team-a", "@PostHog/team-b"]
    assert owned["cross_team"] is True

    outside = detect_ownership(["posthog/models/x.py"], resolvers)
    assert outside["teams"] == []
    assert outside["unowned_files"] == 1


def test_ownership_counts_a_products_generated_directory_and_nothing_wider(tmp_path: Path) -> None:
    # `hogli build:openapi` rewrites a product's generated API types whenever any shared serializer
    # changes anywhere in the repo, so a team owning only those was not touched by the change. The
    # match names one directory shape on purpose: AGENTS.md rules out a general harmless-file rule,
    # and a bare `generated/` match would catch hand-editable code elsewhere in the tree.
    (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
    product_dir = tmp_path / "products" / "foo"
    product_dir.mkdir(parents=True)
    (product_dir / "product.yaml").write_text("owners:\n  - team-a\n")

    resolvers = build_ownership(tmp_path, _HOGLI_RESOLVER)
    ownership = detect_ownership(
        [
            "products/foo/frontend/generated/api.schemas.ts",
            "products/foo/backend/generated/thing.py",
            "products/foo/backend/models.py",
        ],
        resolvers,
    )

    assert ownership["team_file_counts"] == {"@PostHog/team-a": 3}
    assert ownership["team_generated_file_counts"] == {"@PostHog/team-a": 1}
    # The sample is what the digest shows a summarizer as "your files", so a path no person edited
    # does not belong in it. The count above is what the digest subtracts.
    assert ownership["team_files"] == {
        "@PostHog/team-a": ["products/foo/backend/generated/thing.py", "products/foo/backend/models.py"]
    }


def test_owners_candidates_are_fixed_offsets_from_this_file() -> None:
    # policy.repo_root() walks up to find a .stamphog/ directory, and the PR head is untrusted. A PR
    # that adds tools/.stamphog/ would move that root and aim the lookup at a directory that the PR
    # controls. The sandbox would then import that directory, and the sandbox holds the run's LLM
    # credentials. Both candidates must stay fixed offsets from the engine's own file.
    engine_dir = Path(gates.__file__).resolve().parent
    assert gates._OWNERS_PKG_CANDIDATES == (
        engine_dir.parent / "owners",
        engine_dir.parents[3] / "packages" / "owners-yaml",
    )


@pytest.mark.parametrize(
    "engine_file, resolver_dir, planted_dirs",
    [
        pytest.param(
            "root/products/stamphog/packages/pr-approval-agent/gates.py",
            "root/packages/owners-yaml",
            (),
            id="monorepo",
        ),
        pytest.param("root/tools/pr-approval-agent/gates.py", "root/tools/owners", (), id="sandbox-and-vendored"),
        pytest.param(
            "root/a/b/c/pr-approval-agent/gates.py",
            "root/a/b/c/owners",
            ("root/packages/owners-yaml",),
            id="sandbox-engine-moved-by-pr-symlink",
        ),
    ],
)
def test_the_owners_package_is_found_in_both_engine_layouts(
    tmp_path: Path, engine_file: str, resolver_dir: str, planted_dirs: tuple[str, ...]
) -> None:
    expected = tmp_path / resolver_dir
    for package_dir in (resolver_dir, *planted_dirs):
        (tmp_path / package_dir / "owners_yaml").mkdir(parents=True)
    engine_path = tmp_path / engine_file
    engine_path.parent.mkdir(parents=True)
    engine_path.touch()

    found = [candidate for candidate in gates._owners_pkg_candidates(engine_path) if candidate.is_dir()]

    assert found[0] == expected.resolve()