splitting-oversized-modules
Skill721 starsChanged 58 days agoMITView on GitHub
Split an oversized Python module (a thousand-plus-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, once a human has agreed to split one before some other change, or before restructuring code inside a module already over roughly a thousand lines — breaking up a long function or extracting helpers in place leaves everything in the same file, so check the worth-it gate and propose the split first. Covers that 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.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- PostHog/posthogword for word, first seen Oct 4, 2026
Other versions1 project uses a version of this.
Word for word · 1
- PostHog/posthog★ 40k100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository119 other files it gives its agents.
- AGENTS.mdAGENTS.md
- common/AGENTS.mdAGENTS.md
- proto/AGENTS.mdAGENTS.md
- rust/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- common/CLAUDE.mdCLAUDE.md
- proto/CLAUDE.mdCLAUDE.md
- rust/CLAUDE.mdCLAUDE.md
- .cursor/rules/django-python.mdcCursor rule
- .cursor/rules/react-typescript.mdcCursor rule
- .cursor/rules/rust.mdcCursor rule
- adding-activity-loggingSkill
- adding-api-scopesSkill
- adding-inbound-webhooksSkill
- adding-inbox-sourcesSkill
- adding-ingestion-warningsSkill
- adding-mcp-store-serversSkill
- adding-personhog-rpcSkill
- adding-product-alertingSkill
- adding-project-secret-api-key-authSkill
- adopting-generated-api-typesSkill
- analyzing-experiment-precompute-canarySkill
- analyzing-experiment-query-performanceSkill
- analyzing-insights-across-teamsSkill
- announcing-behavior-changesSkill
- auditing-llm-gateway-paritySkill
- auditing-warehouse-source-coverageSkill
- authenticating-to-clickhouseSkill
- authoring-ci-workflowsSkill
- autoresolving-pr-conflictsSkill
- building-product-empty-statesSkill
- clickhouse-migrationsSkill
- debugging-ci-failuresSkill
- debugging-local-replaySkill
- debugging-local-task-agent-runsSkill
- debugging-mcp-analyticsSkill
- debugging-signals-pipelineSkill
- debugging-table-access-deniedSkill
- depot-ciSkill
- depot-container-buildsSkill
- depot-github-runnersSkill
- developing-subscriptionsSkill
- django-migrationsSkill
- django-startup-timeSkill
- documenting-warehouse-sourcesSkill
- editing-agents-mdSkill
- establishing-code-ownershipSkill
- extending-hobby-smoke-testsSkill
- extending-personhog-test-harnessSkill
- finding-llm-gateway-migration-candidatesSkill
- fixing-flaky-testsSkill
- gating-production-deploysSkill
- gating-sensitive-actionsSkill
- generating-clickhouse-query-performance-reportsSkill
- hogliSkill
- implementing-mcp-toolsSkill
- implementing-mcp-ui-appsSkill
- implementing-warehouse-sourcesSkill
- improving-drf-endpointsSkill
- improving-mcp-toolsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 4 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 29
All three must hold: over roughly a thousand lines, several concerns that change independently, and something still actively changing in it.
- Distinctive: line 44
If a human has not asked for the split, propose it and let them decide.
- Distinctive: line 62
Keep the dependency graph acyclic: If two modules need each other, the seam is wrong.
- Very specific: line 96
Every logic.foo() becomes <module>.foo(), and every patch target moves to the module that _defines_ the symbol, since that is the binding …
- Distinctive: line 173
Update any doc or skill that links the old path.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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>).
A complexity warning on one function is a symptom of this, not a separate job. Extracting
that function into helpers leaves every helper in the same file, so the read-set is
unchanged and the file gets longer. Measure the file first (wc -l), and when it clears the
gate, propose the split instead of the in-place extraction.
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
uv run --no-project python $S/split_module.py <module> --skeleton > layout.jsonEdit 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
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:
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:
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
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
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__.pygives 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.yamlalready 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.pysplit is the one case that needs re-exports. Django imports an app'smodelspackage but does not recurse into it, so model classes in submodules never reach the app registry and everyfrom ..models import Modelcaller breaks. Add aggregation imports tomodels/__init__.py;no-init-reexports.yamlexempts**/models/**for exactly this reason. The script warns when it writes amodels/package. - A top-level statement after the first definition stops the split. A module-level
if, anassert, 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.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

