: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): product isolation tooling, skill, and soundness docs (#63193)
Julian Beze81b26a79ae1
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.mdindex 2667f9dd6c01..0a3132feb8eb 100644--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md@@ -1,12 +1,15 @@---name: isolating-product-facade-contracts-description: Plan and execute incremental product isolation migrations to a facade plus contract layer in PostHog, following the Visual review architecture. Use when a product still exposes internals (models/logic/views) across boundaries and needs a safe, multi-PR migration toward contracts.py + facade/api.py + presentation separation.+description: Plan and execute product isolation migrations to a facade plus contract layer in PostHog, following the Visual review architecture. Use when a product still exposes internals (models/logic/views) across boundaries and needs migration toward contracts.py + facade/api.py + presentation separation, with a PR strategy that minimizes review latency and conflicts with parallel work.---# Isolating a product with facade and contractsUse this skill to migrate an existing product to the isolated architecture used by Visual review.-Keep migrations incremental, with narrow PRs that avoid broad breakage.+Optimize for short calendar exposure, not small diffs: authoring is cheap and the verification+chain catches mechanical breakage, while human review latency and a fast-moving master are the+real bottlenecks. Default to one PR structured in reviewable commits; a separate facade-first PR+exists only as the merge base for team-sliced sweeps — per the PR strategy below.**Prerequisite:** the product must already live under `products/<name>/`. This skill does not cover moving code out of `posthog/`, `ee/`, or other shared directories — do that first.@@ -35,12 +38,135 @@ Use Visual review as the concrete reference implementation:Before changing code, get the baseline:```bash-hogli product:maturity <name> # scores models, facade, presentation, boundaries, codegen-hogli product:lint <name> # structural lint + isolation chain (strict if facade/contracts.py exists)-rg -n "from products\.<name>\.backend\.(models|logic|presentation|tasks|storage)" .+hogli 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:isolate:scan <name> # the recon: import map, coupling gate, preflight (see below)```-The `rg` output is your import map: every line is a caller that needs to migrate to the facade.+**First, read the baseline to learn which migration phase you're in — you don't start+knowing whether this is untouched or mid-flight, and that decides where you pick up.**+The signals are all in the output above; there is no status file to consult (a hand-kept+one would drift — the maturity score plus the `ignore_imports` TODO set _is_ the status,+and `lint-imports` prunes the latter as modules finish):++- **Fresh** — facade/presentation score zero, no `backend/facade/`, no `ignore_imports`+ entries for the product. Start at step 1.+- **Mid-sweep** — `facade/contracts.py` + `facade/api.py` exist but core still imports+ internals (scan still lists model-access/etc., or `product:lint` warns `has legacy+interface leaks`). The facade design is settled; continue migrating callers (step 4) —+ don't redesign it.+- **Mid presentation-wave** — the chain is mostly intact but `pyproject.toml` still has+ `ignore_imports` TODO entries for the product. The sweep is done; resume the+ presentation wave on exactly those deferred modules.+- **Effectively done** — chain complete, no `ignore_imports` entries left. Verify against+ the done criteria instead of changing anything.++The scan does the recon that would otherwise cost a dozen ad-hoc greps, and is the+source of truth for the rest of the flow:++- **References by kind** — every cross-boundary reference to the product's internals,+ classified (model-access, query-runner, celery-task, temporal-wiring, test-fixture,+ string-reference) with the facade pattern each kind maps to. This is the sweep+ checklist; string references (`@patch(...)` mock paths, dotted names in config) are+ included, which import-oriented grepping misses.+- **Core-coupling count** — picks the PR strategy below: near zero means the whole+ migration fits the single-PR default; triple digits means the caller sweep needs+ slicing by owning team.+- **Strict-lint preflight** — `product:lint` switches from lenient to strict the moment+ `facade/contracts.py` exists; the scan runs the structural checks in forced-strict+ mode so those demands (root `tsconfig.json`, `tasks.py` at `tasks/tasks.py`, only+ canonical `backend/` subdirectories) surface up front instead of mid-migration.+- **Thin/thick signal per view module** — the future `ignore_imports` allowlist size.+- **Blind spots** — the scan reads `backend.*` imports only. A coupling count of+ zero is necessary, not sufficient: it can't see product-root packages core+ imports (`dags/`) or non-import channels (config dotted strings, hogql system+ tables, in-process API test dispatch). See "Clearing coupling the scan won't+ show" below before declaring a product done.++`--json` emits the machine-readable recipe — keep it with the PR; regenerating the+migration against fresh master starts from a fresh scan.++## When the tooling doesn't fit, fix the tooling++Don't quietly hand-work-around it. If `isolate:scan`/`:move` misses your product's+shape — a layout it doesn't detect, a coupling channel it can't see — and other+products share that shape, extend the tool and update this skill so the next+migration inherits the fix. That's how `backend/api/`-subpackage support and the+Dagster-assets channel got added. Reserve a manual work-around (called out in the+PR) for a true one-off; a silent hand-hack just leaves the next product to hit the+same wall.++## "No in-process callers, so no facade" is the wrong test++The core-coupling count sizes the **sweep** — zero importers means a single-PR+migration with no caller migration — but it does not decide **whether** to isolate.+The facade is also the structural seal that makes the CI skip _sound_, and that has+nothing to do with importer count:++- A product's HTTP API is exercised **in-process** by tests (the Django test client+ dispatches into the view stack in the same process, not over a real socket).+ Cross-cutting tests — permissions, schema, activity-log, "every viewset does X" —+ reach a product's endpoints by URL, coupling to its live behavior with **zero+ imports**. tach, `lint-imports`, and this scan all read the import graph, so none+ of them can see it. "No importers" is necessary, not sufficient.+- Because the channel can't be enumerated, it is closed by construction, not audit:+ keep presentation thin and reaching internals only through the facade, so every+ observable behavior lives in the facade (tested in-product, inside the boundary)+ or in the serializer shape (the OpenAPI schema, whose changes already force the+ full suite); and keep behavior tests in-product.++So a product whose only consumers are over HTTP (node services, the TS/MCP codegen)+is **not** facade-optional — there the facade's whole job is sealing its own+presentation (step 2's second demand source). The genuine exception is+a product with essentially no Django-side logic (a thin shim over an external+service): it has nothing to seal, but it is then simply _not isolated_ — no+`backend:contract-check`, still paying the full suite. That is an accept-the-cost+choice, not "isolated without a facade".++This is the third non-import coupling channel, alongside hogql system tables and+dotted-string config (step 6.4) — and the least visible, since the other two at+least leave a string to grep for.++## Clearing coupling the scan won't show++`product:isolate:scan` walks the import graph of `backend.*`. Three kinds of+coupling escape it — none is a dead end, each has a defined move. After the+backend sweep, `git grep "products.<name>"` (not just `.backend`) and read the+scan's string-reference section to find them.++**Test-infrastructure coupling.** Core tests reach into the product's test+helpers, which no facade re-export naturally covers:++- _Monkeypatch targets_ — a core test base patches a product module attribute+ (e.g. `posthog/test/base.py` patches `execute_hogql_query` on each runner+ module). Re-export the **module object** through the facade+ (`facade/queries.py` re-exports `web_overview`, not just its class) and point+ the patch at the facade path.+- _Shared fixtures / base classes_ — a core test subclasses the product's test+ base. Decide ownership: if the fixture is infrastructure for a **core**+ concern (a preaggregated-table test base, and the tables live in core), move+ it down into core and have both sides import it downward; if the core test is+ really exercising the **product's** behavior, relocate the test into the+ product. Either way the cross-boundary test import disappears.++**Surfaces outside `backend/`.** A product can expose non-Django surfaces at its+root — Dagster assets under `products/<name>/dags/`, for instance — that core+imports directly. The scan only walks `backend.*`, so it won't list them, and+`tach` / `product:lint` fail late with "not part of the public interface" (a+direct interface exposure also trips the legacy-leak check). Re-export them+through a facade submodule (`facade/dags.py` re-exporting the asset modules) and+reroute the core importer, exactly like the temporal and query-runner wiring.++**No external data consumers.** Covered above — the facade serves the product's+own views. Provide facade read functions for its models; wire the cheap views;+defer the expensive ones (nested-serializer or transactional viewsets) as named+`ignore_imports` for the presentation wave. Providing the facade function while+deferring its caller is a legitimate intermediate state, not a half-migration.++The web_analytics migration is the worked example of all three: its preagg test+base moved down to core, its timezone integration test moved into the product,+its Dagster assets gained a `facade/dags.py`, and its filter-preset reads landed+in `facade/api.py` with the viewset deferred.## Guardrails@@ -63,18 +189,76 @@ The `rg` output is your import map: every line is a caller that needs to migrate1. Build an import map for the target product.- Find cross-product imports into target internals (`models`, `logic`, `presentation`, non-facade modules).- Classify each usage by capability (read/list, detail/read, create/update/delete, async/task, webhook/event).-2. Define the minimal contract surface.- - Start from currently consumed fields only.+2. Define the contract surface from both demand sources.+ - External consumers (core, other products): start from currently consumed fields only.+ - The product's own presentation (step 5): the facade functions its views will call. For+ thick views this share may be deferred — but name the deferral; it decides whether the+ isolation you turn on is sound or optimistic (see step 5).- Create frozen dataclasses in `backend/facade/contracts.py` using `pydantic.dataclasses.dataclass` — same shape as the stdlib variant but with runtime type validation on construction.3. Introduce a thin facade in `backend/facade/api.py`.- Map ORM instances to contracts with explicit mapper functions.- Keep method names capability-oriented and stable.-4. Migrate callers in small batches.- - Replace one caller cluster at a time (single endpoint, single task, or single service area).- - Keep compatibility shims only when needed; remove promptly.+ - Wiring that core registers (celery beat tasks, temporal workflows/activities/metrics/+ schedule constants, query-runner registry hooks, Dagster assets) crosses the boundary+ as objects, not data — give each its own facade submodule (`facade/tasks.py`,+ `facade/temporal.py`, `facade/queries.py`, `facade/dags.py`) re-exporting exactly what+ core touches. Registry-style consumers dispatch on class identity (`isinstance`), so+ re-export the class itself; monkeypatch consumers need the module object, so re-export+ that too. Keep `facade/api.py` free of heavy imports (HogQL, temporalio) so config-only+ consumers don't drag them onto the `django.setup()` path — and split light shared+ tables (`facade/hogql.py`) out of the heavy runner re-exports for the same reason.+4. Migrate callers in one pass by default.+ - The rewrite is mechanical (import swap + call mapping) and fully checked by the+ verification chain; batching it only stretches the window in which master drifts+ under the branch.+ - Core test fixtures that need product models: use `apps.get_model("<app_label>",+"Model")` at runtime plus a `TYPE_CHECKING` import for annotations — tach ignores+ type-only imports.+ - Compatibility shims exist to bridge between serial PRs — the one-pass shape rarely+ needs them. If one is unavoidable, it dies in the final cleanup PR, not "later".+ - Exception: callers with subtle behavior (transaction boundaries, write-path+ semantics) may move in their own small PR — see the PR strategy below.5. Move presentation to consume the facade.- - Serializers convert JSON <-> contracts.- - Views call facade methods only.+ - Serializers convert JSON <-> contracts; views call facade methods only.+ - Decide **per view module, on a size estimate**, whether its facade refactor lands+ in this PR or defers. Estimate the wave per module: runner-execution swaps are+ cheap (runners already return `posthog.schema` types — no new contracts needed);+ plain model CRUD needs a small contract plus a few functions; transactional or+ cross-product logic embedded in serializers is the expensive tier. Swap every+ module whose wave is cheap; defer only the expensive ones, naming the reason and+ the surviving `ignore_imports` entries in the PR description.+ - Deferred modules keep exact-pair `ignore_imports` entries in `pyproject.toml`'s+ TODO section. That debt **gates the skip**: while any entry remains the product+ must NOT enable `backend:contract-check` (step 6), so the full suite keeps running+ and there is no coverage hole. This is the soundness boundary — the skip only+ re-runs the suite on facade/presentation changes, so it is honest only once+ presentation is thin. A thick deferred view reaches internals directly, so an+ internals change flowing to HTTP through it would slip past the skip (and past the+ cross-cutting core tests that exercise the product by URL with zero imports).+ `hogli product:lint` enforces the gate — contract-check while `ignore_imports`+ entries exist fails lint. The skip is the reward the presentation-wave PR unlocks+ when it empties them.+ - The mechanical share is one command: `hogli product:isolate:move <name>` (run+ `--dry-run` first) moves the ViewSet modules into `presentation/views/` (auto-detected,+ `--views` to override), `tasks.py` into a `tasks/` package with celery names pinned+ (it re-exports the module's public surface, and warns when a _private_ tasks name is+ reached through the package path — e.g. a `@patch("...backend.tasks._helper")` target+ — since those need repointing to `...backend.tasks.tasks._helper` by hand; auto-rewriting+ them would corrupt the pinned `name=` strings), and rewrites the dotted paths+ repo-wide. A `backend/api/` subpackage moves whole:+ production helper subpackages (e.g. `destination_tests/`) keep their structure under+ `presentation/views/` and ride the prefix rename, while test subpackages (`test/`,+ `tests/`) relocate to `backend/tests/api/` — they leave the api namespace, so a naive+ prefix rewrite can't follow them. The move **refuses** if an `api/` module is already+ mirrored at `presentation/<stem>.py` — that means a prior hand-migration left a compat+ shim, and moving it would duplicate the module; delete the shim and repoint its callers+ first, then re-run for the rest (error_tracking is the worked example).+ - Rewriting is a deliberate two-tool split, mirroring the model-migration tooling rather+ than reinventing it: **absolute** fully-qualified paths and string references+ (`@patch(...)` mock paths) go through guarded word-boundary regex (lexically+ unambiguous); **relative** imports (`from ..x import y`, any depth) go through libcst+ (`cst_helpers.py`, ported from the product-model-migration `import_rewriter`) because+ resolving them needs the importing module's package, which a line regex can't know.6. Enforce boundaries and verify. This is a four-step chain — each step dependson the previous one, and `hogli product:lint` (via `IsolationChainCheck`)fails if any step is skipped:@@ -86,11 +270,20 @@ The `rg` output is your import map: every line is a caller that needs to migrateadd a new dedicated block if the product needs a non-standard exposepattern.3. **`backend:contract-check` script** — add to `package.json` so- turbo-discover treats the product as isolated.+ turbo-discover treats the product as isolated. This is the **last** piece:+ add it only once the product is fully isolated — no `ignore_imports` entries+ left, presentation thin. `hogli product:lint` blocks the script while deferred+ entries remain, because the skip is unsound until then (see step 5).4. **Narrowed `turbo.json` inputs** — restrict `backend:contract-check`inputs to `backend/facade/**` and `backend/presentation/**` so theDjango suite is only re-run on facade/presentation changes (see- `products/visual_review/turbo.json`).+ `products/visual_review/turbo.json`). Widen the inputs when core+ depends on the product **outside the import graph**: add+ `backend/models.py` if hogql system tables expose the product's+ tables or core config references its dotted paths (the scan's+ string-reference section surfaces the latter). tach/import-linter+ only police the import channel; a mechanical check for these+ non-import channels is a known gap, noted and deferred.- Verify with `tach check --dependencies --interfaces`, `lint-imports`(import-linter contract for presentation → facade), and `hogli product:lint <name>`.- Use `hogli product:maturity <name>` for a detailed breakdown of remaining@@ -99,30 +292,118 @@ The `rg` output is your import map: every line is a caller that needs to migrate### Legacy leaks during migration+This is the exception path for high-coupling products whose caller sweep is sliced+across teams (see PR strategy below) — the tach boundary turns on before every core+import has moved, while the `backend:contract-check` CI switch must wait until the+block is gone (`hogli product:lint` rejects the script while leaks remain). With the+single-PR default, all core callers land in the same PR and this block never needs to+exist.+If `posthog/` or `ee/` still imports product internals (`backend.models`,-`backend.oauth`, …) when you cut the first isolation PR, add a second+`backend.oauth`, …) when the isolation chain turns on, add a second`[[interfaces]]` block under the "Legacy leaks" section of `tach.toml`allow-listing exactly the modules core still touches. This keeps the build-green while you migrate callers in subsequent PRs. Shrink and delete that-block as imports move behind the facade — the final PR removes it entirely.+green while the remaining team-sliced PRs land. Shrink and delete that+block as imports move behind the facade — the final cleanup PR removes it entirely.`hogli product:lint` flags any product that still has legacy leak interfaceswith a `⚠ has legacy interface leaks` warning.-## PR slicing strategy+## PR strategy++The scarce resources are reviewer attention and calendar time — not authoring effort.+Every open migration branch rots as parallel work lands, and every extra PR adds a+serialized review window plus a full-suite CI run (the product isn't isolated yet, so+each migration PR pays the full suite). Use the fewest PRs the merge topology requires,+and let commit structure — not PR boundaries — organize review.++**Default: one PR, structured in reviewable commits.**++1. **Commit — facade.** Contracts + facade (including wiring submodules) ++ behavioral-parity tests. Pure additions; reviewers read this commit as the design.+2. **Commit — sweep.** All caller migrations. Mechanical; reviewers sample, the+ verification chain carries it.+3. **Commit — structure + chain.** Presentation move and rewrites+ (`hogli product:isolate:move`), strict-lint fixes, tach interface. Add+ `backend:contract-check` + narrowed `turbo.json` here **only if the product is+ fully isolated in this PR** — no deferred view modules. If any module is deferred+ (`ignore_imports` entries remain), the skip can't turn on yet (`product:lint` blocks+ it), so it lands with the presentation-wave PR; this PR ships without the skip and+ keeps paying the full suite, which is sound.++Don't split the facade into its own PR for reviewability: new files cannot conflict+regardless of which PR they sit in, so a standalone design PR buys no conflict+protection — it only serializes two review windows and doubles the migration's CI cost.+Worse, a facade with no callers can only be reviewed in the abstract; in one PR the+caller diffs sit next to the design and justify (or indict) it. See `user_interviews`+PR #59132 and the logs migration (#63180 + #63184, done as two before this was learned)+for the shapes.++In the PR description, enumerate the behavior-bearing edits — write paths, transaction+boundaries, serializer changes, anything renamed or with pinned compatibility (celery+task names). That list is where review attention goes; everything else is sampled. If a+write path is genuinely subtle, pull those few callers into their own small PR as the+exception.++Treat the PR as regenerable, not rebasable: the import map plus the facade design fully+determine the rewrite, so on conflict, regenerate the branch against fresh master+instead of hand-resolving. Keep it open only for the review window.++**A separate facade-first PR exists for exactly one reason: it is the shared merge base+when the sweep must be sliced.** Gate on the core-coupling count from the baseline:++- **Low (zero to low double digits):** single PR, as above; skip the legacy-leaks+ machinery entirely.+- **High (triple digits):** the sweep won't review as one unit. Land contracts + facade+ - parity tests first — that standalone review is meaningful here, because every slice+ is about to code against it — then slice the sweep by who owns the calling code (the+ consuming team/area, not the product's own owner), reviewed in parallel, never+ serially by capability. Add the legacy-leaks tach block (above) while slices land,+ but do NOT add `backend:contract-check` yet — `hogli product:lint` rejects that+ script while leaks remain. The final cleanup PR drops the block, `ignore_imports`+ TODOs, dead adapters, and shims, and only then enables contract-check + narrowed+ `turbo.json` inputs — the CI payoff for this path lands at the end.++**Deferred view modules (step 5) add one follow-up on either path:** the presentation+wave — see the section below for its flow and outputs.++Trade-off to accept: one PR reverts coarser than several. That is fine because the+mappers are behavior-preserving, the behavior-bearing edits are enumerated up front,+and the whole PR is regenerable — weeks of serial PRs on a hot product cost more in+conflicts and forfeited isolated-CI time than an occasional coarse revert.++## Presentation wave-Default to several PRs instead of one big migration:+The second demand wave on the same facade: the functions the product's _own views_+need, where the first wave served external consumers. Run it once per product, after+the migration PR lands, working from the deferred modules listed in the PR (the scan's+view-module table is the worklist).-- PR 1: Add contracts + facade methods, with no caller behavior changes. For a small product this PR can also flip `api.py`/`webhooks.py` into `presentation/` and enable the 4-step chain (see `user_interviews` PR #59132 for that combined shape).-- PR 2-N: Migrate caller clusters one-by-one to the facade.-- Final PR: Remove deprecated internal import paths, drop "Legacy leaks" `[[interfaces]]` blocks and `ignore_imports` TODOs, and clean dead adapters.+Per deferred module:-If a product has many endpoints, migrate in this order:+1. Design the facade functions its views need. Query endpoints get run-functions that+ take `posthog.schema` query objects and return the runner's response types — those+ are already framework-free, so usually no new contracts. Model-backed endpoints get+ contracts plus CRUD/capability functions (the `DataclassSerializer` pattern from+ visual_review).+2. Draw the line: execution and transaction concerns (`ExecutionMode`, query tagging,+ `select_for_update` caps, cross-product side effects) move behind the facade; HTTP+ concerns (request validation, response codes, `report_user_action` analytics) stay+ in the view.+3. Thin the view to parse → facade → serialize, with parity tests for the new facade+ functions, same as wave one.+4. Delete the module's `ignore_imports` entries — `lint-imports` must pass without+ them. That deletion is the output that marks the module done.-1. Read-only list/detail APIs (lowest risk)-2. Internal service-to-service call sites-3. Write paths (create/update/delete)-4. Background tasks / async entrypoints-5. Remaining edge endpoints and cleanup+This is a design PR, not a sweep: it carries the same review weight as the facade+commit (the contract and function shapes are the long-lived API), so it gets its own+PR rather than riding along with mechanical work. Refactoring a wave-one function while+here (e.g. subsuming a runner builder under a run-function) is fine — its callers are+few and the parity tests pin behavior. The product's done criteria below are only fully+satisfiable once this wave has emptied the allowlist — and emptying it is what unlocks+the skip: the PR that deletes the last `ignore_imports` entry is where+`backend:contract-check` + narrowed `turbo.json` are finally added (`product:lint`+blocks them until then). For a product that deferred modules, this is when it earns the+CI skip.## Done criteria@@ -136,7 +417,11 @@ Treat migration as complete only when:exposing `backend.facade.*` and `backend.presentation.views.*` — no legacyleak block remains.- `tach check --dependencies --interfaces` passes with no violations for this product.-- `lint-imports` passes (import-linter verifies presentation doesn't bypass the facade internally).+- `lint-imports` passes **with no `ignore_imports` entries left for this product** in the+ `pyproject.toml` TODO section — entries are tracked architectural debt from deferred+ view modules; the presentation wave deletes them.- `hogli product:lint <name>` shows no legacy leak warning and the isolation chain is intact.- `backend:contract-check` is present in `package.json` with `turbo.json` inputs- narrowed to `backend/facade/**` and `backend/presentation/**` (enables isolated testing in CI).+ narrowed to `backend/facade/**` and `backend/presentation/**` (enables the CI skip).+ This is the **last** thing added — `product:lint` blocks it until the `ignore_imports`+ entries above are gone, so the skip only ever turns on for a fully isolated product.diff --git a/.claude/rules/product-isolation.md b/.claude/rules/product-isolation.mdindex 3a5fab4432e9..8bba42c87320 100644--- a/.claude/rules/product-isolation.md+++ b/.claude/rules/product-isolation.md@@ -7,12 +7,15 @@ paths:Look at the product's `package.json`: if `backend:contract-check` is listed under `scripts`,this product is isolated.-- **Isolated:** external code (core, other products) may only import from- `backend/facade/api.py`. Do not expose internal modules directly, and do not add- raw cross-product imports — go through the target product's facade instead.+- **Isolated:** external code (core, other products) may only import from the+ `backend/facade/` package — `api.py` for data capabilities, and capability submodules+ (`queries.py`, `tasks.py`, `temporal.py`, …) for wiring that core registers or+ dispatches on. Do not expose internal modules directly, and do not add raw+ cross-product imports — go through the target product's facade instead.- **Not isolated:** boundaries are not yet enforced by CI, but prefer using existingfacades when they exist rather than importing internals.-If you need to extend what's reachable across a boundary, add a method to the relevant-`backend/facade/api.py` — not a `depends_on` entry in `tach.toml`.+If you need to extend what's reachable across a boundary, add a function to the relevant+facade module (or a re-export to its wiring submodule) — not a `depends_on` entry in+`tach.toml`.Run `tach check --dependencies --interfaces` to verify import boundaries are clean.diff --git a/hogli.yaml b/hogli.yamlindex bd1cd5043a7d..0c43d57938be 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -825,6 +825,12 @@ tools:product:lint:click: hogli_commands.product.cli:cmd_lintdescription: Check product structure for misplaced files+ product:isolate:scan:+ click: hogli_commands.product.cli:cmd_isolate_scan+ description: Read-only isolation recon for the facade migration skill+ product:isolate:move:+ click: hogli_commands.product.cli:cmd_isolate_move+ description: Mechanical isolation moves with repo-wide path rewritesproduct:lint:owners:click: hogli_commands.product.cli:cmd_lint_ownersdescription: Validate product.yaml owners against PostHog/posthog GitHub teamsdiff --git a/products/architecture.md b/products/architecture.mdindex 100e71967c14..ed8d45541ffc 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -56,7 +56,7 @@ Focus:- Non-isolated products must **not** declare `backend:contract-check` — `turbo-discover` uses this key to identify isolated products, and its presence causes selective testing to skip the full Django test suite- Facade (`facade/api.py`) will define the **public interface**- Internal files will be private implementation details-- Presentation layer (DRF) will sit above the facade but remain outside the contract surface initially+- Presentation layer (DRF) sits above the facade, outside the contract surface — but a product is only soundly skippable once that presentation is thin and reaches internals exclusively through the facade (see [What makes the skip sound](#what-makes-the-skip-sound)); an unsealed presentation that still holds business logic is notEventually this grows into:@@ -65,6 +65,24 @@ Eventually this grows into:But this document is about foundational structure, not full rollout.+### What makes the skip sound++Skipping the full suite for an isolated product is a claim that _a change inside the product can only break the product's own tests._+tach proves the import half of that claim — no external code reaches past `facade.*` / `presentation.views.*`.+It cannot prove the other half.+A product's HTTP API is exercised **in-process** by tests (the Django test client dispatches into the view stack in the same process, not over a real socket), and cross-cutting tests — permissions, schema, activity-log, "every viewset does X" — reach a product's endpoints by URL.+That couples them to the product's live behavior with **zero imports**, so it is invisible to tach, to `lint-imports`, and to any import-graph audit.+"No importers" is necessary, not sufficient.++Because this channel can't be enumerated, it is closed by construction rather than inspection:++1. Keep the presentation layer thin and reaching internals only through the facade, so every observable behavior lives either in the facade (tested in-product, inside the boundary) or in the serializer shape (the OpenAPI schema, whose changes already force the full suite).+2. Keep behavior tests in-product.++A product whose views still hold business logic is not soundly skippable even if nothing imports it.+This is also why "no in-process callers, so we don't need a facade" is the wrong test: a product whose only consumers are over HTTP (node services, the generated TS/MCP types) is _not_ facade-optional — there the facade's whole job is sealing its own presentation.+The genuine exception is a product with essentially no Django-side logic (a thin shim over an external service): it has nothing to seal, but it is then simply not isolated — no `backend:contract-check`, still paying the full suite — which is an accept-the-cost choice, not "isolated without a facade".+# 3. Folder StructureEach product adopts the following structure:diff --git a/products/user_interviews/package.json b/products/user_interviews/package.jsonindex f020fa356a71..9da337c00782 100644--- a/products/user_interviews/package.json+++ b/products/user_interviews/package.json@@ -1,8 +1,7 @@{"name": "@posthog/products-user-interviews","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",- "backend:contract-check": "echo 'Contract files unchanged'"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},"dependencies": {"kea": "catalog:",diff --git a/products/user_interviews/turbo.json b/products/user_interviews/turbo.jsondeleted file mode 100644index 34a16b3d30ce..000000000000--- a/products/user_interviews/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**"],- "outputs": [],- "cache": true- }- }-}diff --git a/pyproject.toml b/pyproject.tomlindex a5c1210b7774..dbf958a7691e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -274,6 +274,7 @@ dev = ["testcontainers[mysql]~=4.14",# Developer CLI"hogli",+ "libcst>=1.8.6,<2.0.0",]sentiment = ["optimum[onnxruntime]~=1.25.0",diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex 83fec362bb43..7977292d46db 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -11,12 +11,13 @@ from __future__ import annotationsimport reimport jsonimport shlex+import tomllibfrom abc import ABC, abstractmethodfrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom pathlib import Path-from .paths import TACH_TOML, get_tach_block+from .paths import REPO_ROOT, TACH_TOML, get_tach_block# ---------------------------------------------------------------------------# Utilities@@ -80,6 +81,25 @@ def _pattern_targets_public_surface(pattern: str) -> bool:)+def count_presentation_allowlist_entries(name: str, pyproject_text: str | None = None) -> int:+ """Count deferred presentation-wave entries for a product in import-linter's ignore_imports.++ Each pair allows the product's own presentation to bypass its facade — work owed to a+ presentation-wave PR (see the isolating-product-facade-contracts skill).+ """+ if pyproject_text is None:+ pyproject = REPO_ROOT / "pyproject.toml"+ if not pyproject.exists():+ return 0+ pyproject_text = pyproject.read_text()+ try:+ contracts = tomllib.loads(pyproject_text)["tool"]["importlinter"]["contracts"]+ except (tomllib.TOMLDecodeError, KeyError):+ return 0+ prefix = f"products.{name}.backend.presentation"+ return sum(1 for contract in contracts for entry in contract.get("ignore_imports", []) if entry.startswith(prefix))++def has_legacy_interface_leaks(tach_content: str, module_path: str) -> bool:"""Check if a product has legacy interface leak blocks in tach.toml.@@ -431,7 +451,13 @@ class PackageJsonScriptsCheck(ProductCheck):facade_api = ctx.backend_dir / "facade" / "api.py"has_real_facade = facade_api.exists() and has_any_function_defs(facade_api)- needs_contract_check = ctx.is_isolated and not has_leaks and has_real_facade+ # While a product has deferred presentation-wave ignore_imports entries, its+ # views still bypass the facade and reach internals directly. The skip only+ # re-runs the full suite on facade/presentation changes, so an internals+ # 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.+ deferred = count_presentation_allowlist_entries(ctx.name)+ needs_contract_check = ctx.is_isolated and not has_leaks and has_real_facade and deferred == 0required = ["backend:test"] + (["backend:contract-check"] if needs_contract_check else [])for script in required:if script not in scripts:@@ -442,10 +468,17 @@ class PackageJsonScriptsCheck(ProductCheck):)# --- absence check: must NOT have contract-check when not safe for isolation ---- must_not_have_contract_check = not ctx.is_isolated or has_leaks or not has_real_facade+ must_not_have_contract_check = not ctx.is_isolated or has_leaks or not has_real_facade or deferred > 0if must_not_have_contract_check and "backend:contract-check" in scripts:if has_leaks:reason = "has legacy interface leaks (core imports internals directly)"+ elif deferred > 0:+ plural = "entry" if deferred == 1 else "entries"+ reason = (+ f"has {deferred} deferred presentation-wave ignore_imports {plural} — its presentation "+ "still bypasses the facade, so finish the presentation wave (empty the ignore_imports TODO "+ "section) before opting into the skip"+ )else:reason = "non-isolated product must not have 'backend:contract-check' script"result.lines.append("✗ must not have 'backend:contract-check'")@@ -743,6 +776,10 @@ class IsolationChainCheck(ProductCheck):"a real facade should convert models to contracts, not just re-export")+ # Note: a product that has the contract-check script *and* deferred+ # presentation-wave ignore_imports entries is hard-blocked by+ # PackageJsonScriptsCheck — the skip can't be enabled until the wave empties them.+if result.issues or result.warnings:result.file = f"products/{ctx.name}/backend/facade/api.py"if result.issues:diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex 296a32b84b8e..d6b178fae626 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -121,3 +121,50 @@ def cmd_maturity(name: str | None, score_all: bool, codegen_detail: bool) -> Nonps = score_product(name)click.echo(generate_detail(ps))+++ name="product:isolate:scan",+ help="Read-only isolation recon: classified import map, coupling count, strict-lint preflight",+)[email protected]("name")[email protected]("--json", "as_json", is_flag=True, help="Emit the machine-readable recipe instead of the report")+def cmd_isolate_scan(name: str, as_json: bool) -> None:+ import json as json_module++ from .isolate import build_scan_report, render_scan_report++ try:+ report = build_scan_report(name)+ except ValueError as e:+ raise click.ClickException(str(e))+ click.echo(json_module.dumps(report, indent=2) if as_json else render_scan_report(report))+++ name="product:isolate:move",+ help="Mechanical isolation moves: viewsets to presentation/views/, tasks.py to tasks/ (names pinned), repo-wide path rewrites",+)[email protected]("name")+ "--views",+ multiple=True,+ help="Backend-relative view module paths to move, e.g. api/heatmaps_api.py (default: auto-detect ViewSet modules at backend root)",+)[email protected]("--dry-run", is_flag=True, help="Print the plan without changing anything")+def cmd_isolate_move(name: str, views: tuple[str, ...], dry_run: bool) -> None:+ from .isolate import build_move_plan, execute_move_plan++ try:+ plan = build_move_plan(name, list(views) or None)+ if not plan.view_moves and not plan.tasks_move:+ click.echo("Nothing to move: no ViewSet modules at backend root and no root tasks.py")+ return+ for line in execute_move_plan(plan, dry_run=dry_run):+ click.echo(line)+ except ValueError as e:+ raise click.ClickException(str(e))+ if dry_run:+ click.echo("\n(dry run — nothing changed)")+ else:+ click.echo("\nNext: review `git status`, then run tach check + lint-imports + hogli product:lint")diff --git a/tools/hogli-commands/hogli_commands/product/cst_helpers.py b/tools/hogli-commands/hogli_commands/product/cst_helpers.pynew file mode 100644index 000000000000..ab1fa815c96d--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/cst_helpers.py@@ -0,0 +1,79 @@+"""libcst-based source rewriting for product isolation moves.++Kept separate from isolate.py's regex rewriting because the two solve different+problems. Fully qualified absolute paths (and the string references the regex+deliberately also rewrites, like ``@patch`` mock paths) are lexically+unambiguous, so a guarded literal substitution is the right tool. *Relative*+imports are not: ``from ..x import y`` only resolves once you know the importing+module's package, and the depth can be arbitrary — exactly the case a line regex+has to punt on. This resolves them with a real parse instead.++Mirrors the relative-import resolution proven in the product-model-migration+skill's ``import_rewriter.py`` rather than reinventing it.+"""++from __future__ import annotations++import libcst as cst+++def dotted_name(node: cst.BaseExpression | None) -> str | None:+ """Dotted module name from a ``Name``/``Attribute`` expression, else None."""+ if node is None:+ return None+ parts: list[str] = []+ current: cst.BaseExpression | None = node+ while isinstance(current, cst.Attribute):+ parts.append(current.attr.value)+ current = current.value+ if not isinstance(current, cst.Name):+ return None+ parts.append(current.value)+ return ".".join(reversed(parts))+++def resolve_relative(package: str, level: int, module: str | None) -> str | None:+ """Absolute dotted path for a relative import inside ``package``.++ ``package`` is the importing file's own package (the regex tool's contract):+ level 1 (``from .x``) resolves against ``package`` itself, and each extra dot+ climbs one parent. Returns None if the climb runs past the package root.+ """+ parts = package.split(".")+ climb = level - 1+ if climb > len(parts):+ return None+ base = parts[: len(parts) - climb] if climb else list(parts)+ if module:+ base += module.split(".")+ return ".".join(base) or None+++class _RelativeImportAbsolutizer(cst.CSTTransformer):+ def __init__(self, package: str) -> None:+ self.package = package+ self.warnings: list[str] = []++ def leave_ImportFrom(self, _original_node: cst.ImportFrom, updated_node: cst.ImportFrom) -> cst.ImportFrom:+ if not updated_node.relative:+ return updated_node+ level = len(updated_node.relative)+ absolute = resolve_relative(self.package, level, dotted_name(updated_node.module))+ if absolute is None:+ self.warnings.append(f"could not resolve a level-{level} relative import against {self.package}")+ return updated_node+ return updated_node.with_changes(relative=[], module=cst.parse_expression(absolute))+++def absolutize_relative_imports(text: str, package: str) -> tuple[str, list[str]]:+ """Rewrite every relative import in ``text`` to absolute, resolved against ``package``.++ Any depth of leading dots is handled (unlike a line regex), formatting is+ preserved, and a file libcst can't parse is returned unchanged with a warning.+ """+ try:+ module = cst.parse_module(text)+ except cst.ParserSyntaxError as exc:+ return text, [f"libcst could not parse the module, relative imports left untouched ({exc})"]+ transformer = _RelativeImportAbsolutizer(package)+ return module.visit(transformer).code, transformer.warningsdiff --git a/tools/hogli-commands/hogli_commands/product/isolate.py b/tools/hogli-commands/hogli_commands/product/isolate.pynew file mode 100644index 000000000000..6b8a16464236--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/isolate.py@@ -0,0 +1,660 @@+"""Mechanical tooling for product isolation migrations: scan and move.++scan — read-only recon for the isolating-product-facade-contracts skill:+classified cross-boundary import map, core-coupling count, strict-lint+preflight, and a thin/thick signal per view module. Emits a human report or a+JSON recipe (the recipe is what makes the migration PR regenerable).++move — the deterministic structural half of the migration: viewset modules+into ``presentation/views/``, ``tasks.py`` into a ``tasks/`` package with+pinned celery task names, level-1 relative imports absolutized, and a+repo-wide dotted-path rewrite that covers imports *and* string references+(``@patch`` mock paths). Word boundaries are enforced in one tested place so+agents don't re-derive them per shell dialect.++The semantic work — contract design, call-site rewrites, thin-vs-thick view+decisions — deliberately stays with the engineer or agent.+"""++from __future__ import annotations++import re+import ast+import shutil+import subprocess+from dataclasses import asdict, dataclass, field+from pathlib import Path++from .ast_helpers import ast_parse_safe+from .checks import CheckContext, MisplacedFilesCheck, RequiredRootFilesCheck+from .cst_helpers import absolutize_relative_imports+from .paths import PRODUCTS_DIR, REPO_ROOT, load_structure++# ---------------------------------------------------------------------------+# Reference scanning (scan)+# ---------------------------------------------------------------------------++# What each consumer kind maps to in the facade design — mirrored from the+# isolating-product-facade-contracts skill so scan output doubles as the plan.+KIND_GUIDANCE = {+ "model-access": "expose a capability function returning a contract (facade/api.py)",+ "query-runner": "expose a builder plus a class re-export (facade/queries.py) — registry consumers dispatch on class identity",+ "celery-task": "re-export the task object (facade/tasks.py); core beat schedules import it",+ "temporal-wiring": "re-export workflows/activities/metrics/constants (facade/temporal.py)",+ "test-fixture": "use apps.get_model(...) plus a TYPE_CHECKING import, or the facade accessor",+ "string-reference": "dotted path in a string (mock @patch path, config) — must be rewritten when modules move",+ "other-internal": "route through a facade function or re-export",+}+++@dataclass+class Reference:+ file: str+ line: int+ module: str+ kind: str+ is_import: bool+++def classify_reference(module: str, importer: str) -> str:+ parts = Path(importer).parts+ if any(p in ("test", "tests") for p in parts) or Path(importer).name.startswith("test_"):+ return "test-fixture"+ if ".temporal" in module:+ return "temporal-wiring"+ if module.endswith(".tasks") or ".tasks." in module:+ return "celery-task"+ if module.endswith(".models") or ".models." in module:+ return "model-access"+ if "query_runner" in module or "queries" in module:+ return "query-runner"+ return "other-internal"+++def _git_python_files(repo_root: Path) -> list[Path]:+ out = subprocess.run(["git", "ls-files", "*.py"], cwd=repo_root, capture_output=True, text=True, check=True).stdout+ return [repo_root / line for line in out.splitlines() if line]+++def scan_references(name: str, files: list[Path], repo_root: Path) -> list[Reference]:+ """Cross-boundary references to the product's internals (non-facade) in Python source.++ Scans only the given files (``git ls-files *.py``), so dotted-path references+ in non-Python files (YAML config, TS) are out of scope; the string-reference+ kind covers ``@patch`` paths and config strings that live *in* Python.+ """+ dotted = re.compile(rf"products\.{re.escape(name)}\.backend(?:\.[\w.]*\w)?")+ import_line = re.compile(rf"^\s*(?:from|import)\s+products\.{re.escape(name)}\.backend")+ own_prefix = f"products/{name}/"+ facade_prefix = f"products.{name}.backend.facade"+ refs: list[Reference] = []+ for path in files:+ rel = str(path.relative_to(repo_root))+ if rel.startswith(own_prefix):+ continue+ try:+ text = path.read_text()+ except (OSError, UnicodeDecodeError):+ continue+ if f"products.{name}.backend" not in text:+ continue+ for lineno, line in enumerate(text.splitlines(), start=1):+ for match in dotted.finditer(line):+ module = match.group(0).rstrip(".")+ if module.startswith(facade_prefix):+ continue+ is_import = bool(import_line.match(line))+ kind = "string-reference" if not is_import else classify_reference(module, rel)+ refs.append(Reference(file=rel, line=lineno, module=module, kind=kind, is_import=is_import))+ return refs+++def core_coupling_count(refs: list[Reference]) -> int:+ """The PR-strategy gate from the skill: internals imports from posthog/ and ee/."""+ return sum(1 for r in refs if r.is_import and (r.file.startswith("posthog/") or r.file.startswith("ee/")))+++# ---------------------------------------------------------------------------+# Strict-lint preflight and view-module signals (scan)+# ---------------------------------------------------------------------------+++def strict_preflight(name: str) -> list[str]:+ """Run the structural checks as if the product were already isolated.++ `product:lint` flips to strict the moment facade/contracts.py exists; this+ surfaces those demands before the migration starts instead of mid-way.+ """+ product_dir = PRODUCTS_DIR / name+ ctx = CheckContext(+ name=name,+ product_dir=product_dir,+ backend_dir=product_dir / "backend",+ is_isolated=True,+ structure=load_structure(),+ detailed=False,+ )+ issues: list[str] = []+ for check in (RequiredRootFilesCheck(), MisplacedFilesCheck()):+ if check.should_run(ctx):+ issues.extend(check.run(ctx).issues)+ return issues+++def _base_names(node: ast.ClassDef) -> list[str]:+ names = []+ for base in node.bases:+ if isinstance(base, ast.Name):+ names.append(base.id)+ elif isinstance(base, ast.Attribute):+ names.append(base.attr)+ return names+++def detect_viewset_modules(backend_dir: Path, include_api: bool = False) -> list[Path]:+ """Modules defining ViewSet subclasses — the move candidates.++ Backend root by default. ``include_api`` also scans the conventional+ ``api/`` subpackage, where many products keep their viewsets instead of at+ root (web_analytics, conversations, endpoints, …).+ """+ search_dirs = [backend_dir]+ if include_api and (backend_dir / "api").is_dir():+ search_dirs.append(backend_dir / "api")+ found = []+ for directory in search_dirs:+ for path in sorted(directory.glob("*.py")):+ if path.name in ("__init__.py", "apps.py", "routes.py"):+ continue+ tree = ast_parse_safe(path)+ if tree is None:+ continue+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef) and any(b.endswith("ViewSet") for b in _base_names(node)):+ found.append(path)+ break+ return found+++def internal_import_count(path: Path, name: str) -> int:+ """How many internals a view module imports — the future allowlist size (thin/thick signal)."""+ pattern = re.compile(rf"^\s*(?:from|import)\s+products\.{re.escape(name)}\.backend\.(?!facade|presentation)[\w.]+")+ relative = re.compile(r"^\s*from\s+\.")+ count = 0+ for line in path.read_text().splitlines():+ if pattern.match(line) or relative.match(line):+ count += 1+ return count+++def build_scan_report(name: str, repo_root: Path = REPO_ROOT) -> dict:+ backend_dir = PRODUCTS_DIR / name+ if not (backend_dir / "backend").exists():+ raise ValueError(f"products/{name}/backend does not exist")+ refs = scan_references(name, _git_python_files(repo_root), repo_root)+ by_kind: dict[str, list[dict]] = {}+ for ref in sorted(refs, key=lambda r: (r.kind, r.file, r.line)):+ by_kind.setdefault(ref.kind, []).append(asdict(ref))+ view_modules = detect_viewset_modules(backend_dir / "backend", include_api=True)+ return {+ "product": name,+ "core_coupling_count": core_coupling_count(refs),+ "references_by_kind": by_kind,+ "facade_submodules_needed": sorted(+ {"tasks" for k in by_kind if k == "celery-task"}+ | {"temporal" for k in by_kind if k == "temporal-wiring"}+ | {"queries" for k in by_kind if k == "query-runner"}+ ),+ "strict_lint_preflight": strict_preflight(name),+ "view_modules": [+ {+ "module": v.name,+ "internal_imports": internal_import_count(v, name),+ }+ for v in view_modules+ ],+ "kind_guidance": {k: KIND_GUIDANCE[k] for k in by_kind},+ }+++def render_scan_report(report: dict) -> str:+ lines = [f"# Isolation scan: {report['product']}", ""]+ count = report["core_coupling_count"]+ gate = "single PR" if count < 100 else "facade-first PR + team-sliced sweeps"+ lines.append(f"Core-coupling count: {count} -> {gate}")+ lines.append("")+ lines.append("## Cross-boundary references (the sweep checklist)")+ for kind, refs in report["references_by_kind"].items():+ lines.append(f"\n### {kind} ({len(refs)}) — {report['kind_guidance'][kind]}")+ for ref in refs:+ lines.append(f"- {ref['file']}:{ref['line']} {ref['module']}")+ if report["facade_submodules_needed"]:+ lines.append("\n## Facade submodules to scaffold")+ for sub in report["facade_submodules_needed"]:+ lines.append(f"- facade/{sub}.py")+ lines.append("\n## Strict-lint preflight (fails the moment facade/contracts.py exists)")+ if report["strict_lint_preflight"]:+ lines.extend(f"- {issue}" for issue in report["strict_lint_preflight"])+ else:+ lines.append("- clean")+ lines.append("\n## View modules (thin/thick signal = future ignore_imports entries)")+ if report["view_modules"]:+ for view in report["view_modules"]:+ weight = "thin" if view["internal_imports"] <= 2 else "thick"+ lines.append(f"- {view['module']}: {view['internal_imports']} internal imports ({weight})")+ else:+ lines.append("- none detected (backend root or api/)")+ return "\n".join(lines)+++# ---------------------------------------------------------------------------+# Path rewriting and structural moves (move)+# ---------------------------------------------------------------------------+++def rewrite_paths(text: str, renames: dict[str, str]) -> str:+ """Rewrite dotted module paths with real word boundaries.++ Covers imports and string references alike: fully qualified dotted paths+ are lexically unambiguous, so a guarded literal match is the boring, safe+ tool. A trailing dot stays valid (``old.Symbol`` -> ``new.Symbol``); a+ trailing identifier character does not (``...api`` must not match+ ``...apps``).+ """+ for old, new in sorted(renames.items(), key=lambda kv: -len(kv[0])):+ pattern = re.compile(rf"(?<![A-Za-z0-9_.]){re.escape(old)}(?![A-Za-z0-9_])")+ text = pattern.sub(new, text)+ return text+++def _args_span(text: str, open_idx: int) -> int | None:+ """Index just past the ``)`` that balances the ``(`` at ``text[open_idx]``.++ Counts nesting and skips string literals, so decorator args that contain+ their own parens (``expires=timedelta(hours=1)``) are matched whole instead+ of being truncated at the first ``)``. Returns None if the parens never+ balance.+ """+ depth = 0+ quote: str | None = None+ i = open_idx+ while i < len(text):+ ch = text[i]+ if quote is not None:+ if ch == "\\":+ i += 2+ continue+ if ch == quote:+ quote = None+ elif ch in "\"'":+ quote = ch+ elif ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ if depth == 0:+ return i + 1+ i += 1+ return None+++def pin_task_names(text: str, module_path: str) -> tuple[str, list[str]]:+ """Pin ``@shared_task`` registration names to their pre-move dotted path.++ Moving ``tasks.py`` into a ``tasks/`` package silently renames every task's+ registration path, stranding queued messages at deploy. Tasks that already+ pass ``name=`` are left alone; every decorator that can't be pinned safely+ (unbalanced args, not sitting directly above its ``def``) is reported, so a+ partial failure can't hide behind a sibling that did get pinned.+ """+ warnings: list[str] = []+ def_after = re.compile(r"\s*\ndef (?P<fn>\w+)\(")+ # Rewrite back-to-front so each splice leaves earlier match offsets valid.+ for dec in reversed(list(re.finditer(r"@shared_task\b", text))):+ body_start = dec.end()+ if body_start < len(text) and text[body_start] == "(":+ args_end = _args_span(text, body_start)+ if args_end is None:+ warnings.append("a @shared_task decorator has unbalanced args — pin name= manually")+ continue+ args: str | None = text[body_start:args_end]+ else:+ args_end = body_start+ args = None+ following = def_after.match(text, args_end)+ if following is None:+ warnings.append("a @shared_task decorator is not directly above its def — pin name= manually")+ continue+ if args is not None and "name=" in args:+ continue+ pinned_name = f"{module_path}.{following.group('fn')}"+ if args is None:+ replacement = f'@shared_task(name="{pinned_name}")'+ else:+ inner = args[1:-1].strip()+ joined = f'{inner}, name="{pinned_name}"' if inner else f'name="{pinned_name}"'+ replacement = f"@shared_task({joined})"+ text = text[: dec.start()] + replacement + text[args_end:]+ return text, warnings+++def shared_task_names(path: Path) -> list[str]:+ tree = ast_parse_safe(path)+ if tree is None:+ return []+ names = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef):+ continue+ for dec in node.decorator_list:+ target = dec.func if isinstance(dec, ast.Call) else dec+ if (isinstance(target, ast.Name) and target.id == "shared_task") or (+ isinstance(target, ast.Attribute) and target.attr == "shared_task"+ ):+ names.append(node.name)+ return names+++def _module_dotted(name: str, rel: Path) -> str:+ """Dotted module path of a backend-relative file.++ ``api/heatmaps_api.py`` -> ``products.<name>.backend.api.heatmaps_api`` — the+ intermediate package matters, so derive from the full relative path, not the stem.+ """+ return ".".join((f"products.{name}.backend", *rel.with_suffix("").parts))+++@dataclass+class MovePlan:+ product: str+ view_moves: list[tuple[Path, Path]]+ module_renames: dict[str, str]+ tasks_move: tuple[Path, Path] | None+ serializers_move: tuple[Path, Path] | None = None+ # api/ test subpackages relocate out of the api namespace into the product's+ # own test dir, so they can't ride the api -> presentation.views prefix rename.+ test_moves: list[tuple[Path, Path]] = field(default_factory=list)+ # api/ modules whose stem already exists at presentation/<stem>.py — almost+ # always a compat shim for a module already migrated by hand. Moving it would+ # duplicate the module, so the move refuses until it's resolved (see execute).+ presentation_conflicts: list[Path] = field(default_factory=list)+++_TEST_DIRS = ("test", "tests")+++def build_move_plan(name: str, views: list[str] | None = None) -> MovePlan:+ backend_dir = PRODUCTS_DIR / name / "backend"+ target_dir = backend_dir / "presentation" / "views"+ view_moves: list[tuple[Path, Path]] = []+ test_moves: list[tuple[Path, Path]] = []+ presentation_conflicts: list[Path] = []+ renames: dict[str, str] = {}++ if views:+ view_paths = [backend_dir / v for v in views]+ missing = [str(p) for p in view_paths if not p.exists()]+ if missing:+ raise ValueError(f"view modules not found: {missing}")+ for p in view_paths:+ view_moves.append((p, target_dir / p.name))+ renames[_module_dotted(name, p.relative_to(backend_dir))] = (+ f"products.{name}.backend.presentation.views.{p.stem}"+ )+ else:+ for p in detect_viewset_modules(backend_dir):+ view_moves.append((p, target_dir / p.name))+ renames[f"products.{name}.backend.{p.stem}"] = f"products.{name}.backend.presentation.views.{p.stem}"+ api_dir = backend_dir / "api"+ if api_dir.is_dir():+ # Relocate the whole api/ subtree, not just its top-level files —+ # production helper subpackages (e.g. destination_tests/) are part of+ # the package's surface and ride the prefix rename with everything+ # else, so one rename (backend.api -> backend.presentation.views)+ # covers them. Test subpackages can't ride it: they leave the api+ # namespace for the product's test dir, so they get their own rename+ # and their relative imports are absolutized at move time.+ tests_target = backend_dir / "tests" / "api"+ presentation_dir = backend_dir / "presentation"+ for p in sorted(api_dir.rglob("*.py")):+ rel = p.relative_to(api_dir)+ if rel.parts[0] in _TEST_DIRS:+ test_moves.append((p, tests_target / Path(*rel.parts[1:])))+ else:+ view_moves.append((p, target_dir / rel))+ # A top-level api module already mirrored at presentation/<stem>.py+ # is a compat shim for an already-migrated module — moving it would+ # leave the canonical module and a stray shim side by side. The+ # package marker is always mirrored, so it is not a conflict.+ if len(rel.parts) == 1 and p.name != "__init__.py" and (presentation_dir / p.name).is_file():+ presentation_conflicts.append(p)+ renames[f"products.{name}.backend.api"] = f"products.{name}.backend.presentation.views"+ for tdir in _TEST_DIRS:+ if (api_dir / tdir).is_dir():+ # Longer prefix, so rewrite_paths applies it before the api ->+ # presentation.views rename and test paths land in tests/api.+ renames[f"products.{name}.backend.api.{tdir}"] = f"products.{name}.backend.tests.api"++ serializers_py = backend_dir / "serializers.py"+ serializers_move = None+ if serializers_py.is_file():+ serializers_move = (serializers_py, backend_dir / "presentation" / "serializers.py")+ renames[f"products.{name}.backend.serializers"] = f"products.{name}.backend.presentation.serializers"++ tasks_py = backend_dir / "tasks.py"+ tasks_move = (tasks_py, backend_dir / "tasks" / "tasks.py") if tasks_py.is_file() else None+ return MovePlan(+ product=name,+ view_moves=view_moves,+ module_renames=renames,+ tasks_move=tasks_move,+ serializers_move=serializers_move,+ test_moves=test_moves,+ presentation_conflicts=presentation_conflicts,+ )+++_PACKAGE_INIT_DOCSTRINGS = {+ "presentation": '"""HTTP presentation layer of the {name} product (DRF viewsets and serializers)."""\n',+ "views": '"""DRF viewsets for {name} — submodule paths (`backend.presentation.views.*`) are part\nof the shared tach interface for isolated products.\n"""\n',+}+++def _git_move_and_absolutize(+ name: str, src: Path, dst: Path, backend_dir: Path, repo_root: Path, log: list[str]+) -> str:+ """git-mv a file into the isolated layout and rewrite its relative imports.++ Relative imports resolve against the file's *original* package, so absolutize+ against that (``backend.api`` for an api/ file, ``backend`` for a root one)+ before the move changes what a leading dot means. Returns the rewritten text.+ """+ dst.parent.mkdir(parents=True, exist_ok=True)+ src_package = _module_dotted(name, src.parent.relative_to(backend_dir))+ subprocess.run(["git", "mv", str(src), str(dst)], cwd=repo_root, check=True)+ fixed, warnings = absolutize_relative_imports(dst.read_text(), src_package)+ dst.write_text(fixed)+ log.extend(f"WARNING {dst.relative_to(repo_root)}: {w}" for w in warnings)+ return fixed+++def execute_move_plan(plan: MovePlan, repo_root: Path = REPO_ROOT, dry_run: bool = False) -> list[str]:+ log: list[str] = []+ name = plan.product+ backend_dir = PRODUCTS_DIR / name / "backend"++ # The rewrite reads and writes every tracked .py repo-wide, so a modified+ # tracked file anywhere — not just under products/<name> — gets the rewrite+ # mixed into its existing edits and loses the clean `git diff`. Untracked+ # files are never touched (they aren't in `git ls-files`), so ignore them.+ dirty = subprocess.run(+ ["git", "status", "--porcelain", "--untracked-files=no"],+ cwd=repo_root,+ capture_output=True,+ text=True,+ check=True,+ ).stdout.strip()+ if dirty and not dry_run:+ raise ValueError("tracked files have uncommitted changes — commit or stash first so the move stays revertable")++ for src, dst in plan.view_moves:+ log.append(f"move {src.relative_to(repo_root)} -> {dst.relative_to(repo_root)}")+ for src, dst in plan.test_moves:+ log.append(f"move {src.relative_to(repo_root)} -> {dst.relative_to(repo_root)} (test)")+ if plan.serializers_move:+ src, dst = plan.serializers_move+ log.append(f"move {src.relative_to(repo_root)} -> {dst.relative_to(repo_root)}")+ if plan.tasks_move:+ src, dst = plan.tasks_move+ log.append(f"move {src.relative_to(repo_root)} -> {dst.relative_to(repo_root)} (celery names pinned)")+ for old, new in plan.module_renames.items():+ log.append(f"rewrite {old} -> {new} (imports and string references, repo-wide)")+ for p in plan.presentation_conflicts:+ log.append(+ f"BLOCKED {p.relative_to(repo_root)}: presentation/{p.name} already exists "+ "(likely a compat shim for an already-migrated module — resolve by hand)"+ )+ if dry_run:+ return log++ # A test move into an already-populated test dir would clobber a real file+ # (an empty __init__ package marker is the one safe collision — handled below).+ # Fail before mutating anything rather than mid-move.+ collisions = [+ dst+ for src, dst in plan.test_moves+ if dst.exists() and not (src.name == "__init__.py" and dst.name == "__init__.py")+ ]+ if collisions:+ joined = ", ".join(str(c.relative_to(repo_root)) for c in collisions)+ raise ValueError(f"test moves collide with existing files: {joined} — merge them into the test dir by hand")++ # An api module already mirrored under presentation/ is a compat shim for code+ # migrated by hand — moving it would duplicate the module. The right fix is manual+ # (delete the shim, repoint its callers), so refuse before mutating.+ if plan.presentation_conflicts:+ joined = ", ".join(str(p.relative_to(repo_root)) for p in plan.presentation_conflicts)+ raise ValueError(+ f"api modules already mirrored under presentation/ ({joined}) — almost certainly compat "+ "shims for already-migrated modules. Delete each shim and point its callers at the "+ "presentation module, then re-run the move on the rest."+ )++ # __init__ files an api/ subpackage brings with it are move targets — don't+ # pre-create those, or the git mv collides with the scaffolded file.+ move_targets = {dst for _, dst in plan.view_moves}+ if plan.serializers_move:+ move_targets.add(plan.serializers_move[1])++ if plan.view_moves:+ target_dir = backend_dir / "presentation" / "views"+ target_dir.mkdir(parents=True, exist_ok=True)+ for dirname, parent in (("presentation", backend_dir), ("views", backend_dir / "presentation")):+ init = parent / dirname / "__init__.py"+ if not init.exists() and init not in move_targets:+ init.write_text(_PACKAGE_INIT_DOCSTRINGS[dirname].format(name=name))+ for src, dst in plan.view_moves:+ # Nested production subpackages (api/destination_tests/) keep their+ # structure under presentation/views/ — the helper makes the parent.+ fixed = _git_move_and_absolutize(name, src, dst, backend_dir, repo_root, log)+ if "__file__" in fixed:+ # Found the hard way on logs: explain.py resolved its template dir via+ # Path(__file__).parent, which silently points elsewhere after the move.+ log.append(+ f"WARNING {dst.relative_to(repo_root)}: uses __file__-relative paths — "+ "re-anchor resource paths for the new module depth"+ )++ for src, dst in plan.test_moves:+ if dst.exists():+ # Pre-flight left only the safe collision: an empty package marker whose+ # destination already exists. The moved one is redundant — drop it.+ subprocess.run(["git", "rm", "-f", "--quiet", str(src)], cwd=repo_root, check=True)+ log.append(f"drop redundant {src.relative_to(repo_root)} ({dst.relative_to(repo_root)} already exists)")+ continue+ # The repo-wide rename carries the now-absolute paths to the moved code.+ _git_move_and_absolutize(name, src, dst, backend_dir, repo_root, log)++ # Clean up api/ only once everything (production + tests) has moved out of it.+ api_dir = backend_dir / "api"+ api_was_moved = any(src.is_relative_to(api_dir) for src, _ in (*plan.view_moves, *plan.test_moves))+ if api_dir.is_dir() and api_was_moved:+ # git mv moves files but leaves the emptied dirs behind, so look for real+ # files left over (a subpackage the move didn't know how to place), not dir+ # entries — an emptied destination_tests/ is not leftover content.+ remaining = sorted(+ str(p.relative_to(api_dir)) for p in api_dir.rglob("*") if p.is_file() and "__pycache__" not in p.parts+ )+ if remaining:+ log.append(+ f"WARNING {api_dir.relative_to(repo_root)} still holds files after the move ({remaining}) — "+ "relocate them by hand (the move only knows production and test subpackages)"+ )+ else:+ shutil.rmtree(api_dir)+ log.append(f"removed empty {api_dir.relative_to(repo_root)}")++ if plan.serializers_move:+ src, dst = plan.serializers_move+ dst.parent.mkdir(parents=True, exist_ok=True)+ init = backend_dir / "presentation" / "__init__.py"+ if not init.exists():+ init.write_text(_PACKAGE_INIT_DOCSTRINGS["presentation"].format(name=name))+ subprocess.run(["git", "mv", str(src), str(dst)], cwd=repo_root, check=True)+ fixed, warnings = absolutize_relative_imports(dst.read_text(), f"products.{name}.backend")+ dst.write_text(fixed)+ log.extend(f"WARNING {dst.relative_to(repo_root)}: {w}" for w in warnings)++ if plan.tasks_move:+ src, dst = plan.tasks_move+ dst.parent.mkdir(exist_ok=True)+ subprocess.run(["git", "mv", str(src), str(dst)], cwd=repo_root, check=True)+ # Relative imports resolved against backend/ at the old depth — absolutize+ # before the extra package level changes what `.` means, same as the views.+ absolutized, abs_warnings = absolutize_relative_imports(dst.read_text(), f"products.{name}.backend")+ pinned, pin_warnings = pin_task_names(absolutized, f"products.{name}.backend.tasks")+ dst.write_text(pinned)+ log.extend(f"WARNING {dst.relative_to(repo_root)}: {w}" for w in abs_warnings + pin_warnings)+ # Re-export the whole pre-move module surface, not just the task functions:+ # callers reach constants, imported collaborators, and @patch targets through+ # `products.<name>.backend.tasks`, and a task-only re-export breaks them.+ init_lines = [f"from products.{name}.backend.tasks.tasks import * # noqa: F401,F403"]+ task_names = shared_task_names(dst)+ if task_names:+ init_lines.append(+ f"from products.{name}.backend.tasks.tasks import {', '.join(sorted(task_names))} # noqa: F401"+ )+ (dst.parent / "__init__.py").write_text("\n".join(init_lines) + "\n")+ # The re-export exposes public names only; a private name (and any @patch+ # target of a module-internal name) reached through the package path breaks+ # once the module is a level deeper. Auto-rewriting these is unsafe — it would+ # corrupt the pinned `name="...tasks.<fn>"` strings — so flag them for manual+ # repointing to products.<name>.backend.tasks.tasks.<name>.+ private_refs = subprocess.run(+ ["git", "grep", "-lE", rf"products\.{re.escape(name)}\.backend\.tasks\._"],+ cwd=repo_root,+ capture_output=True,+ text=True,+ ).stdout.strip()+ if private_refs:+ files = ", ".join(private_refs.splitlines())+ log.append(+ f"WARNING private names of the moved tasks module are referenced through the package path "+ f"({files}) — the re-export can't expose them; repoint these (e.g. @patch targets) to "+ f"products.{name}.backend.tasks.tasks.<name> by hand"+ )++ if plan.module_renames:+ changed = 0+ for path in _git_python_files(repo_root):+ try:+ text = path.read_text()+ except (OSError, UnicodeDecodeError):+ continue+ rewritten = rewrite_paths(text, plan.module_renames)+ if rewritten != text:+ path.write_text(rewritten)+ changed += 1+ log.append(f"rewrote module paths in {changed} files")++ return logdiff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex aa630296cade..73af418b0b97 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -224,6 +224,27 @@ class TestAbsenceChecks:result = check.run(ctx)assert not result.issues+ def test_contract_check_forbidden_with_deferred_presentation_entries(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """An isolated product still owing presentation-wave work can't opt into the skip."""+ import hogli_commands.product.checks as checks_module++ monkeypatch.setattr(checks_module, "count_presentation_allowlist_entries", lambda *_a, **_k: 2)+ 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,+ extra_dirs=["backend"],+ )+ result = check.run(ctx)+ assert any("presentation-wave ignore_imports" in i for i in result.issues)+ # and it must not nag the same product to *add* the script it can't have yet+ assert not any("missing 'backend:contract-check'" in i for i in result.issues)+# ---------------------------------------------------------------------------# Content checks: pytest path validation@@ -1037,3 +1058,41 @@ class TestOrphanedTestFilesCheck:(ctx.backend_dir / "temporal" / "tests" / "test_workflow.py").write_text("")result = self._orphan_check.run(ctx)assert any("backend/temporal/tests/test_workflow.py" in i for i in result.issues)+++_IGNORE_IMPORTS_PYPROJECT = """+[tool.importlinter]+root_packages = ["products"]++[[tool.importlinter.contracts]]+name = "presentation must use facade"+type = "forbidden"+source_modules = ["products.*.backend.presentation"]+forbidden_modules = ["products.*.backend"]+ignore_imports = [+ "products.**.backend.presentation.** -> products.**.backend.facade.**",+ "products.logs.backend.presentation.views.api -> products.logs.backend.runner",+ "products.logs.backend.presentation.views.alerts_api -> products.logs.backend.models",+ "products.tracing.backend.presentation.views -> products.tracing.backend.logic",+]+"""+++ "name,expected",+ [+ ("logs", 2),+ ("tracing", 1),+ ("wizard", 0),+ ],+)+def test_count_presentation_allowlist_entries(name: str, expected: int) -> None:+ from hogli_commands.product.checks import count_presentation_allowlist_entries++ assert count_presentation_allowlist_entries(name, _IGNORE_IMPORTS_PYPROJECT) == expected+++def test_count_presentation_allowlist_entries_handles_broken_toml() -> None:+ from hogli_commands.product.checks import count_presentation_allowlist_entries++ assert count_presentation_allowlist_entries("logs", "not = [valid") == 0diff --git a/tools/hogli-commands/hogli_commands/tests/test_isolate.py b/tools/hogli-commands/hogli_commands/tests/test_isolate.pynew file mode 100644index 000000000000..cd8e37e103b2--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_isolate.py@@ -0,0 +1,315 @@+"""Tests for product isolation tooling — scan classification and move mechanics."""++from __future__ import annotations++from pathlib import Path++import pytest++import hogli_commands.product.isolate as iso+from hogli_commands.product.isolate import (+ Reference,+ _module_dotted,+ absolutize_relative_imports,+ build_move_plan,+ classify_reference,+ core_coupling_count,+ detect_viewset_modules,+ internal_import_count,+ pin_task_names,+ rewrite_paths,+ scan_references,+ shared_task_names,+)++# ---------------------------------------------------------------------------+# classification+# ---------------------------------------------------------------------------+++ "module,importer,expected",+ [+ ("products.logs.backend.models", "posthog/api/team.py", "model-access"),+ ("products.logs.backend.logs_query_runner", "posthog/hogql_queries/query_runner.py", "query-runner"),+ ("products.logs.backend.tasks", "posthog/tasks/scheduled.py", "celery-task"),+ ("products.logs.backend.temporal.metrics", "posthog/temporal/common/worker.py", "temporal-wiring"),+ ("products.logs.backend.models", "posthog/hogql/database/schema/test/test_system_tables.py", "test-fixture"),+ ("products.logs.backend.models", "posthog/api/test_team.py", "test-fixture"),+ ("products.logs.backend.alert_utils", "posthog/api/team.py", "other-internal"),+ ],+)+def test_classify_reference(module: str, importer: str, expected: str) -> None:+ assert classify_reference(module, importer) == expected+++def test_scan_references_classifies_imports_and_strings(tmp_path: Path) -> None:+ caller = tmp_path / "posthog" / "api" / "thing.py"+ caller.parent.mkdir(parents=True)+ caller.write_text(+ "from products.logs.backend.models import TeamLogsConfig\n"+ 'patched = patch("products.logs.backend.api.export_asset")\n'+ "from products.logs.backend.facade.api import get_config\n"+ )+ own = tmp_path / "products" / "logs" / "backend" / "x.py"+ own.parent.mkdir(parents=True)+ own.write_text("from products.logs.backend.models import TeamLogsConfig\n")++ refs = scan_references("logs", [caller, own], tmp_path)++ kinds = {(r.kind, r.is_import) for r in refs}+ assert ("model-access", True) in kinds+ assert ("string-reference", False) in kinds+ # facade imports and the product's own files are not cross-boundary references+ assert all("facade" not in r.module for r in refs)+ assert all(not r.file.startswith("products/logs/") for r in refs)+++def test_core_coupling_count_only_counts_core_imports() -> None:+ refs = [+ Reference(+ file="posthog/api/team.py", line=1, module="products.x.backend.models", kind="model-access", is_import=True+ ),+ Reference(file="ee/thing.py", line=1, module="products.x.backend.models", kind="model-access", is_import=True),+ Reference(+ file="products/other/backend/y.py",+ line=1,+ module="products.x.backend.models",+ kind="model-access",+ is_import=True,+ ),+ Reference(+ file="posthog/api/team.py",+ line=2,+ module="products.x.backend.api",+ kind="string-reference",+ is_import=False,+ ),+ ]+ assert core_coupling_count(refs) == 2+++# ---------------------------------------------------------------------------+# path rewriting+# ---------------------------------------------------------------------------+++def test_rewrite_paths_respects_word_boundaries() -> None:+ renames = {"products.logs.backend.api": "products.logs.backend.presentation.views.api"}+ text = (+ "from products.logs.backend.api import LogsViewSet\n"+ "import products.logs.backend.api as logs\n"+ 'p = patch("products.logs.backend.api.export_asset")\n'+ "from products.logs.backend.apps import LogsConfig\n"+ "from products.logs.backend.api_extra import x\n"+ )+ result = rewrite_paths(text, renames)+ assert "from products.logs.backend.presentation.views.api import LogsViewSet" in result+ assert "import products.logs.backend.presentation.views.api as logs" in result+ assert 'patch("products.logs.backend.presentation.views.api.export_asset")' in result+ # apps and api_extra must survive untouched+ assert "from products.logs.backend.apps import LogsConfig" in result+ assert "from products.logs.backend.api_extra import x" in result+++def test_rewrite_paths_longest_rename_wins() -> None:+ renames = {+ "products.x.backend.api": "products.x.backend.presentation.views.api",+ "products.x.backend.api_v2": "products.x.backend.presentation.views.api_v2",+ }+ text = "import products.x.backend.api_v2\nimport products.x.backend.api\n"+ result = rewrite_paths(text, renames)+ assert "import products.x.backend.presentation.views.api_v2" in result+ assert "import products.x.backend.presentation.views.api\n" in result+++# ---------------------------------------------------------------------------+# relative import absolutization+# ---------------------------------------------------------------------------+++ "source,package,expected",+ [+ ("from .models import Thing\n", "products.logs.backend", "from products.logs.backend.models import Thing"),+ ("from . import logic\n", "products.logs.backend", "from products.logs.backend import logic"),+ # multi-level now resolves via libcst (the regex version punted on `..`)+ ("from ..shared import other\n", "products.logs.backend.api", "from products.logs.backend.shared import other"),+ (+ "from .destination_tests import get\n",+ "products.logs.backend.api",+ "from products.logs.backend.api.destination_tests import get",+ ),+ ],+)+def test_absolutize_relative_imports(source: str, package: str, expected: str) -> None:+ result, warnings = absolutize_relative_imports(source, package)+ assert expected in result+ assert warnings == []+++# ---------------------------------------------------------------------------+# celery task pinning+# ---------------------------------------------------------------------------+++ "source,expected_fragment",+ [+ ("@shared_task\ndef other_task():\n pass\n", '@shared_task(name="products.logs.backend.tasks.other_task")'),+ (+ "@shared_task(ignore_result=True)\ndef cleanup_task() -> None:\n pass\n",+ '@shared_task(ignore_result=True, name="products.logs.backend.tasks.cleanup_task")',+ ),+ # nested parens in the args must not truncate the match at the inner )+ (+ "@shared_task(expires=timedelta(hours=1))\ndef expiring():\n pass\n",+ '@shared_task(expires=timedelta(hours=1), name="products.logs.backend.tasks.expiring")',+ ),+ ],+)+def test_pin_task_names(source: str, expected_fragment: str) -> None:+ result, warnings = pin_task_names(source, "products.logs.backend.tasks")+ assert expected_fragment in result+ assert warnings == []+++def test_pin_task_names_existing_name_untouched() -> None:+ text = '@shared_task(name="legacy.name")\ndef named_task():\n pass\n'+ result, warnings = pin_task_names(text, "products.logs.backend.tasks")+ assert result == text+ assert warnings == []+++def test_pin_task_names_warns_when_not_directly_above_def() -> None:+ text = "@shared_task\n@wraps(inner)\ndef stacked():\n pass\n"+ result, warnings = pin_task_names(text, "products.logs.backend.tasks")+ assert result == text+ assert len(warnings) == 1+++# ---------------------------------------------------------------------------+# viewset detection and thin/thick signal+# ---------------------------------------------------------------------------+++def _write_backend(tmp_path: Path) -> Path:+ backend = tmp_path / "backend"+ backend.mkdir()+ (backend / "api.py").write_text(+ "from rest_framework import viewsets\n"+ "from products.demo.backend.runner import Runner\n"+ "from .models import Thing\n"+ "class DemoViewSet(viewsets.ViewSet):\n pass\n"+ )+ (backend / "models.py").write_text("class Thing:\n pass\n")+ (backend / "routes.py").write_text("from products.demo.backend.api import DemoViewSet\n")+ (backend / "tasks.py").write_text("from celery import shared_task\n\n@shared_task\ndef tick():\n pass\n")+ return backend+++def test_detect_viewset_modules(tmp_path: Path) -> None:+ backend = _write_backend(tmp_path)+ assert [p.name for p in detect_viewset_modules(backend)] == ["api.py"]+++def test_detect_viewset_modules_includes_api_subpackage(tmp_path: Path) -> None:+ backend = tmp_path / "backend"+ (backend / "api").mkdir(parents=True)+ (backend / "api" / "views.py").write_text(+ "from rest_framework import viewsets\nclass FooViewSet(viewsets.ViewSet):\n pass\n"+ )+ # root-only by default — the api/ subpackage is opt-in+ assert detect_viewset_modules(backend) == []+ assert [p.name for p in detect_viewset_modules(backend, include_api=True)] == ["views.py"]+++def test_module_dotted_keeps_intermediate_package() -> None:+ assert _module_dotted("wa", Path("api/heatmaps_api.py")) == "products.wa.backend.api.heatmaps_api"+ assert _module_dotted("wa", Path("views.py")) == "products.wa.backend.views"+++def test_build_move_plan_relocates_whole_api_subtree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(iso, "PRODUCTS_DIR", tmp_path)+ backend = tmp_path / "wa" / "backend"+ api = backend / "api"+ (api / "destination_tests").mkdir(parents=True)+ (api / "test").mkdir(parents=True)+ (api / "__init__.py").write_text("from .api import WebAnalyticsViewSet\n")+ (api / "api.py").write_text(+ "from rest_framework import viewsets\nclass WebAnalyticsViewSet(viewsets.ViewSet):\n pass\n"+ )+ # production helper subpackage — rides the api -> presentation.views rename+ (api / "destination_tests" / "__init__.py").write_text("")+ (api / "destination_tests" / "s3.py").write_text("WIDTH = 1\n")+ # test subpackage — leaves the api namespace for the product test dir+ (api / "test" / "__init__.py").write_text("")+ (api / "test" / "test_api.py").write_text("def test_x() -> None:\n pass\n")+ (backend / "serializers.py").write_text("from rest_framework import serializers\n")++ plan = build_move_plan("wa")++ views_dir = backend / "presentation" / "views"+ tests_dir = backend / "tests" / "api"+ # production (top-level + helper subpackage) moves under presentation/views/, structure kept+ assert {dst.relative_to(views_dir).as_posix() for _, dst in plan.view_moves} == {+ "__init__.py",+ "api.py",+ "destination_tests/__init__.py",+ "destination_tests/s3.py",+ }+ # tests relocate into the product test dir, not presentation/views/+ assert {dst.relative_to(tests_dir).as_posix() for _, dst in plan.test_moves} == {"__init__.py", "test_api.py"}+ # one prefix rename covers production; the test prefix is distinct and longer so it wins on match+ assert plan.module_renames["products.wa.backend.api"] == "products.wa.backend.presentation.views"+ assert plan.module_renames["products.wa.backend.api.test"] == "products.wa.backend.tests.api"+ # serializers.py is pulled into presentation/ as strict-lint demands+ assert plan.serializers_move == (backend / "serializers.py", backend / "presentation" / "serializers.py")+ assert plan.module_renames["products.wa.backend.serializers"] == "products.wa.backend.presentation.serializers"+++def test_build_move_plan_flags_api_modules_already_in_presentation(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(iso, "PRODUCTS_DIR", tmp_path)+ backend = tmp_path / "et" / "backend"+ (backend / "api").mkdir(parents=True)+ (backend / "presentation").mkdir(parents=True)+ # both packages carry an __init__.py — the marker mirror must NOT count as a conflict+ (backend / "api" / "__init__.py").write_text("")+ (backend / "presentation" / "__init__.py").write_text("")+ # api/external_references.py is a compat shim; presentation/ already has the real module+ (backend / "api" / "external_references.py").write_text("from ..presentation.external_references import X\n")+ (backend / "presentation" / "external_references.py").write_text("class X:\n pass\n")+ # a genuinely un-migrated viewset alongside it+ (backend / "api" / "issues.py").write_text(+ "from rest_framework import viewsets\nclass IssuesViewSet(viewsets.ViewSet):\n pass\n"+ )++ plan = build_move_plan("et")++ assert plan.presentation_conflicts == [backend / "api" / "external_references.py"]+++def test_build_move_plan_views_override_keeps_subdir_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(iso, "PRODUCTS_DIR", tmp_path)+ backend = tmp_path / "wa" / "backend"+ (backend / "api").mkdir(parents=True)+ (backend / "api" / "heatmaps_api.py").write_text("x = 1\n")++ plan = build_move_plan("wa", views=["api/heatmaps_api.py"])++ # the override must not flatten the dotted path to backend.heatmaps_api+ assert plan.module_renames == {+ "products.wa.backend.api.heatmaps_api": "products.wa.backend.presentation.views.heatmaps_api"+ }+++def test_internal_import_count_counts_internals_and_relatives(tmp_path: Path) -> None:+ backend = _write_backend(tmp_path)+ assert internal_import_count(backend / "api.py", "demo") == 2+++def test_shared_task_names(tmp_path: Path) -> None:+ backend = _write_backend(tmp_path)+ assert shared_task_names(backend / "tasks.py") == ["tick"]diff --git a/uv.lock b/uv.lockindex 364e75567a51..7085fb342e72 100644--- a/uv.lock+++ b/uv.lock@@ -5716,6 +5716,7 @@ dev = [{ name = "hypothesis" },{ name = "import-linter" },{ name = "ipython" },+ { name = "libcst" },{ name = "mypy" },{ name = "mypy-extensions" },{ name = "openapi-spec-validator" },@@ -5988,6 +5989,7 @@ dev = [{ name = "hypothesis", specifier = "~=6.151.9" },{ name = "import-linter", specifier = "~=2.11" },{ name = "ipython", specifier = "~=9.3.0" },+ { name = "libcst", specifier = ">=1.8.6,<2.0.0" },{ name = "mypy", specifier = "~=2.1.0" },{ name = "mypy-extensions", specifier = "~=1.1.0" },{ name = "openapi-spec-validator", specifier = "==0.7.1" },