: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
feat(devex): name the isolation ladder and gate facade wiring (#110690)
Julian Beza1d417378dda
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.mdindex 7ebdb076df2b..748e6cc85917 100644--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md@@ -41,7 +41,7 @@ Before changing code, get the baseline:```bashhogli product:maturity <name> # scores models, facade, presentation, boundaries, codegen-hogli product:lint <name> # structural lint + isolation chain (strict if facade/contracts.py exists)+hogli product:lint <name> # structural lint + isolation chain, prints the rung: Lenient → Strict → Sealed → Isolatedhogli product:isolate:scan <name> # the recon: import map, coupling gate, preflight (see below)```diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 03169918e9e2..18f32229d74f 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -1708,6 +1708,13 @@ jobs:REPO: ${{ github.repository }}PR_NUMBER: ${{ github.event.pull_request.number }}run: .github/scripts/list-removed-renamed-paths.sh > "$RUNNER_TEMP/deleted-migration-paths.txt"+ # Above the boundary for the same reason. product:lint compares the crossings ledger+ # with the merge commit's first parent, so the clone needs one more level of history.+ - name: Fetch the pull request base+ if: github.event_name == 'pull_request'+ run: |+ git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"+ git fetch --no-tags --depth=2 origin "$GITHUB_SHA"# Boundary between network-dependent setup and the deterministic# checks below. The "Flag deterministic failure" step keys off this# step's outcome so a transient setup failure doesn't cancel the run.@@ -1720,6 +1727,8 @@ jobs:- name: Bootstrap scaffold productrun: ./bin/hogli product:bootstrap spline_reticulator --non-interactive- name: Lint product structure+ env:+ CROSSINGS_LEDGER_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }}run: ./bin/hogli product:lint --all# Distributed owners.yaml tree: schema, product.yaml/owners.yaml# conflicts, dead rule globs, coverage (warn-only). No --live, so nodiff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex c461f6783f14..c1c6401e575e 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1504,6 +1504,14 @@ jobs:PR_NUMBER: ${{ github.event.pull_request.number }}run: .github/scripts/list-removed-renamed-paths.sh > "$RUNNER_TEMP/deleted-migration-paths.txt"+ # Above the boundary for the same reason. product:lint compares the crossings ledger+ # with the merge commit's first parent, so the clone needs one more level of history.+ - name: Fetch the pull request base+ if: github.event_name == 'pull_request'+ run: |+ git remote get-url origin >/dev/null 2>&1 || git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"+ git fetch --no-tags --depth=2 origin "$GITHUB_SHA"+# Boundary between network-dependent setup and the deterministic# checks below. The "Flag deterministic failure" step keys off this# step's outcome so a transient setup failure doesn't cancel the run.@@ -1522,6 +1530,8 @@ jobs:run: ./bin/hogli product:bootstrap spline_reticulator --non-interactive- name: Lint product structure+ env:+ CROSSINGS_LEDGER_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }}run: ./bin/hogli product:lint --all# Distributed owners.yaml tree: schema, product.yaml/owners.yamldiff --git a/.stamphog/policy.yml b/.stamphog/policy.ymlindex 8c60f27410b8..1da4a55efb13 100644--- a/.stamphog/policy.yml+++ b/.stamphog/policy.yml@@ -73,6 +73,7 @@ deny:- 'dockerfile'- 'docker-compose'- '\.github/workflows'+ - '\.depot/workflows'- '\.github/pr-deploy'- 'iam'- 'cloudflare'@@ -158,7 +159,7 @@ deny:- '^docs/published/handbook/engineering/type-system\.md$'- '^tools/hogli-commands/hogli_commands/(api_ratchet|projections|tach_lint)\.py$'- '^tools/hogli-commands/hogli_commands/product_structure\.yaml$'- - '^tools/hogli-commands/hogli_commands/product/(baseline|checks|crossings|isolation|reverse_accessors)\.py$'+ - '^tools/hogli-commands/hogli_commands/product/'workflows_delivery:description: 'CDP, Workflows and Messaging code that decides which customer configurations exist and what gets delivered.'rationale: "Owner-only: stamphog approves team-workflows' own changes here and refuses everyone else's. Another team's change here breaks a customer silently: the API and models decide which of a tenant's rows get listed and updated, and the plugin-server worker decides what gets delivered. Teams usually edit these paths to carve out an exception for their own rows, their tests still pass, and existing customer configurations stop appearing or stop being delivered. Product frontends stay out, because a mistake there is visible. As in CODEOWNERS, only the API test directories and `*.test.ts` files stay out. Nothing else under the worker does: the template, legacy-plugin, legacy-webhook and segment directories hold live delivery code and mutable registries."diff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.pyindex 7b1a9309f9c7..2ec9907a95db 100644--- a/posthog/test/repo_invariants/test_model_crossing_uses.py+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py@@ -28,6 +28,8 @@ promises rather than what a caller does. `facade-returns` and `facade-accepts(<ppublic facade callable puts a Django, a DRF or an ORM type on its signature; `facade-logic` means acapability submodule holds bodies instead of re-exports. An import linter sees the same edge eitherway, so the shape is frozen here. The rule is `products/architecture.md` § Facades: The Public Interface.+`facade-wiring` means an Isolated product's facade hands out a class from a wiring location that+implements no approved interface (§ Wiring couplings). Only Isolated products get these lines.The check is strict equality, not "no worse than": a line that disappears must be deleted from thefile in the same change, so the file can never go stale behind the code.@@ -37,9 +39,9 @@ The two directions are not symmetric. A line that went away is regenerated out:bin/hogli product:crossings --all --write-baselineThat command refuses to write while the scan holds a line the file does not, so a new line is-never absorbed. Change the caller back, or seal the relation. A coupling that must stand is a-hand-edited line in the baseline plus an amendment in products/architecture.md § Wiring couplings,-which is what a reviewer reads.+never absorbed. Change the caller back, or seal the relation. A hand-edited line passes this test,+because the scan holds it too, so `hogli product:lint --all` compares the file with the pull+request's base and refuses growth unless the change touches the scanner."""from hogli_commands.product.crossings import (@@ -47,6 +49,7 @@ from hogli_commands.product.crossings import (all_crossing_uses,baseline_drift,baseline_drift_message,+ grown_debt,names_defined_in,read_baseline,scanned_baseline_lines,@@ -61,7 +64,9 @@ def test_disallowed_crossing_uses_match_the_baseline() -> None:returndrift = baseline_drift(recorded, scanned)- raise AssertionError(baseline_drift_message(drift.grown, drift.shrunk))+ # A moved or split consumer raises no debt, so a regenerate records its new lines.+ added = drift.grown if grown_debt(recorded, scanned) else []+ raise AssertionError(baseline_drift_message(added, drift.shrunk))# product_analytics watches backend/hogql_queries/trends/ alone, because trends is the only subtreediff --git a/products/architecture.md b/products/architecture.mdindex 576c8e2c9879..217f6de731e0 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -93,7 +93,7 @@ Core sometimes needs behavior from a product, not data: query runners it dispatcThese cross the boundary as classes — allowed only under all three rules:1. **Approved interface.**- The class implements a core-owned base from the approved list — today `QueryRunner` (`posthog/hogql_queries/query_runner.py`), `MaxTool` (`ee/hogai/tool.py`), Temporal's `@workflow.defn`/`@activity.defn`, and Celery's `@shared_task`.+ The class implements a core-owned base from the approved list — today `QueryRunner` (`posthog/hogql_queries/query_runner.py`), `MaxTool` (`ee/hogai/tool.py`), Temporal's `@workflow.defn`/`@activity.defn` and `Interceptor` (the worker in `posthog/temporal/common/worker.py` registers each one), and Celery's `@shared_task`.Core code may rely only on the base's interface, never on product-specific members.Extending the list is a core PR: define the base and validate at the registration point.DRF viewsets are not part of this channel: they live in `presentation/`, register through `routes.py`, and never pass through the facade (a facade must not import DRF, and not its own `presentation/`; the `facade must not import presentation or DRF` import-linter contract enforces both, with the existing violations grandfathered in its TODO list) — their soundness is governed by the presentation rules above.@@ -183,8 +183,10 @@ Run `hogli product:crossings --all --write-baseline` to record a decrease.**The baseline only shrinks.**`--write-baseline` refuses to write when the scan holds a line the file does not, prints those lines, and changes nothing, so a new coupling cannot enter by regenerating.-A coupling that must stand is a hand-edited line in the baseline plus a note here that says why it stands.-Both are in the diff, which is what a reviewer reads; a regenerated line is not.+A hand edit cannot add a line either.+New lines come only with a DevEx change to the scanner: a new check that records the findings that exist when it lands, or an approved exception (an approved interface, a `MODEL_CROSSINGS` entry, a carve-out).+A coupling that must stand needs such a change, not a line.+A change that only moves or splits a consumer module carries its lines along.**What the check cannot see.**The check reads uses of the class name, plus `get_model` string references.@@ -199,6 +201,7 @@ All three are a declared residual, not permission to add more.A behavioral class that fits no approved interface must not cross at all.Wrap it in a facade function returning contracts, or register a plain function (see the managed-view provider registry in `products/data_modeling/backend/facade/managed_viewset_hooks.py`).A product whose facade hands out unapproved behavior is not soundly isolated: it loses `backend:contract-check` and pays the full suite until fixed.+The one exception is a check that DevEx introduces: findings that already exist in Isolated products at that moment are recorded in the crossings ledger instead, and those lines may only go away.**Inbound webhook consumers are a designated location of the same kind.**A product declares its handlers in `backend/webhook_consumers.py`, in a `WEBHOOK_CONSUMERS` sequence.@@ -548,7 +551,7 @@ Django auto-generates a reverse accessor (`project.visualreview_set`), a reverse**Rule:** declare every relation field (FK, O2O, M2M) that crosses a product boundary with `related_name="+"`, and do not set an explicit `related_query_name` on it. `related_name="+"` alone removes the reverse accessor and the reverse query name; an explicit `related_query_name` keeps `filter()` traversal alive, and the ratchet records it as a `query:<name>` row. A product may point relations _at_ core models; other products must not reference models _inside_ this product. When a caller needs reverse access, add a facade read function — do not traverse the ORM.-A repo invariant enforces this: every cross-boundary reverse accessor is frozen as a `reverse-accessor(...)` line in `products/model_crossing_uses_baseline.txt`, next to the other crossing kinds. The set may only shrink. A new relation without `related_name="+"` fails CI until you seal it or a review adds a hand-edited baseline line. Regenerate after a removal with `bin/hogli product:crossings --all --write-baseline`.+A repo invariant enforces this: every cross-boundary reverse accessor is frozen as a `reverse-accessor(...)` line in `products/model_crossing_uses_baseline.txt`, next to the other crossing kinds. The set may only shrink. A new relation without `related_name="+"` fails CI until you seal it. Regenerate after a removal with `bin/hogli product:crossings --all --write-baseline`.`db_constraint` is a separate concern: it is migration safety (see the hot-table FK rules in [products/README.md](README.md)) and multi-database planning, not Python isolation. Both `db_constraint=False` and a two-phase validated constraint are sanctioned.diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txtindex 2dd34535b7ba..d0d87befe8a6 100644--- a/products/isolation_baseline.txt+++ b/products/isolation_baseline.txt@@ -7,14 +7,14 @@## 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.+# Isolated 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.+# Once a product reaches the Isolated rung, regenerate this file and its line drops out.access_controlactionsdiff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 9166e013ba30..48f5a2f62b23 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -24,15 +24,19 @@# submodule holds bodies rather than re-exports, and its count is how many are left. The first# column says what crosses — `<product>.<Class>`, `<library>.<Type>`, or the facade module for a# `facade-logic` line — and the consumer column holds the symbol or the module that carries it.-# The rule is products/architecture.md § Facades: The Public Interface.+# The rule is products/architecture.md § Facades: The Public Interface. `facade-wiring` means an+# Isolated product's facade hands out a class from a wiring location that implements no approved+# interface (§ Wiring couplings). Only Isolated products get these lines; below that rung the+# lint reports the class as information.## Counts may only go down, and a line that disappears must be deleted here too.## Regenerate after a removal: bin/hogli product:crossings --all --write-baseline# That command refuses to write when the scan holds a line this file does not, or a count that-# went up. A coupling that-# must stand is a hand-edited line here, together with the amendment in products/architecture.md-# § Wiring couplings that permits it, because a reviewer can see both.+# went up. Do not hand-edit a line in: `hogli product:lint --all` refuses growth against the pull+# request's base unless the change also touches the scanner in tools/hogli-commands/hogli_commands/product/.+# A coupling that must stand needs that DevEx change (an approved interface, a MODEL_CROSSINGS+# entry or a carve-out).access_control.Role approvals.ApprovalPolicy.bypass_roles reverse-accessor(bypass_policies) 1access_control.Role posthog.Organization.default_role reverse-accessor(default_for_organizations) 1actions.Action cdp.PluginConfig.match_action reverse-accessor(plugin_configs) 1@@ -268,6 +272,7 @@ error_tracking.ErrorTrackingIssueFingerprintV2 posthog.models.team.util get_modeerror_tracking.ErrorTrackingIssueFingerprintV2 products.demo.backend.logic.products.hedgebox.matrix get_model 1error_tracking.ErrorTrackingIssueFingerprintV2 products.posthog_ai.evals.error_tracking.seeders get_model 1error_tracking.ErrorTrackingStackFrame products.demo.backend.logic.products.hedgebox.matrix get_model 1+error_tracking.RecommendationsRefreshInputs products.error_tracking.backend.facade.temporal facade-wiring 1error_tracking:backend/facade/queries.py products.error_tracking.backend.facade.queries facade-logic 1error_tracking:backend/hogql_queries/ products.posthog_ai.eval_harness.test.test_eval_seeders drives(ErrorTrackingQueryRunner) 1error_tracking:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_query drives(ErrorTrackingQuery) 1@@ -313,6 +318,11 @@ feature_flags.FeatureFlag surveys.Survey.internal_response_sampling_flag reversefeature_flags.FeatureFlag surveys.Survey.internal_targeting_flag reverse-accessor(surveys_internal_targeting_flag) 1feature_flags.FeatureFlag surveys.Survey.linked_flag reverse-accessor(surveys_linked_flag) 1feature_flags.FeatureFlag surveys.Survey.targeting_flag reverse-accessor(surveys_targeting_flag) 1+managed_warehouse.DataImportsDuckLakeCopyInputs products.managed_warehouse.backend.facade.temporal facade-wiring 1+managed_warehouse.DataModelingDuckLakeCopyInputs products.managed_warehouse.backend.facade.temporal facade-wiring 1+managed_warehouse.DuckLakeCopyModelInput products.managed_warehouse.backend.facade.temporal facade-wiring 1+managed_warehouse.DuckLakeRegisterDataImportsInputs products.managed_warehouse.backend.facade.temporal facade-wiring 1+managed_warehouse.DucklakeCompactionInput products.managed_warehouse.backend.facade.temporal facade-wiring 1mcp_store.MCPServerInstallation products.mcp_store.backend.facade.api.member_installation_for_host facade-returns 1metrics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(MetricsQuery) 1notebooks.Notebook posthog.SharingConfiguration.notebook reverse-accessor(sharing_configurations) 1@@ -601,6 +611,8 @@ product_analytics.Insight products.reminders.backend.constants in-collection 1product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1product_analytics.Insight products.surveys.backend.api.survey instance-single 1product_analytics.Insight surveys.Survey.linked_insight reverse-accessor(surveys_linked_insight) 1+product_analytics.TrendsDisplay products.product_analytics.backend.facade.queries facade-wiring 1+product_analytics.UpgradeQueriesWorkflowInputs products.product_analytics.backend.facade.temporal facade-wiring 1product_analytics:backend/facade/models.py products.product_analytics.backend.facade.models facade-logic 1product_analytics:backend/facade/queries.py products.product_analytics.backend.facade.queries facade-logic 1product_analytics:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(TrendsQuery) 2@@ -738,6 +750,19 @@ typing.Any products.signals.backend.facade.api.create_scout_for_source facade-actyping.Any products.signals.backend.facade.api.create_scout_for_source facade-accepts(user) 1typing.Any products.tasks.backend.facade.agents.extract_json_from_text facade-returns 1user_interviews.IntervieweeContext posthog.SharingConfiguration.interviewee_context reverse-accessor(sharing_configurations) 1+warehouse_sources.AccountPropertyRowSink products.warehouse_sources.backend.facade.temporal facade-wiring 1+warehouse_sources.AccountPropertySourceProjection products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.CDCExtractionInput products.warehouse_sources.backend.facade.pipelines facade-wiring 1+warehouse_sources.CDCRepairError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CDCRepairInProgress products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CDCSourceAdapter products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CDPProducer products.warehouse_sources.backend.facade.pipelines facade-wiring 1+warehouse_sources.ClickHouseConnectionError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.ClickHouseSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.Config products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CredentialAccountsMixin products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CustomSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.CustomSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1warehouse_sources.DataWarehouseCredential posthog.hogql.database.database instance-many(filter) 1warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table drf-model-serializer 1warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table write(create) 1@@ -802,6 +827,9 @@ warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.managewarehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder construct 1warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(create) 1+warehouse_sources.DocsFetchError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.DottedNameParts products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.EmitSignalsActivityInputs products.warehouse_sources.backend.facade.hooks facade-wiring 1warehouse_sources.ExternalDataJob products.data_warehouse.backend.facade.api.update_external_job_status facade-returns 1warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.data_load.source_templates instance-single 2warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.jobs lock 1@@ -865,6 +893,7 @@ warehouse_sources.ExternalDataSchema products.marketing_analytics.backend.servicwarehouse_sources.ExternalDataSchema products.signals.backend.emission.emit_signals instance-many(aget) 1warehouse_sources.ExternalDataSchema products.signals.backend.management.commands.emit_signals_from_warehouse instance-single 1warehouse_sources.ExternalDataSchema products.signals.backend.views instance-many(select_related) 1+warehouse_sources.ExternalDataSchemaSyncPausedError products.warehouse_sources.backend.facade.temporal facade-wiring 1warehouse_sources.ExternalDataSource data_warehouse.ExternalDataSourceRevenueAnalyticsConfig.external_data_source reverse-accessor(revenue_analytics_config) 1warehouse_sources.ExternalDataSource ee.hogai.tools.execute_sql.direct_connection_suggestions instance-many(defer) 1warehouse_sources.ExternalDataSource posthog.hogql.database.database instance-many(filter) 1@@ -912,11 +941,48 @@ warehouse_sources.ExternalDataSource products.marketing_analytics.backend.managewarehouse_sources.ExternalDataSource products.marketing_analytics.backend.services.data_source_health instance-many(order_by) 1warehouse_sources.ExternalDataSource products.posthog_ai.evals.data_warehouse.seeder write(create) 1warehouse_sources.ExternalDataSource products.signals.backend.management.commands.reset_signals_self_driving instance-many(filter) 1+warehouse_sources.ExternalWebhookInfo products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.GithubSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.GithubSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.HostNotAllowedError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.IntegrationAccountListingError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.MotherDuckConnectionError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.MotherduckSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.MotherduckSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.MySQLSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.MySQLSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.NamingConvention products.warehouse_sources.backend.facade.sources facade-wiring 1+warehouse_sources.OAuthMixin products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.PersonPropertyRowSink products.warehouse_sources.backend.facade.temporal facade-wiring 1+warehouse_sources.PersonPropertySourceProjection products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.PersonPropertySyncActivityInputs products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.PersonPropertySyncRunRecord products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.PersonPropertySyncSource products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.PostgresSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.PostgresSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.RedshiftSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.RowFilterValidationError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SQLSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SSLRequiredError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SavedQueryNotFoundError products.warehouse_sources.backend.facade.temporal facade-wiring 1+warehouse_sources.SavedQueryNotOnV2ScheduleError products.warehouse_sources.backend.facade.temporal facade-wiring 1+warehouse_sources.SnowflakeSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SnowflakeSourceConfig products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SourceRegistry products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SourceSchema products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.SyncNewSchemasActivityInputs products.warehouse_sources.backend.facade.pipelines facade-wiring 1+warehouse_sources.TemporaryHostResolutionError products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.WarehouseBinding products.warehouse_sources.backend.facade.hooks facade-wiring 1+warehouse_sources.WarehouseBindingMissingError products.warehouse_sources.backend.facade.temporal facade-wiring 1warehouse_sources.WarehouseColumnAnnotation products.data_modeling.backend.logic.enrich_view_semantics instance-many(filter) 1warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.presentation.views.column_annotation drf-model-serializer 1warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.presentation.views.column_annotation instance-many(unscoped) 1warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder construct 2warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1+warehouse_sources.WebhookCreationResult products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.WebhookDeletionResult products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.WebhookSource products.warehouse_sources.backend.facade.source_management facade-wiring 1+warehouse_sources.WebhookSyncResult products.warehouse_sources.backend.facade.source_management facade-wiring 1web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.edit_proposal facade-returns 1web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.regenerate_proposal facade-returns 1web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.reject_proposal facade-returns 1diff --git a/products/stamphog/packages/pr-approval-agent/test_policy.py b/products/stamphog/packages/pr-approval-agent/test_policy.pyindex 20c15ddf2aca..2428faa753c8 100644--- a/products/stamphog/packages/pr-approval-agent/test_policy.py+++ b/products/stamphog/packages/pr-approval-agent/test_policy.py@@ -84,6 +84,7 @@ OLD_DENY_PATTERN_DEFS = {"dockerfile","docker-compose","\\.github/workflows",+ "\\.depot/workflows","\\.github/pr-deploy","iam","cloudflare",@@ -136,7 +137,7 @@ OLD_DENY_PATTERN_DEFS = {"^docs/published/handbook/engineering/type-system\\.md$","^tools/hogli-commands/hogli_commands/(api_ratchet|projections|tach_lint)\\.py$","^tools/hogli-commands/hogli_commands/product_structure\\.yaml$",- "^tools/hogli-commands/hogli_commands/product/(baseline|checks|crossings|isolation|reverse_accessors)\\.py$",+ "^tools/hogli-commands/hogli_commands/product/",]},"workflows_delivery": {diff --git a/tools/hogli-commands/hogli_commands/product/baseline.py b/tools/hogli-commands/hogli_commands/product/baseline.pyindex d3c45f09412b..d8ab8a28d59f 100644--- a/tools/hogli-commands/hogli_commands/product/baseline.py+++ b/tools/hogli-commands/hogli_commands/product/baseline.py@@ -1,18 +1,18 @@"""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.+`product:bootstrap` emits a product that is already on the Isolated rung: 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 below+Isolated 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)+ - product below Isolated missing from the baseline -> fail (a new product skipped the+ scaffold, or an isolated one regressed)+ - baseline entry that is now Isolated -> 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+permission slip: a product could reach Isolated, keep its line, then lose its facade again and stillpass. 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@@ -36,33 +36,32 @@ HEADER = """\## 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.+# Isolated 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.+# Once a product reaches the Isolated rung, regenerate this file and its line drops out."""-def unsealed_products() -> list[str]:- """Every backend product whose `backend:contract-check` skip is not live.+def not_isolated_products() -> list[str]:+ """Every backend product below the Isolated rung.- 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.+ Keyed on the full rung, 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 = []+ not_isolated = []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+ if not status.isolation_enabled:+ not_isolated.append(product_dir.name)+ return not_isolateddef read_baseline() -> set[str]:@@ -77,22 +76,22 @@ def write_baseline(names: list[str]) -> None:def regenerate_baseline() -> None:- names = unsealed_products()+ names = not_isolated_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]:+def baseline_issues(not_isolated: 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):+ for name in sorted(not_isolated - 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"`hogli product:bootstrap` (products are Isolated 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):+ for name in sorted(baseline - not_isolated):issues.append(f"{name} is in the baseline but is now isolated — run "f"`hogli product:lint --regenerate-baseline` to drop its line"@@ -101,4 +100,4 @@ def baseline_issues(unsealed: set[str], baseline: set[str]) -> list[str]:def check_baseline() -> list[str]:- return baseline_issues(set(unsealed_products()), read_baseline())+ return baseline_issues(set(not_isolated_products()), read_baseline())diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex b2935d38ff9a..46a942367b82 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -17,18 +17,20 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom .ast_helpers import module_import_targets-from .crossings import driven_wiring_locations, facade_shape_use, recorded_facade_shape_rows+from .crossings import driven_wiring_locations, facade_shape_use, facade_wiring_use, recorded_facade_shape_rowsfrom .isolation import (GARAGE_PREFIXES,FacadeShapeFinding,+ IsolationRung,IsolationStatus,+ UnapprovedWiringClass,compute_isolation_status,facade_shape_findings,+ has_contracts_module,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,names_from_pattern as _names_from_pattern,@@ -37,6 +39,7 @@ from .isolation import (webhook_consumers_unwatched,)from .paths import TACH_TOML, get_tach_block+from .wiring_interfaces import APPROVED_WIRING_BASES, APPROVED_WIRING_DECORATORS, WiringVerdict# ---------------------------------------------------------------------------# Utilities@@ -106,10 +109,10 @@ def validate_facade_alternation(tach_content: str, products_dir: Path) -> list[s1. Every product named in the canonical alternation must exist asproducts/<name>/.2. Every product named in the canonical alternation must have- backend/facade/contracts.py (be isolated).+ backend/facade/contracts.py (the Strict rung or above).3. Names in alternation regexes must be sorted alphabetically.- The inverse direction ("every isolated product must be listed") is not+ The inverse direction ("every Strict product must be listed") is notenforced — having `facade/contracts.py` is just scaffolding and doesn'tmean the product is ready for canonical exposure."""@@ -147,7 +150,7 @@ def validate_facade_alternation(tach_content: str, products_dir: Path) -> list[s"remove the stale entry from tach.toml")continue- if not is_isolated_product(product_dir / "backend"):+ if not has_contracts_module(product_dir / "backend"):issues.append(f"canonical facade alternation lists '{name}' but products/{name}/backend/facade/contracts.py ""is missing — either add contracts.py or remove the entry from tach.toml"@@ -254,7 +257,7 @@ class CheckContext:name: strproduct_dir: Pathbackend_dir: Path- is_isolated: bool+ has_facade_contracts: boolstructure: dictdetailed: bool # True = single-product run, False = --all_isolation: IsolationStatus | None = field(default=None, repr=False, compare=False)@@ -270,7 +273,7 @@ class CheckContext:self.name,self.product_dir,self.backend_dir,- is_isolated=self.is_isolated,+ has_facade_contracts=self.has_facade_contracts,driven_wiring_locations=driven_wiring_locations(self.name),)return self._isolation@@ -287,13 +290,13 @@ class CheckResult:class ProductCheck(ABC):label: str- for_isolated: bool = True+ for_strict: bool = Truefor_lenient: bool = Truedef should_run(self, ctx: CheckContext) -> bool:- if ctx.is_isolated and not self.for_isolated:+ if ctx.has_facade_contracts and not self.for_strict:return False- if not ctx.is_isolated and not self.for_lenient:+ if not ctx.has_facade_contracts and not self.for_lenient:return Falsereturn True@@ -310,7 +313,7 @@ class RequiredRootFilesCheck(ProductCheck):label = "required root files"def run(self, ctx: CheckContext) -> CheckResult:- required_key = "required" if ctx.is_isolated else "required_lenient"+ required_key = "required" if ctx.has_facade_contracts else "required_lenient"missing = [filenamefor filename, config in ctx.structure.get("root_files", {}).items()@@ -469,7 +472,7 @@ class ImportSurfaceCheck(ProductCheck):def _surfaces(self, ctx: CheckContext) -> tuple[tuple[str, tuple[str, ...]], ...]:"""A product that is not sealed yet has no routes/presentation contract to hold, soonly its ingress entry point is checked."""- return self.SURFACES if ctx.is_isolated else (self.WEBHOOK_CONSUMERS_SURFACE,)+ return self.SURFACES if ctx.has_facade_contracts else (self.WEBHOOK_CONSUMERS_SURFACE,)def _surface_files(self, ctx: CheckContext, source: str) -> list[Path]:root = ctx.backend_dir / source@@ -539,13 +542,18 @@ class PackageJsonScriptsCheck(ProductCheck):# change flowing to HTTP through such a view would be hidden. The skip is the# reward for finishing — it can't be enabled until the wave empties them.status = ctx.isolation_status()- needs_contract_check = status.eligible_for_isolated_tests+ # This gate leaves out the tach interface on purpose. The external boundary is required too,+ # but TachCheck demands the interface and IsolationChainCheck blocks a script without it, so+ # this gate does not report the same gap a third time.+ needs_contract_check = status.internally_sealed and status.has_real_facade and not status.has_legacy_leaks# The wiring gate also withholds the skip script: a facade that still hands out unsanctioned# classes can't soundly narrow, so don't nag it to carry 'backend:contract-check' (the script# would be inert, and IsolationChainCheck blocks the narrowing that would make it bite). The# absence check below still keys on plain eligibility, so the five products that deliberately# keep script+broad while un-narrowed aren't told to drop it.- require_contract_check_script = needs_contract_check and not status.facade_leaks+ require_contract_check_script = (+ needs_contract_check and not status.facade_leaks and not status.unapproved_wiring+ )required = ["backend:test"] + (["backend:contract-check"] if require_contract_check_script else [])for script in required:if script not in scripts:@@ -578,7 +586,7 @@ class PackageJsonScriptsCheck(ProductCheck):# --- surface the withholding decision (single-product view only; keep the CI sweep quiet) ---if (ctx.detailed- and ctx.is_isolated+ and ctx.has_facade_contractsand not require_contract_check_scriptand "backend:contract-check" not in scripts):@@ -721,11 +729,11 @@ class TachCheck(ProductCheck):)tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""- if ctx.is_isolated and not has_tach_interface(ctx.name, tach_content):+ if ctx.has_facade_contracts and not has_tach_interface(ctx.name, tach_content):return CheckResult(lines=["✗ missing interfaces declaration"],issues=[- f"Isolated product missing interface definition in tach.toml — "+ f"Strict product (it has facade/contracts.py) missing interface definition in tach.toml — "f'add a [[interfaces]] block with from = ["{module_path}"]'],)@@ -742,7 +750,7 @@ class IsolationChainCheck(ProductCheck):The chain: real facade → tach interfaces → contract-check script → narrowed turbo.json.Each step requires the previous one, so a product can't claim a CI benefit it hasn'tearned (the Django suite skipped on changes). The final step also can't be left- half-wired: once a product is fully sealed and eligible, it must actually turn the skip+ half-wired: once a product is Sealed, it must actually turn the skipon by narrowing turbo.json inputs — otherwise the contract-check script is inert(inputs default to all of backend/, so every change still re-runs the Django suite)."""@@ -849,7 +857,7 @@ class IsolationChainCheck(ProductCheck):f"suite. Add the matching input(s) ({surface_globs})")- # Earned but not turned on: a fully sealed, eligible product that already carries+ # Earned but not turned on: a Sealed product that already carries# 'backend:contract-check' (real facade, tach interface, no legacy leaks, presentation# wave emptied). Without a turbo.json narrowing its inputs to facade/presentation, that# script inherits the root task's all-of-backend inputs, so every internal change still@@ -860,14 +868,14 @@ class IsolationChainCheck(ProductCheck):# rejected by the gate above, so nagging toward it is counterproductive — say what blocks it.needs_turn_on = (has_script- and status.eligible_for_isolated_tests- and status.externally_sealed+ and status.is_sealedand not has_narrowedand not facade_violations+ and not status.unapproved_wiring)if needs_turn_on:result.issues.append(- "product is fully sealed and eligible for isolated tests and carries "+ "product is Sealed and carries ""'backend:contract-check', but turbo.json does not narrow contract-check inputs to ""facade/presentation — the skip is inert (every change still re-runs the full Django "'suite). Add a turbo.json narrowing inputs to ["backend/facade/**", '@@ -878,7 +886,8 @@ class IsolationChainCheck(ProductCheck):)# When needs_turn_on is suppressed purely because of a facade violation (the other four# conjuncts hold), the facade_violations warning above already explains what blocks narrowing,- # so there's nothing more to say here — the nag is silently withheld, not replaced.+ # so there's nothing more to say here — the nag is silently withheld, not replaced. The same+ # holds for unapproved wiring classes, which WiringInterfaceCheck lists below Isolated.# Watching the route registration: routes.py is the product's route-registration entry# point (public API surface, imported by core to assemble the router), but it lives at@@ -1060,14 +1069,74 @@ class FacadeShapeCheck(ProductCheck):if result.issues:result.lines = [f"✗ {len(result.issues)} issue(s)"] + [f" → {i}" for i in result.issues]- elif recorded:- result.warnings.append(f"facade shape debt: {len(recorded)} row(s) in {_CROSSING_LEDGER}")- result.lines = [f"⚠ facade shape debt: {len(recorded)} rows"]+ elif shape_rows := {row for row in recorded if " facade-wiring " not in row}:+ result.warnings.append(f"facade shape debt: {len(shape_rows)} row(s) in {_CROSSING_LEDGER}")+ result.lines = [f"⚠ facade shape debt: {len(shape_rows)} rows"]else:result.lines = ["✓ ok"]return result+_APPROVED_INTERFACES = ", ".join(+ [qualified.rsplit(".", 1)[1] for qualified in sorted(APPROVED_WIRING_BASES)]+ + [f"@{qualified.split('.', 1)[1]}" for qualified in sorted(APPROVED_WIRING_DECORATORS)]+)+++def _wiring_issue(finding: UnapprovedWiringClass) -> str:+ """The lint line for one class: where it crosses, why it fails, and the moves that clear it."""+ reason = (+ "whose bases or members the lint cannot read statically"+ if finding.verdict is WiringVerdict.UNRESOLVED+ else f"which implements no approved interface ({_APPROVED_INTERFACES})"+ )+ return (+ f"facade/{finding.facade_module} hands out {finding.class_name} from {finding.source_path}, {reason}. "+ "A wiring folder alone does not make a class wiring. Return contracts from a facade function, "+ "register a plain function, or put the class behind an approved interface "+ "(products/architecture.md § Wiring couplings). The ledger only shrinks, so this is not a row to add"+ )+++class WiringInterfaceCheck(ProductCheck):+ """Hold the approved-interface rule of § Wiring couplings for classes from wiring locations.++ The class re-export check accepts a wiring location by its path. This check reads the class: it+ must carry an approved decorator or reach an approved base. Only an Isolated product is held to+ it, so every product clears it on the way to Isolated. Below that rung the finding is+ information. An Isolated product's findings that existed when the check was introduced are+ `facade-wiring` rows in the crossings ledger, and an unrecorded finding blocks.+ """++ label = "wiring interfaces"++ def should_run(self, ctx: CheckContext) -> bool:+ return super().should_run(ctx) and (ctx.backend_dir / "facade").is_dir()++ def run(self, ctx: CheckContext) -> CheckResult:+ status = ctx.isolation_status()+ findings = status.unapproved_wiring+ result = CheckResult(file=f"products/{ctx.name}/backend/facade")+ if not findings:+ result.lines = ["✓ ok"]+ return result+ if status.rung is not IsolationRung.ISOLATED:+ names = ", ".join(sorted({f.class_name for f in findings}))+ result.lines = [f"ℹ {len(findings)} class(es) from wiring locations without an approved interface"]+ if ctx.detailed:+ result.lines.append(f" → information below the Isolated rung, clear before isolating: {names}")+ return result+ recorded = recorded_facade_shape_rows(ctx.name)+ unrecorded = [f for f in findings if facade_wiring_use(ctx.name, f).as_baseline_line() not in recorded]+ result.issues.extend(_wiring_issue(f) for f in unrecorded)+ if result.issues:+ result.lines = [f"✗ {len(result.issues)} issue(s)"] + [f" → {i}" for i in result.issues]+ else:+ result.warnings.append(f"wiring debt: {len(findings)} grandfathered row(s) in {_CROSSING_LEDGER}")+ result.lines = [f"⚠ wiring debt: {len(findings)} grandfathered rows"]+ return result++class ProductYamlCheck(ProductCheck):"""Validates product.yaml exists, parses, and has correct field types."""@@ -1290,5 +1359,6 @@ CHECKS: list[ProductCheck] = [TachCheck(),IsolationChainCheck(),FacadeShapeCheck(),+ WiringInterfaceCheck(),OrphanedTestFilesCheck(),]diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.pyindex 840b2bdd6b90..c5d9b6c831dd 100644--- a/tools/hogli-commands/hogli_commands/product/crossings.py+++ b/tools/hogli-commands/hogli_commands/product/crossings.py@@ -44,7 +44,9 @@ linter sees the same edge whether a facade imports a model module to build contrthe model, so publicness has to come from the shape of the API and not from the location of thefile. isolation.py reads the signatures; each finding lands as one of the disallowed kinds`facade-returns`, `facade-accepts(<parameter>)` and `facade-logic`. The rule is-products/architecture.md § Facades: The Public Interface.+products/architecture.md § Facades: The Public Interface. The kind `facade-wiring` reads the classes a+facade hands out from a wiring location: one without an approved interface is a row, but only for a+product on the Isolated rung, because below that rung the finding is information."""from __future__ import annotations@@ -60,16 +62,22 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path+from posthog.dataclasses import frozen+from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map, lazy_reexport_prefixesfrom .isolation import (COMPUTED_WIRING_LOCATIONS,MODEL_CROSSINGS,FacadeShapeFinding,+ IsolationRung,+ UnapprovedWiringClass,+ _facade_module_dotted,_iter_facade_modules,+ compute_isolation_status,facade_model_crossings,facade_shape_findings,)-from .paths import PRODUCTS_DIR, REPO_ROOT, backend_product_dirs+from .paths import PRODUCTS_DIR, REPO_ROOT, TACH_TOML, backend_product_dirsfrom .reverse_accessors import reverse_accessor_edge_lines# Where Python that can consume a product model lives. Everything else at the repo root is@@ -1688,9 +1696,42 @@ def facade_shape_uses(products: Iterable[str] | None = None) -> list[CrossingUse]+def facade_wiring_use(product: str, finding: UnapprovedWiringClass) -> CrossingUse:+ """One unapproved wiring class as a baseline row. The class crosses, and the consumer slot holds+ the facade module that hands it out."""+ return CrossingUse(+ f"{product}.{finding.class_name}", _facade_module_dotted(product, finding.facade_module), "facade-wiring", 1+ )+++def facade_wiring_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:+ """Unapproved wiring classes of Isolated products, as CrossingUse rows.++ Below the Isolated rung the finding is information and leaves no row, so a product reaches+ Isolated only after it clears every finding. The rows that exist were recorded when the check+ was introduced, and they may only go away."""+ wanted = set(products) if products is not None else None+ tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""+ uses: list[CrossingUse] = []+ for product_dir in backend_product_dirs():+ if wanted is not None and product_dir.name not in wanted:+ continue+ status = compute_isolation_status(+ product_dir.name, product_dir, product_dir / "backend", tach_content=tach_content+ )+ if status.rung is IsolationRung.ISOLATED:+ uses.extend(facade_wiring_use(product_dir.name, finding) for finding in status.unapproved_wiring)+ return uses++def all_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:- """Every channel: the three AST scans, the model-graph reverse accessors, and the facade shapes."""- return scan_crossing_uses(products) + reverse_accessor_uses(products) + facade_shape_uses(products)+ """Every channel: the three AST scans, the model-graph reverse accessors, and the facade rows."""+ return (+ scan_crossing_uses(products)+ + reverse_accessor_uses(products)+ + facade_shape_uses(products)+ + facade_wiring_uses(products)+ )# ---------------------------------------------------------------------------@@ -1765,10 +1806,12 @@ NEW_LINE_INSTRUCTION = ("traversal alive); seal it, remove the explicit query name, and give callers a facade read ""function. A 'drives(...)' line is a test outside the product that executes one of its query ""runners; move that test into the product. A 'facade-...' line is a facade that puts a Django, a "- "DRF or an ORM type on its own boundary, or a capability submodule that holds bodies; the "- "lint prints the move that clears each kind. A coupling that "- "must stand is a doctrine amendment: hand-edit the line in, and record why in "- "products/architecture.md § Wiring couplings. Regenerating the baseline cannot add a line."+ "DRF or an ORM type on its own boundary, a capability submodule that holds bodies, or an "+ "Isolated product's class from a wiring location without an approved interface; the "+ "lint prints the move that clears each kind. A coupling that must stand needs a DevEx change "+ "to the scanner, such as an approved interface, a MODEL_CROSSINGS entry or a carve-out. "+ "Neither a regenerate nor a hand edit adds a line: product:lint refuses ledger growth in any "+ "change that does not touch the scanner.")BASELINE_HEADER = f"""\@@ -1798,15 +1841,19 @@ BASELINE_HEADER = f"""\# submodule holds bodies rather than re-exports, and its count is how many are left. The first# column says what crosses — `<product>.<Class>`, `<library>.<Type>`, or the facade module for a# `facade-logic` line — and the consumer column holds the symbol or the module that carries it.-# The rule is products/architecture.md § Facades: The Public Interface.+# The rule is products/architecture.md § Facades: The Public Interface. `facade-wiring` means an+# Isolated product's facade hands out a class from a wiring location that implements no approved+# interface (§ Wiring couplings). Only Isolated products get these lines; below that rung the+# lint reports the class as information.## Counts may only go down, and a line that disappears must be deleted here too.## Regenerate after a removal: {REGENERATE_COMMAND}# That command refuses to write when the scan holds a line this file does not, or a count that-# went up. A coupling that-# must stand is a hand-edited line here, together with the amendment in products/architecture.md-# § Wiring couplings that permits it, because a reviewer can see both.+# went up. Do not hand-edit a line in: `hogli product:lint --all` refuses growth against the pull+# request's base unless the change also touches the scanner in tools/hogli-commands/hogli_commands/product/.+# A coupling that must stand needs that DevEx change (an approved interface, a MODEL_CROSSINGS+# entry or a carve-out)."""@@ -1818,8 +1865,12 @@ def render_baseline(uses: Iterable[CrossingUse]) -> str:return BASELINE_HEADER + "\n".join(scanned_baseline_lines(uses)) + "\n"+def parse_baseline(text: str) -> list[str]:+ return [line for line in text.splitlines() if line.strip() and not line.startswith("#")]++def read_baseline(path: Path = BASELINE_PATH) -> list[str]:- return [line for line in path.read_text().splitlines() if line.strip() and not line.startswith("#")]+ return parse_baseline(path.read_text())def _counts_by_identity(lines: Iterable[str]) -> dict[str, int]:@@ -1843,6 +1894,35 @@ class BaselineDrift:shrunk: list[str]+@frozen(order=True)+class _Debt:+ crossing: str+ kind: str+++def _debt_by_crossing_and_kind(lines: Iterable[str]) -> Counter[_Debt]:+ debt: Counter[_Debt] = Counter()+ for line in lines:+ crossing, _consumer, kind, count = line.split(" ")+ debt[_Debt(crossing=crossing, kind=kind)] += int(count)+ return debt+++def grown_debt(base_lines: Iterable[str], current_lines: Iterable[str]) -> list[str]:+ """The debt that rose, summed per crossing and kind over all consumers.++ A change that moves or splits a consumer module carries its lines along, so it raises no debt+ even though its lines are new. This is the one growth rule: a regenerate and the PR-base check+ in ledger_growth.py both apply it."""+ base = _debt_by_crossing_and_kind(base_lines)+ current = _debt_by_crossing_and_kind(current_lines)+ return [+ f"{debt.crossing} {debt.kind}: {base[debt]} → {count}"+ for debt, count in sorted(current.items())+ if count > base[debt]+ ]++def baseline_drift(recorded: Iterable[str], scanned: Iterable[str]) -> BaselineDrift:recorded_counts = _counts_by_identity(recorded)scanned_counts = _counts_by_identity(scanned)@@ -1889,16 +1969,16 @@ class BaselineWouldGrow(Exception):def write_baseline(uses: Iterable[CrossingUse], path: Path = BASELINE_PATH) -> None:- """Record the scan, but only while every difference against the file is a removal.+ """Record the scan, but only while no crossing's debt of any kind rises.- A regenerate that absorbs a new line hides the coupling from the review of the change that- caused it. A deliberate coupling therefore goes in by hand, next to the doctrine note that- permits it. There is no flag to skip this: a hand-edited line is what a reviewer reads, and a- flag would be pasted from one change into the next."""+ A regenerate that absorbs new debt hides the coupling from the review of the change that caused+ it. A moved or split consumer module keeps the debt where it was, so its new lines are written.+ There is no flag to skip this, because a flag would be pasted from one change into the next."""scanned = list(uses)if path.exists():- drift = baseline_drift(read_baseline(path), scanned_baseline_lines(scanned))- if drift.grown:- raise BaselineWouldGrow(path, drift.grown)+ recorded = read_baseline(path)+ lines = scanned_baseline_lines(scanned)+ if grown_debt(recorded, lines):+ raise BaselineWouldGrow(path, baseline_drift(recorded, lines).grown)path.write_text(render_baseline(scanned))_baseline_lines.cache_clear()diff --git a/tools/hogli-commands/hogli_commands/product/isolate.py b/tools/hogli-commands/hogli_commands/product/isolate.pyindex f930e8273b91..abf1faae0b26 100644--- a/tools/hogli-commands/hogli_commands/product/isolate.py+++ b/tools/hogli-commands/hogli_commands/product/isolate.py@@ -132,7 +132,7 @@ def strict_preflight(name: str) -> list[str]:name=name,product_dir=product_dir,backend_dir=product_dir / "backend",- is_isolated=True,+ has_facade_contracts=True,structure=load_structure(),detailed=False,)diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex ed5faed22840..e231eb681fe7 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -26,6 +26,7 @@ import tomllibimport functoolsfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclass+from enum import StrEnumfrom pathlib import Pathfrom .ast_helpers import (@@ -53,6 +54,7 @@ from .import_resolution import (source_file,)from .paths import REPO_ROOT, TACH_TOML, get_tach_block+from .wiring_interfaces import WiringInterfaceResolver, WiringVerdict# ---------------------------------------------------------------------------# tach.toml parsing@@ -148,8 +150,9 @@ def names_from_pattern(pattern: str) -> set[str]:# ----------------------------------------------------------------------------def is_isolated_product(backend_dir: Path) -> bool:- """A product is in the strict isolation regime once it has a contracts module."""+def has_contracts_module(backend_dir: Path) -> bool:+ """The Strict rung: a contracts module turns on the strict lint. The file alone is no evidence of+ isolation, because an empty contracts.py satisfies it."""return (backend_dir / "facade" / "contracts.py").exists() or (backend_dir / "facade" / "contracts").exists()@@ -832,6 +835,66 @@ def facade_class_imports(backend_dir: Path, name: str) -> list[FacadeClassImportreturn list(_split_facade_reexports(backend_dir, name).leaks)+@dataclass(frozen=True)+class UnapprovedWiringClass:+ """A class a facade hands out from a wiring location without an approved interface."""++ facade_module: str # path inside facade/, e.g. "destinations/s3.py"+ class_name: str # the name the facade exports, unique within its module+ source_path: str # backend-relative, e.g. "backend/temporal/destinations/s3_batch_export.py"+ verdict: WiringVerdict # UNAPPROVED or UNRESOLVED+++def _backend_module(name: str, source_path: str) -> str:+ """The dotted module of a backend-relative path: 'backend/temporal/x.py' -> 'products.<name>.backend.temporal.x'."""+ relative = source_path.removeprefix("backend").strip("/").removesuffix(".py")+ parts = [part for part in relative.split("/") if part]+ if parts and parts[-1] == "__init__":+ parts.pop()+ return ".".join([f"products.{name}.backend", *parts])+++def facade_unapproved_wiring(backend_dir: Path, name: str) -> list[UnapprovedWiringClass]:+ """Classes a facade hands out from a wiring location that implement no approved interface.++ The class re-export check accepts a wiring location by its path. This check reads the class:+ a location is necessary but not enough under § Wiring couplings, which also requires an approved+ decorator or base (APPROVED_WIRING_BASES, APPROVED_WIRING_DECORATORS)."""+ resolver = WiringInterfaceResolver(REPO_ROOT, roots={f"products.{name}.backend": backend_dir})+ findings: dict[str, UnapprovedWiringClass] = {}+ for module_file in _iter_facade_modules(backend_dir):+ module_key = _facade_module_key(backend_dir, module_file)+ if module_key in ("contracts.py", "enums.py"):+ continue+ tree = ast_parse_safe(module_file)+ if tree is None:+ continue+ for handed in _iter_handed_out_names(tree, backend_dir, _facade_package_parts(module_key)):+ if not handed.source_path.startswith(GARAGE_PREFIXES):+ continue+ qualified = f"{_backend_module(name, handed.source_path)}.{handed.original}"+ # The resolver follows absolute and chained re-exports, which _name_is_class stops at.+ if resolver.is_class(qualified):+ exported = {handed.bound: qualified}+ else:+ # A collection such as WORKFLOWS hands out every class it holds, and core registers+ # each one.+ members = resolver.collection_members(qualified)+ if members is None:+ finding = UnapprovedWiringClass(+ module_key, handed.bound, handed.source_path, WiringVerdict.UNRESOLVED+ )+ findings[f"{module_key}:{handed.bound}"] = finding+ continue+ exported = {member.rpartition(".")[2]: member for member in members if resolver.is_class(member)}+ for class_name, class_qualified in exported.items():+ verdict = resolver.verdict(class_qualified)+ if verdict is not WiringVerdict.APPROVED:+ finding = UnapprovedWiringClass(module_key, class_name, handed.source_path, verdict)+ findings[f"{module_key}:{class_name}"] = finding+ return list(findings.values())++def facade_carveout_modules(backend_dir: Path, name: str) -> set[str]:"""Backend-relative modules that define the carve-out classes this product's facade re-exports.@@ -1629,10 +1692,19 @@ def facade_shape_findings(backend_dir: Path, name: str) -> list[FacadeShapeFindi# ---------------------------------------------------------------------------+class IsolationRung(StrEnum):+ """The isolation ladder. Each rung includes the one before it."""++ LENIENT = "Lenient"+ STRICT = "Strict"+ SEALED = "Sealed"+ ISOLATED = "Isolated"++@dataclass(frozen=True)class IsolationStatus:name: str- is_isolated: bool # has facade/contracts.py — in the strict regime+ has_facade_contracts: bool # has facade/contracts.py, which puts the product on the Strict runghas_real_facade: boolhas_tach_interface: boolhas_legacy_leaks: bool@@ -1663,6 +1735,9 @@ class IsolationStatus:# product fails to keep in its contract-check inputs; every narrowed product must watch them.model_crossings: tuple[FacadeClassImport, ...] = ()uncovered_model_surface: tuple[str, ...] = ()+ # Classes from wiring locations without an approved interface (see facade_unapproved_wiring).+ # Information below the Isolated rung; on an Isolated product each one needs a ledger row.+ unapproved_wiring: tuple[UnapprovedWiringClass, ...] = ()@propertydef deferred_count(self) -> int:@@ -1676,29 +1751,41 @@ class IsolationStatus:@propertydef internally_sealed(self) -> bool:"""Presentation reaches internals only through the facade — no open bypasses."""- return self.is_isolated and self.deferred_count == 0+ return self.has_facade_contracts and self.deferred_count == 0@property- def eligible_for_isolated_tests(self) -> bool:- """Prerequisites for the contract-check skip, mirroring the lint gate's package.json- check exactly. Deliberately does NOT include `has_tach_interface` — the external- boundary is required too, but it's enforced separately (TachCheck demands the- interface; IsolationChainCheck blocks a script without it). Callers that gate a- "ready" *display* should additionally require `externally_sealed`."""- return self.is_isolated and self.has_real_facade and not self.has_legacy_leaks and self.deferred_count == 0+ def is_sealed(self) -> bool:+ """The Sealed rung: both seals hold and facade/api.py defines real functions."""+ return self.externally_sealed and self.internally_sealed and self.has_real_facade@property- def isolated_tests_enabled(self) -> bool:+ def test_skip_configured(self) -> bool:"""The skip is physically wired up right now (script present + turbo narrowed)."""return self.has_contract_check_script and self.has_narrowed_turbo+ @property+ def isolation_enabled(self) -> bool:+ """The Isolated rung: a sealed product whose test skip is configured. A configured skip on an+ unsealed product does not count, because the lint rejects that state."""+ return self.is_sealed and self.test_skip_configured++ @property+ def rung(self) -> IsolationRung:+ if self.isolation_enabled:+ return IsolationRung.ISOLATED+ if self.is_sealed:+ return IsolationRung.SEALED+ if self.has_facade_contracts:+ return IsolationRung.STRICT+ return IsolationRung.LENIENT+def compute_isolation_status(name: str,product_dir: Path,backend_dir: Path,*,- is_isolated: bool | None = None,+ has_facade_contracts: bool | None = None,tach_content: str | None = None,pyproject_text: str | None = None,repo_root: Path | None = None,@@ -1708,8 +1795,8 @@ def compute_isolation_status(`driven_wiring_locations` is the evidence `unwatched_garages` reads. Without it, every present wiringlocation must stay watched."""- if is_isolated is None:- is_isolated = is_isolated_product(backend_dir)+ if has_facade_contracts is None:+ has_facade_contracts = has_contracts_module(backend_dir)if tach_content is None:tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""if repo_root is None:@@ -1720,7 +1807,7 @@ def compute_isolation_status(carveout_modules = reexports.carveout_modulesreturn IsolationStatus(name=name,- is_isolated=is_isolated,+ has_facade_contracts=has_facade_contracts,has_real_facade=has_real_facade(backend_dir),has_tach_interface=has_tach_interface(name, tach_content),has_legacy_leaks=has_legacy_interface_leaks(tach_content, module_path),@@ -1740,4 +1827,5 @@ def compute_isolation_status(uncovered_carveout_modules=tuple(sorted(uncovered_carveout_modules(product_dir, carveout_modules))),model_crossings=reexports.model_crossings,uncovered_model_surface=tuple(sorted(unwatched_model_surface(product_dir))),+ unapproved_wiring=tuple(facade_unapproved_wiring(backend_dir, name)),)diff --git a/tools/hogli-commands/hogli_commands/product/ledger_growth.py b/tools/hogli-commands/hogli_commands/product/ledger_growth.pynew file mode 100644index 000000000000..556d2af61ebe--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/ledger_growth.py@@ -0,0 +1,64 @@+"""The crossings ledger grows only in a change to the scanner.++products/architecture.md § Wiring couplings: the ledger records the debt that existed when a check+landed, and it takes no new exceptions. The repo-invariant test holds the file equal to a scan of+the tree, so it passes a change that adds a coupling and its line together. This check compares the+file with the pull request's base instead. A change to the scanner may add lines, because a new+check records the findings that already exist when it lands, and because an approved exception+(an approved interface, a MODEL_CROSSINGS entry, a carve-out) is a scanner change too.++Growth is crossings.grown_debt, the rule a regenerate applies too.+"""++from __future__ import annotations++import os+import subprocess+from pathlib import Path++from .crossings import BASELINE_PATH, grown_debt, parse_baseline, read_baseline+from .paths import REPO_ROOT++# CI sets this to the pull request's base commit. Unset, the check does not run.+LEDGER_BASE_ENV = "CROSSINGS_LEDGER_BASE"++# A change here may add ledger lines, so .stamphog/policy.yml holds the whole folder under+# devex_guardrails: such a change always gets a human review.+SCANNER_DIR = "tools/hogli-commands/hogli_commands/product/"++LEDGER_GROWTH_INSTRUCTION = (+ f"{BASELINE_PATH.name} records the debt that existed when a DevEx check landed. It takes no new "+ "lines, and a hand-edited line is not an exception. Change the caller instead: "+ "`hogli product:crossings <product>` and `hogli product:lint <product>` print the move for each "+ "kind. A coupling that must stand needs a DevEx change to the scanner in "+ f"{SCANNER_DIR} (an approved interface, a MODEL_CROSSINGS entry or a carve-out). Only such a "+ "change may add lines."+)+++class LedgerBaseUnreadable(Exception):+ pass+++def _git(repo_root: Path, *args: str) -> str:+ result = subprocess.run(["git", *args], cwd=repo_root, capture_output=True, text=True, check=False)+ if result.returncode != 0:+ raise LedgerBaseUnreadable(f"git {' '.join(args)}: {result.stderr.strip()}")+ return result.stdout+++def ledger_growth_issues(repo_root: Path = REPO_ROOT, ledger_path: Path = BASELINE_PATH) -> list[str] | None:+ """The debt the ledger gained since the base, or None when no base is set."""+ ref = os.environ.get(LEDGER_BASE_ENV)+ if not ref:+ return None+ ledger = ledger_path.relative_to(repo_root).as_posix()+ try:+ base = _git(repo_root, "merge-base", ref, "HEAD").strip()+ base_text = _git(repo_root, "show", f"{base}:{ledger}")+ scanner_changes = _git(repo_root, "diff", "--name-only", base, "HEAD", "--", SCANNER_DIR)+ except LedgerBaseUnreadable as error:+ return [f"{LEDGER_BASE_ENV}={ref} could not be read: {error}"]+ if scanner_changes.strip():+ return []+ return grown_debt(parse_baseline(base_text), read_baseline(ledger_path))diff --git a/tools/hogli-commands/hogli_commands/product/lint.py b/tools/hogli-commands/hogli_commands/product/lint.pyindex 4ffffafb44ff..bedfa4320742 100644--- a/tools/hogli-commands/hogli_commands/product/lint.py+++ b/tools/hogli-commands/hogli_commands/product/lint.py@@ -8,7 +8,9 @@ from pathlib import Pathimport clickfrom .baseline import check_baseline-from .checks import CHECKS, CheckContext, ProductYamlOwnersCheck, is_isolated_product, validate_tach_toml+from .checks import CHECKS, CheckContext, ProductYamlOwnersCheck, has_contracts_module, validate_tach_toml+from .crossings import BASELINE_PATH+from .ledger_growth import LEDGER_BASE_ENV, LEDGER_GROWTH_INSTRUCTION, ledger_growth_issuesfrom .paths import ISOLATION_BASELINE, PRODUCTS_DIR, REPO_ROOT, TACH_TOML, backend_product_dirs, load_structure_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"@@ -25,8 +27,10 @@ def lint_product(name: str, verbose: bool = True, detailed: bool = False, structLint a product's structure. Returns list of issues found.Runs in two modes based on whether the product has backend/facade/contracts.py:- strict — isolated product, all structure rules enforced- lenient — legacy product, subset of rules enforced (see product_structure.yaml)+ strict — the Strict rung or above, all structure rules enforced+ lenient — the Lenient rung, subset of rules enforced (see product_structure.yaml)++ The detailed output also prints the product's isolation rung (Lenient, Strict, Sealed, Isolated).Set detailed=True (single-product run) for richer isolation progress output.Pass structure= to avoid re-parsing product_structure.yaml on every call (useful in --all mode).@@ -37,20 +41,26 @@ def lint_product(name: str, verbose: bool = True, detailed: bool = False, structif not product_dir.exists():raise click.ClickException(f"Product '{name}' not found at {product_dir}")- isolated = is_isolated_product(backend_dir)- mode = "strict" if isolated else "lenient"+ strict = has_contracts_module(backend_dir)+ mode = "strict" if strict else "lenient"if verbose:- click.echo(f" mode: {mode}" + (" (has backend/facade/contracts.py)" if isolated else " (legacy)"))+ click.echo(+ f" mode: {mode}"+ + (" (has backend/facade/contracts.py)" if strict else " (no backend/facade/contracts.py)")+ )ctx = CheckContext(name=name,product_dir=product_dir,backend_dir=backend_dir,- is_isolated=isolated,+ has_facade_contracts=strict,structure=structure or load_structure(),detailed=detailed,)+ # The checks below read the same memoized status, so printing the rung costs no extra scan.+ if verbose and backend_dir.is_dir():+ click.echo(f" rung: {ctx.isolation_status().rung}")issues: list[str] = []for check in CHECKS:@@ -86,14 +96,14 @@ def _lint_tach_toml() -> list[str]:def lint_all_products() -> None: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")]+ strict = [d.name for d in product_dirs if has_contracts_module(d / "backend")]+ lenient = [d.name for d in product_dirs if not has_contracts_module(d / "backend")]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), "- "facade shape, isolation baseline\n"+ "facade shape, isolation baseline, crossings ledger growth\n")structure = load_structure()@@ -129,13 +139,31 @@ def lint_all_products() -> None:click.echo(" ✓ ok")click.echo("")- if failed or tach_issues or baseline_issues:+ click.echo("─ crossings ledger growth")+ growth_issues = ledger_growth_issues()+ if growth_issues is None:+ click.echo(f" – skipped: {LEDGER_BASE_ENV} is not set (CI sets it on pull requests)")+ elif growth_issues:+ click.echo(f" ✗ {len(growth_issues)} issue(s)")+ click.echo(f" {LEDGER_GROWTH_INSTRUCTION}")+ for issue in growth_issues:+ click.echo(f" → {issue}")+ _gh_annotation(+ "error", "products", "crossings ledger growth", issue, file=str(BASELINE_PATH.relative_to(REPO_ROOT))+ )+ else:+ click.echo(" ✓ ok")+ click.echo("")++ if failed or tach_issues or baseline_issues or growth_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)")+ if growth_issues:+ click.echo(f"✗ {len(growth_issues)} crossings ledger growth issue(s)")raise SystemExit(1)click.echo(f"✓ All {len(product_dirs)} products passed")@@ -185,7 +213,7 @@ def lint_owners(names: list[str] | None = None) -> None:name=product_dir.name,product_dir=product_dir,backend_dir=product_dir / "backend",- is_isolated=is_isolated_product(product_dir / "backend"),+ has_facade_contracts=has_contracts_module(product_dir / "backend"),structure=structure,detailed=False,)diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex a895ea850e29..79dd5d62553d 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -35,6 +35,7 @@ from .ast_helpers import (view_facade_usage,)from .isolation import (+ IsolationRung,IsolationStatus,compute_isolation_status,has_legacy_interface_leaks,@@ -954,11 +955,9 @@ def _dim_line(dim: DimensionScore, connector: str = "\u251c\u2500") -> str:def _isolated_tests_state(status: IsolationStatus) -> tuple[str, str]:"""(state, reason) for the isolated-tests certificate \u2014 the contract-check skip."""- if status.isolated_tests_enabled:+ if status.test_skip_configured:return "ON", "contract-check skip live \u2014 Django suite stays off unrelated CI shards"- # Eligibility deliberately excludes the tach interface (see IsolationStatus), but the skip- # is unsound without the external boundary, so READY also requires it.- if status.eligible_for_isolated_tests and status.externally_sealed:+ if status.is_sealed:missing = []if not status.has_contract_check_script:missing.append("add backend:contract-check")@@ -966,7 +965,7 @@ def _isolated_tests_state(status: IsolationStatus) -> tuple[str, str]:missing.append("narrow turbo.json inputs")return "READY", f"{' + '.join(missing)} to turn the skip on"blockers: list[str] = []- if not status.is_isolated:+ if not status.has_facade_contracts:blockers.append("add a facade (contracts.py + api.py)")elif not status.has_real_facade:blockers.append("make facade/api.py real (define functions, not re-exports)")@@ -979,6 +978,14 @@ def _isolated_tests_state(status: IsolationStatus) -> tuple[str, str]:return "OFF", "; ".join(blockers) if blockers else "prerequisites incomplete"+_RUNG_DETAIL: dict[IsolationRung, str] = {+ IsolationRung.LENIENT: "no facade/contracts.py, lenient lint",+ IsolationRung.STRICT: "facade/contracts.py present, strict lint",+ IsolationRung.SEALED: "both seals and a real facade, isolated tests not on",+ IsolationRung.ISOLATED: "sealed, isolated tests on",+}++def _isolation_capstone(status: IsolationStatus) -> list[str]:"""Render the external-vs-internal seal synthesis: the headline an agent acts on.@@ -993,8 +1000,10 @@ def _isolation_capstone(status: IsolationStatus) -> list[str]:else:ext_state, ext_detail = "open", "legacy interface leak block present \u2014 core still imports internals"- if not status.is_isolated:- int_state, int_detail = "n/a", "no facade yet \u2014 product not isolated"+ if not status.has_facade_contracts:+ int_state, int_detail = "n/a", "no facade yet, so the product is Lenient"+ elif not status.has_real_facade:+ int_state, int_detail = "n/a", "facade/api.py defines no functions, so there is nothing to seal yet"elif status.internally_sealed:int_state, int_detail = "sealed", "presentation reaches internals only through the facade"else:@@ -1006,6 +1015,7 @@ def _isolation_capstone(status: IsolationStatus) -> list[str]:tests_state, tests_detail = _isolated_tests_state(status)rows = [+ ("rung", status.rung, _RUNG_DETAIL[status.rung]),("external boundary", ext_state, ext_detail),("internal seal", int_state, int_detail),("isolated tests", tests_state, tests_detail),@@ -1016,21 +1026,21 @@ def _isolation_capstone(status: IsolationStatus) -> list[str]:return lines-SEAL_LEGEND = "seal: on=tests live ready=eligible, not wired int:N=N internal bypasses open ext\u2717=external boundary open \u2014=not isolated"+SEAL_LEGEND = "seal: on=tests live ready=eligible, not wired int:N=N internal bypasses open ext\u2717=external boundary open \u2014=Lenient (no facade contracts)"def _seal_token(status: IsolationStatus | None) -> str:"""Compact seal state for the --all grid. Each token names the remaining blocker."""- if status is None or not status.is_isolated:+ if status is None or not status.has_facade_contracts:return "\u2014"- if status.isolated_tests_enabled:+ if status.test_skip_configured:return "on"if not status.externally_sealed:return "ext\u2717"if status.deferred_count > 0:# externally sealed but internally unsealed \u2014 looks done, isn'treturn f"int:{status.deferred_count}"- if status.eligible_for_isolated_tests:+ if status.is_sealed:return "ready"return "partial"diff --git a/tools/hogli-commands/hogli_commands/product/wiring_interfaces.py b/tools/hogli-commands/hogli_commands/product/wiring_interfaces.pynew file mode 100644index 000000000000..8a580cb87d54--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/wiring_interfaces.py@@ -0,0 +1,336 @@+"""Whether a class implements an approved wiring interface, read from source.++products/architecture.md § Wiring couplings lets a behavior class cross a product boundary only when+it implements an approved core interface and lives in a wiring location. The location is a path+check. The interface is a property of the class, so this module follows the class through the+repository: a product query runner reaches QueryRunner through core's AnalyticsQueryRunner. It+parses source and never imports a module, because a lint run must not boot Django.+"""++from __future__ import annotations++import ast+import builtins+import functools+from collections.abc import Mapping+from enum import StrEnum+from pathlib import Path++from posthog.dataclasses import frozen++from .ast_helpers import ast_parse_safe, module_level_import_nodes++# Rule 1 of § Wiring couplings, by the qualified name a class reaches. A base counts through any+# depth of repository classes. A decorator counts only on the class itself.+APPROVED_WIRING_BASES: frozenset[str] = frozenset(+ {+ "ee.hogai.tool.MaxTool",+ "posthog.hogql_queries.query_runner.QueryRunner",+ "temporalio.worker.Interceptor",+ }+)+APPROVED_WIRING_DECORATORS: frozenset[str] = frozenset(+ {+ "celery.shared_task",+ "temporalio.activity.defn",+ "temporalio.workflow.defn",+ }+)++# Top-level packages whose modules sit in this repository. A name from any other package is a+# library, so it resolves without a file and never approves.+_REPOSITORY_PACKAGES: frozenset[str] = frozenset({"common", "ee", "posthog", "products"})+++class WiringVerdict(StrEnum):+ APPROVED = "approved"+ UNAPPROVED = "unapproved"+ # A base or a re-export that the source does not name statically, such as a star import. The+ # lint cannot confirm an approved interface, so it reports the class like an unapproved one.+ UNRESOLVED = "unresolved"+++@frozen+class _ModuleScope:+ """What one module binds at its top level."""++ module: str+ tree: ast.Module+ bindings: Mapping[str, str] # each imported name and the qualified name it refers to+ classes: Mapping[str, ast.ClassDef]+ rebound: frozenset[str] # names a top-level statement other than an import binds+ mutated: frozenset[str] # names a top-level statement changes in place+++@frozen+class _ClassSite:+ scope: _ModuleScope+ node: ast.ClassDef+++def _rebound_names(tree: ast.Module) -> frozenset[str]:+ names: set[str] = set()+ for statement in tree.body:+ if isinstance(statement, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):+ names.add(statement.name)+ elif isinstance(statement, ast.Assign):+ names.update(target.id for target in statement.targets if isinstance(target, ast.Name))+ elif isinstance(statement, (ast.AnnAssign, ast.AugAssign)) and isinstance(statement.target, ast.Name):+ names.add(statement.target.id)+ return frozenset(names)+++# Methods that add to a list, set or dict in place.+_MUTATING_METHODS: frozenset[str] = frozenset({"append", "extend", "insert", "add", "update"})+++def _mutated_names(tree: ast.Module) -> frozenset[str]:+ """Names a top-level statement changes in place, such as `FLOWS.append(Plain)` or `FLOWS += [Plain]`."""+ names: set[str] = set()+ for statement in tree.body:+ if (+ isinstance(statement, ast.Expr)+ and isinstance(statement.value, ast.Call)+ and isinstance(statement.value.func, ast.Attribute)+ and isinstance(statement.value.func.value, ast.Name)+ and statement.value.func.attr in _MUTATING_METHODS+ ):+ names.add(statement.value.func.value.id)+ elif isinstance(statement, ast.AugAssign) and isinstance(statement.target, ast.Name):+ names.add(statement.target.id)+ elif isinstance(statement, ast.Assign):+ names.update(+ target.value.id+ for target in statement.targets+ if isinstance(target, ast.Subscript) and isinstance(target.value, ast.Name)+ )+ return frozenset(names)+++def _assigned_value(tree: ast.Module, name: str) -> ast.expr | None:+ """The expression the last top-level assignment binds to the name, which is the one Python keeps."""+ for statement in reversed(tree.body):+ if isinstance(statement, ast.Assign) and any(+ isinstance(target, ast.Name) and target.id == name for target in statement.targets+ ):+ return statement.value+ if isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name):+ if statement.target.id == name and statement.value is not None:+ return statement.value+ return None+++def _parsed(path: Path) -> ast.Module | None:+ """One parse per file for the whole run, because many products reach the same core modules."""+ return ast_parse_safe(path)+++class WiringInterfaceResolver:+ """Decides the wiring verdict of a class by its module and name.++ `roots` maps a dotted package prefix to the directory that holds it, so a product under test+ resolves from a temporary directory. Every other repository module resolves from `repo_root`.+ """++ def __init__(self, repo_root: Path, roots: Mapping[str, Path] | None = None) -> None:+ self._repo_root = repo_root+ self._roots = dict(roots or {})+ self._ancestor_verdicts: dict[str, WiringVerdict] = {}++ def is_class(self, qualified: str) -> bool:+ """Whether the name reaches a class definition through any chain of re-exports here."""+ return isinstance(self._locate(qualified, frozenset()), _ClassSite)++ def collection_members(self, qualified: str) -> list[str] | None:+ """The qualified names that a top-level list, tuple or set literal holds, such as WORKFLOWS.++ None when a later top-level statement changes the collection, such as `WORKFLOWS.append(Plain)`.+ The lint then cannot see which classes it holds."""+ return self._members(qualified, frozenset())++ def verdict(self, qualified: str) -> WiringVerdict:+ site = self._locate(qualified, frozenset())+ if isinstance(site, WiringVerdict):+ return site+ # Temporal registers a class by its own decorator only, so a decorator counts on the class+ # the facade hands out and never on one of its bases.+ if any(+ self._qualify(decorator, site.scope) in APPROVED_WIRING_DECORATORS for decorator in site.node.decorator_list+ ):+ return WiringVerdict.APPROVED+ return self._bases_verdict(site, frozenset({qualified}))++ def _module_file(self, module: str) -> tuple[Path, bool] | None:+ """The file of a dotted module and whether it is a package, or None when it is not here."""+ base: Path | None = None+ for prefix, directory in self._roots.items():+ if module == prefix or module.startswith(f"{prefix}."):+ relative = module.removeprefix(prefix).lstrip(".")+ base = directory.joinpath(*relative.split(".")) if relative else directory+ break+ if base is None:+ if module.split(".", 1)[0] not in _REPOSITORY_PACKAGES:+ return None+ base = self._repo_root.joinpath(*module.split("."))+ if base.with_suffix(".py").is_file():+ return base.with_suffix(".py"), False+ if (base / "__init__.py").is_file():+ return base / "__init__.py", True+ return None++ def _bindings(self, module: str, is_package: bool, tree: ast.Module) -> dict[str, str]:+ """The qualified name of each name the module-level imports bind."""+ package = module if is_package else module.rpartition(".")[0]+ bindings: dict[str, str] = {}+ for node in module_level_import_nodes(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.asname:+ bindings[alias.asname] = alias.name+ else:+ head = alias.name.split(".", 1)[0]+ bindings[head] = head+ continue+ if node.level:+ parts = package.split(".")+ if node.level - 1 >= len(parts):+ continue+ source = ".".join(parts[: len(parts) - (node.level - 1)])+ if node.module:+ source = f"{source}.{node.module}"+ else:+ source = node.module or ""+ for alias in node.names:+ if alias.name != "*":+ bindings[alias.asname or alias.name] = f"{source}.{alias.name}"+ return bindings++ def _scope(self, module: str) -> _ModuleScope | None:+ located = self._module_file(module)+ if located is None:+ return None+ path, is_package = located+ tree = _parsed(path)+ if tree is None:+ return None+ return _ModuleScope(+ module=module,+ tree=tree,+ bindings=self._bindings(module, is_package, tree),+ classes={node.name: node for node in tree.body if isinstance(node, ast.ClassDef)},+ rebound=_rebound_names(tree),+ mutated=_mutated_names(tree),+ )++ def _qualify(self, node: ast.expr, scope: _ModuleScope) -> str | None:+ """The qualified name an expression in a base, decorator or collection refers to."""+ if isinstance(node, ast.Subscript):+ return self._qualify(node.value, scope)+ if isinstance(node, ast.Call):+ return self._qualify(node.func, scope)+ if isinstance(node, ast.Attribute):+ head = self._qualify(node.value, scope)+ return f"{head}.{node.attr}" if head else None+ if isinstance(node, ast.Name):+ # A module that imports a name and binds it again binds it by statement order, so the+ # lint leaves it unread rather than guess which binding a base refers to.+ if node.id in scope.bindings and node.id in scope.rebound:+ return None+ if node.id in scope.bindings:+ return scope.bindings[node.id]+ if node.id in scope.classes:+ return f"{scope.module}.{node.id}"+ if hasattr(builtins, node.id):+ return f"builtins.{node.id}"+ return None++ def _locate(self, qualified: str, seen: frozenset[str]) -> _ClassSite | WiringVerdict:+ """The class definition a qualified name reaches through re-exports.++ Where no definition stands at the end, the verdict stands in for it: an approved base, a+ library class, or a name the source does not resolve statically."""+ if qualified in APPROVED_WIRING_BASES:+ return WiringVerdict.APPROVED+ if qualified in seen:+ return WiringVerdict.UNRESOLVED+ module, _, name = qualified.rpartition(".")+ scope = self._scope(module) if module else None+ if scope is None:+ if qualified.split(".", 1)[0] in _REPOSITORY_PACKAGES:+ return WiringVerdict.UNRESOLVED+ return WiringVerdict.UNAPPROVED+ if name in scope.classes:+ return _ClassSite(scope=scope, node=scope.classes[name])+ # A name the module only re-exports is judged where it is defined.+ if name in scope.bindings:+ return self._locate(scope.bindings[name], seen | {qualified})+ # An alias such as `Handed = Plain` is judged as the class it names.+ value = _assigned_value(scope.tree, name)+ if isinstance(value, (ast.Name, ast.Attribute)) and (target := self._qualify(value, scope)) is not None:+ return self._locate(target, seen | {qualified})+ return WiringVerdict.UNRESOLVED++ def _members(self, qualified: str, seen: frozenset[str]) -> list[str] | None:+ if qualified in seen:+ return []+ module, _, name = qualified.rpartition(".")+ scope = self._scope(module) if module else None+ if scope is None:+ return []+ value = _assigned_value(scope.tree, name)+ if value is not None:+ if name in scope.mutated:+ return None+ return self._expression_members(value, scope, seen | {qualified})+ if name in scope.bindings:+ return self._members(scope.bindings[name], seen | {qualified})+ return []++ def _element_members(self, element: ast.expr, scope: _ModuleScope, seen: frozenset[str]) -> list[str] | None:+ """One entry of a collection literal: a class name, or a `*OTHER_FLOWS` that unpacks another collection."""+ if isinstance(element, ast.Starred):+ return self._expression_members(element.value, scope, seen)+ member = self._qualify(element, scope)+ return [member] if member is not None else []++ def _expression_members(self, node: ast.expr, scope: _ModuleScope, seen: frozenset[str]) -> list[str] | None:+ """The class names a collection expression holds, such as `[A, B]` or `FLOWS + OTHER_FLOWS`."""+ parts: list[list[str] | None]+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):+ parts = [self._element_members(element, scope, seen) for element in node.elts]+ elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):+ parts = [+ self._expression_members(node.left, scope, seen),+ self._expression_members(node.right, scope, seen),+ ]+ elif isinstance(node, (ast.Name, ast.Attribute)) and (operand := self._qualify(node, scope)) is not None:+ return self._members(operand, seen)+ else:+ return []+ if any(part is None for part in parts):+ return None+ return [member for part in parts if part is not None for member in part]++ def _ancestor_verdict(self, qualified: str, seen: frozenset[str]) -> WiringVerdict:+ if qualified not in self._ancestor_verdicts:+ site = self._locate(qualified, seen)+ if isinstance(site, WiringVerdict):+ self._ancestor_verdicts[qualified] = site+ else:+ self._ancestor_verdicts[qualified] = self._bases_verdict(site, seen | {qualified})+ return self._ancestor_verdicts[qualified]++ def _bases_verdict(self, site: _ClassSite, seen: frozenset[str]) -> WiringVerdict:+ verdicts = []+ for base in site.node.bases:+ base_name = self._qualify(base, site.scope)+ if base_name is None:+ verdicts.append(WiringVerdict.UNRESOLVED)+ else:+ verdicts.append(self._ancestor_verdict(base_name, seen))+ if WiringVerdict.APPROVED in verdicts:+ return WiringVerdict.APPROVED+ if WiringVerdict.UNRESOLVED in verdicts:+ return WiringVerdict.UNRESOLVED+ return WiringVerdict.UNAPPROVEDdiff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex afcd7ef9f2e7..b69731a32632 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -10,6 +10,7 @@ import pytestfrom hogli_commands.product import (checks as checks_module,gh as gh_module,+ isolation as isolation_module,)from hogli_commands.product.checks import (BackendPackageMarkerCheck,@@ -22,6 +23,7 @@ from hogli_commands.product.checks import (PackageJsonScriptsCheck,ProductYamlCheck,ProductYamlOwnersCheck,+ WiringInterfaceCheck,_has_test_files,_is_noop_script,_names_from_pattern,@@ -34,10 +36,12 @@ from hogli_commands.product.checks import (from hogli_commands.product.crossings import facade_shape_usefrom hogli_commands.product.isolation import (MODEL_SURFACE_PREFIXES,+ IsolationRung,facade_carveout_modules,facade_class_imports,facade_model_crossings,facade_shape_findings,+ facade_unapproved_wiring,has_narrowed_turbo_inputs,permanent_interface_modules,routes_in_turbo_inputs,@@ -58,7 +62,7 @@ def _make_product(*,scripts: dict[str, str] | None = None,has_backend: bool = True,- isolated: bool = False,+ strict: bool = False,test_files: list[str] | None = None,extra_dirs: list[str] | None = None,) -> CheckContext:@@ -70,7 +74,7 @@ def _make_product(if has_backend:backend_dir.mkdir()- if isolated:+ 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")@@ -92,7 +96,7 @@ def _make_product(name="my_product",product_dir=product_dir,backend_dir=backend_dir,- is_isolated=isolated,+ has_facade_contracts=strict,structure={},detailed=False,)@@ -218,24 +222,24 @@ class TestPresenceChecks:result = check.run(ctx)assert not result.issues- def test_contract_check_required_for_isolated(self, tmp_path: Path) -> None:+ 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"},- isolated=True,+ 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_isolated_passes(self, tmp_path: Path) -> None:+ 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'",},- isolated=True,+ strict=True,extra_dirs=["backend"],)result = check.run(ctx)@@ -254,7 +258,7 @@ class TestPresenceChecks:class TestAbsenceChecks:- def test_contract_check_forbidden_for_non_isolated(self, tmp_path: Path) -> None:+ 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,@@ -262,18 +266,18 @@ class TestAbsenceChecks:"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short","backend:contract-check": "echo 'Contract files unchanged'",},- isolated=False,+ strict=False,extra_dirs=["backend"],)result = check.run(ctx)assert result.issuesassert any("turbo-discover" in i for i in result.issues)- def test_no_contract_check_for_non_isolated_passes(self, tmp_path: Path) -> None:+ 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"},- isolated=False,+ strict=False,extra_dirs=["backend"],)result = check.run(ctx)@@ -292,7 +296,7 @@ class TestAbsenceChecks:"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short","backend:contract-check": "echo 'Contract files unchanged'",},- isolated=True,+ strict=True,extra_dirs=["backend"],)result = check.run(ctx)@@ -377,14 +381,14 @@ class TestIsolationChainTurnOn:self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:_seal_externally(monkeypatch)- ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ 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, isolated=True)+ 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@@ -399,7 +403,7 @@ class TestIsolationChainTurnOn:ctx = _make_product(tmp_path,scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},- isolated=True,+ strict=True,)result = chain_check.run(ctx)assert not any("inert" in i for i in result.issues)@@ -412,15 +416,177 @@ class TestIsolationChainTurnOn: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, isolated=True)+ 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 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\[email protected]\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\[email protected]\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\[email protected]\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, isolated=True)+ 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)@@ -429,7 +595,7 @@ class TestIsolationChainRoutes: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, isolated=True)+ 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)@@ -441,7 +607,7 @@ class TestIsolationChainRoutes:# 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, isolated=True)+ 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)@@ -453,7 +619,7 @@ class TestIsolationChainRoutes:) -> 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, isolated=True)+ 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)@@ -462,7 +628,7 @@ class TestIsolationChainRoutes:# 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, isolated=True)+ 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)@@ -553,7 +719,7 @@ class TestIsolationChainWebhookConsumers: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, isolated=True)+ 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))@@ -733,7 +899,7 @@ class TestCombinedScenarios:"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short","backend:contract-check": "echo 'Contract files unchanged'",},- isolated=True,+ strict=True,test_files=["tests/test_api.py"],)result = check.run(ctx)@@ -744,7 +910,7 @@ class TestCombinedScenarios:ctx = _make_product(tmp_path,scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},- isolated=False,+ strict=False,extra_dirs=["backend"],)result = check.run(ctx)@@ -759,7 +925,7 @@ class TestCombinedScenarios:"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/nonexistent -v --tb=short || true","backend:contract-check": "echo 'Contract files unchanged'",},- isolated=False,+ strict=False,)result = check.run(ctx)# Should report: contract-check forbidden, || true, nonexistent path@@ -1014,7 +1180,7 @@ class TestPermanentInterfaceQualification: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, isolated=True)+ 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"@@ -1039,7 +1205,7 @@ def _make_yaml_ctx(tmp_path: Path, yaml_content: str | None = None) -> CheckContname="test_product",product_dir=product_dir,backend_dir=backend_dir,- is_isolated=False,+ has_facade_contracts=False,structure={},detailed=False,)@@ -1158,7 +1324,7 @@ def _make_backend(tmp_path: Path, files: list[str]) -> CheckContext:name="p",product_dir=product_dir,backend_dir=backend,- is_isolated=False,+ has_facade_contracts=False,structure=_CONFLICT_STRUCTURE,detailed=False,)@@ -1175,10 +1341,10 @@ class TestImportSurfaceCheck:files: dict[str, str],monkeypatch: pytest.MonkeyPatch,ignored=None,- is_isolated: bool = True,+ has_facade_contracts: bool = True,) -> CheckContext:ctx = _make_backend(tmp_path, list(files))- ctx.is_isolated = is_isolated+ ctx.has_facade_contracts = has_facade_contractsfor path, content in files.items():(ctx.backend_dir / path).write_text(content)monkeypatch.setattr(checks_module, "ignored_import_edges", lambda: set(ignored or ()))@@ -1348,7 +1514,7 @@ class TestImportSurfaceCheck:expected: int,monkeypatch: pytest.MonkeyPatch,) -> None:- ctx = self._ctx(tmp_path, files, monkeypatch, is_isolated=False)+ ctx = self._ctx(tmp_path, files, monkeypatch, has_facade_contracts=False)check = ImportSurfaceCheck()assert check.should_run(ctx) is should_runassert len(check.run(ctx).issues) == expected@@ -1362,7 +1528,7 @@ class TestFileFolderConflictsCheck:name="p",product_dir=product_dir,backend_dir=product_dir / "backend",- is_isolated=False,+ has_facade_contracts=False,structure=_CONFLICT_STRUCTURE,detailed=False,)@@ -1407,12 +1573,12 @@ class TestFileFolderConflictsCheck:# ----------------------------------------------------------------------------def _mkproduct(products_dir: Path, name: str, *, isolated: bool) -> None:+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 isolated:+ if strict:(p / "backend" / "facade").mkdir()(p / "backend" / "facade" / "contracts.py").write_text("")@@ -1494,8 +1660,8 @@ class TestValidateFacadeAlternation:tach: str,expected_substrings: list[tuple[str, ...]],) -> None:- for name, isolated in products:- _mkproduct(tmp_path, name, isolated=isolated)+ for name, strict in products:+ _mkproduct(tmp_path, name, strict=strict)issues = validate_facade_alternation(tach, tmp_path)if not expected_substrings:assert issues == []@@ -1652,8 +1818,8 @@ class TestValidateTachReferences:class TestAlternationSorting:def test_sorted_passes(self, tmp_path: Path) -> None:- _mkproduct(tmp_path, "alpha", isolated=True)- _mkproduct(tmp_path, "beta", isolated=True)+ _mkproduct(tmp_path, "alpha", strict=True)+ _mkproduct(tmp_path, "beta", strict=True)tach = _iface(["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],"products\\\\.(alpha|beta)",@@ -1661,8 +1827,8 @@ class TestAlternationSorting:assert validate_facade_alternation(tach, tmp_path) == []def test_unsorted_fails(self, tmp_path: Path) -> None:- _mkproduct(tmp_path, "alpha", isolated=True)- _mkproduct(tmp_path, "beta", isolated=True)+ _mkproduct(tmp_path, "alpha", strict=True)+ _mkproduct(tmp_path, "beta", strict=True)tach = _iface(["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],"products\\\\.(beta|alpha)",@@ -1693,7 +1859,7 @@ class TestOrphanedTestFilesCheck:name=name,product_dir=product_dir,backend_dir=backend_dir,- is_isolated=False,+ has_facade_contracts=False,structure={},detailed=False,)@@ -2071,7 +2237,7 @@ class TestWatchedModelsAllowance:_seal_externally(monkeypatch)monkeypatch.setattr(isolation_module, "MODEL_CROSSINGS", frozenset({("my_product", "Table")}))- ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ 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")@@ -2100,7 +2266,7 @@ class TestWatchedModelsAllowance: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, isolated=True)+ 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(@@ -2243,7 +2409,7 @@ def _add_facade_reexport(ctx: CheckContext) -> None: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, isolated=True)+ 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)@@ -2255,7 +2421,7 @@ class TestIsolationChainWiringGate:# 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, isolated=True)+ 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...@@ -2266,7 +2432,7 @@ class TestIsolationChainWiringGate: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, isolated=True)+ 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))@@ -2284,7 +2450,7 @@ class TestPackageJsonScriptsWiringWithheld:ctx = _make_product(tmp_path,scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},- isolated=True,+ strict=True,)_add_facade_reexport(ctx)result = check.run(ctx)@@ -2296,7 +2462,7 @@ class TestPackageJsonScriptsWiringWithheld:# 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, isolated=True)+ 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)@@ -2306,7 +2472,7 @@ class TestBackendPackageMarker:check = BackendPackageMarkerCheck()def _product(self, tmp_path: Path, *, markers: list[str], trees: list[str]) -> CheckContext:- ctx = _make_product(tmp_path, isolated=True)+ 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")@@ -2829,7 +2995,7 @@ 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, isolated=True)+ 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"diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.pyindex 332f3c6fa197..074b64b57839 100644--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py@@ -255,6 +255,11 @@ class TestBaselineRatchet:crossings.write_baseline([self._use("posthog.api.a", scanned)], path)assert refusal.value.added == [f"alerts.AlertConfiguration posthog.api.a instance-many(all) {scanned}"]+ def test_a_moved_consumer_is_written(self, tmp_path: Path) -> None:+ path = self._recorded(tmp_path, "posthog.api.a")+ crossings.write_baseline([self._use("posthog.api.b")], path)+ assert crossings.read_baseline(path) == [self.LINE_B]+def test_a_removal_is_written(self, tmp_path: Path) -> None:path = self._recorded(tmp_path, "posthog.api.a", "posthog.api.b")crossings.write_baseline([self._use("posthog.api.a")], path)diff --git a/tools/hogli-commands/hogli_commands/tests/test_ledger_growth.py b/tools/hogli-commands/hogli_commands/tests/test_ledger_growth.pynew file mode 100644index 000000000000..04c9dbca64c4--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_ledger_growth.py@@ -0,0 +1,90 @@+from __future__ import annotations++import re+import subprocess+from pathlib import Path++import pytest++import yaml+from hogli_commands.product.crossings import grown_debt+from hogli_commands.product.ledger_growth import LEDGER_BASE_ENV, SCANNER_DIR, ledger_growth_issues+from hogli_commands.product.paths import REPO_ROOT+from parameterized import parameterized++LEDGER = "products/model_crossing_uses_baseline.txt"+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(+ ["git", "-c", "user.name=test", "-c", "[email protected]", "-c", "commit.gpgsign=false", *args],+ cwd=repo,+ check=True,+ capture_output=True,+ text=True,+ ).stdout+++def _commit(repo: Path, files: dict[str, str]) -> str:+ for relative, text in files.items():+ path = repo / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text)+ _git(repo, "add", relative)+ _git(repo, "commit", "-m", "change")+ return _git(repo, "rev-parse", "HEAD").strip()+++class TestGrownDebt:+ @parameterized.expand(+ [+ (+ "split_consumer",+ ["products.a.X posthog.api.old write 2"],+ ["products.a.X posthog.api.one write 1", "products.a.X posthog.api.two write 1"],+ [],+ ),+ (+ "new_consumer",+ ["products.a.X posthog.api.old write 1"],+ ["products.a.X posthog.api.old write 1", "products.a.X posthog.api.new write 1"],+ ["products.a.X write: 1 → 2"],+ ),+ (+ "new_kind",+ ["products.a.X posthog.api.old write 1"],+ ["products.a.X posthog.api.old write 1", "products.a.X posthog.api.old get_model 1"],+ ["products.a.X get_model: 0 → 1"],+ ),+ ]+ )+ def test_debt_counts_per_crossing_and_kind(+ self, _name: str, base: list[str], current: list[str], expected: list[str]+ ) -> None:+ assert grown_debt(base, current) == expected+++class TestLedgerGrowthIssues:+ @pytest.mark.parametrize("touch_scanner, expected_issues", [(False, 1), (True, 0)])+ def test_only_a_scanner_change_may_grow_the_ledger(+ self, touch_scanner: bool, expected_issues: int, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _git(tmp_path, "init", "-q", "-b", "master")+ line = "products.a.X posthog.api.old write 1\n"+ base = _commit(tmp_path, {LEDGER: line, f"{SCANNER_DIR}scan.py": "RULES = 1\n"})+ _git(tmp_path, "checkout", "-q", "-b", "feature")+ head_files = {LEDGER: line + "products.a.X posthog.api.new write 1\n"}+ if touch_scanner:+ head_files[f"{SCANNER_DIR}scan.py"] = "RULES = 2\n"+ _commit(tmp_path, head_files)+ monkeypatch.setenv(LEDGER_BASE_ENV, base)++ issues = ledger_growth_issues(tmp_path, tmp_path / LEDGER)++ assert issues is not None+ assert len(issues) == expected_issues++ def test_a_change_that_may_grow_the_ledger_always_gets_a_human_review(self) -> None:+ policy = yaml.safe_load((REPO_ROOT / ".stamphog" / "policy.yml").read_text())+ guardrails = policy["deny"]["devex_guardrails"]["match"]["paths"]+ assert any(re.match(pattern, f"{SCANNER_DIR}a_new_module.py") for pattern in guardrails)