Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): add splitting-oversized-modules skill (#83672)

Julian Bezd7a21e83a1a9
diff --git a/.agents/skills/splitting-oversized-modules/SKILL.md b/.agents/skills/splitting-oversized-modules/SKILL.md
new file mode 100644
index 000000000000..748239635fd7
--- /dev/null
+++ b/.agents/skills/splitting-oversized-modules/SKILL.md
@@ -0,0 +1,165 @@
+---
+name: splitting-oversized-modules
+description: >
+ Split an oversized Python module (a 2000+ line logic.py, models.py, api.py, or its test
+ file) into a package of one module per concern, mechanically and provably without changing
+ behavior. Use on a request to split / break up / decompose a god module or move functions
+ out of one, or once a human has agreed to split one before some other change. Covers the
+ worth-it gate, assigning symbols to concerns with an acyclic dependency graph, the AST plus
+ tokenize move script, and proving the result is a pure move. Python only — for frontend
+ files use writing-ui-components. Not for extracting a shared helper into common/, and not
+ for moving code between products, which is isolating-product-facade-contracts.
+---
+
+# Splitting oversized modules
+
+A module nobody wants to open taxes every change in it, and agents pay that tax on every
+task because they do not carry knowledge between them. A 3000-line `logic.py` beside a
+3000-line `test_logic.py` is roughly 55k input tokens of reading before a line gets written.
+Splitting one measured case cut the read-set 81 to 97% depending on the concern touched,
+while total lines grew about 5% from the repeated import headers.
+
+So the goal is a small read-set for a typical change, not tidiness.
+
+## Is it worth doing here?
+
+All three must hold: over roughly a thousand lines, several concerns that change
+independently, and something still actively changing in it. A big cohesive frozen file buys
+nothing. Skip generated files, and skip a file several people are mid-change in
+(`git log --oneline -20 -- <file>`).
+
+Splitting is a separate PR from whatever you came to do. Land the move as its own base PR
+and branch your work on top — see `/stacking-prs`. Never bundle it into a feature diff, and
+say what you are doing in one line before you start: which file, and that the split lands
+separately. Nobody minds the base PR; they mind finding it inside a feature diff.
+
+If a human has not asked for the split, propose it and let them decide.
+
+## Method
+
+Commands assume the repo root. `S=.agents/skills/splitting-oversized-modules/scripts`.
+
+### 1. Map the symbols and assign them to concerns
+
+```sh
+uv run --no-project python $S/split_module.py <module> --skeleton > layout.json
+```
+
+Edit `layout.json` into modules named after concerns (`baselines`, `quarantine`,
+`ci_status`), not layers (`helpers`, `utils`, `core`). Put module-level state every module
+needs its own copy of — a logger, a compiled regex — under `"__shared__"`.
+
+Two rules while assigning:
+
+**Keep the dependency graph acyclic.** If two modules need each other, the seam is wrong.
+Separating reads from writes fixes most cycles: a lifecycle module and a verification module
+that both need the same lookups should share a third leaf module holding those lookups.
+
+**Do not name a module after a common local variable.** A module called `artifacts` or
+`runs` gets shadowed by `artifacts = [...]` inside a function, and Python binds the whole
+scope, so a call _above_ the assignment fails too. `ruff` catches the reachable cases
+(`F811`, `F823`) but not one where the local is assigned before any module use. Pick a
+non-colliding name, or split finer until the name is specific.
+
+### 2. Move the code
+
+```sh
+uv run --no-project python $S/split_module.py <module> layout.json
+ruff check <package>/ --fix && ruff format <package>/
+```
+
+Hand-editing a 3000-line move loses code and silently rewrites it. The script copies each
+symbol verbatim by AST line range, refuses to run unless the layout covers every symbol
+exactly once, and requalifies cross-module references with `tokenize` so it never rewrites a
+name inside a docstring or string literal.
+
+Cross-module calls come out as `from . import baselines` plus `baselines.foo(...)`, never
+`from .baselines import foo`. One binding per symbol means a mock patch on the definition
+reaches every caller, and `from . import x` also survives an accidental cycle by falling
+back to `sys.modules`.
+
+`ruff --fix` leaves an emptied `if TYPE_CHECKING: pass` behind. Delete those, then re-run
+`ruff check --fix` so the orphaned `TYPE_CHECKING` import goes too. The
+`# --- Section ---` dividers from the monolith are usually redundant once the module name
+says it: `rg -n '^#\s*-{2,}' <package>/`.
+
+### 3. Retarget callers and mock patch targets
+
+Every `logic.foo()` becomes `<module>.foo()`, and every patch target moves to the module
+that _defines_ the symbol, since that is the binding its callers resolve:
+
+```python
+patch("products.foo.backend.logic._post_commit_status") # -> ...logic.ci_status._post_commit_status
+patch.object(logic, "_post_commit_status") # -> patch.object(ci_status, "_post_commit_status")
+```
+
+Sweep `conftest.py` too, not just `test_*.py` — fixtures patch, and a pass matched on test
+files leaves conftest pointing at paths that no longer exist. Enumerate candidates with
+`rg -n 'patch\(|patch\.object\(' <tests>/`. Watch for forms a naive sweep misses: a combined
+`from x import a, logic`, a symbol import (`from ..logic import SomeError`), and a name the
+old module merely re-exported, which should now come from its real source.
+
+### 4. Split the tests the same way
+
+A split module beside an untouched 3000-line test file solves half the problem. Mirror the
+package, so `logic/comments.py` pairs with `tests/logic/test_comments.py`:
+
+```sh
+uv run --no-project python $S/split_module.py <test file> tests_layout.json \
+ --package-dir <tests>/logic --init-doc "Unit tests for the logic package."
+```
+
+Assign whole test classes. Carving up a class stops being a pure move.
+
+### 5. Prove it is a pure move
+
+```sh
+git show HEAD:<module> > /tmp/before.py
+uv run --no-project python $S/verify_pure_move.py /tmp/before.py <package>
+```
+
+It compares every top-level definition before and after, ignoring the module qualification
+and relative-import depth the split introduces, and reports anything missing, unexpected,
+duplicated with drift, or changed. This is what makes a 50-file diff reviewable: "every
+definition is identical" is checkable, unlike the diff. Always re-derive the before side
+from git, never from your own earlier output. Re-run it after any cleanup pass.
+
+For a test split, pass `--strip-package <package>` so the source package's module names are
+normalized too.
+
+### 6. Then the suite
+
+```sh
+hogli test <tests>/
+```
+
+Static checks cover import wiring and equivalence, not behavior. Deferred imports inside
+function bodies fail at call time, so only running the tests catches a mistake there.
+
+## Traps worth knowing
+
+- **A re-export shim in `__init__.py`** gives every symbol two bindings, so patching one
+ leaves internal callers on the real implementation: the patch applies, the test passes,
+ and nothing intercepted. `.semgrep/rules/devex/no-init-reexports.yaml` already blocks
+ eager re-exports repo-wide; the silent-mock failure is the extra reason not to add one.
+- **Moving code makes its old semgrep findings new.** Semgrep skips its baseline comparison
+ for findings in files that did not exist in the baseline commit, so every pre-existing
+ violation in the moved code comes back as blocking. Check before pushing:
+ `uv run --no-project --with semgrep semgrep --config .semgrep/rules/devex <package>/`.
+- **Relative imports break one level down.** The script deepens them, including inside
+ function bodies. A missed one is invisible until the function runs.
+- **A `models.py` split is the one case that needs re-exports.** Django imports an app's
+ `models` package but does not recurse into it, so model classes in submodules never reach
+ the app registry and every `from ..models import Model` caller breaks. Add aggregation
+ imports to `models/__init__.py`; `no-init-reexports.yaml` exempts `**/models/**` for
+ exactly this reason. The script warns when it writes a `models/` package.
+- **A top-level statement after the first definition stops the split.** A module-level `if`,
+ an `assert`, or a registration call cannot be attributed to a concern, and copying it into
+ every module would run its side effect once per module. Move it into a function or above
+ the definitions first.
+
+## Left for you
+
+- Decide on the section dividers the move leaves behind.
+- Rename locals that shadow a new module name.
+- Update any doc or skill that links the old path; a split leaves dead links behind.
diff --git a/.agents/skills/splitting-oversized-modules/scripts/split_module.py b/.agents/skills/splitting-oversized-modules/scripts/split_module.py
new file mode 100644
index 000000000000..c4134d2ed499
--- /dev/null
+++ b/.agents/skills/splitting-oversized-modules/scripts/split_module.py
@@ -0,0 +1,296 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 — CLI tool; stdout is the intended output
+"""Split one oversized module into a package, one module per concern.
+
+ uv run --no-project python split_module.py products/foo/backend/logic.py layout.json
+
+`layout.json` maps module name -> {"doc": str, "symbols": [...]} (see map_symbols.py
+--skeleton). Every top-level symbol in the source must be assigned exactly once, or
+this refuses to run — that check is what stops code from silently going missing.
+
+What it does:
+ - copies each symbol's source verbatim by AST line range
+ - gives every new module the original import header (ruff strips what it doesn't need)
+ - deepens relative imports one level (`from .models` -> `from ..models`)
+ - requalifies cross-module references via tokenize (`get_run` -> `run_queries.get_run`)
+ and adds the matching `from . import run_queries`
+ - copies "__shared__" state (a logger, a compiled regex) into each module that uses it
+ - writes a package __init__.py with a docstring and no re-exports (--init-doc to set it)
+
+It does NOT reformat or fix imports. Run afterwards:
+
+ ruff check <package>/ --fix && ruff format <package>/
+ uv run --no-project python verify_pure_move.py <original> <package>
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import argparse
+from pathlib import Path
+
+# Reserved layout key for module-level state each module needs its own copy of.
+SHARED = "__shared__"
+
+
+def names_of(node: ast.stmt) -> list[str]:
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
+ return [node.name]
+ if isinstance(node, ast.Assign):
+ return [t.id for t in node.targets if isinstance(t, ast.Name)]
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ return [node.target.id]
+ return []
+
+
+def segment(tree: ast.Module, lines: list[str]) -> tuple[dict[str, tuple[int, int]], int, list[int]]:
+ """Symbol -> (first_line, last_line), the header boundary, and any unsupported statements.
+
+ Only statements *before* the first definition extend the header. A bare statement after
+ one (a module-level `if`, an `assert`, a registration call) cannot be attributed to a
+ concern, and copying it into every module would run its side effect N times, so it is
+ reported and the caller refuses to split.
+ """
+ segments: dict[str, tuple[int, int]] = {}
+ header_end = 0
+ prev_end = 0
+ late: list[int] = []
+ seen_definition = False
+ for node in tree.body:
+ start = min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])])
+ j = start - 2
+ while j > prev_end - 1 and (lines[j].lstrip().startswith("#") or lines[j].strip() == ""):
+ j -= 1
+ found = names_of(node)
+ for name in found:
+ segments[name] = (j + 2, node.end_lineno or start)
+ if found:
+ seen_definition = True
+ elif seen_definition:
+ late.append(node.lineno)
+ else:
+ header_end = node.end_lineno or start
+ prev_end = node.end_lineno or start
+ return segments, header_end, late
+
+
+def deepen_relative_imports(text: str) -> str:
+ """Add one dot to every relative import: the modules now sit a level deeper.
+
+ Locates the statements with the AST rather than by matching raw lines, so a docstring or
+ string literal whose line happens to read ``from .models import Thing`` is left alone.
+ Covers deferred imports inside function bodies too — those fail at call time rather than
+ at import, so nothing catches a missed one early.
+ """
+ lines = text.splitlines(keepends=True)
+ # Right-to-left so an earlier edit cannot shift a later column on the same line.
+ spots = sorted(
+ (node.lineno, node.col_offset)
+ for node in ast.walk(ast.parse(text))
+ if isinstance(node, ast.ImportFrom) and node.level > 0
+ )
+ for lineno, col in reversed(spots):
+ line = lines[lineno - 1]
+ dot = line.index(".", col)
+ lines[lineno - 1] = line[:dot] + "." + line[dot:]
+ return "".join(lines)
+
+
+def shadowed_symbols(body: str, self_module: str, owner: dict[str, str]) -> list[str]:
+ """Foreign symbol names that the moved code also binds locally.
+
+ A local `get_run` makes the name ambiguous: requalifying its reads would point them at
+ another module, and leaving them alone is only right because the local exists. Rather
+ than resolve scopes, refuse and let a human rename the local — the same stance the
+ module-name shadowing trap takes, and a one-line fix.
+ """
+ bound: dict[str, int] = {}
+ for node in ast.walk(ast.parse(body)):
+ if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Load):
+ bound.setdefault(node.id, node.lineno)
+ elif isinstance(node, ast.arg):
+ bound.setdefault(node.arg, node.lineno)
+ elif isinstance(node, ast.alias) and node.asname:
+ bound.setdefault(node.asname, getattr(node, "lineno", 0))
+ return [
+ f"{name} (bound at line {line}, owned by {owner[name]})"
+ for name, line in sorted(bound.items())
+ if name in owner and owner[name] != self_module
+ ]
+
+
+def requalify(body: str, self_module: str, owner: dict[str, str]) -> tuple[str, set[str], set[str]]:
+ """Prefix foreign symbols with their module, rewriting reads only.
+
+ Uses `ast.Name` nodes in `Load` context rather than raw tokens, which excludes three
+ things a token scan gets wrong: a name being *bound* (an assignment target or loop
+ target would become `mod.name = ...`, which is valid Python writing to the wrong place),
+ a parameter or keyword argument (`f(name=1)` would not even parse), and an attribute
+ (`obj.name`). Strings and comments hold no Name nodes, so prose mentioning a function
+ survives untouched.
+
+ Returns the rewritten body, the modules it now depends on, and every name it reads.
+ """
+ tree = ast.parse(body)
+ edits: list[tuple[int, int, int, str]] = []
+ used: set[str] = set()
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Name):
+ continue
+ names.add(node.id)
+ if not isinstance(node.ctx, ast.Load):
+ continue
+ module = owner.get(node.id)
+ if module is not None and module != self_module:
+ used.add(module)
+ edits.append((node.lineno, node.col_offset, node.end_col_offset or node.col_offset, f"{module}.{node.id}"))
+
+ lines = body.splitlines(keepends=True)
+ # Right-to-left within each line so an earlier edit cannot shift a later column.
+ for lineno, col, end_col, replacement in sorted(edits, reverse=True):
+ line = lines[lineno - 1]
+ lines[lineno - 1] = line[:col] + replacement + line[end_col:]
+ return "".join(lines), used, names
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("source", type=Path, help="module to split, e.g. products/foo/backend/logic.py")
+ parser.add_argument("layout", type=Path, nargs="?", help="JSON layout: module -> {doc, symbols}")
+ parser.add_argument(
+ "--skeleton",
+ action="store_true",
+ help="print a layout skeleton with every symbol in one bucket, then exit. Edit it into "
+ "concern-named modules and pass it back as the layout argument",
+ )
+ parser.add_argument(
+ "--package-dir",
+ type=Path,
+ help="where to write the package (default: the source path without .py). Use this to split a "
+ "test file into a directory that mirrors the source package, e.g. tests/logic/",
+ )
+ parser.add_argument(
+ "--init-doc",
+ default="",
+ help="use this as the whole __init__.py docstring instead of the module-per-concern template "
+ "(for a tests package, where the import advice does not apply)",
+ )
+ args = parser.parse_args()
+
+ source = args.source.read_text()
+ lines = source.splitlines(keepends=True)
+ tree = ast.parse(source)
+ segments, header_end, late = segment(tree, lines)
+
+ if args.skeleton:
+ ordered = sorted(segments, key=lambda n: segments[n][0])
+ print(json.dumps({"UNASSIGNED": {"doc": "TODO one line per module", "symbols": ordered}}, indent=2))
+ return 0
+ if args.layout is None:
+ parser.error("a layout is required unless --skeleton is given")
+
+ if late:
+ print(f"{args.source} has top-level statements after its first definition, on lines:")
+ print(f" {late}")
+ print("Those cannot be attributed to a concern, and copying them into every module")
+ print("would run their side effects once per module. Move them into a function or")
+ print("above the first definition, then split.")
+ return 1
+
+ raw: dict[str, dict] = json.loads(args.layout.read_text())
+ # State every module needs its own copy of (a logger) goes under "__shared__", so no
+ # module has to import a sibling just to log. Kept out of `modules` so the coverage
+ # check and the write loop read a dict nothing has mutated.
+ shared_names = raw.get(SHARED, {}).get("symbols", [])
+ modules = {name: spec for name, spec in raw.items() if name != SHARED}
+
+ # A symbol listed twice would be emitted into both modules, and the verifier would read
+ # the identical copies as shared state and still say "pure move" — so catch it here.
+ seen: dict[str, str] = {}
+ duplicates: list[str] = []
+ for mod, spec in [*modules.items(), (SHARED, raw.get(SHARED, {"symbols": []}))]:
+ for sym in spec["symbols"]:
+ if sym in seen:
+ duplicates.append(f"{sym} (in {seen[sym]} and {mod})")
+ seen[sym] = mod
+ if duplicates:
+ print("layout assigns a symbol to more than one destination:")
+ for entry in duplicates:
+ print(f" {entry}")
+ return 1
+
+ owner = {sym: mod for mod, spec in modules.items() for sym in spec["symbols"]}
+
+ unassigned = sorted(set(segments) - set(owner) - set(shared_names))
+ unknown = sorted((set(owner) | set(shared_names)) - set(segments))
+ if unassigned or unknown:
+ print("layout does not cover the source.")
+ print(f" unassigned: {unassigned}")
+ print(f" not in source: {unknown}")
+ print(f' (module state belongs under "{SHARED}", not in a module)')
+ return 1
+
+ docstring_end = tree.body[0].end_lineno if ast.get_docstring(tree) else 0
+ header = deepen_relative_imports("".join(lines[docstring_end:header_end]))
+ shared_src = {
+ name: "".join(lines[segments[name][0] - 1 : segments[name][1]]).strip("\n") + "\n"
+ for name in sorted(shared_names, key=lambda n: segments[n][0])
+ }
+
+ # Build every module first, so a refusal below leaves nothing half-written on disk.
+ built: dict[str, tuple[str, set[str], int]] = {}
+ shadowed: dict[str, list[str]] = {}
+ for module, spec in modules.items():
+ ordered = sorted(spec["symbols"], key=lambda n: segments[n][0])
+ body = "\n\n".join("".join(lines[segments[n][0] - 1 : segments[n][1]]).strip("\n") for n in ordered) + "\n"
+ # Deferred imports sit inside function bodies, so the body needs deepening too.
+ # This runs before the sibling imports below, which are already at the right depth.
+ body = deepen_relative_imports(body)
+ collisions = shadowed_symbols(body, module, owner)
+ if collisions:
+ shadowed[module] = collisions
+ continue
+ body, used, names = requalify(body, module, owner)
+ siblings = "".join(f"from . import {m}\n" for m in sorted(used))
+ # Only carry shared state into modules that reference it: `ruff --fix` prunes an
+ # unused import, but never an unused module-level assignment, so a blanket copy
+ # leaves a dead logger in every module that doesn't log. `names` holds the names the
+ # code reads, so a mention inside a docstring does not count as a reference.
+ carried = "".join(src for name, src in shared_src.items() if name in names)
+ built[module] = (f'"""{spec["doc"]}"""\n\n{header}{siblings}\n{carried}\n\n{body}', used, len(ordered))
+
+ if shadowed:
+ for module, collisions in shadowed.items():
+ print(f"{module}.py binds names that belong to other modules:")
+ for entry in collisions:
+ print(f" {entry}")
+ print("Rename the local, then split — otherwise its reads cannot be told apart from")
+ print("reads of the moved symbol.")
+ return 1
+
+ package = args.package_dir or args.source.with_suffix("")
+ package.mkdir(parents=True, exist_ok=True)
+ for module, (text, used, count) in built.items():
+ (package / f"{module}.py").write_text(text)
+ print(f"{module + '.py':<26} {count:>3} symbols deps={sorted(used) or '-'}")
+
+ init_doc = args.init_doc or f"{package.name} for {package.parent.name}. One module per concern."
+ (package / "__init__.py").write_text(f'"""{init_doc}"""\n')
+ if package.name == "models":
+ print()
+ print("This is a models package, so the empty __init__.py is not enough: Django imports")
+ print("an app's `models` package but does not recurse into it, so the classes would be")
+ print("missing from the app registry. Add aggregation imports to __init__.py — the one")
+ print("case where re-exporting is right, and why no-init-reexports.yaml exempts models/.")
+ args.source.unlink()
+ print(f"\nwrote {len(modules)} modules to {package}/ and removed {args.source}")
+ if shared_names:
+ print(f"shared state carried into the modules that use it: {sorted(shared_names)}")
+ print("next: ruff check --fix, ruff format, then verify_pure_move.py")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.agents/skills/splitting-oversized-modules/scripts/verify_pure_move.py b/.agents/skills/splitting-oversized-modules/scripts/verify_pure_move.py
new file mode 100644
index 000000000000..7997b11a73f7
--- /dev/null
+++ b/.agents/skills/splitting-oversized-modules/scripts/verify_pure_move.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 — CLI tool; stdout is the intended output
+"""Prove a split moved code without changing it.
+
+ git show HEAD:products/foo/backend/logic.py > /tmp/before.py
+ uv run --no-project python verify_pure_move.py /tmp/before.py products/foo/backend/logic
+
+Compares every top-level definition before and after, ignoring the module
+qualification the split introduces (`get_run` vs `run_queries.get_run`) and any
+formatting the formatter changed. Reports symbols that went missing, appeared from
+nowhere, got duplicated across modules, or actually changed.
+
+This is the check that makes a large split reviewable: "48 files changed" means
+nothing on its own, but "every definition is byte-identical modulo qualification"
+is a claim a reviewer can trust. Works the same for a test-file split (compare
+test classes) since it just diffs top-level definitions.
+"""
+
+from __future__ import annotations
+
+import re
+import ast
+import sys
+import argparse
+from pathlib import Path
+
+
+def definitions(source: str) -> dict[str, ast.stmt]:
+ out: dict[str, ast.stmt] = {}
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
+ out[node.name] = node
+ elif isinstance(node, ast.Assign):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ out[target.id] = node
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
+ out[node.target.id] = node
+ return out
+
+
+def canonical(node: ast.stmt, modules: list[str], deepen: bool = False) -> str:
+ """Unparse, then collapse module qualification so both sides compare equal.
+
+ Do this textually on the unparsed form, not with a NodeTransformer: a transformer
+ that rewrites `mod.attr` into `attr` is order-sensitive on nested attributes and
+ reports differences that are not there. Text canonicalization is symmetric.
+ """
+ text = ast.unparse(node)
+ # The split adds exactly one dot to every relative import, since the modules sit a level
+ # deeper. Apply that same transformation to the before side rather than collapsing depth
+ # on both: collapsing would accept an import deepened by two levels, which imports from
+ # somewhere else entirely and only fails when the enclosing function runs.
+ if deepen:
+ text = re.sub(r"\bfrom (\.+)", r"from .\1", text)
+ if modules:
+ alternation = "|".join(sorted(modules, key=len, reverse=True))
+ text = re.sub(rf"\b({alternation})\.", "", text)
+ # bare module names appear as arguments, e.g. patch.object(ci_status, "x")
+ text = re.sub(rf"\b({alternation})\b", "<module>", text)
+ return text
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("before", type=Path, help="the original single file (e.g. from git show)")
+ parser.add_argument("after", type=Path, help="the package directory it became")
+ parser.add_argument(
+ "--also-strip",
+ nargs="*",
+ default=[],
+ help="extra names to treat as module qualification, e.g. the old module's own name",
+ )
+ parser.add_argument(
+ "--strip-package",
+ type=Path,
+ help="also strip the module names in this package — use when verifying a test split, "
+ "since the tests reference the source package's modules, not their own",
+ )
+ args = parser.parse_args()
+
+ modules = [p.stem for p in sorted(args.after.glob("*.py")) if p.stem != "__init__"]
+ strip = modules + list(args.also_strip)
+ if args.strip_package:
+ strip += [p.stem for p in sorted(args.strip_package.glob("*.py")) if p.stem != "__init__"]
+
+ before = {name: canonical(node, strip, deepen=True) for name, node in definitions(args.before.read_text()).items()}
+
+ forms: dict[str, set[str]] = {}
+ where: dict[str, list[str]] = {}
+ for path in sorted(args.after.glob("*.py")):
+ if path.stem == "__init__":
+ continue
+ for name, node in definitions(path.read_text()).items():
+ forms.setdefault(name, set()).add(canonical(node, strip))
+ where.setdefault(name, []).append(path.name)
+
+ missing = sorted(set(before) - set(forms))
+ unexpected = sorted(set(forms) - set(before))
+ changed = sorted(n for n in set(before) & set(forms) if before[n] not in forms[n])
+ # Shared module state (a logger, a compiled regex) is legitimately repeated once per
+ # module. Identical copies are fine; copies that drifted apart are a real finding.
+ repeated = sorted(n for n, mods in where.items() if len(mods) > 1)
+ conflicting = sorted(n for n in repeated if len(forms[n]) > 1)
+
+ print(f"definitions: {len(before)} before -> {len(forms)} after")
+ print(f"missing: {missing or 'none'}")
+ print(f"unexpected: {unexpected or 'none'}")
+ print(f"changed: {changed or 'none'}")
+ print(f"conflicting copies: {conflicting or 'none'}")
+ if repeated:
+ print(f"repeated identically across modules (per-module state): {repeated}")
+
+ if missing or unexpected or changed or conflicting:
+ print("\nNOT a pure move — inspect the symbols above before committing.")
+ return 1
+ print("\nPure move confirmed.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/AGENTS.md b/AGENTS.md
index ebb8087421ca..c521f1bc2e8b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -265,6 +265,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- `/authoring-ci-workflows` — adding or editing any `.github/workflows` workflow, composite action, or reusable workflow
- `/reviewing-personhog-protocol` — any personhog coordination-protocol change (leases, fencing, handoffs, supervisors, budgets, warming, changelog semantics), and any request for an exhaustive review of personhog code
- `/gating-production-deploys` — any workflow that builds and pushes a production image or dispatches a deploy
+- `/splitting-oversized-modules` — splitting a Python module into a package, or deciding whether to propose splitting one before you work in it; propose, and land the move as a stacked base PR rather than inside your feature diff
- `/auditing-llm-gateway-parity` — changing either gateway's auth, attribution, billing, endpoints, providers, models, routing, or metadata contract; reviewing a `services/llm-gateway` change; or refreshing `services/llm-gateway/PARITY.md`
- `/finding-llm-gateway-migration-candidates` — finding, auditing, or ranking callers that could move from `services/llm-gateway` to `PostHog/ai-gateway`, including requests for the next or lowest-risk migration candidate
- `/migrating-llm-gateway-callers` — adding an LLM gateway caller or migrating an existing caller from `services/llm-gateway` to `PostHog/ai-gateway`, including shared client and gateway setting changes made for that migration