Harden Architecture
ASecurityRuns wave-based architectural hardening of a live codebase by lifting duplicated logic into shared primitives, giving each state machine a single typed owner, separating a pure functional core from an imperative shell, fixing concurrency and lifecycle races, and locking every invariant with property and chaos tests, TLA+ model checking, Lean 4 proofs over exported tables, and CI ratchets. Use when asked to reduce architectural entropy, harden or deduplicate a codebase, make state machines exp...
- 92 stars
- 0 votes
- 0 copies
- 3 views
- Added December 1, 2026
Works with
Security analysis
100/100Pro scans all 7 files and shows the line behind each finding
npx -y skills add existential-birds/beagle --skill harden-architecture --agent claude-codeAre you the author of Harden Architecture?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/existential-birds-harden-architecture)---
name: harden-architecture
description: Runs wave-based architectural hardening of a live codebase by lifting duplicated logic into shared primitives, giving each state machine a single typed owner, separating a pure functional core from an imperative shell, fixing concurrency and lifecycle races, and locking every invariant with property and chaos tests, TLA+ model checking, Lean 4 proofs over exported tables, and CI ratchets. Use when asked to reduce architectural entropy, harden or deduplicate a codebase, make state machines explicit, systematically fix race conditions or stuck UI states, add formal verification or CI ratchets, safely delete dead code, or speed up tests and CI without changing product behavior. Operates at repository scale over multiple waves and is not meant for a single refactoring or a diff review.
---
# Architectural Hardening
Reduce architectural entropy in a live codebase through small, closed, verified waves: one canonical owner or shared primitive per wave, every caller migrated, the replaced path deleted, and the resulting invariant locked by a machine check. This skill edits code. Working product behavior and external contracts stay intact unless a change is recorded as a confirmed bug fix or a sign-off item.
## When to Use
- "Reduce the architectural entropy in this repo." / "Harden this codebase."
- "Make the order/job/session state machine explicit and give it one owner."
- "We keep fixing the same race in different places; fix it at the root."
- "Add TLA+, Lean, property tests, or CI ratchets for our critical flows."
- "Delete dead code and speed up the test suite without breaking anything."
Use a narrower skill when the request is narrower:
- Survey a repository and file issues without editing code: `refactor-repo` ([../refactor-repo/SKILL.md](../refactor-repo/SKILL.md)).
- Review a branch diff for structural quality: `review-structure` ([../review-structure/SKILL.md](../review-structure/SKILL.md)).
- Mechanics of one named refactoring: `fowler-refactoring` ([../fowler-refactoring/SKILL.md](../fowler-refactoring/SKILL.md)).
## Authorization and Setup
Loading this skill is not an instruction to start editing. All four gates pass before the first edit:
| Gate | Pass condition |
|------|----------------|
| **A1 Scope** | The request names the repository and, optionally, subsystems, a budget, and a deliverable. Missing pieces take these defaults: whole repository ranked by live user impact; no budget, so the run ends at convergence as defined under the wave loop; commits on local branches. Push or open pull requests only when the user asked for them. |
| **A2 Isolation** | After `git fetch origin`, work happens in a dedicated worktree cut from the remote default branch (`git worktree add --no-track -b hardening/<slug> ../<repo>-hardening origin/<default-branch>`) or the host's equivalent isolated workspace. `<slug>` is a short kebab-case name for the campaign, such as `orders-state`. The user's checkout is never modified. |
| **A3 Baseline** | The repository's own verification commands (from its contributor docs and CI config) ran on the untouched branch. Commands, pass/fail counts, and wall-clock are recorded. Pre-existing failures are listed, never hidden by weakening a check. **Green**, everywhere below, means every check passes, including checks a wave adds, except the failures listed here. |
| **A4 Repository rules** | The repository's contributor and agent instruction files were read. They take precedence over this skill. |
## Target Architecture
Design the architecture the product would have if it started today with full knowledge of its real requirements, edge cases, and production constraints, then converge toward it. Persisted rows, queued work, deployed clients, and rolling deploys are part of those requirements. Work on live, user-facing code first: confirm a subsystem is live (routes, feature flags, decision records, usage evidence) before investing in it, and rank live user flows, hot APIs, shared UI and domain primitives, and core infrastructure above dormant features.
Eight properties define the target. Detection steps, remedies, traps, and per-stack mappings are in [references/engineering-properties.md](references/engineering-properties.md).
1. **Explicit state machines, single owners, stronger typing.** Every persisted status column and every multi-step client or async flow has one owner module holding its transition table or total pure reducer. Coupled boolean flags become one closed state type with exhaustive matching, so illegal states cannot be constructed.
2. **Functional core, imperative shell.** Transitions, rules, planners, eligibility matrices, recovery logic, and codecs are pure functions with time, randomness, and configuration passed in. Handlers, workers, and components read inputs, call the core, and perform effects at the edge.
3. **DRY through shared primitives.** When siblings repeat the same loader, lifecycle, persistence, retry, or state-machine code, lift one typed primitive, migrate every caller, and delete the copies. Apply the deletion test to every layer: *if this were deleted, would complexity disappear or spread to callers?* Keep only layers where it would spread.
4. **One source of truth, generated downstream.** Each enum, error code, transition table, limit, and API contract is defined once. Other copies are generated from it and CI fails on drift.
5. **Deep modules and locality of change.** Small interfaces hide real complexity. One domain rule changes in one logical module. No import cycles and no hidden module-level mutable state.
6. **Concurrency and lifecycle safety.** Server writes use compare-and-swap that checks rows affected, atomic single-statement updates, idempotency keys, and post-commit effects gated on a real transition. Clients guard every async result with a generation token plus cancellation and tear down every timer and listener.
7. **Enforceable architecture.** Each invariant a wave establishes gets a CI ratchet in that same wave. Prose guidelines do not count.
8. **Evidence over confidence.** Characterization tests pin behavior before risky edits. Deletions follow verified zero usage, not names or comments.
For stack conventions, also load the matching entry-point review skill when installed: `review-python`, `review-frontend`, `review-go`, `review-rust`, `review-elixir`, or `review-ios`.
## Cheapest Sufficient Proof
Lock each invariant with the lowest rung that fully discharges it. A higher rung does not excuse skipping a lower one that applies.
| Invariant | Mechanism |
|-----------|-----------|
| An illegal combination of states | Closed state type plus exhaustive matching |
| A property of a small finite table or decision matrix | Exhaustive enumeration test in the repository's language. Use a Lean 4 `decide` proof over the exported table when the repository already builds Lean, the user asked for machine-checked proofs, or the theorem set is clearer as declarative statements than as test loops |
| An algebraic law over a large or unbounded input space | Property-based test |
| An interleaving: races, retries, duplicate or out-of-order events, leases, recovery | A deterministic schedule test against the real code when the interleavings can be enumerated. A TLA+ spec checked by TLC with paired fixed and buggy configs when they cannot, plus an implementation test for each buggy trace that a test can reproduce |
| Messy boundaries and UI lifecycles | Chaos simulation against the real reducer or store |
Do not formalize trivial CRUD, and never keep a model that is not wired to production code. Introducing a toolchain the repository lacks (a JVM for TLC, Lean) is a maintenance cost: record it as a sign-off item and keep it on its own branch and pull request.
- TLA+ and Lean rules, verified examples, CI runners, and exit-code semantics: [references/formal-verification.md](references/formal-verification.md).
- Invariant catalog, chaos matrix, and the checkable definition of "no user stuck": [references/property-chaos-testing.md](references/property-chaos-testing.md).
## Backlog Phases
Phases order the backlog. They are not separate passes: every wave in every phase runs the full loop, and the proof and ratchet for an invariant land in the wave that establishes it.
- **Phase 0, map before editing.** Write the architecture map: live versus dormant subsystems ranked by user impact; every persisted state column and every file that writes it; duplicated flows and coupled-boolean ladders; server concurrency and data-integrity hotspots; client lifecycle and stuck-UI hotspots; test and CI bottlenecks. Template in [references/log-and-report-templates.md](references/log-and-report-templates.md).
- **Phase 1, shared primitives, state ownership, concurrency.** Lift the primitives that collapse the most duplicated code. Route every stateful write through its owner with transition validation and compare-and-swap. Fix effect ordering and clock handling at the root.
- **Phase 2, pure UI reducers and typed contracts.** Replace component-level boolean ladders with pure, total view reducers (`deriveXState`, `resolveXView`) covered by property tests. Make error, empty, and offline states impossible to mask with loading. Derive sibling views from one reducer. Remove hand-copied enums and weak types.
- **Phase 3, formalize the highest-risk flows.** Add TLA+ specs for the riskiest concurrent and recovery flows, table proofs where finite tables exist, and any ratchet still missing.
- **Phase 4, delete dead code and speed up tests and CI.** Delete code with verified zero usage. Cut wall-clock with fake time, sharding, caching, and removal of duplicate passes. Rules in [references/ci-ratchets.md](references/ci-ratchets.md).
Pull a Phase 4 speed fix forward when slow verification is what limits wave throughput.
## Wave Loop
Once the setup gates pass, work autonomously wave after wave without pausing for confirmation between waves. One root cause per wave. Advance only when the pass condition is met by an artifact: command output, a search result, or a file on disk.
| Step | Action | Pass condition |
|------|--------|----------------|
| 1. Select | Take the highest-impact live target from the map | Target, owner module, and expected invariant are written in the log |
| 2. Verify reality | Check callers, contracts, flags, dynamic references, and live usage, read-only | Search patterns and results are recorded. Unknown liveness is treated as live for deletion |
| 3. Pin | Add characterization tests for the behavior about to move | Tests pass on unchanged code, and each fails when the pinned behavior is deliberately broken |
| 4. Build | Create the canonical owner, shared primitive, pure core, or fix | Typecheck and new unit tests pass |
| 5. Migrate and delete | Move every caller and delete the replaced path | A search for the old entry point returns zero hits. The exception is a compatibility reader that persisted rows, queued payloads, or deployed clients still need: each is listed in the wave record with its removal condition |
| 6. Lock | Add the proof or property test and the CI ratchet | The negative check fails for the named reason: the buggy config violates its named invariant, or the ratchet rejects a seeded violation. A check that needs a CI workflow change is recorded as lock pending sign-off |
| 7. Commit and verify | Commit the wave with a Conventional Commit message, then run the repository's full verification plus TLC, Lean, and ratchets | Green. Every command, count, and timing is recorded. Anything not run is stated |
| 8. Cold review | Run the adversarial review below on the wave's commit range | Findings are written in `[FILE:LINE] ISSUE_TITLE` form |
| 9. Fix | Verify each finding, fix confirmed ones in follow-up commits, repeat the step 7 verification | Green. Rejected findings carry a reason |
| 10. Log | Complete the wave record and the decisions log | The wave is fully migrated and its record has no empty field |
A wave that cannot finish is parked: commit it to a side branch, return the hardening branch to the last completed wave, and record it with the reason in the sign-off bucket of the decisions log. Never leave the hardening branch half-migrated, and never run `git clean` in the worktree, because the working logs are untracked.
Stop at convergence, meaning every backlog row ranked high impact is either completed or recorded in the sign-off bucket (parked waves included). Stop earlier when a budget the user set is spent or when the baseline verification cannot run at all. Report at every stop.
## Cold Adversarial Review
Each wave is attacked by a reviewer with no attachment to the edits. **If the agent supports subagents or fresh sessions**, dispatch one read-only reviewer that receives the diff range, the invariants the wave claims, and the five lenses, and does not receive the author's reasoning. **Otherwise** re-read the diff from disk in a separate pass and state in the report that the review was not independent.
The five lenses: concurrency, locking, and performance; external boundaries, types, and clocks; UI stuck states and lifecycle; formal spec honesty; DRY, legibility, and restraint. The reviewer brief, per-lens questions, and output format are in [references/adversarial-review.md](references/adversarial-review.md).
Verify every finding against the code before acting on it, using the `review-verification-protocol` skill ([../review-verification-protocol/SKILL.md](../review-verification-protocol/SKILL.md)). Reviewers produce false positives.
## Guardrails
- **Restraint.** Do not over-abstract, rename or move directories without reducing complexity, trade legibility for line count, or merge concepts that look alike but differ in domain meaning.
- **No weakened checks.** Never bypass hooks, skip or delete a failing test, lower a threshold, or grow a ratchet baseline to get green.
- **Transparent behavior deltas.** Keep `decisions-and-risks.md` with three buckets: confirmed bugs fixed (root cause plus regression test or proof); behavior-preserving structural cleanups; ambiguous product changes and deferred items needing human sign-off. Record bucket-three items and keep moving on independent waves.
- **Sign-off classes.** Authentication, billing, data deletion or retention, CI workflow definitions, production migrations, and public contract changes may be authored, but each goes on its own branch cut from the hardening branch and in its own pull request, flagged, and is never merged by the agent.
- **Locks that need CI changes.** A ratchet that runs inside an existing CI command lands with its wave. One that needs a workflow change is authored on the CI sign-off branch, runs locally in step 7 meanwhile, and is reported as lock pending sign-off.
- **No merging by default.** Do not merge, deploy, or run migrations against shared environments unless the user explicitly authorized that action.
- **No fabricated verification.** Report exact commands and exact counts (tests, theorems, TLC configs with distinct states, ratchet baselines, timings). State plainly what could not be run.
- **Reviewable units.** One wave per commit or short commit series. Keep behavior-preserving waves, confirmed bug fixes, and each sign-off class on separate branches so structural changes are not blocked behind sign-off items.
## Reporting
Close every run, including early stops, with a report built from the templates in [references/log-and-report-templates.md](references/log-and-report-templates.md). When no pull request carries the decisions log, append it to the report in full, because the working files are untracked.
```markdown
## Hardening Report: <repo> @ <branch>
Waves completed: <n> | Stop reason: <converged | budget spent | baseline cannot run>
| Wave | Target | Kind | Net production LOC | Lock | Review |
|------|--------|------|--------------------|------|--------|
| 1 | order status owner | structural | -212 | state-writes ratchet (baseline 0), 14 property tests | independent, 2 confirmed, fixed |
### Verification
| Command | Result | Wall-clock |
|---------|--------|------------|
| <exact command> | <exact counts> | <seconds> |
### Needs human sign-off
- <item, why it is ambiguous or high risk, where the change lives>
### Not run
- <command or check, and why>
```
## Supporting Files
Load on demand by reading the relative path.
- [references/engineering-properties.md](references/engineering-properties.md): the eight properties with detection, remedies, traps, and per-stack mappings.
- [references/formal-verification.md](references/formal-verification.md): TLA+ and Lean 4 rules, verified examples, CI runner, toolchain pinning.
- [references/property-chaos-testing.md](references/property-chaos-testing.md): invariant catalog, chaos matrix, determinism rules, "no user stuck" properties.
- [references/ci-ratchets.md](references/ci-ratchets.md): ratchet mechanics, the standard ratchets, model-sync check, test and CI speed rules.
- [references/adversarial-review.md](references/adversarial-review.md): cold reviewer brief, five lenses, finding format, triage.
- [references/log-and-report-templates.md](references/log-and-report-templates.md): architecture map, decisions log, wave record, pull request description.
Files in this skill
- SKILL.md
- references/adversarial-review.md
- references/ci-ratchets.md
- references/engineering-properties.md
- references/formal-verification.md
- references/log-and-report-templates.md
- references/property-chaos-testing.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.