Repository Layout Refactor
Refactor repository structure around authoritative concept ownership. The goal
is not more folders or shorter files; it is a repository where future changes
have an obvious owner, bounded context, predictable impact, and verified
behavior.
Example: concept-owned package migration.
Repository Layout Quality Criteria
Evaluate the current and target layouts by the outcomes they enable, not by
file count, line count, or directory depth:
- Concept discoverability: A realistic change request should point to a
likely owner from package and module names without requiring a broad search.
Prefer capability names over vague names such as
manager, processor, or
helper.
- Ownership visibility: Each important concept or capability should have
one authoritative owner. Group code by meaningful ownership, not arbitrary
file type or convenient colocation.
- Change locality: A localized behavior change should remain within its
owner, direct contracts, and focused tests. Repeated edits across unrelated
modules are evidence that the boundary may be wrong.
- Context locality: An agent should be able to load the smallest useful
context for a change without reading unrelated behavior. Keep the rules,
contracts, and collaborators needed to understand one responsibility near
its owner.
- Dependency clarity: The physical structure should expose the intended
dependency direction, and actual imports should follow it. A tidy tree that
hides cycles or cross-layer shortcuts does not have a good layout.
- Evolution path: Likely new capabilities should have a predictable home
within an existing concept boundary. Avoid layouts that naturally grow
parallel managers, numbered services, or generic helper modules.
- Canonical terminology: Name internal authoritative modules and packages
with the repository's current domain terms. Keep a legacy name only at a
verified compatibility boundary; do not let a compatibility alias remain
the apparent internal owner of the canonical concept.
Treat these criteria as contextual checks, not a scorecard. A good layout makes
ownership and change impact visible; it does not merely produce more folders or
smaller files.
Layout Migration Criteria
Use these criteria to judge the migration itself. This skill implements a
resolved ownership model; it does not invent new architectural authority:
- Resolved destination ownership: Every target module or package has one
accepted responsibility and cutover condition. Use
architecture-review
first when ownership or boundary decisions remain unresolved.
- Behavior-preserving slices: Move one coherent responsibility at a time,
keep the repository working after each slice, and validate through public
behavior rather than the proposed internal tree.
- Complete consumer cutover: Update real callers, imports, registries,
bootstrap paths, generated discovery surfaces, and focused tests in the
same slice as the moved owner.
- Single active authority: Do not leave the old and new locations as
competing implementations. Delete old ownership or retain only a verified,
time-bounded compatibility surface with a retirement condition.
- Contract and dependency integrity: Preserve in-scope public APIs,
serialized shapes, import contracts, metadata, and dependency direction.
Do not hide new cycles behind dynamic imports or indirection.
- Reviewable recovery: Keep each slice small enough to review, validate,
and reverse without discarding unrelated work. Record baseline failures and
distinguish them from migration regressions.
A migration is incomplete when it only adds the target tree, re-exports the old
monolith, or postpones consumer cutover and cleanup indefinitely.
When To Use
Use this skill when:
- a working repository has broad modules with several independent reasons to
change
- one file or directory has become the default edit point for unrelated work
- concept ownership is ambiguous or scattered across layers
- common changes require loading or touching unrelated behavior
- source or test layout no longer exposes clear capability boundaries
- the user asks to implement a behavior-preserving package or module refactor
When Not To Use
Do not use this skill for:
- splitting a file only because it crosses a line-count threshold
- adding folder depth without a clearer owner or change boundary
- formatting, naming cleanup, or a narrow bug fix
- greenfield architecture design without an existing behavior baseline
- a read-only ownership or boundary assessment; use
architecture-review
- a standalone future-agent navigation audit; use
agent-legibility-review
- a broad rewrite that intentionally changes product behavior
If the user asks only for evaluation or a plan, complete discovery and target
design but do not edit code.
Inputs To Infer Or Request
Infer from repository evidence when possible:
- requested repository and scope
- local instructions and protected or generated areas
- current branch, revision, and working-tree state
- public APIs, import surfaces, schemas, migrations, serialized shapes, events,
and other contracts
- test, lint, type-check, build, and packaging commands
- current concepts, owners, consumers, and hotspot modules
Stop or narrow the task when the target behavior, public contract, ownership
authority, or allowed mutation scope cannot be established safely from local
evidence and the user's request.
Evidence Hierarchy
Use this order when sources conflict:
- User's latest explicit scope and behavior requirements.
- Local repository instructions and protected-surface rules.
- Actual code paths, callers, schemas, migrations, runtime wiring, and public
interfaces.
- Passing tests and reproducible runtime behavior.
- Architecture docs, ADRs, specifications, examples, and comments.
- Naming, line count, directory depth, and architectural inference.
Do not let a target tree, style preference, or line-count goal outrank observed
behavior and real consumers.
Workflow
1. Establish The Baseline
- Read repository instructions and inspect the worktree before editing.
- Map the current package tree, entrypoints, public contracts, tests, generated
areas, persistence registration, and runtime/bootstrap imports relevant to the
scope.
- Run focused baseline tests and record pre-existing failures.
- Treat large files, flat layout, and repeated edits as investigation signals,
not conclusions.
2. Build The Ownership Map
For each hotspot, record:
- concepts and capabilities it currently owns
- independent reasons it changes
- authoritative rules and lifecycle decisions
- callers, consumers, side effects, and validation anchors
- whether responsibility is cohesive or only colocated
Use architecture-review when ownership or boundary decisions are unresolved.
Use agent-legibility-review when the key question is whether future agents can
discover the owner, relevant context, hidden rules, or impact surface.
3. Design The Target Ownership
Define a target package tree and ownership matrix. Each proposed module or
package must have:
- one primary concept or capability owner
- a name aligned with the repository's canonical domain term, with any legacy
public alias isolated at an explicit compatibility boundary
- a clear reason to change
- explicit inbound and outbound dependencies
- contract-preservation requirements
- a cutover and deletion condition
- focused validation
Preserve the existing top-level architecture unless evidence supports changing
it. Prefer concept-owned packages inside established layers over a big-bang
architectural rewrite.
Reject a target layout when it merely:
- splits by arbitrary line ranges
- produces
service1.py, service2.py, or similarly meaningless names
- introduces generic
utils.py, common.py, or helpers.py dumping grounds
- adds re-exports or facades while the old monolith remains the real owner
- creates many shallow modules with hidden shared state
4. Plan Vertical Migration Slices
Sequence work by concept or capability, not by file type:
- Freeze the public behavior and import contract for the slice.
- Move one coherent responsibility and its tests or validation anchors.
- Cut real consumers over.
- Remove old ownership.
- Run focused validation.
Each slice must be reviewable, reversible, and leave the repository in a
working state. Use prd-to-issues when the user wants a durable,
dependency-aware implementation issue set.
5. Migrate Green-To-Green
Use the tdd Behavior-Preserving Refactor Mode:
- add characterization tests only for material behavior that lacks coverage
- move one responsibility at a time
- test through public behavior, not the proposed internal layout
- update imports, registries, bootstrap paths, and generated discovery surfaces
together
- remove the old implementation before starting the next slice
- preserve compatibility only for verified public consumers or rollout
constraints, with a retirement condition
Do not maintain duplicate implementations as a safety strategy.
6. Complete The Cutover
Verify that:
- the old hotspot is deleted or materially reduced to a justified stable facade
- every moved concept has one authoritative owner
- dead imports, obsolete tests, temporary adapters, and unused exports are
removed
- tests are organized around public capabilities rather than private module
layout
- documentation and navigation entrypoints point to the new owner when needed
- internal imports and ownership names use the canonical term while retained
compatibility aliases remain visibly boundary-only
7. Validate The Repository
Run the strongest checks available for the changed surface:
- focused tests after each slice
- full relevant test suite
- lint, formatting, type checking, build, and packaging checks
- import-cycle or dependency-boundary checks
- API/OpenAPI, serialization, schema, migration discovery, or metadata checks
when those contracts are in scope
- repository diff checks
Report skipped, unavailable, or inconclusive checks. Do not claim improved
maintainability, speed, token use, or model accuracy without measurements.
Validation Requirements
Before claiming completion:
- behavior is preserved at the public interface
- baseline failures are distinguished from new failures
- the old owner no longer contains duplicate active behavior
- the target ownership map matches the implementation
- representative changes have an obvious owner and bounded context
- the physical structure exposes dependency direction and predictable extension
points
- no generic dumping ground or unjustified wrapper was introduced
- focused and full available checks pass
- the final diff contains real cutover and cleanup, not only new facades
Output Contract
Report:
- scope and baseline state
- current and target ownership maps
- migration slices completed
- old files or ownership removed
- public contracts intentionally preserved
- exact validation commands and results
- remaining debt, skipped checks, and unresolved risks
Side-Effect Policy
Default and maximum normal level: git-working-tree.
- User intent to refactor or implement authorizes scoped working-tree edits.
- A review-only or planning request remains read-only.
- Do not stage, commit, push, create branches, or publish without explicit user
instruction or an already established repository workflow.
- Preserve unrelated user changes and avoid destructive Git operations.
- Use the diff and validation output as the normal post-edit review surface.
Failure Modes
- Baseline tests fail: record the existing failure, narrow validation where
possible, and do not claim the refactor caused or fixed it without evidence.
- Public contract is unclear: pause that slice or preserve the current
surface until real consumers and repository guidance establish authority.
- Target layout adds indirection without ownership: reject or redesign it.
- Circular dependencies appear: move the boundary or extract a true
contract owner; do not hide the cycle behind dynamic imports.
- Compatibility cannot be retired: identify the real consumer and record a
bounded transition instead of leaving an unowned wrapper.
- The task requires behavior change: separate that change from the
behavior-preserving refactor and obtain the appropriate product decision or
test contract.
1---2name: repository-layout-refactor3description: Refactor a working repository from broad, weakly owned modules into concept-owned packages and localized change surfaces while preserving behavior. Use when large or flat modules contain multiple independent responsibilities, agents repeatedly edit the same hotspots, ownership is ambiguous, or the user asks to redesign and implement the source or test layout. Do not use for LOC-only cleanup, formatting, a narrow bug, a greenfield package layout, or a read-only architecture review.4---56# Repository Layout Refactor78Refactor repository structure around authoritative concept ownership. The goal9is not more folders or shorter files; it is a repository where future changes10have an obvious owner, bounded context, predictable impact, and verified11behavior.1213Example: [concept-owned package migration](examples/concept-owned-package-migration.md).1415## Repository Layout Quality Criteria1617Evaluate the current and target layouts by the outcomes they enable, not by18file count, line count, or directory depth:19201. **Concept discoverability:** A realistic change request should point to a21 likely owner from package and module names without requiring a broad search.22 Prefer capability names over vague names such as `manager`, `processor`, or23 `helper`.242. **Ownership visibility:** Each important concept or capability should have25 one authoritative owner. Group code by meaningful ownership, not arbitrary26 file type or convenient colocation.273. **Change locality:** A localized behavior change should remain within its28 owner, direct contracts, and focused tests. Repeated edits across unrelated29 modules are evidence that the boundary may be wrong.304. **Context locality:** An agent should be able to load the smallest useful31 context for a change without reading unrelated behavior. Keep the rules,32 contracts, and collaborators needed to understand one responsibility near33 its owner.345. **Dependency clarity:** The physical structure should expose the intended35 dependency direction, and actual imports should follow it. A tidy tree that36 hides cycles or cross-layer shortcuts does not have a good layout.376. **Evolution path:** Likely new capabilities should have a predictable home38 within an existing concept boundary. Avoid layouts that naturally grow39 parallel managers, numbered services, or generic helper modules.407. **Canonical terminology:** Name internal authoritative modules and packages41 with the repository's current domain terms. Keep a legacy name only at a42 verified compatibility boundary; do not let a compatibility alias remain43 the apparent internal owner of the canonical concept.4445Treat these criteria as contextual checks, not a scorecard. A good layout makes46ownership and change impact visible; it does not merely produce more folders or47smaller files.4849## Layout Migration Criteria5051Use these criteria to judge the migration itself. This skill implements a52resolved ownership model; it does not invent new architectural authority:53541. **Resolved destination ownership:** Every target module or package has one55 accepted responsibility and cutover condition. Use `architecture-review`56 first when ownership or boundary decisions remain unresolved.572. **Behavior-preserving slices:** Move one coherent responsibility at a time,58 keep the repository working after each slice, and validate through public59 behavior rather than the proposed internal tree.603. **Complete consumer cutover:** Update real callers, imports, registries,61 bootstrap paths, generated discovery surfaces, and focused tests in the62 same slice as the moved owner.634. **Single active authority:** Do not leave the old and new locations as64 competing implementations. Delete old ownership or retain only a verified,65 time-bounded compatibility surface with a retirement condition.665. **Contract and dependency integrity:** Preserve in-scope public APIs,67 serialized shapes, import contracts, metadata, and dependency direction.68 Do not hide new cycles behind dynamic imports or indirection.696. **Reviewable recovery:** Keep each slice small enough to review, validate,70 and reverse without discarding unrelated work. Record baseline failures and71 distinguish them from migration regressions.7273A migration is incomplete when it only adds the target tree, re-exports the old74monolith, or postpones consumer cutover and cleanup indefinitely.7576## When To Use7778Use this skill when:7980- a working repository has broad modules with several independent reasons to81 change82- one file or directory has become the default edit point for unrelated work83- concept ownership is ambiguous or scattered across layers84- common changes require loading or touching unrelated behavior85- source or test layout no longer exposes clear capability boundaries86- the user asks to implement a behavior-preserving package or module refactor8788## When Not To Use8990Do not use this skill for:9192- splitting a file only because it crosses a line-count threshold93- adding folder depth without a clearer owner or change boundary94- formatting, naming cleanup, or a narrow bug fix95- greenfield architecture design without an existing behavior baseline96- a read-only ownership or boundary assessment; use `architecture-review`97- a standalone future-agent navigation audit; use `agent-legibility-review`98- a broad rewrite that intentionally changes product behavior99100If the user asks only for evaluation or a plan, complete discovery and target101design but do not edit code.102103## Inputs To Infer Or Request104105Infer from repository evidence when possible:106107- requested repository and scope108- local instructions and protected or generated areas109- current branch, revision, and working-tree state110- public APIs, import surfaces, schemas, migrations, serialized shapes, events,111 and other contracts112- test, lint, type-check, build, and packaging commands113- current concepts, owners, consumers, and hotspot modules114115Stop or narrow the task when the target behavior, public contract, ownership116authority, or allowed mutation scope cannot be established safely from local117evidence and the user's request.118119## Evidence Hierarchy120121Use this order when sources conflict:1221231. User's latest explicit scope and behavior requirements.1242. Local repository instructions and protected-surface rules.1253. Actual code paths, callers, schemas, migrations, runtime wiring, and public126 interfaces.1274. Passing tests and reproducible runtime behavior.1285. Architecture docs, ADRs, specifications, examples, and comments.1296. Naming, line count, directory depth, and architectural inference.130131Do not let a target tree, style preference, or line-count goal outrank observed132behavior and real consumers.133134## Workflow135136### 1. Establish The Baseline137138- Read repository instructions and inspect the worktree before editing.139- Map the current package tree, entrypoints, public contracts, tests, generated140 areas, persistence registration, and runtime/bootstrap imports relevant to the141 scope.142- Run focused baseline tests and record pre-existing failures.143- Treat large files, flat layout, and repeated edits as investigation signals,144 not conclusions.145146### 2. Build The Ownership Map147148For each hotspot, record:149150- concepts and capabilities it currently owns151- independent reasons it changes152- authoritative rules and lifecycle decisions153- callers, consumers, side effects, and validation anchors154- whether responsibility is cohesive or only colocated155156Use `architecture-review` when ownership or boundary decisions are unresolved.157Use `agent-legibility-review` when the key question is whether future agents can158discover the owner, relevant context, hidden rules, or impact surface.159160### 3. Design The Target Ownership161162Define a target package tree and ownership matrix. Each proposed module or163package must have:164165- one primary concept or capability owner166- a name aligned with the repository's canonical domain term, with any legacy167 public alias isolated at an explicit compatibility boundary168- a clear reason to change169- explicit inbound and outbound dependencies170- contract-preservation requirements171- a cutover and deletion condition172- focused validation173174Preserve the existing top-level architecture unless evidence supports changing175it. Prefer concept-owned packages inside established layers over a big-bang176architectural rewrite.177178Reject a target layout when it merely:179180- splits by arbitrary line ranges181- produces `service1.py`, `service2.py`, or similarly meaningless names182- introduces generic `utils.py`, `common.py`, or `helpers.py` dumping grounds183- adds re-exports or facades while the old monolith remains the real owner184- creates many shallow modules with hidden shared state185186### 4. Plan Vertical Migration Slices187188Sequence work by concept or capability, not by file type:1891901. Freeze the public behavior and import contract for the slice.1912. Move one coherent responsibility and its tests or validation anchors.1923. Cut real consumers over.1934. Remove old ownership.1945. Run focused validation.195196Each slice must be reviewable, reversible, and leave the repository in a197working state. Use `prd-to-issues` when the user wants a durable,198dependency-aware implementation issue set.199200### 5. Migrate Green-To-Green201202Use the `tdd` Behavior-Preserving Refactor Mode:203204- add characterization tests only for material behavior that lacks coverage205- move one responsibility at a time206- test through public behavior, not the proposed internal layout207- update imports, registries, bootstrap paths, and generated discovery surfaces208 together209- remove the old implementation before starting the next slice210- preserve compatibility only for verified public consumers or rollout211 constraints, with a retirement condition212213Do not maintain duplicate implementations as a safety strategy.214215### 6. Complete The Cutover216217Verify that:218219- the old hotspot is deleted or materially reduced to a justified stable facade220- every moved concept has one authoritative owner221- dead imports, obsolete tests, temporary adapters, and unused exports are222 removed223- tests are organized around public capabilities rather than private module224 layout225- documentation and navigation entrypoints point to the new owner when needed226- internal imports and ownership names use the canonical term while retained227 compatibility aliases remain visibly boundary-only228229### 7. Validate The Repository230231Run the strongest checks available for the changed surface:232233- focused tests after each slice234- full relevant test suite235- lint, formatting, type checking, build, and packaging checks236- import-cycle or dependency-boundary checks237- API/OpenAPI, serialization, schema, migration discovery, or metadata checks238 when those contracts are in scope239- repository diff checks240241Report skipped, unavailable, or inconclusive checks. Do not claim improved242maintainability, speed, token use, or model accuracy without measurements.243244## Validation Requirements245246Before claiming completion:247248- behavior is preserved at the public interface249- baseline failures are distinguished from new failures250- the old owner no longer contains duplicate active behavior251- the target ownership map matches the implementation252- representative changes have an obvious owner and bounded context253- the physical structure exposes dependency direction and predictable extension254 points255- no generic dumping ground or unjustified wrapper was introduced256- focused and full available checks pass257- the final diff contains real cutover and cleanup, not only new facades258259## Output Contract260261Report:2622631. scope and baseline state2642. current and target ownership maps2653. migration slices completed2664. old files or ownership removed2675. public contracts intentionally preserved2686. exact validation commands and results2697. remaining debt, skipped checks, and unresolved risks270271## Side-Effect Policy272273Default and maximum normal level: `git-working-tree`.274275- User intent to refactor or implement authorizes scoped working-tree edits.276- A review-only or planning request remains read-only.277- Do not stage, commit, push, create branches, or publish without explicit user278 instruction or an already established repository workflow.279- Preserve unrelated user changes and avoid destructive Git operations.280- Use the diff and validation output as the normal post-edit review surface.281282## Failure Modes283284- **Baseline tests fail:** record the existing failure, narrow validation where285 possible, and do not claim the refactor caused or fixed it without evidence.286- **Public contract is unclear:** pause that slice or preserve the current287 surface until real consumers and repository guidance establish authority.288- **Target layout adds indirection without ownership:** reject or redesign it.289- **Circular dependencies appear:** move the boundary or extract a true290 contract owner; do not hide the cycle behind dynamic imports.291- **Compatibility cannot be retired:** identify the real consumer and record a292 bounded transition instead of leaving an unowned wrapper.293- **The task requires behavior change:** separate that change from the294 behavior-preserving refactor and obtain the appropriate product decision or295 test contract.