:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): gate new products on an isolation baseline (#83813)
Julian Bez17fad3c3bf0d
diff --git a/.claude/rules/product-isolation.md b/.claude/rules/product-isolation.mdindex 6a5d985b1f27..031af8b39b58 100644--- a/.claude/rules/product-isolation.md+++ b/.claude/rules/product-isolation.md@@ -3,7 +3,11 @@ paths:- 'products/*/backend/**'----**Check this product's isolation status before making changes.**+**Creating a new product? Run `hogli product:bootstrap <name>` — do not hand-roll the directory.**+The scaffold emits a product that is isolated from its first commit, and `product:lint --all`+fails on a new product that is not — see "New products must be isolated" in `products/README.md`.++**Otherwise, check this product's isolation status before making changes.**Look at the product's `package.json`: if `backend:contract-check` is listed under `scripts`,this product is isolated.@@ -20,8 +24,11 @@ this product is isolated.`(product, class)` pairs on the frozen watched-models allowance (`MODEL_CROSSINGS`),whose `backend/models/` + `backend/migrations/` must stay in the contract-check inputs(see `products/architecture.md` § Wiring couplings).-- **Not isolated:** boundaries are not yet enforced by CI, but prefer using existing- facades when they exist rather than importing internals.+- **Not isolated** (the product is listed in `products/isolation_baseline.txt`): boundaries+ are not enforced by CI for it yet, but prefer using existing facades when they exist rather+ than importing internals.+ A product that is neither isolated nor on that list is a new product that skipped the+ scaffold — see above.If you need to extend what's reachable across a boundary, add a function to the relevantfacade module (or a re-export to its wiring submodule) — not a `depends_on` entry indiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 5bd30cfbee0e..60d731e8f4dc 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -327,6 +327,9 @@ jobs:- 'tools/hogli-commands/hogli_commands/hints.py'- 'tools/hogli-commands/hogli_commands/product/**'- 'tools/hogli-commands/hogli_commands/product_structure.yaml'+ # product:lint --all checks this generated file against the tree,+ # so a baseline-only edit must run it too+ - products/isolation_baseline.txt# Make sure we run if someone is explicitly changing the workflow- .depot/workflows/ci-backend.yml- .github/clickhouse-versions.jsondiff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 326266c82235..592029030b05 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -72,3 +72,9 @@ bin/dev-sandbox* @PostHog/team-security# deploy — installable by all tenants and feeding tool results into their LLM agents. The# probe only verifies liveness, so PR review is the vendor-identity gate.products/mcp_store/backend/catalog.py @PostHog/team-self-driving @cvolzer3++# Adding a line here exempts a product from isolation, so the full Django backend suite+# keeps running on every change it makes — a cost paid by everyone, not just its team.+# `hogli product:bootstrap` scaffolds a sealed product, so a new one should never need an+# entry. Removals are the mechanical result of a product sealing and are a rubber stamp.+products/isolation_baseline.txt @PostHog/team-devexdiff --git a/.github/scripts/check-product-scaffold.sh b/.github/scripts/check-product-scaffold.shnew file mode 100755index 000000000000..c2d7d2169540--- /dev/null+++ b/.github/scripts/check-product-scaffold.sh@@ -0,0 +1,40 @@+#!/usr/bin/env bash+# Warn when a commit introduces a product directory that did not come from+# `hogli product:bootstrap`. Never blocks: the author may be mid-work, and CI+# holds the real gate (`hogli product:lint --all` against+# products/isolation_baseline.txt).+#+# Scoped to product backends that are new in this commit. Existing products are+# skipped outright, so this never has to answer "is this product isolated" — a+# question that already has one implementation, in+# tools/hogli-commands/hogli_commands/product/isolation.py, and does not need a+# second one in shell.+set -uo pipefail++BASELINE=products/isolation_baseline.txt++# Keyed on backend/, not on the product directory. Several directories under+# products/ hold only skills or scripts and are not Django products at all, and a+# frontend-only product has nothing to isolate. Keying on the backend also keeps+# the warning working when the backend arrives in a later commit than the+# directory it lands in.+new_backends=$(+ git diff --cached --name-only --diff-filter=A \+ | sed -n 's|^products/\([^/.][^/]*\)/backend/.*|\1|p' \+ | sort -u+)++for product in $new_backends; do+ # Backend already tracked, so this commit is not introducing it.+ git rev-parse -q --verify "HEAD:products/$product/backend" >/dev/null 2>&1 && continue+ # Scaffolded: bootstrap always writes turbo.json with narrowed inputs.+ [ -f "products/$product/turbo.json" ] && continue+ # Signed onto the baseline in this same commit, so devex has reviewed it.+ [ -f "$BASELINE" ] && grep -qx "$product" "$BASELINE" && continue++ printf "\n\033[33mWarning: products/%s is a new product that did not come from the scaffold.\n" "$product"+ printf " Run: hogli product:bootstrap %s\n" "$product"+ printf " The scaffold produces a product that is isolated from its first commit, so its\n"+ printf " changes skip the full Django backend suite. A hand-rolled product fails\n"+ printf " 'hogli product:lint --all' unless devex lists it in %s.\033[0m\n\n" "$BASELINE"+donediff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 337c5e99b625..a0f31c0a6877 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -203,6 +203,9 @@ jobs:- 'tools/hogli-commands/hogli_commands/hints.py'- 'tools/hogli-commands/hogli_commands/product/**'- 'tools/hogli-commands/hogli_commands/product_structure.yaml'+ # product:lint --all checks this generated file against the tree,+ # so a baseline-only edit must run it too+ - products/isolation_baseline.txt# Make sure we run if someone is explicitly changing the workflow- .github/workflows/ci-backend.yml- .github/clickhouse-versions.jsondiff --git a/.husky/pre-commit b/.husky/pre-commitindex 070259d3510e..3463d01f6f42 100755--- a/.husky/pre-commit+++ b/.husky/pre-commit@@ -33,6 +33,13 @@ if [ -x .github/scripts/check-access-control-doc-sync.sh ]; then.github/scripts/check-access-control-doc-sync.sh || truefi+# Same deal for a product directory that appears without coming from+# `hogli product:bootstrap`: warn at the commit that introduces it, rather than+# leaving the author to find out from CI after the shape is set.+if [ -x .github/scripts/check-product-scaffold.sh ]; then+ .github/scripts/check-product-scaffold.sh || true+fi+# Activate Flox environment if available and not already active# This ensures lint-staged commands work in GUI Git clients (GitHub Desktop, etc.)if command -v flox > /dev/null 2>&1 && [ -d ".flox/cache" ] && [ -z "$FLOX_ENV" ]; thendiff --git a/AGENTS.md b/AGENTS.mdindex e718c37e343b..d14b1bb6bb77 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -31,7 +31,6 @@- Cloud task VMs (prebaked dev-stack image): run `bootstrap-dev-stack` first (restores compose host aliases, starts dockerd), then `uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait` (the detached start returns while the stack is still booting; `hogli wait` blocks until every process is ready) — always detached: the sandbox has no TTY, and phrocs under a pseudo-TTY balloons in memory until OOM-killed- Cloud task VMs, frontend work: `pnpm install --frozen-lockfile --prefer-offline` links from the prebaked pnpm store, and Playwright Chromium is preinstalled; product/Storybook builds still run from source- OpenAPI/types: `hogli build:openapi` (regenerate after changing serializers/viewsets)-- New product: `bin/hogli product:bootstrap <name>`- LSP: Pyright is configured against the flox venv. Prefer LSP (`goToDefinition`, `findReferences`, `hover`) over grep when navigating or refactoring Python code.- Dev experience feedback: `hogli devex:feedback "<message>"` sends feedback about repo tooling — hogli, the dev stack, tests, CI, migrations, this setup — straight to the devex team as a `hogli_feedback` event (add `-c bug|idea|praise|question`).**Local agents must use it too**: when a hogli command or local dev workflow is broken, slow, or confusing, run it — e.g. `hogli devex:feedback -c bug "migrations:run failed with <error>"`. Do not run it from cloud tasks or agent-server sandboxes; the command is a no-op there.@@ -185,7 +184,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least- MCP tools are generated from the same OpenAPI spec — see [implementing MCP tools](docs/published/handbook/engineering/ai/implementing-mcp-tools.md) for the YAML config and codegen workflow- MCP UI apps (interactive visualizations for tool results) are defined in `products/*/mcp/tools.yaml` under `ui_apps` and auto-generated — see [services/mcp/CONTRIBUTING.md](services/mcp/CONTRIBUTING.md) or use the `implementing-mcp-ui-apps` skill- When touching a viewset or serializer, ensure schema annotations are present (`@extend_schema` or `@validated_request` on viewset methods, `help_text` on serializer fields) — these flow into generated frontend types and MCP tool schemas-- New features should live in `products/` — read [products/README.md](products/README.md) for layout and setup. When _creating a new_ product, follow [products/architecture.md](products/architecture.md) (DTOs, facades, isolation). Code a single product owns — not just backend/frontend, but scripts, CLIs, services, packages, MCP tools, skills — belongs under `products/<product>/`; reserve top-level `tools/`/`services/`/`packages/`/`cli/` for cross-product things+- New features should live in `products/`. **Create one with `hogli product:bootstrap <name>` — never hand-roll the directory.** The scaffold emits a product that is isolated from its first commit, and `product:lint --all` fails on a new product that is not (see "New products must be isolated" in [products/README.md](products/README.md); [products/architecture.md](products/architecture.md) covers the facade and contract design). Code a single product owns — not just backend/frontend, but scripts, CLIs, services, packages, MCP tools, skills — belongs under `products/<product>/`; reserve top-level `tools/`/`services/`/`packages/`/`cli/` for cross-product things- **Every tenant-data model must have `team_id`** — either as a FK (`models.ForeignKey("posthog.Team", ...)`) or a plain `BigIntegerField` (for multi-DB products). This is the primary tenant isolation boundary. Models without `team_id` must be org-scoped, user-scoped, or instance-global — never silently unscoped. New models should inherit from `TeamScopedRootMixin` (main DB) or `ProductTeamModel` (separate DB) so they start fail-closed — see `posthog/models/scoping/README.md`. CI enforces this via `posthog/models/scoping/baseline_unmigrated.txt`: any new team-scoped model not on a fail-closed manager fails the IDOR coverage check. In serializers, access the team via `self.context["get_team"]()`. When querying a fail-closed model for one team outside request context (Temporal activities, Celery tasks, management commands), use `Model.objects.for_team(team_id)` — not `Model.all_teams.filter(team_id=...)` or `objects.unscoped().filter(...)`; reserve `all_teams`/`unscoped()` for genuinely cross-team access and Django framework internals. Caveat: `for_team(...).get_or_create(...)`/`.create(...)` still need `team_id` passed explicitly — queryset filters don't propagate into row creation- **Do not add domain-specific fields to the `Team` model.** Use a Team Extension model instead — see `posthog/models/team/README.md` for the pattern and helpers- **PostHog event capture in Celery tasks:** Do not use `posthoganalytics.capture()` in Celery tasks — events are silently lost. Use `ph_scoped_capture` from `posthog.ph_client` instead (see its docstring for why and usage).diff --git a/products/README.md b/products/README.mdindex 6f52339c8cfb..8d992d4e6879 100644--- a/products/README.md+++ b/products/README.md@@ -165,6 +165,20 @@ The lint command validates:> [!NOTE]> To migrate a product to full isolation (facade + contracts + selective testing), use the `isolating-product-facade-contracts` skill. See [products/architecture.md](architecture.md) for the target architecture.+### New products must be isolated++`products/isolation_baseline.txt` lists every product that is not isolated, and `hogli product:lint --all` fails when the tree and that file disagree in either direction.+A new product not on the list must be isolated; a product that seals drops off it.++`hogli product:bootstrap` scaffolds a product that is already sealed — real facade, contracts, tach `[[interfaces]]`, `backend:contract-check`, narrowed `turbo.json` — so a new product should never need a line.+Adding one exempts the product from isolation and keeps the full Django backend suite running on every change it makes, which is why the file is owned by DevEx in `.github/CODEOWNERS`.++Regenerate after sealing a product:++```bash+bin/hogli product:lint --regenerate-baseline+```+### Manual setup- Create a new folder `products/your_product_name`, keep it underscore-cased.diff --git a/products/architecture.md b/products/architecture.mdindex 9f0d6c70f97b..8f28aee8c8d1 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -158,6 +158,8 @@ myproduct/views.py # DRF views (HTTP endpoints)urls.py # HTTP routing+ routes.py # register_routes(routers): the one module core reads to mount the views+tests/test_models.pytest_logic.py@@ -174,6 +176,18 @@ myproduct/- Provides an explicit, enforced boundary (`facade/`)- Scales naturally with contract-based selective testing+### Which locations are fixed, and which are yours++Only the paths the tooling is pointed at have fixed names: `facade/`, `presentation/`, `tasks/`, `routes.py`, and the wiring locations (`hogql_queries/`, `max_tools.py`, `temporal/`) — see [Wiring couplings](#wiring-couplings).+They are the narrowed `backend:contract-check` inputs, and two import-linter contracts hold the HTTP surface inside them by shape: `routes.py` may only import `presentation/`, and `presentation/` may only import `facade/`.+Core reaches a product's views only through `routes.py`, so the chain core → routes → presentation → facade is three import edges, and a view anywhere else simply cannot be routed.+`hogli product:lint` holds the same two rules by reading the imports directly, because import-linter cannot see a module under a directory without `__init__.py`.++Everything else under `backend/` is internal implementation.+`logic/` is the default home and the scaffold creates it as a package, but as a domain grows into `services/`, `queries/`, `reviewer/`, or whatever it is called in that product, no lint polices the name.+Nothing outside the product can import those packages, and their changes are exactly what the isolation skip is meant to skip.+The boundary is the shape of what crosses the facade, not the location of what stays behind it.+For the broader monorepo structure (products, services, platform), see [monorepo-layout.md](/docs/internal/monorepo-layout.md).# 4. Contracts (`contracts.py`)@@ -292,9 +306,10 @@ The value isn't the copying — it's having **one place** where "internal" becomThe alternative — returning ORM objects — works until it doesn't, then you're retrofitting isolation under pressure.-# 6. Business Logic (backend/logic.py)+# 6. Business Logic (backend/logic/)Business logic lives here: validation, calculations, business rules, ORM queries.+Further internal packages beside it are fine (see [Which locations are fixed](#which-locations-are-fixed-and-which-are-yours)).Start as a single `logic.py`.Once it outgrows one file, split it into a `logic/` package with one module per concern and mirror that split in `tests/logic/` — `products/visual_review/backend/logic/` is the reference, and `/splitting-oversized-modules` does the move.@@ -328,6 +343,8 @@ Responsibilities:Presentation may only import `facade` and other `presentation` modules within the same product. It must not import `models`, `logic`, or any other internal module directly — even utility modules like `cache.py` or `permissions.py`. This is enforced by import-linter in CI.+`backend/routes.py` may only import `presentation` — it exists to hand the views to core's router (`register_routes(routers)`), nothing else. Also enforced by import-linter; a product whose routes still register views from `backend/api/` carries a grandfathered `ignore_imports` line, and `hogli product:maturity` counts it as an open presentation bypass until `hogli product:isolate:move` relocates them.+### Where do cross-cutting utilities go?If both presentation and logic need the same utility (caching, permissions, etc.), putting it at `backend/cache.py` and importing from both layers creates an "accidental shared kernel" — a hidden coupling that bypasses the facade. Instead:diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txtnew file mode 100644index 000000000000..16517ba05ca2--- /dev/null+++ b/products/isolation_baseline.txt@@ -0,0 +1,80 @@+# Products that are not isolated — the full Django backend suite still runs on+# every change they make.+#+# DO NOT EDIT BY HAND. This file is the mechanical output of+# `hogli product:lint --regenerate-baseline`. Hand-editing turns a ratchet back+# into a curated allowlist, which is the thing it exists to prevent.+#+# Adding a line needs DevEx review (see .github/CODEOWNERS). New products should+# not need one: `hogli product:bootstrap <name>` scaffolds a product that is+# sealed from its first commit.+#+# Getting off this list: build the facade (contracts.py + real api.py), add the+# tach [[interfaces]] block, then wire `backend:contract-check` and narrow+# turbo.json inputs. `hogli product:maturity <name>` names the remaining blocker+# at every step, and /isolating-product-facade-contracts walks the migration.+#+# Once a product is sealed, regenerate this file and its line drops out.++access_control+actions+ai_gateway+ai_observability+alerts+analytics_platform+annotations+apm+approvals+batch_exports+billing_alerts+business_knowledge+canvas+cdp+cohorts+conversations+dashboards+data_catalog+data_modeling+data_quality+data_tools+data_warehouse+demo+early_access_features+endpoints+event_definitions+experiments+exports+feature_flags+field_notes+growth+links+live_debugger+llm_analytics+logs+managed_migrations+marketing_analytics+mcp_analytics+mcp_store+messaging+notebooks+notifications+platform_features+posthog_ai+product_analytics+product_tours+pulse+reminders+replay+replay_vision+revenue_analytics+review_hog+signals+skills+slack_app+surveys+tasks+tracing+user_interviews+warehouse_sources_queue+web_analytics+workflowsdiff --git a/pyproject.toml b/pyproject.tomlindex b53ce11ae089..d1b1fda0f821 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -678,6 +678,88 @@ ignore_imports = [# backend:contract-check stays off until this list is empty.]+# routes.py is the one module core reads to assemble a product's API router, so it is the+# only way a view becomes reachable over HTTP. Restricting what it may import gives the chain+# core -> routes -> presentation -> facade as three import edges: a ViewSet outside+# presentation/ cannot be routed, and the contract above already keeps presentation/ from+# reaching past the facade. Grandfathered edges below are products whose views still live in+# backend/api/; `hogli product:isolate:move` relocates them and the line comes out.+[[tool.importlinter.contracts]]+name = "routes must only import presentation"+type = "forbidden"+source_modules = ["products.*.backend.routes"]+forbidden_modules = [+ "products.*.backend",+]+allow_indirect_imports = true+ignore_imports = [+ "products.**.backend.routes -> products.**.backend.presentation.**",+ # TODO: views still registered from backend/api/ — move them into presentation/ and drop the line+ "products.actions.backend.routes -> products.actions.backend.api.action",+ "products.ai_observability.backend.routes -> products.ai_observability.backend.api",+ "products.alerts.backend.routes -> products.alerts.backend.api.alert",+ "products.annotations.backend.routes -> products.annotations.backend.api.annotation",+ "products.approvals.backend.routes -> products.approvals.backend.api",+ "products.batch_exports.backend.routes -> products.batch_exports.backend.api.batch_export",+ "products.batch_exports.backend.routes -> products.batch_exports.backend.api.file_download",+ "products.business_knowledge.backend.routes -> products.business_knowledge.backend.api",+ "products.cdp.backend.routes -> products.cdp.backend.api.hog_function",+ "products.cdp.backend.routes -> products.cdp.backend.api.hog_function_template",+ "products.cdp.backend.routes -> products.cdp.backend.api.plugin",+ "products.cdp.backend.routes -> products.cdp.backend.api.plugin_log_entry",+ "products.cohorts.backend.routes -> products.cohorts.backend.api.staff_tools",+ "products.conversations.backend.routes -> products.conversations.backend.api",+ "products.dashboards.backend.routes -> products.dashboards.backend.api.dashboard",+ "products.dashboards.backend.routes -> products.dashboards.backend.api.dashboard_templates",+ "products.early_access_features.backend.routes -> products.early_access_features.backend.api",+ "products.exports.backend.routes -> products.exports.backend.api.exports",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.feature_flag",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.flag_value",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.organization_feature_flag",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.scheduled_change",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.staff_cache",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.staff_team_config",+ "products.feature_flags.backend.routes -> products.feature_flags.backend.api.staff_teams",+ "products.field_notes.backend.routes -> products.field_notes.backend.api",+ "products.growth.backend.routes -> products.growth.backend.api.ai_enrichment",+ "products.growth.backend.routes -> products.growth.backend.api.identity_matching",+ "products.growth.backend.routes -> products.growth.backend.api.product_push",+ "products.links.backend.routes -> products.links.backend.api",+ "products.live_debugger.backend.routes -> products.live_debugger.backend.api",+ "products.managed_migrations.backend.routes -> products.managed_migrations.backend.api.batch_imports",+ "products.managed_migrations.backend.routes -> products.managed_migrations.backend.api.support_batch_imports",+ "products.marketing_analytics.backend.routes -> products.marketing_analytics.backend.api",+ "products.messaging.backend.routes -> products.messaging.backend.api.message_categories",+ "products.messaging.backend.routes -> products.messaging.backend.api.message_preferences",+ "products.messaging.backend.routes -> products.messaging.backend.api.message_suppression",+ "products.messaging.backend.routes -> products.messaging.backend.api.message_templates",+ "products.posthog_ai.backend.routes -> products.posthog_ai.backend.api",+ # product_analytics registers the alerts viewset under insights; that moves with alerts'+ # own routes.py and presentation/ (cross-product ownership is tach's concern, not this one)+ "products.product_analytics.backend.routes -> products.alerts.backend.api.alert",+ "products.product_tours.backend.routes -> products.product_tours.backend.api",+ "products.pulse.backend.routes -> products.pulse.backend.api.brief",+ "products.reminders.backend.routes -> products.reminders.backend.api.reminder",+ "products.replay_vision.backend.routes -> products.replay_vision.backend.api",+ "products.revenue_analytics.backend.routes -> products.revenue_analytics.backend.api",+ "products.review_hog.backend.routes -> products.review_hog.backend.api",+ "products.signals.backend.routes -> products.signals.backend.views",+ "products.signals.backend.routes -> products.signals.backend.scout_chat",+ "products.signals.backend.routes -> products.signals.backend.scout_harness.views",+ "products.skills.backend.routes -> products.skills.backend.api.community_skills",+ "products.skills.backend.routes -> products.skills.backend.api.marketplace_views",+ "products.skills.backend.routes -> products.skills.backend.api.skills",+ "products.surveys.backend.routes -> products.surveys.backend.api.survey",+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api",+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api.heatmaps_api",+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_achievements",+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_filter_preset",+ "products.web_analytics.backend.routes -> products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions",+ "products.workflows.backend.routes -> products.workflows.backend.api.hog_flow",+ "products.workflows.backend.routes -> products.workflows.backend.api.hog_flow_template",+ "products.workflows.backend.routes -> products.workflows.backend.api.workflow_tasks",+]+[tool.ty.rules]# Import resolution - ty can't always find all modules/stubsunresolved-import = "ignore"diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex 3100619353e6..af6c72f4f7a2 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -356,6 +356,37 @@ def count_viewset_files(directory: Path) -> int:return count+def module_import_targets(file_path: Path, package_root: Path, package_prefix: str) -> list[tuple[int, str]]:+ """(line, dotted module) for every absolute import in the file that names a module under+ `package_prefix` (e.g. "products.foo.backend"), resolved against `package_root` (the+ directory that prefix maps to) so `from a.b import c` yields `a.b.c` when c is a+ module or package and `a.b` when c is a name.++ Pure AST: unlike grimp it does not need __init__.py markers to see a module, which is+ what lets a lint hold an import-linter contract in directories grimp cannot descend into.+ """+ tree = ast_parse_safe(file_path)+ if not tree:+ return []+ prefix_dot = package_prefix + "."++ def is_module(dotted: str) -> bool:+ rel = Path(*dotted[len(prefix_dot) :].split("."))+ return (package_root / rel).is_dir() or (package_root / rel).with_suffix(".py").exists()++ targets: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ targets.extend((node.lineno, a.name) for a in node.names if a.name.startswith(prefix_dot))+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:+ if node.module != package_prefix and not node.module.startswith(prefix_dot):+ continue+ for alias in node.names:+ candidate = f"{node.module}.{alias.name}"+ targets.append((node.lineno, candidate if is_module(candidate) else node.module))+ return [(line, dotted) for line, dotted in targets if dotted.startswith(prefix_dot)]++def _collect_py_files(path: Path) -> list[Path]:"""Return list of .py files — the file itself if a file, or all *.py in dir (non-recursive)."""if path.is_file():diff --git a/tools/hogli-commands/hogli_commands/product/baseline.py b/tools/hogli-commands/hogli_commands/product/baseline.pynew file mode 100644index 000000000000..d3c45f09412b--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/baseline.py@@ -0,0 +1,104 @@+"""Isolation baseline ratchet — the entry gate for new products.++`product:bootstrap` emits a product that is already sealed: real facade, contracts,+tach `[[interfaces]]`, narrowed `turbo.json`, `backend:contract-check`. So "new products+are isolated" costs a team nothing beyond using the scaffold, and every product that+isn't sealed is either pre-scaffold debt or a deliberate exemption.++`products/isolation_baseline.txt` records exactly that set. The check is strict equality:++ - unsealed product missing from the baseline -> fail (a new product skipped the scaffold,+ or a sealed one regressed)+ - baseline entry that is now sealed -> fail (regenerate to shrink)++Equality is what makes the file safe to trust. A baseline that may be stale is a standing+permission slip: a product could seal, keep its line, then lose its facade again and still+pass. Requiring both directions to match means a line exists only while it is earned.++The file is CODEOWNERS-owned by DevEx, so adding an exemption is a conversation. Removals+are a rubber stamp on a win.+"""++from __future__ import annotations++import click++from .isolation import compute_isolation_status+from .paths import ISOLATION_BASELINE, PRODUCTS_DIR, TACH_TOML, backend_product_dirs++HEADER = """\+# Products that are not isolated — the full Django backend suite still runs on+# every change they make.+#+# DO NOT EDIT BY HAND. This file is the mechanical output of+# `hogli product:lint --regenerate-baseline`. Hand-editing turns a ratchet back+# into a curated allowlist, which is the thing it exists to prevent.+#+# Adding a line needs DevEx review (see .github/CODEOWNERS). New products should+# not need one: `hogli product:bootstrap <name>` scaffolds a product that is+# sealed from its first commit.+#+# Getting off this list: build the facade (contracts.py + real api.py), add the+# tach [[interfaces]] block, then wire `backend:contract-check` and narrow+# turbo.json inputs. `hogli product:maturity <name>` names the remaining blocker+# at every step, and /isolating-product-facade-contracts walks the migration.+#+# Once a product is sealed, regenerate this file and its line drops out.+"""+++def unsealed_products() -> list[str]:+ """Every backend product whose `backend:contract-check` skip is not live.++ Keyed on the skip actually being wired, not on the facade merely existing: a+ re-export shim with an empty contracts.py would otherwise buy its way off the+ list without sealing anything.+ """+ tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""+ unsealed = []+ for product_dir in backend_product_dirs():+ status = compute_isolation_status(+ product_dir.name, product_dir, product_dir / "backend", tach_content=tach_content+ )+ if not status.isolated_tests_enabled:+ unsealed.append(product_dir.name)+ return unsealed+++def read_baseline() -> set[str]:+ if not ISOLATION_BASELINE.exists():+ return set()+ lines = ISOLATION_BASELINE.read_text().splitlines()+ return {line.strip() for line in lines if line.strip() and not line.startswith("#")}+++def write_baseline(names: list[str]) -> None:+ ISOLATION_BASELINE.write_text(HEADER + "\n" + "".join(f"{name}\n" for name in sorted(names)))+++def regenerate_baseline() -> None:+ names = unsealed_products()+ write_baseline(names)+ click.echo(f" Regenerated {ISOLATION_BASELINE.relative_to(PRODUCTS_DIR.parent)}")+ click.echo(f" {len(names)} product(s) not isolated.")+++def baseline_issues(unsealed: set[str], baseline: set[str]) -> list[str]:+ """Strict equality in both directions. Returns issues; empty means in sync."""+ issues = []+ for name in sorted(unsealed - baseline):+ issues.append(+ f"{name} is not isolated and is not in the baseline — scaffold it with "+ f"`hogli product:bootstrap` (products are sealed from their first commit), or ask "+ f"DevEx to sign off on an exemption. `hogli product:maturity {name}` names the blocker"+ )+ for name in sorted(baseline - unsealed):+ issues.append(+ f"{name} is in the baseline but is now isolated — run "+ f"`hogli product:lint --regenerate-baseline` to drop its line"+ )+ return issues+++def check_baseline() -> list[str]:+ return baseline_issues(set(unsealed_products()), read_baseline())diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex a787573bb9a0..b0f9cdda9c0f 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -16,12 +16,14 @@ from collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom pathlib import Path+from .ast_helpers import module_import_targetsfrom .isolation import (IsolationStatus,compute_isolation_status,has_legacy_interface_leaks,has_routes_module,has_tach_interface,+ ignored_import_edges,is_isolated_product,iter_interface_blocks as _iter_interface_blocks,location_input_glob,@@ -428,6 +430,62 @@ def _contract_check_withheld_note(status: IsolationStatus) -> str | None:return None+class ImportSurfaceCheck(ProductCheck):+ """Hold the two import-linter contracts by AST, so a namespace package cannot dodge them.++ The contracts say routes.py imports only presentation/, and presentation/ imports only+ facade/ and itself. import-linter enforces both through grimp, and grimp does not descend+ into a directory without an __init__.py — so `from ...backend.services.views import X`+ with no `services/__init__.py` is invisible to it and the contract passes vacuously.+ That is a live view outside presentation/ that the narrowed contract-check inputs do not+ watch. This check reads the same imports straight from the AST, honors the same+ ignore_imports deferrals, and fails on what grimp cannot see.+ """++ label = "import surface"+ for_lenient = False++ # (source subtree or module, allowed destination subtrees)+ SURFACES = (+ ("routes", ("presentation",)),+ ("presentation", ("presentation", "facade")),+ )++ def should_run(self, ctx: CheckContext) -> bool:+ return super().should_run(ctx) and ctx.backend_dir.is_dir()++ def _module_name(self, ctx: CheckContext, path: Path) -> str:+ rel = path.relative_to(ctx.backend_dir).with_suffix("")+ parts = [p for p in rel.parts if p != "__init__"]+ return ".".join([f"products.{ctx.name}.backend", *parts]) if parts else f"products.{ctx.name}.backend"++ def run(self, ctx: CheckContext) -> CheckResult:+ prefix = f"products.{ctx.name}.backend"+ ignored = ignored_import_edges()+ issues = []+ for source, allowed in self.SURFACES:+ root = ctx.backend_dir / source+ files = [root.with_suffix(".py")] if root.with_suffix(".py").exists() else []+ if root.is_dir():+ files += sorted(f for f in root.rglob("*.py") if "__pycache__" not in f.parts)+ allowed_prefixes = tuple(f"{prefix}.{a}" for a in allowed)+ for f in files:+ importer = self._module_name(ctx, f)+ for line, target in module_import_targets(f, ctx.backend_dir, prefix):+ if target.startswith(allowed_prefixes) or f"{importer} -> {target}" in ignored:+ continue+ issues.append(+ f"{f.relative_to(ctx.product_dir)}:{line} imports {target} — {source} may only import "+ f"{'/'.join(allowed)}. If import-linter did not flag this, the target sits under a "+ "directory without __init__.py, which grimp cannot see"+ )+ if issues:+ return CheckResult(+ lines=[f"✗ {len(issues)} import(s) outside the surface"] + [f" → {i}" for i in issues], issues=issues+ )+ return CheckResult(lines=["✓ ok"])++class PackageJsonScriptsCheck(ProductCheck):label = "package.json scripts"@@ -543,42 +601,13 @@ class MisplacedFilesCheck(ProductCheck):label = "misplaced backend files"for_lenient = False- # Directories allowed in backend/ for strict products.- # Anything else won't be covered by import-linter's wildcard contracts.- # `templates` is allowed because Django's app_directories loader requires- # the folder to live at <app>/templates/, and templates aren't Python- # imports so import-linter contracts don't apply.- # `admin` is allowed because Django's autodiscover_modules("admin") requires- # the admin module at <app>.admin — and that module can be a flat `admin.py`- # or an `admin/` package (both resolve to the same import). The file form is- # already accepted, so the package form has to be too.- # `hogql_queries` is the established home for HogQL query runners across- # products (web_analytics, revenue_analytics, product_analytics), so it is- # allowed in isolated products too rather than forcing query code into logic/.- # `temporal` is the established home for Temporal workflow + activity code- # across products (batch_exports, data_warehouse, tasks, experiments, and- # others), so it is allowed in isolated products on the same grounds.- # `sandbox` holds Docker build context (Dockerfiles + helper scripts) for- # sandboxed execution, not importable Python — its path is referenced by- # image-build workflows and COPY directives, so it can't follow the- # Python-package convention and is allowed at backend root.- _KNOWN_DIRS = {- "facade",- "presentation",- "tasks",- "tests",- "test",- "migrations",- "management",- "models",- "logic",- "hogql_queries",- "temporal",- "sandbox",- "templates",- "admin",- "__pycache__",- }+ # Only the root-level files in `backend_known_files` are checked here. Directory+ # names are deliberately not: which internal packages a product has (`logic/`,+ # `services/`, `reviewer/`) is its own business, and the thing that must not+ # drift — presentation code outside presentation/ — is enforced by shape in+ # pyproject.toml: routes.py may only import presentation, and presentation may+ # only import facade, so a view anywhere else cannot be routed. ImportSurfaceCheck+ # holds the same two rules by AST where grimp cannot see.def run(self, ctx: CheckContext) -> CheckResult:if not ctx.backend_dir.exists():@@ -594,16 +623,6 @@ class MisplacedFilesCheck(ProductCheck):else:misplaced.append(f"backend/{filename} should be at backend/{correct_path}")- # Flag directories not in the canonical structure — these bypass- # import-linter's wildcard enforcement (presentation/facade/etc.)- for child in sorted(ctx.backend_dir.iterdir()):- if child.is_dir() and child.name not in self._KNOWN_DIRS:- misplaced.append(- f"backend/{child.name}/ is not a recognized directory — "- "import-linter only enforces canonical paths (presentation, facade, logic, models). "- "Move code into an existing directory or update the product structure"- )-if misplaced:return CheckResult(lines=[f"✗ {len(misplaced)} misplaced file(s)"] + [f" → {m}" for m in misplaced],@@ -1142,6 +1161,7 @@ CHECKS: list[ProductCheck] = [ProductYamlCheck(),RequiredRootFilesCheck(),BackendPackageMarkerCheck(),+ ImportSurfaceCheck(),PackageJsonScriptsCheck(),MisplacedFilesCheck(),FileFolderConflictsCheck(),diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex d6b178fae626..b39adde22659 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport click+from .baseline import regenerate_baseline as do_regenerate_baselinefrom .lint import lint_all_products, lint_owners, lint_productfrom .maturity import generate_codegen_report, generate_detail, generate_report, score_all_products, score_productfrom .scaffold import bootstrap_product@@ -62,7 +63,18 @@ def cmd_bootstrap(@click.command(name="product:lint", help="Check product structure for misplaced files")@click.argument("name", required=False)@click.option("--all", "lint_all", is_flag=True, help="Lint all products")-def cmd_lint(name: str | None, lint_all: bool) -> None:+ "--regenerate-baseline",+ is_flag=True,+ help="Rewrite products/isolation_baseline.txt from the current tree (adding a line needs DevEx review)",+)+def cmd_lint(name: str | None, lint_all: bool, regenerate_baseline: bool) -> None:+ if regenerate_baseline:+ if name or lint_all:+ raise click.UsageError("--regenerate-baseline takes no product name and does not combine with --all")+ do_regenerate_baseline()+ return+if lint_all:lint_all_products()returndiff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex 70d5a1e5b794..672e318b4013 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -222,13 +222,8 @@ def permanent_interface_modules(tach_content: str, module_path: str) -> set[str]return modules-def presentation_bypass_entries(name: str, pyproject_text: str | None = None) -> list[str]:- """import-linter ignore_imports entries that still let this product's presentation- reach its own internals directly — the deferred presentation-wave worklist.-- Each entry is one view -> internal edge to remove before the product is internally- sealed (see the isolating-product-facade-contracts skill).- """+def _importlinter_ignore_entries(pyproject_text: str | None = None) -> list[str]:+ """Every ignore_imports entry across the import-linter contracts, or [] if unreadable."""if pyproject_text is None:pyproject = REPO_ROOT / "pyproject.toml"if not pyproject.exists():@@ -238,8 +233,35 @@ def presentation_bypass_entries(name: str, pyproject_text: str | None = None) ->contracts = tomllib.loads(pyproject_text)["tool"]["importlinter"]["contracts"]except (tomllib.TOMLDecodeError, KeyError):return []- prefix = f"products.{name}.backend.presentation"- return [entry for contract in contracts for entry in contract.get("ignore_imports", []) if entry.startswith(prefix)]+ return [entry for contract in contracts for entry in contract.get("ignore_imports", [])]+++def ignored_import_edges(pyproject_text: str | None = None) -> set[str]:+ """The exact edges the import-linter contracts ignore, normalized to "importer -> imported".++ Wildcard entries are dropped: they only ever allow the presentation/facade trees, which the+ AST surface check permits outright."""+ edges = set()+ for entry in _importlinter_ignore_entries(pyproject_text):+ if "*" in entry or "->" not in entry:+ continue+ importer, imported = entry.split("->", 1)+ edges.add(f"{importer.strip()} -> {imported.strip()}")+ return edges+++def presentation_bypass_entries(name: str, pyproject_text: str | None = None) -> list[str]:+ """import-linter ignore_imports entries that still let this product's HTTP surface+ reach past the facade — the deferred presentation-wave worklist.++ Two contracts feed it: presentation reaching internals directly (one view -> internal+ edge per entry), and routes.py registering views that live outside presentation/ (one+ routes -> view-module edge per entry). Both mean presentation code the contract cannot+ see, so both block the internal seal until removed (see the+ isolating-product-facade-contracts skill).+ """+ prefixes = (f"products.{name}.backend.presentation", f"products.{name}.backend.routes ->")+ return [entry for entry in _importlinter_ignore_entries(pyproject_text) if entry.startswith(prefixes)]def has_contract_check_script(product_dir: Path) -> bool:diff --git a/tools/hogli-commands/hogli_commands/product/lint.py b/tools/hogli-commands/hogli_commands/product/lint.pyindex 3b5f35679a13..75e0ac98f98d 100644--- a/tools/hogli-commands/hogli_commands/product/lint.py+++ b/tools/hogli-commands/hogli_commands/product/lint.py@@ -7,8 +7,9 @@ from pathlib import Pathimport click+from .baseline import check_baselinefrom .checks import CHECKS, CheckContext, ProductYamlOwnersCheck, is_isolated_product, validate_tach_toml-from .paths import PRODUCTS_DIR, TACH_TOML, load_structure+from .paths import ISOLATION_BASELINE, PRODUCTS_DIR, REPO_ROOT, TACH_TOML, backend_product_dirs, load_structure_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"@@ -82,30 +83,8 @@ def _lint_tach_toml() -> list[str]:return issues-def _is_backend_product_dir(d: Path) -> bool:- """Identify products with backend code that should be linted.-- A `backend/` directory is the load-bearing signal. Discovery- deliberately does NOT depend on `__init__.py` — that's the file- we want the lint itself to enforce, so using it as the discovery- signal would silently drop products that are missing it (the bug- that let `actions/` slip through for weeks after the model move).-- Frontend-only products (no `backend/`) are skipped — they carry no- Python that needs `__init__.py`, `apps.py`, `backend:test`, etc.-- `query_performance_ai/` is the one exception today — a local-only- macOS+Docker dev coordinator that lives under `products/` but isn't- really a product (no `apps.py`, no `manifest.tsx`, no CI). It's a- candidate for moving under `tools/`, not for widening discovery here.- """- if not d.is_dir() or d.name.startswith((".", "_")):- return False- return (d / "backend").is_dir()--def lint_all_products() -> None:- product_dirs = sorted(d for d in PRODUCTS_DIR.iterdir() if _is_backend_product_dir(d))+ product_dirs = backend_product_dirs()strict = [d.name for d in product_dirs if is_isolated_product(d / "backend")]lenient = [d.name for d in product_dirs if not is_isolated_product(d / "backend")]@@ -113,7 +92,8 @@ def lint_all_products() -> None:click.echo(f"Linting {len(product_dirs)} products ({len(strict)} strict, {len(lenient)} lenient)")click.echo("Checks: required root files, package.json scripts (presence + content), misplaced files (strict), "- "file/folder conflicts, tach boundaries (+ interfaces for strict), isolation progress (lenient)\n"+ "file/folder conflicts, tach boundaries (+ interfaces for strict), isolation progress (lenient), "+ "isolation baseline\n")structure = load_structure()@@ -136,11 +116,26 @@ def lint_all_products() -> None:click.echo(" ✓ ok")click.echo("")- if failed or tach_issues:+ click.echo("─ isolation baseline")+ baseline_issues = check_baseline()+ if baseline_issues:+ click.echo(f" ✗ {len(baseline_issues)} issue(s)")+ for issue in baseline_issues:+ click.echo(f" → {issue}")+ _gh_annotation(+ "error", "products", "isolation baseline", issue, file=str(ISOLATION_BASELINE.relative_to(REPO_ROOT))+ )+ else:+ click.echo(" ✓ ok")+ click.echo("")++ if failed or tach_issues or baseline_issues:if failed:click.echo(f"✗ {len(failed)} product(s) failed: {', '.join(failed)}")if tach_issues:click.echo(f"✗ {len(tach_issues)} tach.toml issue(s)")+ if baseline_issues:+ click.echo(f"✗ {len(baseline_issues)} isolation baseline issue(s)")raise SystemExit(1)click.echo(f"✓ All {len(product_dirs)} products passed")diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex 1865dd3ceacb..2216483731e0 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -392,6 +392,14 @@ def _format_bypass(entry: str) -> str:m = re.match(r"products\.[^.]+\.backend\.(.+)", side.strip())return m.group(1) if m else side.strip()+ def product(side: str) -> str:+ m = re.match(r"products\.([^.]+)\.", side.strip())+ return m.group(1) if m else ""++ # a cross-product edge (routes registering another product's view) keeps its full path,+ # otherwise the product name would be the one detail the line loses+ if product(sides[0]) != product(sides[1]):+ return f"{strip(sides[0])} → {sides[1].strip()}"return f"{strip(sides[0])} → backend.{strip(sides[1])}"diff --git a/tools/hogli-commands/hogli_commands/product/paths.py b/tools/hogli-commands/hogli_commands/product/paths.pyindex d27ae57c866b..4972f0d330eb 100644--- a/tools/hogli-commands/hogli_commands/product/paths.py+++ b/tools/hogli-commands/hogli_commands/product/paths.py@@ -14,6 +14,42 @@ TACH_TOML = REPO_ROOT / "tach.toml"FRONTEND_PACKAGE_JSON = REPO_ROOT / "frontend" / "package.json"DJANGO_SETTINGS = REPO_ROOT / "posthog" / "settings" / "web.py"DB_ROUTING_YAML = PRODUCTS_DIR / "db_routing.yaml"+ISOLATION_BASELINE = PRODUCTS_DIR / "isolation_baseline.txt"+++def is_backend_product_dir(d: Path) -> bool:+ """Identify products with backend code that should be linted.++ A `backend/` directory holding at least one `.py` is the load-bearing signal.+ Discovery deliberately does NOT depend on `__init__.py` — that's the file+ we want the lint itself to enforce, so using it as the discovery+ signal would silently drop products that are missing it (the bug+ that let `actions/` slip through for weeks after the model move).++ The `.py` condition is what keeps a deleted product out. Git does not track+ directories, so removing a product leaves its empty `backend/` behind in+ every existing worktree — `agent_platform` and `desktop_recordings` are both+ sitting there today. CI clones fresh and never sees them, so anything that+ only runs in CI is unaffected, but the isolation baseline is generated+ locally and committed, and would carry the ghosts into the repo.++ Frontend-only products (no `backend/`) are skipped — they carry no+ Python that needs `__init__.py`, `apps.py`, `backend:test`, etc.++ `query_performance_ai/` is the one exception today — a local-only+ macOS+Docker dev coordinator that lives under `products/` but isn't+ really a product (no `apps.py`, no `manifest.tsx`, no CI). It's a+ candidate for moving under `tools/`, not for widening discovery here.+ """+ if not d.is_dir() or d.name.startswith((".", "_")):+ return False+ backend = d / "backend"+ return backend.is_dir() and any(backend.rglob("*.py"))+++def backend_product_dirs() -> list[Path]:+ """Every product directory with backend code, sorted by name."""+ return sorted(d for d in PRODUCTS_DIR.iterdir() if is_backend_product_dir(d))def load_structure() -> dict:diff --git a/tools/hogli-commands/hogli_commands/tests/test_baseline.py b/tools/hogli-commands/hogli_commands/tests/test_baseline.pynew file mode 100644index 000000000000..de67758fa8c9--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_baseline.py@@ -0,0 +1,42 @@+from __future__ import annotations++from pathlib import Path++import pytest++from hogli_commands.product.baseline import baseline_issues+from hogli_commands.product.paths import is_backend_product_dir+++class TestIsolationBaseline:+ @pytest.mark.parametrize(+ "unsealed,baseline,expected",+ [+ pytest.param({"alerts"}, {"alerts"}, 0, id="in_sync"),+ pytest.param({"alerts", "canvas"}, {"alerts"}, 1, id="unsealed_missing_from_baseline"),+ pytest.param({"alerts"}, {"alerts", "wizard"}, 1, id="baseline_entry_now_sealed"),+ pytest.param({"canvas"}, {"wizard"}, 2, id="drift_in_both_directions"),+ pytest.param(set(), set(), 0, id="empty_both"),+ ],+ )+ def test_strict_equality(self, unsealed: set[str], baseline: set[str], expected: int) -> None:+ assert len(baseline_issues(unsealed, baseline)) == expected++ @pytest.mark.parametrize(+ "with_python,expected",+ [+ pytest.param(True, True, id="with_python"),+ pytest.param(False, False, id="empty_leftover_dir"),+ ],+ )+ def test_discovery_requires_python(self, with_python: bool, expected: bool, tmp_path: Path) -> None:+ backend = tmp_path / "some_product" / "backend"+ backend.mkdir(parents=True)+ if with_python:+ (backend / "models.py").write_text("")+ assert is_backend_product_dir(tmp_path / "some_product") is expected++ def test_discovery_skips_products_without_a_backend(self, tmp_path: Path) -> None:+ product = tmp_path / "frontend_only"+ product.mkdir()+ assert is_backend_product_dir(product) is Falsediff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 4b89f9c388d8..1b131d1fc4c5 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -7,11 +7,15 @@ from pathlib import Pathimport pytest-from hogli_commands.product import gh as gh_module+from hogli_commands.product import (+ checks as checks_module,+ gh as gh_module,+)from hogli_commands.product.checks import (BackendPackageMarkerCheck,CheckContext,FileFolderConflictsCheck,+ ImportSurfaceCheck,IsolationChainCheck,OrphanedTestFilesCheck,PackageJsonScriptsCheck,@@ -1039,6 +1043,73 @@ def _make_backend(tmp_path: Path, files: list[str]) -> CheckContext:)+class TestImportSurfaceCheck:+ """The AST twin of the two 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+ ) -> CheckContext:+ ctx = _make_backend(tmp_path, list(files))+ 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",+ ),+ ],+ )+ 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 == []++class TestFileFolderConflictsCheck:def test_skip_when_no_backend(self, tmp_path: Path) -> None:product_dir = tmp_path / "p"@@ -1477,6 +1548,16 @@ ignore_imports = ["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",+]"""@@ -1484,7 +1565,7 @@ ignore_imports = ["name,expected",[("logs", 2),- ("tracing", 1),+ ("tracing", 2), # one presentation bypass + one routes -> backend/api/ deferral("wizard", 0),],)