Improve Codebase Architecture
Surface architectural friction and propose deepening opportunities: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
This is a survey, not a refactor. It reads the code and writes one report; it never edits the repository.
It is informed by the project’s domain language and built on a shared design vocabulary:
- Read CODEBASE-DESIGN.md in this folder for the architecture vocabulary (module, interface, depth, seam, adapter, leverage, locality) and its principles (the deletion test, “the interface is the test surface”, “one adapter = hypothetical seam, two = real”). Use these terms exactly in every suggestion, and don’t drift into “component,” “service,” “API,” or “boundary.”
- If the repo has a
GLOSSARY.md, its domain language gives names to good seams; if it has ADRs (usuallydocs/adr/), they record decisions this survey should not re-litigate. Read them; don’t create them (see step 3).
Where this fits
- It runs on request only. It is not a step in the build flow.
- If the repo has a
.specify/folder, any module context files in it are a quick map of where to look. They can be stale: check anything that matters against the code. A.specify/with only scripts, config and templates has no map; skip it. - Whatever refactor comes out of it goes through the repo’s normal flow (the team’s own process), in a separate session, with its own tests and review. This skill ends with a recommendation, not a patch.
Process
1. Explore
If the repository path the user gave doesn’t exist, or it isn’t clear which repository or worktree is meant, stop and ask; don’t pick the nearest match.
Scope before you scan: YAGNI. Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide where to look before you look:
- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below.
-
Otherwise, find the hot spots in the commit history, the files that keep coming up, and let those paths pull your attention first. Count over the last 12 months, for the repo’s source files only (swap
*.javafor the repo’s language), and drop paths that no longer exist at HEAD; a renamed file otherwise tops the list with a name that is gone:git log --since="12 months ago" --name-only --pretty=format: -- '*.java' | grep . | sort | uniq -c | sort -rn | head -20Keep only paths that still exist at HEAD. In PowerShell the same idea is
git log --since="12 months ago" --name-only --pretty=format: -- '*.java' | Where-Object { $_ } | Group-Object | Sort-Object Count -Descending | Where-Object { Test-Path $_.Name } | Select-Object -First 20 Count, Name. To count one renamed file’s whole history usegit log --follow --oneline -- <path>. Skip generated code (the repo’sAGENTS.mdor README usually names those folders) and vendored code. If the changes are scattered with no clear hot spot, widen the window to the whole history, then narrow again.
Read the project’s glossary (GLOSSARY.md) and any ADRs in the area you’re touching first.
Then, if you can start a sub-agent with a fresh context window, have it walk the codebase; if you can’t, do the walk yourself and keep notes short. Don’t follow rigid heuristics; explore organically and note where you experience friction:
- Where does understanding one concept require bouncing between many small modules?
- Where are modules shallow, with an interface nearly as complex as the implementation?
- Where have pure functions been extracted just for testability, but the real bugs hide in how they’re called (no locality)?
- Where do tightly-coupled modules leak across their seams?
- Which parts of the codebase are untested, or hard to test through their current interface?
Apply the deletion test to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A “yes, concentrates” is the signal you want.
2. Present candidates as an HTML report
Write a self-contained HTML file to a temp directory so nothing lands in the repo. If the environment names a temp directory for you to use, use that one. Otherwise take $TMPDIR, falling back to /tmp (on Windows, $env:TEMP). Write to <tmpdir>/architecture-review-<timestamp>.html with the timestamp as yyyyMMdd-HHmmss (no colons, sorts by date), so each run gets a fresh file. Open it for the user (xdg-open <path> on Linux, open <path> on macOS, Start-Process <path> in PowerShell on Windows) and tell them the absolute path. When you run non-interactively (for example as a sub-agent), don’t open it: report the path and the candidate list, and let whoever started you decide what happens next.
The report uses Tailwind via CDN for layout and styling, and Mermaid via CDN for diagrams where a graph/flow/sequence reliably communicates the structure. These two scripts are the only external resources: nothing from the repo is sent anywhere, and the report must not add fonts, images, analytics or any other remote content. If the CDNs can’t be reached the page is unstyled but its text is still readable; say so rather than silently shipping a broken file. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a before/after visualisation. Be visual.
For each candidate, render a card with:
- Files: which files/modules are involved
- Problem: why the current architecture is causing friction
- Solution: plain English description of what would change
- Benefits: explained in terms of locality and leverage, and how tests would improve
- Before / After diagram: side-by-side, custom-drawn, illustrating the shallowness and the deepening. The “After” shows responsibilities only, never method names or signatures: that is the interface, and proposing it comes after the user picks a candidate.
- Recommendation strength: one of
Strong,Worth exploring,Speculative, rendered as a badge - Dependency category: one of
in-process,local-substitutable,ports & adapters,mock(defined in DEEPENING.md), rendered as a second badge
Keep the cards short: HTML-REPORT.md sets the length (one sentence per field, short bullets), and where it is stricter than the list above, it wins.
End the report with a Top recommendation section: which candidate you’d tackle first and why.
Names from the code: the vocabulary rules cover your own words. When a class or package is called OrderService or PipePassSvcHelper, quote that name as it is; don’t rename it, and don’t treat it as breaking the “never say service” rule.
Language: write the report’s prose in the language the user writes in (when you were started by another agent, the language of the brief you were given). Keep the architecture terms (module, interface, depth, seam, adapter, leverage, locality) in English, and when the user writes Chinese add the Chinese in brackets the first time a term appears.
Use the glossary’s words for the domain, and the CODEBASE-DESIGN.md vocabulary for the architecture. If GLOSSARY.md defines “Order,” talk about “the Order intake module,” not “the FooBarHandler,” and not “the Order service.” With no GLOSSARY.md, use the names the code itself uses.
ADR conflicts: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: “contradicts ADR-0007, but worth reopening because…”). Don’t list every theoretical refactor an ADR forbids.
See HTML-REPORT.md for the full HTML scaffold, diagram patterns, and styling guidance.
Do NOT propose interfaces yet. After the file is written, ask the user: “Which of these would you like to explore?”
3. Grilling loop
Once the user picks a candidate, load the doc-probe skill and use it to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. (If doc-probe isn’t available, ask the same questions yourself in rounds, each with your recommended answer, and wait for the answers before the next round.)
Things that come up along the way. Do not create or edit GLOSSARY.md or any ADR yourself. These are files in a shared repo, so ask first, and say which file and what the first entry would be:
- Naming a deepened module after a concept not in the glossary, or sharpening a fuzzy term? Say so and offer to add it to
GLOSSARY.md. If the file doesn’t exist, offering to create it is a separate yes/no for the user. - User rejects the candidate with a load-bearing reason? Offer an ADR, framed as: “Want me to record this as an ADR so future architecture reviews don’t re-suggest it?” Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons (“not worth it right now”) and self-evident ones. The ADR only needs to exist if all three hold: hard to reverse, surprising without context, the result of a real trade-off.
- Want to explore alternative interfaces for the deepened module? Follow DESIGN-IT-TWICE.md. It uses parallel sub-agents; with no sub-agents, work through the three designs one after another yourself, each from a different constraint.
- Deepening a cluster given its dependencies? See DEEPENING.md: dependency categories, seam discipline, replace-don’t-layer testing.
Finish with a short summary the user can carry into a spec: the chosen candidate, the decisions made, the open questions, and the tests that would survive. Then stop. Do not start the refactor.