# AI-Optimized Code Quality: Universal Style and Architecture Guide
> Universal style and architecture guide for codebases built and maintained with AI.
## Why this guide exists
Software maintained with AI has an unusual continuity problem. A small human
team—or one owner—may direct many capable sessions, but no individual session
holds the whole system in memory, and the next maintainer may arrive without the
reasoning that shaped the last change. The codebase therefore has to carry more
of its own understanding.
The goal is the smallest practical blast radius: each responsibility should be
understandable, changeable, testable, and able to fail without pulling unrelated
work into the same reading set or failure path. That does not mean maximizing
file count or abstraction. Split where ownership, state authority, runtime, or
lifecycle genuinely changes; keep cohesive behavior together. Parallel work
should meet through narrow supported contracts, not shared implicit state.
Context efficiency protects understanding, not merely token budgets. A
maintainer should be able to load the smallest *complete* set of code needed to
reason correctly about a change—including its owner, promises, consumers,
failure behavior, and proof—without reconstructing the application around it.
Clarity and beauty matter because code is a working environment for future
maintainers. Pleasant code is not ornamental: its names tell the truth, its
boundaries match reality, and its important reasons remain recoverable. The
rules below turn that aspiration into operational safety: local failures, honest
authority, predictable dependencies, durable knowledge, and changes that can
proceed in parallel without quietly endangering their neighbors.
## Canonical scope
This file is the single authored universal standard for the AI-Optimized Code
Quality add-on. It defines project-independent architecture and working rules.
Project-specific paths, frameworks, runtime details, thresholds, and accepted
exceptions belong in a project overlay. Installed, generated, website, or agent
copies are derived views; they must not become competing authored sources.
**Every project gets its own overlay, named `style-guide.<project>.md`.**
One overlay per project, fitted to that project's real architecture — not a
generic copy of this file with the nouns swapped. It lives in the project's own
docs directory (`config/docs/style-guide.valo.md`,
`docs/style-guide.chonkler.md`) and the project's `CLAUDE.md` links to it.
An overlay that could apply to any project is not an overlay; delete it.
This first version is intentionally one readable Markdown file. Add schemas,
language profiles, or generators only when a real consumer requires them.
### How to route through this guide
For a focused task, read Canonical scope, Core principles, the Shared
vocabulary definitions the task uses, the linked section, and the relevant
Completion checklist block. Follow other sections only when the change crosses
their boundary.
| Task | Start here |
|---|---|
| Add a module or capability | [Module ownership](#3-module-ownership-and-isolation), [supported entrypoints](#4-supported-entrypoints-and-public-contracts), [dependencies](#5-dependency-direction) |
| Connect modules or features | [Cross-module and cross-feature communication](#6-cross-module-and-cross-feature-communication), [composition points](#8-composition-and-integration-points) |
| Change state or persistence | [State and data authority](#7-authority-models-for-state-and-data) |
| Cross a process, service, worker, or plugin boundary | [Runtime boundaries](#9-runtime-boundaries) |
| Refactor or review code shape | [Context-efficient code shape](#10-context-efficient-code-shape), [comments and scars](#11-comments-decisions-and-scars) |
| Work beside other sessions | [Parallel-session ownership](#12-parallel-session-ownership) |
| Prove a change | [Tests and evidence](#13-tests-and-evidence) |
| Touch an older codebase | [Incremental legacy adoption](#14-incremental-legacy-adoption) |
### Strength of the language
- **Required** means a universal invariant. A project may document a narrow
exception, but must record why and how risk is contained.
- **Preferred** means the default when no local constraint points elsewhere.
- **Signal** means inspect and use judgment. A signal is not an automatic
violation.
This guide governs architecture and maintainability. Project formatters,
linters, and language conventions govern mechanical syntax.
---
## 1. Core principles
1. **Ownership before organization.** Every behavior, state, persisted shape,
and integration has an identifiable owner. A folder helps routing; it does
not create ownership.
2. **Boundaries before file counts.** Architecture is the shape of
responsibilities, dependencies, state, and runtime crossings. File length
is only a signal that those things may be hard to see.
3. **Direct inside, intentional across.** Prefer direct calls within one
ownership boundary. Cross a module, data-owner, or runtime boundary through
an intentionally supported access path with maintained promises. This does
not by itself require an interface, wrapper, or separate file.
4. **Context efficiency.** Minimize the unrelated context needed for a correct
change, not the number of files. Keep responsibilities local, contracts easy
to find, dependency direction predictable, and always-loaded instructions
lean.
5. **Why over what.** Code usually reveals what it does, but not why a
constraint exists or an obvious approach was rejected. Preserve that reason
close to the decision.
6. **Scars over architecture narration.** Working structure can be recovered
from code. Failed approaches, dangerous assumptions, incidents, and
non-obvious constraints cannot. Record those scars instead of retelling the
file tree.
7. **Evidence over confidence.** Match proof to risk: behavior tests for owned
logic, contract tests for public surfaces, runtime validation at boundaries,
and integration evidence where wiring matters.
8. **Ratchet, do not renovate by accident.** New modules follow every
applicable rule. Touched legacy code must not introduce or worsen
violations. Unchanged legacy debt stays quiet. Ordinary work does not become
repository-wide cleanup.
---
## 2. Shared vocabulary
### Capability
A user-facing or domain concern, such as search, billing, messaging, or import.
A capability may span several modules and runtimes.
### Module
An independently changeable ownership unit with one coherent responsibility.
A module is a design boundary, not necessarily a package, class, or single
folder.
For example, one capability might contain separate core, UI, worker, and
contract modules because those parts run in different places and change for
different reasons.
### Supported entrypoint
The official front door that code outside a module is allowed to use. The
module owner intentionally promises to maintain it, so a maintainer can enter
without depending on internal file layout.
Make that intent recoverable through a package export, explicit module note,
established naming convention, project rule, or contract evidence. Technical
reachability alone does not make a path supported.
A supported entrypoint may be:
- an explicitly supported leaf file or function;
- a package export;
- a small `public` or `index` module;
- a service object;
- a command or query interface.
Everything else is internal even if the language technically allows it to be
imported. A barrel file is one possible front door, never a universal
requirement.
### Public contract
The promises outside consumers may rely on through a supported entrypoint:
accepted inputs, returned outputs, behavior, errors, ordering, lifecycle, and
compatibility. "Public" means public to other modules, not necessarily public
on the internet.
A message, event, schema, or protocol is also a public contract when it crosses
an ownership or runtime boundary.
### Adapter
A small translator between different models, runtimes, vendors, or protocols.
Adapters keep outside details from spreading into owned behavior. They may be
valuable even when short or used by only one consumer.
### Composition point
The deliberate place where modules are wired together. An application entry
file, dependency builder, route table, plugin registry, or startup coordinator
can be a composition point.
### Runtime boundary
A crossing where compile-time assumptions no longer guarantee the value that
arrives: another process, service, worker, thread, plugin, storage layer, or
untrusted input.
### Authority model and authoritative writer
An authority model defines who may write mutable state, within which scope, and
how ordering, conflicts, convergence, and recovery work. The preferred model is
one authoritative writer allowed to decide the current value at a given
lifecycle stage.
Intentional multi-writer systems are valid when their write scopes and
convergence rules are explicit. Copies must never become competing writers by
accident.
---
## 3. Module ownership and isolation
### 3.1 Make ownership recoverable
For every new module, a maintainer must be able to recover:
- its stable name and one-sentence responsibility;
- the files or path roots it owns;
- its runtime zone;
- its supported entrypoints;
- the state, storage, schemas, and authority model it owns;
- the modules it may depend on;
- where it is composed or registered;
- the tests or other evidence that protect its contract.
This information may be obvious from structure plus a short module note or
project map. A machine-readable manifest is not required by this version.
### 3.2 One coherent reason to change
A module owns behavior that changes for the same product or domain reason.
Split when responsibilities have different owners, lifecycles, runtime
requirements, dependency directions, or test strategies.
Do not split only to satisfy a counter. Do not merge only because two pieces
currently change together.
### 3.3 Feature folders are routing aids
Colocating related code is preferred when it reduces navigation. A feature
folder alone does not create isolation. Isolation exists only when:
- responsibility is clear;
- outside code uses supported contracts;
- dependency direction is respected;
- state and data authority is explicit;
- internals can change without unrelated consumers changing.
A capability that crosses runtimes will often need several runtime-local
modules rather than one giant cross-runtime feature folder.
### 3.4 Consumer count is evidence, not a verdict
One consumer does not automatically mean two files should merge. Keep a small
contract, adapter, schema, or boundary module when it protects:
- ownership;
- lifecycle or runtime separation;
- translation from an external model;
- independent testing;
- a stable contract around volatile internals;
- parallel-edit isolation.
Merging is appropriate when the pieces have no independent boundary, are
always understood and changed as one unit, and separation adds navigation
without reducing blast radius.
### 3.5 Shared code needs shared meaning
Move code into a shared module only when it represents a shared domain concept
or stable technical responsibility, and its contract is stable across
consumers. Similar-looking code in two modules is not automatically one
concept.
Small, controlled duplication is often cheaper than a premature shared
abstraction that couples unrelated owners. Revisit duplication when the shared
meaning becomes clear.
---
## 4. Supported entrypoints and public contracts
### 4.1 Give each module a deliberate front door
Outside consumers use supported entrypoints rather than reaching through the
module to convenient internal files. The front door should expose the smallest
surface that lets consumers use the capability without knowing its
implementation.
Do not confuse "exported" with "supported." Languages often expose symbols for
testing or tooling that are not promises to other modules.
### 4.2 No mandatory barrel
Use a barrel when it creates a clear, stable surface without hiding dependency
edges or causing load, cycle, or bundling problems.
Use a selective direct path when it is clearer or safer. A supported leaf path
is still a public contract if the module declares and maintains it.
### 4.3 Keep contracts low-dependency
Contracts, schemas, shared primitives, and port definitions must not import
the implementations they describe. Consumers should not have to load a UI,
database driver, process API, or vendor SDK merely to name a value or call a
capability.
Define each concept authoritatively in one place. Derived representations must
have an explicit translation or generation path rather than drifting copies.
### 4.4 Change contracts deliberately
Before changing a supported entrypoint:
1. Find its consumers.
2. Identify compatibility, migration, and runtime implications.
3. Update producer and consumer evidence.
4. Preserve compatibility or make the breaking change explicit.
5. Record a scar when the safe shape is non-obvious.
Discovering a consumer expands the review surface, not automatically the edit
surface. Modify only consumers whose contract or behavior is affected.
Contract convenience is not worth a broad, hidden blast radius.
### 4.5 Abstract for a boundary, not a fashion
Direct dependencies are preferred inside one ownership boundary.
Introduce a port, interface, adapter, or protocol when it protects a real
variation or boundary: a replaceable external service, a runtime crossing, a
test seam around expensive infrastructure, or a policy/implementation split.
Do not create one interface per function by default.
---
## 5. Dependency direction
When a project has non-trivial module boundaries, its allowed dependency
direction must be recoverable from structure, tooling, or concise project
guidance. Universal architecture cannot be reduced to a framework-specific
ladder such as Component -> Hook -> Utility -> Constant.
Regardless of the project graph, these invariants are required:
1. Composition points may import implementations to wire them together;
implementations do not import the composition point.
2. Contracts and shared primitives do not depend on implementations.
3. A module does not depend on UI, infrastructure, or vendor details unrelated
to its stated responsibility.
4. Peer modules use one another's supported entrypoints, not internals.
5. Runtime-local implementations do not leak into incompatible runtimes.
6. New cycles across module boundaries are prohibited unless a narrow
exception documents why the cycle is safe and how it is contained.
### 5.1 Make new edges intentional
When a change adds a cross-module dependency, answer:
- Which module owns the behavior?
- Why does the dependency point this way?
- Which supported entrypoint carries it?
- Does it expose internal state or runtime-specific types?
- What evidence protects the edge?
If neither side clearly owns the interaction, fix ownership before inventing a
shared helper.
### 5.2 Keep generic layers honest
Names such as `shared`, `common`, `utils`, and `core` do not grant
permission to import everything. A broadly imported module should contain
stable, dependency-light concepts with a clear owner.
High fan-in makes a module more expensive to change. Treat that as a
blast-radius signal and keep its contract deliberately small.
---
## 6. Cross-module and cross-feature communication
Choose the simplest mechanism that keeps ownership and failure behavior
honest.
| Situation | Preferred mechanism |
|---|---|
| Code inside one module | Direct call |
| Local parent/child UI | Explicit inputs and callbacks |
| Stable synchronous capability | Supported module API |
| Replaceable external implementation | Port implemented by an adapter |
| Optional or multiple consumers | Defined event contract wired at composition |
| Cross-runtime request or notification | Versioned, serializable protocol |
| Shared mutable data | Commands governed by the authority model plus read models |
| Repeated enumeration of integrations | Defined registry or descriptor source |
### 6.1 Avoid hidden coordination
Do not coordinate modules through:
- another module's internal mutable state;
- undeclared global variables;
- incidental UI or filesystem state;
- deep imports that bypass policy;
- a global event bus used as a substitute for ownership;
- duplicated lists that must stay in sync by memory.
### 6.2 Events are not the default
Use events when the producer should not know optional or multiple consumers,
and wire subscriptions at a composition point. A direct supported call is
clearer for a required synchronous dependency.
Events need named payload contracts, ownership, ordering expectations, error
behavior, and unsubscribe or teardown behavior.
### 6.3 Registries solve repeated inventory, not every integration
Create a registry when the same set of integrations is otherwise repeated
across several concerns such as startup, permissions, availability, UI, and
teardown.
Keep explicit wiring when order, readiness, or lifecycle matters. Avoid
filesystem auto-discovery or a god catalog unless the product genuinely needs
dynamic discovery.
---
## 7. Authority models for state and data
### 7.1 Prefer one authoritative writer per lifecycle stage
Every mutable value has an explicit authority model. Prefer one authoritative
writer at each lifecycle stage; authority may transfer deliberately.
When multiple writers are intentional, define their allowed scopes, ordering
or convergence rules, conflict resolution, and recovery. Other modules honor
the model through supported commands or APIs rather than mutating storage
through an accidental side door.
### 7.2 Make copies honest
A cache, replica, projection, optimistic value, or persisted copy must declare:
- its source of truth;
- who writes each copy;
- how changes propagate;
- invalidation or freshness rules;
- conflict policy;
- recovery after interruption or partial failure.
If those answers are missing, duplicated state is a latent consistency and
recovery risk. For persisted or user-authored data, it may become a data-loss
risk.
### 7.3 Keep derived state derived
Prefer computing a value from owned state over storing another independently
mutable copy. Cache only when cost or runtime constraints justify it, and keep
the invalidation path beside the cache.
### 7.4 Storage belongs to a module
The module that owns persisted data also owns:
- its schema and validation;
- migrations and compatibility;
- transaction boundaries;
- recovery and corruption behavior;
- supported queries and commands.
Other modules do not read or write its files, tables, keys, or provider records
directly merely because they are accessible.
### 7.5 Treat migration as product behavior
Persistence changes require evidence for old data, interrupted upgrades,
partial writes, and rollback or forward recovery where relevant. Validating
only the new shape does not prove existing data can survive.
---
## 8. Composition and integration points
Composition points own assembly:
- dependency wiring;
- startup order;
- registration and routing;
- readiness;
- environment selection;
- teardown.
They do not own feature policy or the internal behavior of the modules they
assemble.
### 8.1 Keep composition explicit and thin
An integration root will naturally be shared. The goal is not to eliminate
shared files; it is to make edits narrow, declarative, and easy to verify.
Prefer module-owned descriptors or small registration calls over copying
feature logic into the root. Keep order explicit when order matters.
### 8.2 One inventory, several projections
When startup, settings, permissions, navigation, and teardown all enumerate
the same integrations, define one authoritative descriptor source and derive
the views that truly share its meaning.
Do not force unrelated concerns into one registry just because their lists
look similar. A registry is an ownership tool, not a universal abstraction.
### 8.3 Prove completeness
Registries and composition points need focused evidence for:
- unique identifiers;
- required fields;
- supported combinations;
- ordering and readiness;
- registration and teardown symmetry;
- a minimal composition smoke path.
---
## 9. Runtime boundaries
Static checks, when present, do not validate values that arrive at runtime.
Values crossing a process, service, worker, thread, plugin, persistence, or
untrusted-input boundary require a runtime contract.
### 9.1 Boundary contract
At a runtime boundary:
- send plain, serializable data rather than framework or runtime objects;
- use named, discriminated messages or operations;
- version contracts when producer and consumer can drift;
- validate at ingress before translating into internal models;
- recognize every supported variant and reject unknown variants explicitly;
- define errors, timeouts, cancellation, retry, and idempotency where relevant;
- define startup readiness and teardown behavior;
- enforce authorization and trust assumptions at the receiving boundary.
The adapter at the boundary translates between the transport shape and the
module's owned model. Transport details should not spread through owned
behavior.
### 9.2 Share contracts, not implementations
Code shared across runtimes must use only APIs available in every target
runtime. Runtime-specific implementations stay on their side of the boundary.
A shared contract definition is useful, but it does not replace runtime
validation. Test serialized examples, malformed input, version skew, and
failure responses.
### 9.3 Make lifecycle failures visible
Cross-runtime behavior must fail loudly enough to diagnose. Distinguish not
ready, unavailable, timed out, rejected, and malformed from successful empty
results.
Retry only operations that are safe to repeat, or give them an idempotency
mechanism.
### 9.4 Freeze asynchronous ownership
Work that can outlive the call, request, view, process, or owner that started it
must carry an immutable operation identity and the ownership scope captured at
admission. A late completion validates that identity before it mutates state or
publishes a result; it never consults mutable "current" state to rediscover who
owns the work.
Every spawned task, worker, helper, or process has a lifecycle owner and a death
contract: readiness, cancellation, teardown, descendant cleanup, and the narrow
conditions under which it may intentionally outlive its owner. Lost ownership is
a failure state, not permission for work to continue indefinitely.
### 9.5 Bound runtime work and queues
Responsiveness is part of correctness for interactive and coordinating runtimes.
Potentially large scans, parsing, hashing, rendering, publication, and recovery
work require explicit bounds, scheduling, or isolation appropriate to their cost.
Queues define concurrency, backpressure, cancellation, and overload behavior.
A clean startup or fast unit test does not prove sustained behavior. When a
change affects a hot path, shared coordinator, or long-running process, evidence
should cover realistic duration, data growth, and concurrent activity.
### 9.6 Define perceived readiness and progressive activation
For a user transition that can activate several expensive surfaces, define the
smallest complete surface that makes the action feel finished and make that the
first readiness boundary. “Complete” includes everything the user understands as
one surface; do not split core content from its status, controls, or activity and
call a partial projection ready.
Defer independent secondary work until after that boundary, then admit it in a
bounded order instead of starting every eligible load, renderer, worker, or
provider simultaneously. Existing or discoverable data does not by itself
authorize eager activation. Each deferred unit keeps an exact owner, cancellation
path, and retirement condition, and progressive activation must not weaken durable
availability or make settled UI flicker.
When several readiness orders are technically valid but materially change the
human experience, ask the owner which surface matters first before implementing.
Do not ask when the product contract or measured user flow already makes the order
clear. Instrument the transition before deferring work so the optimization removes
proven pre-readiness cost rather than merely moving latency out of sight.
---
## 10. Context-efficient code shape
### 10.1 Optimize for the smallest correct reading set
A change should usually require:
- the owning module;
- the supported contracts it touches;
- the relevant composition point;
- focused evidence.
If every change requires reading a root file, global type catalog, shared state
bag, and several unrelated features, the boundaries are not doing enough work.
### 10.2 Prefer predictable local shape
Within a project, use a consistent top-to-bottom order for similar files.
Make inputs, outputs, state, side effects, and public operations easy to find.
Keep names domain-specific and make ownership visible in paths.
Colocate code, tests, schemas, and narrowly owned styles or fixtures when they
change together. Move them apart when runtime or ownership boundaries require
it.
### 10.3 File length is a signal, not architecture
Review a growing file for:
- multiple unrelated reasons to change;
- more than one state or data owner;
- mixed runtime or policy boundaries;
- unrelated callers needing different slices;
- high parallel-edit collision;
- navigation that requires loading most of the file.
Split at a real responsibility or boundary. Do not split by arbitrary line
ranges, and do not interrupt ordinary work solely because a file crossed a
number.
Projects may define advisory review thresholds. Those thresholds trigger
inspection, not automatic guilt or a mandatory repo-wide refactor.
### 10.4 Small files can be strong boundaries
A tiny contract, adapter, validator, schema, or registration descriptor may
carry substantial architectural value. File size and consumer count do not
measure that value.
Conversely, many tiny files that have no independent responsibility and must
always be loaded together can waste context. Merge them when no boundary would
be lost.
### 10.5 Add navigation when it earns its tokens
Use descriptive headings, section markers, diagrams, or short file summaries
when structure is genuinely hard to recover from names. Do not require
headers, tables of contents, or diagrams at universal numeric thresholds.
Preserve useful navigation aids during edits. Remove stale navigation that
lies about the code.
### 10.6 Keep instructions progressively disclosed
Always-loaded project instructions contain only rules needed for nearly every
task and links to deeper guidance. Module notes, scars, and specialized
workflows live near their triggers and are loaded on demand.
Do not copy the same rule into several prompts or documents and expect manual
sync to preserve it.
### 10.7 Make working knowledge directly navigable
For an important boundary, a maintainer should be able to move from the owning
code to its supported contract, focused evidence, and relevant scar without
searching the whole repository or trusting remembered prose. Use stable links,
trigger metadata, module notes, generated maps, or another project-appropriate
mechanism; no single format is required.
Authored code, contracts, and deliberate scars remain authoritative. Generated
indexes and maps are projections: verify or regenerate them rather than letting
them become competing explanations of the system.
---
## 11. Comments, decisions, and scars
### 11.1 Comment the missing reason
Keep comments that explain:
- why a constraint exists;
- why order or timing matters;
- why an apparently simpler approach is unsafe;
- which external behavior or consumer limits a change;
- what failed before and under which conditions;
- where the authoritative deeper record lives.
Remove comments that merely translate a clear statement into English.
Useful prefixes are optional but scannable: `Why:`, `Invariant:`,
`Workaround:`, `Security:`, and `Compatibility:`.
### 11.2 Put scars where they can prevent repetition
A useful scar records:
1. the tempting approach;
2. the failure or cost it caused;
3. the condition that triggers the danger;
4. the safe alternative or evidence needed to revisit it.
Keep a short warning at the decision point and link to a longer incident,
concept page, or decision record when history matters. Do not paste the full
incident into every consumer.
### 11.3 Keep comments executable in spirit
Where possible, protect a scar with a test, validation rule, type, or runtime
assertion. A comment explains the reason; evidence prevents silent regression.
Update or remove a scar when the constraint is genuinely gone. Permanent fear
without a current trigger is not knowledge.
---
## 12. Parallel-session ownership
Parallel work succeeds when ownership is explicit before edits begin.
### 12.1 Claim change surfaces
Before working:
- inspect the current tree and existing changes;
- name the module, paths, contracts, and composition points the session owns;
- identify shared files another session may also need;
- assign one writer for each shared contract or integration point;
- agree on a supported contract before parallel implementations diverge.
Ownership is temporary coordination, not permanent territory.
### 12.2 Preserve other sessions' work
During the change:
- edit only owned paths unless coordination expands the scope;
- do not revert, reformat, move, or "clean up" unfamiliar changes;
- avoid broad mechanical rewrites in a shared working tree;
- keep commits coherent and limited to owned files;
- stop and coordinate when two sessions need incompatible contract changes.
Version-control convenience never justifies absorbing another session's work
into an unrelated commit.
### 12.3 Design for additive integration
Prefer modules that can be built and tested behind stable contracts, then
connected through a narrow composition edit. Registrations should be small and
data-like where lifecycle permits.
A common sequence is:
1. One owner defines or changes the contract.
2. Parallel sessions implement separate owned modules against it.
3. One integration owner wires the composition point.
4. The combined graph and runtime path are verified.
Composition roots will still be shared. Low blast radius means shared edits are
small and intentional, not that shared files never exist.
### 12.4 Do not abstract solely to avoid a merge conflict
Parallelism can justify a stable seam, but not an artificial architecture.
Temporary controlled duplication may be safer than forcing unrelated work
through a premature global helper.
---
## 13. Tests and evidence
Evidence follows behavior and boundaries, not file count.
| Risk or boundary | Useful evidence |
|---|---|
| Owned deterministic behavior | Focused unit or property tests |
| Supported module entrypoint | Public contract tests |
| Runtime message or untrusted input | Validation and malformed-input tests |
| Registry or descriptor inventory | Completeness and uniqueness tests |
| Composition point | Startup or composition smoke test |
| State synchronization or cache | Invalidation, ordering, and recovery tests |
| Persistence change | Migration and compatibility tests |
| External adapter | Contract fixtures and controlled integration tests |
| Legacy extraction | Characterization tests before movement |
| Dependency rule | Architecture graph or import-boundary check |
### 13.1 Prove the important seam
Tests should protect behavior consumers rely on, not mirror private
implementation line by line. A test per file is not required.
When a public contract changes, test both producer behavior and the affected
consumer path. When wiring changes, unit tests alone are insufficient.
### 13.2 Report evidence honestly
Distinguish:
- passed;
- failed;
- not run;
- unavailable;
- not applicable.
An unavailable check is not a pass. If full verification is disproportionate
or impossible, run the safest focused evidence and state the remaining risk.
### 13.3 Review the blast radius
Before completion:
- inspect all consumers of changed supported contracts, while editing only
those whose contract or behavior is affected;
- verify new dependency edges point in the declared direction;
- verify authority models and runtime validation remain intact;
- check the final integrated diff, not only each isolated edit;
- preserve or add scars for non-obvious failure modes.
---
## 14. Incremental legacy adoption
Adopt this standard as a ratchet: touched architecture moves forward without
making every feature task pay for the whole repository's history.
### 14.1 Classify the scope
| Scope | Required treatment |
|---|---|
| New module | Follow every applicable rule in the standard |
| Touched existing module | Apply the standard to changed behavior and new edges; do not introduce or worsen violations |
| Unchanged legacy code | Keep existing debt quiet |
| Dedicated migration | Select and improve one explicit boundary |
A new module is a newly declared ownership unit, not merely a new file or
folder. Moving old code does not launder it into "new compliant code."
### 14.2 Define touched legacy narrowly
Touched scope includes:
- changed behavior and hunks;
- affected symbols;
- supported contracts and consumers affected by the change;
- new or changed dependency edges;
- files required to compile, migrate, and prove the change.
It does not automatically include the whole folder, capability, or repository.
### 14.3 Prevent review and pipeline scope explosion
For ordinary work:
- report and fix newly introduced violations;
- report and fix worsened violations in the touched seam;
- recognize resolved debt without demanding adjacent cleanup;
- omit unchanged legacy findings, or summarize them without investigation;
- do not refresh a debt baseline to make a new violation disappear;
- do not turn suggestions in untouched files into required work.
A directly observed critical security, corruption, or data-loss risk may be
reported separately. That report does not authorize a broad cleanup.
### 14.4 Adjacent cleanup has a stop rule
Adjacent cleanup is optional. It must stay inside the verified touched seam and
is safe only when it:
- stays within the same ownership boundary;
- preserves public contracts, persisted data, runtime protocols, and user
behavior;
- is independently understandable and revertible;
- does not require broader coordination or verification;
- fits the task's explicit cleanup budget.
If any condition fails, defer it to a dedicated migration. Explicitly expand
scope when cleanup adds files, contracts, coordination, or verification beyond
the task. Outside the touched seam, the default cleanup budget is zero.
### 14.5 Migrate one boundary at a time
Choose legacy migrations by risk, not descending file length. Strong signals
include:
- frequent edits or merge collisions;
- high fan-in or fan-out;
- mixed ownership or runtime responsibilities;
- incident and scar history;
- an available characterization seam;
- a boundary whose extraction unlocks safer future work.
A focused migration should characterize current behavior, extract one
responsibility, establish its supported contract, update dependency rules, and
prove the new seam. Do not perform folder-wide makeovers under a feature
commit.
### 14.6 Document exceptions honestly
An architectural exception records:
- the rule and exact scope;
- the constraint or rationale;
- the risk and mitigation;
- the allowed change, if bounded;
- the event or version that should trigger review.
Exceptions are not permission to spread the pattern. Existing debt, accepted
exceptions, and newly introduced violations are three different things.
---
## 15. Completion checklist
Use this short pass before declaring a meaningful change complete:
### Ownership and boundaries
- [ ] The owning module and responsibility are clear.
- [ ] Outside consumers use a supported entrypoint.
- [ ] New dependency edges point in the declared direction.
- [ ] Cross-module communication uses the simplest honest mechanism.
### State and runtime
- [ ] Mutable state and persisted data have an explicit authority model.
- [ ] Copies define synchronization, invalidation, conflicts, and recovery.
- [ ] Runtime crossings use serializable, validated contracts.
- [ ] Delayed work preserves immutable ownership and rejects replaced owners.
- [ ] Spawned work has bounded scheduling and an explicit death contract.
- [ ] Composition code wires behavior without absorbing feature policy.
### Maintainability
- [ ] The change can be understood from a small, relevant reading set.
- [ ] File splits or merges follow responsibility, not counts.
- [ ] Comments preserve reasons and scars rather than narrating code.
- [ ] Important boundaries link directly to their contracts, evidence, and scars.
- [ ] Parallel-session ownership and shared integration edits are explicit.
### Evidence and scope
- [ ] Evidence matches the changed behavior and boundaries.
- [ ] Unavailable or skipped checks are reported honestly.
- [ ] New and worsened violations are handled.
- [ ] Unchanged legacy debt did not expand the task.
The goal is not maximal abstraction or perfect uniformity. The goal is a
codebase where the next correct change is local, understandable, provable, and
unlikely to break unrelated work.