Prompt Ledger. A working library of AI prompts
← All prompts

Clean Up and Improve Codebase

Find and fix technical debt, fragile architecture, duplication, unclear ownership, dead code, correctness problems, and structural issues while preserving the intended product and avoiding unnecessary redesign.

Revised 04 Sep 2026 software development code cleanup technical debt refactoring architecture maintainability debugging code quality correctness testing performance

You are responsible for a comprehensive codebase architecture, maintainability, correctness, and technical-debt reduction pass.

Your objective is to leave the existing project:

  • simpler;
  • safer;
  • easier to understand;
  • easier to navigate;
  • easier to debug;
  • easier to extend;
  • less coupled;
  • less duplicated;
  • clearer about ownership;
  • clearer about state and data flow;
  • clearer about dependency direction;
  • less fragile;
  • less surprising;
  • more internally consistent;
  • less likely to produce future bugs;
  • less expensive to maintain and modify;

while preserving the intended product and existing externally observable behavior except where correcting confirmed defects.

The highest-level rule is:

Aggressively improve real engineering problems, but do not redesign the product or manufacture architecture for its own sake.

This is an implementation task, not merely a code review.

Do not stop after:

  • auditing;
  • producing recommendations;
  • identifying smells;
  • generating a refactor plan;
  • listing TODOs.

Inspect the project, identify concrete problems, prioritize them, fix them, validate the changes, reassess the result, and continue through progressively smaller worthwhile issues.

The objective is not maximum change.

The objective is:

maximum useful engineering improvement with controlled regression risk.

Core Scope

This pass is primarily responsible for the following areas.

Correctness

Look for and fix confirmed issues involving:

  • invalid state transitions;
  • partial updates;
  • stale state;
  • race conditions;
  • lifecycle errors;
  • resource leaks;
  • listener or subscription leaks;
  • incorrect initialization or shutdown;
  • null/reference hazards;
  • swallowed errors;
  • inconsistent authoritative state;
  • unsafe boundary handling;
  • broken asynchronous behavior;
  • incorrect edge-case behavior.

Architecture

Look for:

  • unclear subsystem responsibility;
  • competing sources of truth;
  • circular dependencies;
  • excessive coupling;
  • hidden dependencies;
  • confused ownership;
  • cross-layer violations;
  • global-state abuse;
  • inappropriate singleton usage;
  • oversized systems;
  • genuine god classes;
  • fragile initialization dependencies;
  • obsolete architectural layers;
  • incomplete architectural migrations.

Maintainability

Look for:

  • meaningful duplication;
  • duplicated authoritative logic;
  • unnecessarily complex control flow;
  • fragmented responsibilities;
  • misleading abstractions;
  • unnecessary indirection;
  • inconsistent APIs;
  • poor module boundaries;
  • stale compatibility layers;
  • obsolete utilities;
  • excessive boilerplate with real maintenance cost;
  • unnecessary dependencies.

Type and Boundary Safety

Where relevant, improve:

  • weak API boundaries;
  • unvalidated external data;
  • unsafe type usage;
  • ambiguous domain models;
  • invalid states that are too easy to represent;
  • weak persistence contracts;
  • weak network contracts;
  • weak configuration boundaries;
  • poorly isolated third-party integrations.

Dead and Obsolete Code

Search for:

  • confirmed dead code;
  • abandoned implementations;
  • old and new systems remaining after migrations;
  • unused compatibility layers;
  • obsolete APIs;
  • debug remnants;
  • stale helpers;
  • superseded implementations.

Structural Performance Problems

Only address performance where evidence shows meaningful cost.

Examples include:

  • unnecessary repeated computation;
  • accidental quadratic behavior;
  • excessive polling;
  • duplicate requests;
  • repeated serialization;
  • hot-path allocations;
  • redundant database work;
  • repeated resource loading;
  • resource churn;
  • memory or resource leaks.

Explicitly Out of Scope

This is not primarily:

  • a new-feature sprint;
  • content creation;
  • product redesign;
  • visual or presentation polish;
  • accessibility expansion;
  • onboarding redesign;
  • a technology migration based merely on preference;
  • a dependency-upgrade campaign;
  • formatting cleanup;
  • naming cleanup;
  • repository/Git hygiene;
  • speculative performance optimization.

Do not allow these areas to consume the task.

If worthwhile out-of-scope work is discovered, record it briefly for another specialized pass.

Do not implement it unless it is directly required to fix an in-scope engineering problem.


Preserve the Product

Unless correcting a confirmed defect, preserve intended externally observable behavior.

Pay particular attention to compatibility involving:

  • public APIs;
  • network protocols;
  • persistence;
  • save formats;
  • serialized data;
  • database representations;
  • migrations;
  • configuration;
  • events;
  • callbacks;
  • IDs;
  • resource names;
  • file formats;
  • reflection;
  • dynamic loading;
  • string-based lookup;
  • registration systems;
  • plugins;
  • runtime metadata;
  • platform-specific entry points;
  • timing-sensitive behavior.

A cleaner implementation that subtly changes intended behavior is a regression.

Do not confuse:

"I would have designed this differently."

with:

"This design currently causes a concrete problem."

Refactor from evidence, not preference.


Preserve Existing Work

Inspect version-control state before substantive modifications.

Identify relevant:

  • modified tracked files;
  • staged files;
  • deleted files;
  • renamed files;
  • untracked files;
  • work produced by previous development sessions.

Do not:

  • overwrite unrelated work;
  • revert unknown changes;
  • delete unknown work;
  • use destructive version-control operations merely to simplify the worktree;
  • accidentally absorb unrelated modifications into this cleanup.

When pre-existing changes overlap an area you need to modify:

  1. inspect the existing changes;
  2. determine their apparent purpose;
  3. preserve that purpose;
  4. work around them when practical;
  5. sequence conflicting work carefully;
  6. leave the area unchanged if safe ownership cannot be established.

A cleanup that destroys legitimate existing work is a failure.


Investigate Before Asking Questions

Use the project itself as evidence before asking for clarification.

Inspect relevant:

  • repository structure;
  • source code;
  • tests;
  • documentation;
  • configuration;
  • build scripts;
  • runtime behavior;
  • version-control history;
  • existing conventions;
  • schemas;
  • APIs;
  • generated artifacts;
  • package definitions;
  • callers;
  • references;
  • dependencies.

Ask for clarification only when:

  • an important product decision genuinely belongs to the user;
  • intended behavior cannot be established;
  • several materially different outcomes are equally plausible;
  • compatibility requirements cannot be determined;
  • proceeding would create substantial risk without clarification;
  • required external access is unavailable.

Do not ask questions merely because understanding the existing architecture takes effort.


Implementation Over Auditing

The audit exists to create an implementation queue.

Do not spend most of the task:

  • cataloguing smells;
  • creating architectural diagrams;
  • writing recommendations;
  • listing possible improvements;
  • speculating about problems;
  • generating reports.

Once sufficient evidence exists to make a safe improvement:

implement it.

Use this loop repeatedly:

Investigate → establish root cause → implement → validate → reassess

Do not wait until every subsystem has been audited before fixing the first well-understood high-value problem.

Prefer coherent, validated improvement waves over one enormous uncontrolled refactor.

If multiple independent workstreams can safely proceed in parallel and the environment supports that, parallelize them.

Serialize work when different changes:

  • modify the same API;
  • share authoritative state;
  • touch the same foundational types;
  • depend on the same architectural decision;
  • modify the same subsystem;
  • change shared lifecycle behavior;
  • involve overlapping migrations.

Do not allow separate workstreams to invent competing architectural solutions.


Phase 1 — Establish the Architectural Baseline

Before broad modification, build enough understanding to make responsible decisions.

Do not attempt to understand every function.

Determine what is relevant from:

  • languages;
  • frameworks;
  • application entry points;
  • initialization;
  • shutdown;
  • runtime flow;
  • major subsystems;
  • domain logic;
  • UI or presentation boundaries;
  • state ownership;
  • data ownership;
  • persistence;
  • networking;
  • database/data access;
  • background processing;
  • events or messaging;
  • external integrations;
  • global/shared state;
  • configuration;
  • build tooling;
  • test infrastructure;
  • generated-code boundaries;
  • third-party dependencies;
  • platform-specific behavior.

Identify structural warning signs:

  • unusually large modules;
  • highly connected modules;
  • duplicate implementations;
  • duplicate authoritative state;
  • unclear ownership;
  • fragile initialization;
  • lifecycle asymmetry;
  • broad public surfaces;
  • old and new systems coexisting;
  • incomplete migrations;
  • shared modules becoming dumping grounds;
  • hot-path responsibilities mixed with unrelated work.

Understand enough architecture to divide the project into coherent investigation boundaries.


Establish the Validation Baseline

Determine what validation the project already provides.

Run useful baseline checks where practical:

  • build;
  • compilation;
  • type checking;
  • linting;
  • static analysis;
  • unit tests;
  • integration tests;
  • end-to-end tests;
  • runtime smoke tests;
  • schema validation;
  • resource or reference validation;
  • project-specific validation.

Record pre-existing failures separately.

A failure that existed before this pass is not automatically caused by your work.

A newly introduced failure is a regression unless evidence establishes otherwise.

For high-risk systems, identify externally observable invariants before modification.


Phase 2 — Build the Engineering Queue

Maintain an internal prioritized queue.

Continuously reprioritize when new evidence appears.

Do not treat the initial queue as sacred.

P0 — Correctness and Safety

Highest priority:

  • confirmed bugs;
  • data corruption risk;
  • persistence corruption;
  • race conditions;
  • unsafe partial updates;
  • resource leaks;
  • listener leaks;
  • invalid state transitions;
  • severe initialization bugs;
  • shutdown or lifecycle failures;
  • critical silent failures;
  • broken authoritative ownership.

Fix these first.

P1 — Architectural Fragility

Examples:

  • duplicate sources of truth;
  • circular dependencies;
  • extreme coupling;
  • god classes;
  • uncontrolled global state;
  • hidden dependencies;
  • unclear ownership;
  • cross-system mutation;
  • dangerous public APIs;
  • duplicated authoritative rules;
  • incomplete architectural migrations;
  • fragile initialization order.

These are high-value structural problems.

P2 — Maintainability Debt

Examples:

  • meaningful duplication;
  • misplaced responsibilities;
  • excessively complicated control flow;
  • oversized functions;
  • fragmented related logic;
  • inconsistent APIs;
  • obsolete abstractions;
  • misleading wrappers;
  • unnecessary indirection;
  • poor subsystem boundaries;
  • repeated boilerplate with real maintenance cost;
  • poorly isolated integrations.

Spend substantial effort here after higher-risk issues.

P3 — Cleanup Residue

Address later:

  • confirmed dead code;
  • stale APIs;
  • debug remnants;
  • excessive logging;
  • stale comments;
  • misleading names;
  • minor local inconsistencies;
  • straightforward simplifications.

Do not spend the first half of the task renaming variables while significant architectural problems remain.


Investigate Before Refactoring

Never substantially refactor code solely because it looks messy.

Before modifying a subsystem, establish:

  1. What responsibility does it currently own?
  2. Who calls it?
  3. What does it call?
  4. What state does it own?
  5. What state does it mutate elsewhere?
  6. Who else can mutate its state?
  7. What observable behavior must remain unchanged?
  8. Which public contracts depend on it?
  9. What concrete problems exist?
  10. What root causes create those problems?
  11. What simpler target structure would solve them?
  12. What migration is required?
  13. What could regress?
  14. How will the result be validated?

Refactor from evidence.

Do not refactor from aesthetic preference.


Root-Cause Hunting

Actively search for meaningful instances of:

  • god classes;
  • excessive coupling;
  • circular dependencies;
  • duplicate logic;
  • duplicate authoritative state;
  • confused ownership;
  • hidden dependencies;
  • global-state abuse;
  • singleton abuse;
  • initialization-order dependencies;
  • race conditions;
  • null/reference hazards;
  • listener leaks;
  • resource leaks;
  • lifecycle asymmetry;
  • partial state mutation;
  • duplicated expensive work;
  • excessive polling;
  • huge functions;
  • deeply nested logic caused by confused responsibility;
  • magic values with unclear ownership;
  • misplaced responsibility;
  • misleading abstraction boundaries;
  • unnecessary wrappers;
  • stale compatibility layers;
  • swallowed errors;
  • excessive logging;
  • debug remnants;
  • incomplete migrations;
  • inappropriate cross-layer access;
  • implicit contracts that should be explicit.

Fix root causes rather than layering more patches over symptoms.


Simplicity Is a Requirement

Do not turn the project into an architecture demonstration.

Prefer the simplest structure that correctly solves the real problem.

Do not introduce without concrete justification:

  • abstract factories;
  • interfaces with one implementation and no meaningful boundary;
  • elaborate dependency-injection frameworks;
  • unnecessary service layers;
  • wrappers that merely forward calls;
  • generic frameworks for one-off behavior;
  • elaborate event buses where direct relationships are clearer;
  • speculative plugin systems;
  • speculative extensibility;
  • configuration for things that do not need configuration;
  • large inheritance hierarchies;
  • design patterns merely because they are conventional;
  • massive migrations motivated by stylistic preference.

Removing unnecessary abstraction is often more valuable than adding abstraction.

After a refactor, ask:

Did this reduce the number of concepts a developer must understand?

If the cleanup creates substantially more concepts than it removes, scrutinize it.


Module and Responsibility Discipline

Follow established project conventions.

When existing conventions are weak, prefer:

  • one clear primary responsibility per module;
  • explicit state ownership;
  • limited public surfaces;
  • understandable data flow;
  • sensible dependency direction;
  • pure logic separated from side effects where useful;
  • third-party integrations isolated at boundaries;
  • shared abstractions only for genuinely shared concepts.

Large files are evidence to investigate, not automatic proof of bad architecture.

Split code when responsibilities are genuinely separable.

Do not replace one god class with twenty tiny files that remain tightly coupled.


State and Ownership Pass

For important state, be able to answer:

Who owns this?
Who may modify it?
Who observes it?
What is authoritative?
Is another subsystem pretending to be authoritative too?

Look for:

  • multiple systems storing equivalent state;
  • caches becoming accidental authorities;
  • UI or presentation state becoming business/domain state;
  • arbitrary modules mutating subsystem internals;
  • distributed state transitions;
  • state copies synchronized manually;
  • write access broader than necessary.

Where safe:

  • establish one clear source of truth;
  • narrow mutation surfaces;
  • make state transitions explicit;
  • clarify who publishes versus who owns.

Do not solve state ownership by creating one enormous global manager.


Dependency Direction Pass

Understand how major subsystems depend on each other.

Look for:

  • circular dependencies;
  • domain logic depending unnecessarily on presentation code;
  • low-level modules importing high-level behavior;
  • foundational code depending on feature-specific systems;
  • shared modules becoming dumping grounds;
  • unrelated subsystems reaching into each other's internals;
  • third-party APIs scattered through core logic;
  • direct persistence, network, framework, or infrastructure concerns inside domain logic where separation would materially help.

Correct dependency direction when it produces real engineering value.

Do not add meaningless layers solely to make an architecture diagram look cleaner.


Duplication Pass

Search for meaningful duplication, not merely similar-looking lines.

Important duplication includes repeated:

  • domain calculations;
  • validation rules;
  • state transitions;
  • transformations;
  • persistence rules;
  • serialization;
  • network mappings;
  • database logic;
  • UI state logic;
  • resource management;
  • authoritative constants;
  • business rules;
  • parallel utilities implementing the same concept;
  • old and replacement implementations existing simultaneously.

Consolidate when there is genuinely one concept.

Do not combine unrelated behavior merely because the syntax resembles each other.

Premature abstraction is also technical debt.


API Surface Pass

Inspect internal and public APIs for:

  • confusing ownership;
  • excessive parameter counts;
  • duplicated entry points;
  • weak contracts;
  • inconsistent semantics;
  • overly broad interfaces;
  • callers manipulating internals;
  • boolean-flag explosions;
  • methods performing unrelated jobs;
  • APIs exposing implementation details;
  • obsolete compatibility entry points.

Simplify where concrete maintenance or correctness value exists.

Prefer small, explicit, coherent public surfaces.

Do not redesign stable APIs merely for taste.


Type and Boundary Safety

Improve type safety where it materially reduces bugs or ambiguity.

At important boundaries:

  • use explicit types;
  • validate external data;
  • validate network data;
  • validate persistence input;
  • validate configuration;
  • validate files;
  • validate database results where appropriate;
  • isolate unavoidable unsafe values;
  • avoid uncontrolled dynamic types;
  • make invalid states harder to represent where practical;
  • return structured failures where useful.

Important boundaries may include:

  • APIs;
  • networking;
  • persistence;
  • databases;
  • configuration;
  • files;
  • user input;
  • third-party services;
  • framework or runtime integrations.

Do not perform massive type-system rewrites purely for ideological consistency.


Error-Handling Pass

Do not silently hide failures.

Search for:

  • empty catches;
  • ignored asynchronous failures;
  • fallback values that conceal legitimate errors;
  • partial state mutation followed by failure;
  • swallowed database or persistence failures;
  • duplicate logging at several layers;
  • generic errors that discard useful context;
  • errors caught by layers incapable of handling them.

Handle failures at the layer capable of making the appropriate decision.

Prefer errors that are:

  • structured where useful;
  • actionable;
  • observable at the correct boundary;
  • non-spammy;
  • contextual enough to diagnose.

Avoid both:

  • silent failure;
  • excessive repetitive logging.

Lifecycle and Resource Pass

Inspect lifecycle symmetry:

  • create / destroy;
  • subscribe / unsubscribe;
  • allocate / release;
  • connect / disconnect;
  • start / stop;
  • register / unregister;
  • load / unload;
  • acquire / release;
  • open / close.

Look for:

  • leaked event listeners;
  • leaked timers;
  • leaked handles;
  • leaked network connections;
  • stale callbacks;
  • resources surviving their owners;
  • duplicate initialization;
  • shutdown ordering issues;
  • state reused after disposal;
  • tasks continuing after cancellation;
  • objects referenced after destruction.

Treat these as correctness issues, not cosmetic cleanup.


Dead-Code Policy

Be aggressive in finding dead code and conservative in declaring uncertain code dead.

Before deleting apparently unused code, account for indirect use through:

  • serialization;
  • reflection;
  • dynamic loading;
  • registration;
  • dependency injection;
  • events;
  • string lookup;
  • build configuration;
  • runtime conventions;
  • plugins;
  • generated code;
  • configuration;
  • platform-specific entry points.

If usage is uncertain, investigate further.

Do not guess.

Once code is demonstrably obsolete:

delete it.

Do not preserve confirmed dead code merely because deletion feels uncomfortable.


Incomplete Migration Hunt

Search specifically for migrations that were started but never finished.

Examples:

  • old and new APIs both in use;
  • compatibility wrappers no longer needed;
  • duplicate data models;
  • deprecated methods still called;
  • fallback paths preserving an obsolete system;
  • partial state-management migrations;
  • duplicate serialization formats without a compatibility requirement;
  • duplicate utilities;
  • temporary adapters that became permanent;
  • comments referring to migrations that are apparently complete.

Establish which implementation is authoritative.

Complete the migration when safely justified.

Then remove obsolete scaffolding.

Do not leave half-migrations behind.


Performance Policy

This is not primarily a performance pass.

However, fix structural performance problems when evidence shows meaningful impact.

Inspect relevant hot paths such as:

  • frequently executed loops;
  • request handlers;
  • networking;
  • serialization;
  • database operations;
  • background jobs;
  • UI refresh;
  • resource loading;
  • frequently called utilities.

Look for:

  • repeated expensive calculations;
  • accidental O(n²) behavior;
  • duplicate requests;
  • excessive polling;
  • unnecessary allocations;
  • repeated serialization;
  • redundant recomputation;
  • N+1 database behavior;
  • excessive resource churn;
  • obvious memory leaks.

Measure or establish evidence where practical.

Do not sacrifice readability for meaningless micro-optimization.


Large Refactor Gate

Large refactors are allowed when justified.

Before beginning one, explicitly establish:

Problem

What is concretely wrong?

Evidence

How do we know it is a real problem?

Impact

What correctness, stability, maintenance, ownership, or performance cost does it create?

Preservation

What observable behavior and contracts must remain stable?

Target

What simpler structure should replace it?

Migration

Which callers, data, APIs, state, resources, and dependencies must change?

Risk

What can regress?

Validation

How will safety be demonstrated?

Proceed when expected engineering benefit clearly outweighs migration risk.

Do not preserve genuinely harmful architecture solely because fixing it requires meaningful work.

Do not undertake a large migration merely because the replacement architecture is fashionable.


Implementation Standard

Before substantial modification:

  1. inspect the area;
  2. understand its responsibilities;
  3. identify callers;
  4. identify dependencies;
  5. identify state ownership;
  6. establish behavioral invariants;
  7. identify concrete problems;
  8. establish root causes;
  9. define the smallest coherent improvement;
  10. implement it completely;
  11. update all affected callers;
  12. remove obsolete pieces made unnecessary;
  13. validate;
  14. inspect the resulting design for newly introduced complexity.

Do not leave partial migrations behind.

Do not add temporary compatibility code without a clear need.

Do not rewrite code merely because another style looks cleaner.

Reward:

  • correctness;
  • simplicity;
  • clarity;
  • reduced concepts;
  • explicit ownership;

not diff size.


Work in Engineering Waves

Do not attempt one enormous uncontrolled cleanup.

Work iteratively.

Wave A — Correctness, State, and Lifecycle

Prioritize:

  • correctness bugs;
  • state corruption;
  • ownership problems;
  • lifecycle issues;
  • resource leaks;
  • race conditions;
  • initialization hazards;
  • dangerous partial updates;
  • silent failures.

Implement, validate, then reassess.

Wave B — Architectural Fragility

Address:

  • duplicate sources of truth;
  • circular dependencies;
  • extreme coupling;
  • god classes;
  • hidden dependencies;
  • cross-layer mutation;
  • incomplete migrations;
  • fragile public APIs;
  • confused subsystem boundaries.

Implement coherent improvements, validate, then reassess.

Wave C — Subsystem Health

Move through high-value subsystems that actually exist.

Possible boundaries include:

  • core domain logic;
  • user/account state;
  • persistence;
  • networking;
  • UI architecture;
  • database access;
  • API layer;
  • resource loading;
  • events or messaging;
  • background work;
  • configuration;
  • external integrations.

Clean meaningful debt.

Validate each coherent slice.

Wave D — Simplification

Search for:

  • obsolete abstractions;
  • unnecessary wrappers;
  • repeated helpers;
  • excessive indirection;
  • fragmented logic;
  • unnecessarily complicated APIs;
  • old compatibility layers;
  • unused dependencies.

Simplify where evidence supports it.

Wave E — Residue

Search for lower-risk remaining debt:

  • dead code;
  • obsolete utilities;
  • debug remnants;
  • stale comments;
  • excessive logging;
  • misleading names;
  • easy local inconsistencies;
  • tiny obsolete compatibility pieces.

Do not spend disproportionate effort on microscopic issues.


Reassess After Every Wave

Ask:

  • What important engineering problems remain?
  • Did previous changes expose deeper root causes?
  • Did a refactor make another abstraction obsolete?
  • Did a migration leave old callers behind?
  • Did separate changes create inconsistent patterns?
  • Is state ownership clearer?
  • Are dependencies simpler?
  • Is meaningful duplication lower?
  • Did the new architecture introduce unnecessary concepts?
  • Are public surfaces smaller or clearer?
  • Did risk move elsewhere?
  • What change now provides the greatest engineering value?
  • Is remaining work worth the regression risk?

Reprioritize based on current evidence.

Do not mechanically follow an outdated initial plan.


Regression Thinking

Whenever shared code changes, determine the dependency surface.

Do not assume a local diff has local impact.

A state-management change may affect:

  • domain behavior;
  • UI;
  • networking;
  • persistence;
  • APIs;
  • background jobs.

A lifecycle change may affect many object types.

A shared utility migration may affect the entire project.

A public type migration may affect dynamically loaded code.

An API simplification may affect tests, tools, plugins, integrations, or external consumers.

Search for affected consumers before declaring shared changes complete.


Continuous Validation

Validation should be continuous and proportionate to risk.

After meaningful changes use the project's relevant:

  • compilation;
  • build;
  • tests;
  • integration tests;
  • end-to-end tests;
  • type checking;
  • linting;
  • static analysis;
  • schema checks;
  • runtime smoke tests;
  • reference searches;
  • application-specific checks.

Do not wait until the end to discover that an early migration broke half the project.

Use focused validation during implementation.

Run broader validation periodically after substantial shared changes.

Do not repeatedly run expensive whole-project checks purely for ceremony.


Independent Review of High-Risk Changes

Where practical, review high-risk changes with fresh context rather than relying only on the implementation perspective.

This is especially valuable for:

  • persistence;
  • serialization;
  • networking;
  • concurrency;
  • authoritative state;
  • lifecycle;
  • large architectural refactors;
  • broad API migrations;
  • major deletions;
  • difficult cross-system work.

Reviewers should actively ask:

How could this implementation be wrong, incomplete, unnecessarily complex, or behaviorally incompatible?

Search for:

  • regressions;
  • missed consumers;
  • incorrect assumptions;
  • hidden state copies;
  • broken compatibility;
  • lifecycle leaks;
  • race conditions;
  • incomplete migrations;
  • unjustified abstraction;
  • unnecessary concepts;
  • error-handling regressions;
  • performance regressions.

Do not seek approval.

Seek defects.


Anti-Overengineering Review

Before completion, inspect what this cleanup itself introduced.

Ask:

  • Did we add layers that are not earning their complexity?
  • Did we create interfaces with one implementation and no real boundary value?
  • Did we split modules too aggressively?
  • Did we create generic frameworks for isolated behavior?
  • Did we introduce excessive indirection?
  • Did we replace obvious direct relationships with unnecessary event machinery?
  • Did we create configuration nobody needs?
  • Did we introduce unnecessary dependencies?
  • Did we merely move complexity rather than remove it?
  • Did we replace one god object with many tightly coupled fragments?
  • Are there temporary migration adapters that can already be removed?

A technical-debt cleanup that creates new technical debt is a failure.

Prefer deleting unnecessary concepts before adding more abstractions.


Final Cross-System Review

Before finishing, explicitly inspect whether the pass introduced:

  • regressions;
  • architectural inconsistencies;
  • duplicate solutions;
  • incomplete migrations;
  • dead compatibility paths;
  • unused abstractions;
  • new circular dependencies;
  • hidden state copies;
  • lifecycle problems;
  • performance regressions;
  • unsafe API changes;
  • type regressions;
  • error-handling regressions;
  • new warnings;
  • temporary hacks;
  • unintended product behavior changes.

Repair justified issues.

Then run final validation.


Completion Standard

The cleanup is complete when, to the degree available evidence and validation can establish:

  1. intended product behavior remains intact except for intentional bug fixes;
  2. the project builds and runs as expected;
  3. relevant validation passes apart from documented pre-existing failures;
  4. no known regressions introduced by the pass remain;
  5. meaningful correctness issues discovered during the pass have been resolved;
  6. state ownership is clearer;
  7. subsystem ownership is clearer;
  8. competing sources of truth are reduced;
  9. hidden dependencies are reduced;
  10. harmful coupling is reduced;
  11. circular dependencies are reduced where safely actionable;
  12. meaningful duplication is reduced;
  13. confirmed dead code is reduced;
  14. lifecycle and resource handling is clearer and safer;
  15. dependency direction is easier to understand;
  16. important API inconsistencies are reduced;
  17. justified oversized systems have been improved;
  18. incomplete migrations discovered in scope have been completed where worthwhile;
  19. unnecessary abstractions and indirection are reduced;
  20. relevant error handling is more reliable;
  21. type and boundary safety is improved where it materially matters;
  22. structural performance problems discovered in scope are corrected where justified;
  23. future changes are easier and safer to make;
  24. the project contains fewer concepts a developer must understand to accomplish ordinary work;
  25. remaining technical debt is low-value, speculative, disproportionately risky, or better suited to another specialized pass.

The objective is not:

maximum refactoring

It is:

the simplest, safest, most coherent version of the same project that can be justified by the available evidence.

Final Report

When complete, provide a concise engineering report.

1. Overall Result

Summarize the most meaningful improvements to project health.

2. Major Problems Found

Describe concrete problems that actually existed.

Do not list hypothetical smells.

3. Correctness and Stability

Summarize meaningful:

  • bugs;
  • state problems;
  • lifecycle issues;
  • race conditions;
  • resource issues;
  • error-handling problems;

that were actually fixed.

4. Architecture and Ownership

Explain meaningful changes to:

  • subsystem responsibility;
  • state authority;
  • dependency direction;
  • module boundaries;
  • public surfaces.

5. Simplification

Summarize important:

  • duplication removed;
  • obsolete abstractions removed;
  • indirection reduced;
  • dead code removed;
  • incomplete migrations completed;
  • APIs simplified.

6. Performance

Include only meaningful structural performance improvements actually implemented.

Omit this section if none were made.

7. Validation

State exactly what was run and the result.

Distinguish:

  • pre-existing failures;
  • failures introduced and subsequently corrected;
  • unresolved environmental limitations.

8. Deliberately Unchanged

Mention significant suspicious areas intentionally preserved because:

  • evidence was insufficient;
  • compatibility was unclear;
  • risk exceeded value;
  • the issue was outside scope.

9. Remaining Technical Debt

List only genuinely worthwhile remaining engineering work.

Do not pad the report with:

  • formatting;
  • tiny renames;
  • stylistic preferences;
  • microscopic cleanup.

10. Out-of-Scope Findings

Briefly list worthwhile findings that belong to another specialized pass.

Do not implement them here.


Final Directive

Think globally. Investigate concretely. Simplify deliberately. Preserve behavior. Implement fully. Validate continuously.

Do not rewrite code merely for aesthetics.

Do not introduce architecture merely because it looks sophisticated.

Do not preserve harmful architecture merely because fixing it requires effort.

Do not accidentally redesign the product.

Do not manufacture problems.

Do not leave half-migrations behind.

Do not stop after superficial cleanliness.

Continue the:

investigate → root cause → implement → validate → reassess

cycle while clear, material, safely actionable engineering improvements remain.

Leave behind a:

simpler, safer, clearer, less coupled, less duplicated, more coherent, more maintainable version of the same project.
View raw markdown
You are responsible for a comprehensive **codebase architecture, maintainability, correctness, and technical-debt reduction pass**.

Your objective is to leave the existing project:

- simpler;
- safer;
- easier to understand;
- easier to navigate;
- easier to debug;
- easier to extend;
- less coupled;
- less duplicated;
- clearer about ownership;
- clearer about state and data flow;
- clearer about dependency direction;
- less fragile;
- less surprising;
- more internally consistent;
- less likely to produce future bugs;
- less expensive to maintain and modify;

while preserving the intended product and existing externally observable behavior except where correcting confirmed defects.

The highest-level rule is:

> **Aggressively improve real engineering problems, but do not redesign the product or manufacture architecture for its own sake.**

This is an **implementation task**, not merely a code review.

Do not stop after:

- auditing;
- producing recommendations;
- identifying smells;
- generating a refactor plan;
- listing TODOs.

Inspect the project, identify concrete problems, prioritize them, fix them, validate the changes, reassess the result, and continue through progressively smaller worthwhile issues.

The objective is not maximum change.

The objective is:

> **maximum useful engineering improvement with controlled regression risk.**

---

# Core Scope

This pass is primarily responsible for the following areas.

## Correctness

Look for and fix confirmed issues involving:

- invalid state transitions;
- partial updates;
- stale state;
- race conditions;
- lifecycle errors;
- resource leaks;
- listener or subscription leaks;
- incorrect initialization or shutdown;
- null/reference hazards;
- swallowed errors;
- inconsistent authoritative state;
- unsafe boundary handling;
- broken asynchronous behavior;
- incorrect edge-case behavior.

## Architecture

Look for:

- unclear subsystem responsibility;
- competing sources of truth;
- circular dependencies;
- excessive coupling;
- hidden dependencies;
- confused ownership;
- cross-layer violations;
- global-state abuse;
- inappropriate singleton usage;
- oversized systems;
- genuine god classes;
- fragile initialization dependencies;
- obsolete architectural layers;
- incomplete architectural migrations.

## Maintainability

Look for:

- meaningful duplication;
- duplicated authoritative logic;
- unnecessarily complex control flow;
- fragmented responsibilities;
- misleading abstractions;
- unnecessary indirection;
- inconsistent APIs;
- poor module boundaries;
- stale compatibility layers;
- obsolete utilities;
- excessive boilerplate with real maintenance cost;
- unnecessary dependencies.

## Type and Boundary Safety

Where relevant, improve:

- weak API boundaries;
- unvalidated external data;
- unsafe type usage;
- ambiguous domain models;
- invalid states that are too easy to represent;
- weak persistence contracts;
- weak network contracts;
- weak configuration boundaries;
- poorly isolated third-party integrations.

## Dead and Obsolete Code

Search for:

- confirmed dead code;
- abandoned implementations;
- old and new systems remaining after migrations;
- unused compatibility layers;
- obsolete APIs;
- debug remnants;
- stale helpers;
- superseded implementations.

## Structural Performance Problems

Only address performance where evidence shows meaningful cost.

Examples include:

- unnecessary repeated computation;
- accidental quadratic behavior;
- excessive polling;
- duplicate requests;
- repeated serialization;
- hot-path allocations;
- redundant database work;
- repeated resource loading;
- resource churn;
- memory or resource leaks.

---

# Explicitly Out of Scope

This is **not primarily**:

- a new-feature sprint;
- content creation;
- product redesign;
- visual or presentation polish;
- accessibility expansion;
- onboarding redesign;
- a technology migration based merely on preference;
- a dependency-upgrade campaign;
- formatting cleanup;
- naming cleanup;
- repository/Git hygiene;
- speculative performance optimization.

Do not allow these areas to consume the task.

If worthwhile out-of-scope work is discovered, record it briefly for another specialized pass.

Do not implement it unless it is directly required to fix an in-scope engineering problem.

---

# Preserve the Product

Unless correcting a confirmed defect, preserve intended externally observable behavior.

Pay particular attention to compatibility involving:

- public APIs;
- network protocols;
- persistence;
- save formats;
- serialized data;
- database representations;
- migrations;
- configuration;
- events;
- callbacks;
- IDs;
- resource names;
- file formats;
- reflection;
- dynamic loading;
- string-based lookup;
- registration systems;
- plugins;
- runtime metadata;
- platform-specific entry points;
- timing-sensitive behavior.

A cleaner implementation that subtly changes intended behavior is a **regression**.

Do not confuse:

> **"I would have designed this differently."**

with:

> **"This design currently causes a concrete problem."**

Refactor from evidence, not preference.

---

# Preserve Existing Work

Inspect version-control state before substantive modifications.

Identify relevant:

- modified tracked files;
- staged files;
- deleted files;
- renamed files;
- untracked files;
- work produced by previous development sessions.

Do not:

- overwrite unrelated work;
- revert unknown changes;
- delete unknown work;
- use destructive version-control operations merely to simplify the worktree;
- accidentally absorb unrelated modifications into this cleanup.

When pre-existing changes overlap an area you need to modify:

1. inspect the existing changes;
2. determine their apparent purpose;
3. preserve that purpose;
4. work around them when practical;
5. sequence conflicting work carefully;
6. leave the area unchanged if safe ownership cannot be established.

A cleanup that destroys legitimate existing work is a failure.

---

# Investigate Before Asking Questions

Use the project itself as evidence before asking for clarification.

Inspect relevant:

- repository structure;
- source code;
- tests;
- documentation;
- configuration;
- build scripts;
- runtime behavior;
- version-control history;
- existing conventions;
- schemas;
- APIs;
- generated artifacts;
- package definitions;
- callers;
- references;
- dependencies.

Ask for clarification only when:

- an important product decision genuinely belongs to the user;
- intended behavior cannot be established;
- several materially different outcomes are equally plausible;
- compatibility requirements cannot be determined;
- proceeding would create substantial risk without clarification;
- required external access is unavailable.

Do not ask questions merely because understanding the existing architecture takes effort.

---

# Implementation Over Auditing

The audit exists to create an **implementation queue**.

Do not spend most of the task:

- cataloguing smells;
- creating architectural diagrams;
- writing recommendations;
- listing possible improvements;
- speculating about problems;
- generating reports.

Once sufficient evidence exists to make a safe improvement:

> **implement it.**

Use this loop repeatedly:

> **Investigate → establish root cause → implement → validate → reassess**

Do not wait until every subsystem has been audited before fixing the first well-understood high-value problem.

Prefer coherent, validated improvement waves over one enormous uncontrolled refactor.

If multiple independent workstreams can safely proceed in parallel and the environment supports that, parallelize them.

Serialize work when different changes:

- modify the same API;
- share authoritative state;
- touch the same foundational types;
- depend on the same architectural decision;
- modify the same subsystem;
- change shared lifecycle behavior;
- involve overlapping migrations.

Do not allow separate workstreams to invent competing architectural solutions.

---

# Phase 1 — Establish the Architectural Baseline

Before broad modification, build enough understanding to make responsible decisions.

Do not attempt to understand every function.

Determine what is relevant from:

- languages;
- frameworks;
- application entry points;
- initialization;
- shutdown;
- runtime flow;
- major subsystems;
- domain logic;
- UI or presentation boundaries;
- state ownership;
- data ownership;
- persistence;
- networking;
- database/data access;
- background processing;
- events or messaging;
- external integrations;
- global/shared state;
- configuration;
- build tooling;
- test infrastructure;
- generated-code boundaries;
- third-party dependencies;
- platform-specific behavior.

Identify structural warning signs:

- unusually large modules;
- highly connected modules;
- duplicate implementations;
- duplicate authoritative state;
- unclear ownership;
- fragile initialization;
- lifecycle asymmetry;
- broad public surfaces;
- old and new systems coexisting;
- incomplete migrations;
- shared modules becoming dumping grounds;
- hot-path responsibilities mixed with unrelated work.

Understand enough architecture to divide the project into coherent investigation boundaries.

---

# Establish the Validation Baseline

Determine what validation the project already provides.

Run useful baseline checks where practical:

- build;
- compilation;
- type checking;
- linting;
- static analysis;
- unit tests;
- integration tests;
- end-to-end tests;
- runtime smoke tests;
- schema validation;
- resource or reference validation;
- project-specific validation.

Record pre-existing failures separately.

A failure that existed before this pass is not automatically caused by your work.

A newly introduced failure is a regression unless evidence establishes otherwise.

For high-risk systems, identify externally observable invariants before modification.

---

# Phase 2 — Build the Engineering Queue

Maintain an internal prioritized queue.

Continuously reprioritize when new evidence appears.

Do not treat the initial queue as sacred.

## P0 — Correctness and Safety

Highest priority:

- confirmed bugs;
- data corruption risk;
- persistence corruption;
- race conditions;
- unsafe partial updates;
- resource leaks;
- listener leaks;
- invalid state transitions;
- severe initialization bugs;
- shutdown or lifecycle failures;
- critical silent failures;
- broken authoritative ownership.

Fix these first.

## P1 — Architectural Fragility

Examples:

- duplicate sources of truth;
- circular dependencies;
- extreme coupling;
- god classes;
- uncontrolled global state;
- hidden dependencies;
- unclear ownership;
- cross-system mutation;
- dangerous public APIs;
- duplicated authoritative rules;
- incomplete architectural migrations;
- fragile initialization order.

These are high-value structural problems.

## P2 — Maintainability Debt

Examples:

- meaningful duplication;
- misplaced responsibilities;
- excessively complicated control flow;
- oversized functions;
- fragmented related logic;
- inconsistent APIs;
- obsolete abstractions;
- misleading wrappers;
- unnecessary indirection;
- poor subsystem boundaries;
- repeated boilerplate with real maintenance cost;
- poorly isolated integrations.

Spend substantial effort here after higher-risk issues.

## P3 — Cleanup Residue

Address later:

- confirmed dead code;
- stale APIs;
- debug remnants;
- excessive logging;
- stale comments;
- misleading names;
- minor local inconsistencies;
- straightforward simplifications.

Do not spend the first half of the task renaming variables while significant architectural problems remain.

---

# Investigate Before Refactoring

Never substantially refactor code solely because it looks messy.

Before modifying a subsystem, establish:

1. What responsibility does it currently own?
2. Who calls it?
3. What does it call?
4. What state does it own?
5. What state does it mutate elsewhere?
6. Who else can mutate its state?
7. What observable behavior must remain unchanged?
8. Which public contracts depend on it?
9. What concrete problems exist?
10. What root causes create those problems?
11. What simpler target structure would solve them?
12. What migration is required?
13. What could regress?
14. How will the result be validated?

Refactor from evidence.

Do not refactor from aesthetic preference.

---

# Root-Cause Hunting

Actively search for meaningful instances of:

- god classes;
- excessive coupling;
- circular dependencies;
- duplicate logic;
- duplicate authoritative state;
- confused ownership;
- hidden dependencies;
- global-state abuse;
- singleton abuse;
- initialization-order dependencies;
- race conditions;
- null/reference hazards;
- listener leaks;
- resource leaks;
- lifecycle asymmetry;
- partial state mutation;
- duplicated expensive work;
- excessive polling;
- huge functions;
- deeply nested logic caused by confused responsibility;
- magic values with unclear ownership;
- misplaced responsibility;
- misleading abstraction boundaries;
- unnecessary wrappers;
- stale compatibility layers;
- swallowed errors;
- excessive logging;
- debug remnants;
- incomplete migrations;
- inappropriate cross-layer access;
- implicit contracts that should be explicit.

Fix root causes rather than layering more patches over symptoms.

---

# Simplicity Is a Requirement

Do not turn the project into an architecture demonstration.

Prefer the simplest structure that correctly solves the real problem.

Do not introduce without concrete justification:

- abstract factories;
- interfaces with one implementation and no meaningful boundary;
- elaborate dependency-injection frameworks;
- unnecessary service layers;
- wrappers that merely forward calls;
- generic frameworks for one-off behavior;
- elaborate event buses where direct relationships are clearer;
- speculative plugin systems;
- speculative extensibility;
- configuration for things that do not need configuration;
- large inheritance hierarchies;
- design patterns merely because they are conventional;
- massive migrations motivated by stylistic preference.

Removing unnecessary abstraction is often more valuable than adding abstraction.

After a refactor, ask:

> **Did this reduce the number of concepts a developer must understand?**

If the cleanup creates substantially more concepts than it removes, scrutinize it.

---

# Module and Responsibility Discipline

Follow established project conventions.

When existing conventions are weak, prefer:

- one clear primary responsibility per module;
- explicit state ownership;
- limited public surfaces;
- understandable data flow;
- sensible dependency direction;
- pure logic separated from side effects where useful;
- third-party integrations isolated at boundaries;
- shared abstractions only for genuinely shared concepts.

Large files are evidence to investigate, not automatic proof of bad architecture.

Split code when responsibilities are genuinely separable.

Do not replace one god class with twenty tiny files that remain tightly coupled.

---

# State and Ownership Pass

For important state, be able to answer:

> **Who owns this?**

> **Who may modify it?**

> **Who observes it?**

> **What is authoritative?**

> **Is another subsystem pretending to be authoritative too?**

Look for:

- multiple systems storing equivalent state;
- caches becoming accidental authorities;
- UI or presentation state becoming business/domain state;
- arbitrary modules mutating subsystem internals;
- distributed state transitions;
- state copies synchronized manually;
- write access broader than necessary.

Where safe:

- establish one clear source of truth;
- narrow mutation surfaces;
- make state transitions explicit;
- clarify who publishes versus who owns.

Do not solve state ownership by creating one enormous global manager.

---

# Dependency Direction Pass

Understand how major subsystems depend on each other.

Look for:

- circular dependencies;
- domain logic depending unnecessarily on presentation code;
- low-level modules importing high-level behavior;
- foundational code depending on feature-specific systems;
- shared modules becoming dumping grounds;
- unrelated subsystems reaching into each other's internals;
- third-party APIs scattered through core logic;
- direct persistence, network, framework, or infrastructure concerns inside domain logic where separation would materially help.

Correct dependency direction when it produces real engineering value.

Do not add meaningless layers solely to make an architecture diagram look cleaner.

---

# Duplication Pass

Search for **meaningful duplication**, not merely similar-looking lines.

Important duplication includes repeated:

- domain calculations;
- validation rules;
- state transitions;
- transformations;
- persistence rules;
- serialization;
- network mappings;
- database logic;
- UI state logic;
- resource management;
- authoritative constants;
- business rules;
- parallel utilities implementing the same concept;
- old and replacement implementations existing simultaneously.

Consolidate when there is genuinely **one concept**.

Do not combine unrelated behavior merely because the syntax resembles each other.

Premature abstraction is also technical debt.

---

# API Surface Pass

Inspect internal and public APIs for:

- confusing ownership;
- excessive parameter counts;
- duplicated entry points;
- weak contracts;
- inconsistent semantics;
- overly broad interfaces;
- callers manipulating internals;
- boolean-flag explosions;
- methods performing unrelated jobs;
- APIs exposing implementation details;
- obsolete compatibility entry points.

Simplify where concrete maintenance or correctness value exists.

Prefer small, explicit, coherent public surfaces.

Do not redesign stable APIs merely for taste.

---

# Type and Boundary Safety

Improve type safety where it materially reduces bugs or ambiguity.

At important boundaries:

- use explicit types;
- validate external data;
- validate network data;
- validate persistence input;
- validate configuration;
- validate files;
- validate database results where appropriate;
- isolate unavoidable unsafe values;
- avoid uncontrolled dynamic types;
- make invalid states harder to represent where practical;
- return structured failures where useful.

Important boundaries may include:

- APIs;
- networking;
- persistence;
- databases;
- configuration;
- files;
- user input;
- third-party services;
- framework or runtime integrations.

Do not perform massive type-system rewrites purely for ideological consistency.

---

# Error-Handling Pass

Do not silently hide failures.

Search for:

- empty catches;
- ignored asynchronous failures;
- fallback values that conceal legitimate errors;
- partial state mutation followed by failure;
- swallowed database or persistence failures;
- duplicate logging at several layers;
- generic errors that discard useful context;
- errors caught by layers incapable of handling them.

Handle failures at the layer capable of making the appropriate decision.

Prefer errors that are:

- structured where useful;
- actionable;
- observable at the correct boundary;
- non-spammy;
- contextual enough to diagnose.

Avoid both:

- silent failure;
- excessive repetitive logging.

---

# Lifecycle and Resource Pass

Inspect lifecycle symmetry:

- create / destroy;
- subscribe / unsubscribe;
- allocate / release;
- connect / disconnect;
- start / stop;
- register / unregister;
- load / unload;
- acquire / release;
- open / close.

Look for:

- leaked event listeners;
- leaked timers;
- leaked handles;
- leaked network connections;
- stale callbacks;
- resources surviving their owners;
- duplicate initialization;
- shutdown ordering issues;
- state reused after disposal;
- tasks continuing after cancellation;
- objects referenced after destruction.

Treat these as correctness issues, not cosmetic cleanup.

---

# Dead-Code Policy

Be aggressive in **finding** dead code and conservative in **declaring uncertain code dead**.

Before deleting apparently unused code, account for indirect use through:

- serialization;
- reflection;
- dynamic loading;
- registration;
- dependency injection;
- events;
- string lookup;
- build configuration;
- runtime conventions;
- plugins;
- generated code;
- configuration;
- platform-specific entry points.

If usage is uncertain, investigate further.

Do not guess.

Once code is demonstrably obsolete:

> **delete it.**

Do not preserve confirmed dead code merely because deletion feels uncomfortable.

---

# Incomplete Migration Hunt

Search specifically for migrations that were started but never finished.

Examples:

- old and new APIs both in use;
- compatibility wrappers no longer needed;
- duplicate data models;
- deprecated methods still called;
- fallback paths preserving an obsolete system;
- partial state-management migrations;
- duplicate serialization formats without a compatibility requirement;
- duplicate utilities;
- temporary adapters that became permanent;
- comments referring to migrations that are apparently complete.

Establish which implementation is authoritative.

Complete the migration when safely justified.

Then remove obsolete scaffolding.

Do not leave half-migrations behind.

---

# Performance Policy

This is not primarily a performance pass.

However, fix structural performance problems when evidence shows meaningful impact.

Inspect relevant hot paths such as:

- frequently executed loops;
- request handlers;
- networking;
- serialization;
- database operations;
- background jobs;
- UI refresh;
- resource loading;
- frequently called utilities.

Look for:

- repeated expensive calculations;
- accidental O(n²) behavior;
- duplicate requests;
- excessive polling;
- unnecessary allocations;
- repeated serialization;
- redundant recomputation;
- N+1 database behavior;
- excessive resource churn;
- obvious memory leaks.

Measure or establish evidence where practical.

Do not sacrifice readability for meaningless micro-optimization.

---

# Large Refactor Gate

Large refactors are allowed when justified.

Before beginning one, explicitly establish:

## Problem

What is concretely wrong?

## Evidence

How do we know it is a real problem?

## Impact

What correctness, stability, maintenance, ownership, or performance cost does it create?

## Preservation

What observable behavior and contracts must remain stable?

## Target

What simpler structure should replace it?

## Migration

Which callers, data, APIs, state, resources, and dependencies must change?

## Risk

What can regress?

## Validation

How will safety be demonstrated?

Proceed when expected engineering benefit clearly outweighs migration risk.

Do not preserve genuinely harmful architecture solely because fixing it requires meaningful work.

Do not undertake a large migration merely because the replacement architecture is fashionable.

---

# Implementation Standard

Before substantial modification:

1. inspect the area;
2. understand its responsibilities;
3. identify callers;
4. identify dependencies;
5. identify state ownership;
6. establish behavioral invariants;
7. identify concrete problems;
8. establish root causes;
9. define the smallest coherent improvement;
10. implement it completely;
11. update all affected callers;
12. remove obsolete pieces made unnecessary;
13. validate;
14. inspect the resulting design for newly introduced complexity.

Do not leave partial migrations behind.

Do not add temporary compatibility code without a clear need.

Do not rewrite code merely because another style looks cleaner.

Reward:

- correctness;
- simplicity;
- clarity;
- reduced concepts;
- explicit ownership;

not diff size.

---

# Work in Engineering Waves

Do not attempt one enormous uncontrolled cleanup.

Work iteratively.

## Wave A — Correctness, State, and Lifecycle

Prioritize:

- correctness bugs;
- state corruption;
- ownership problems;
- lifecycle issues;
- resource leaks;
- race conditions;
- initialization hazards;
- dangerous partial updates;
- silent failures.

Implement, validate, then reassess.

## Wave B — Architectural Fragility

Address:

- duplicate sources of truth;
- circular dependencies;
- extreme coupling;
- god classes;
- hidden dependencies;
- cross-layer mutation;
- incomplete migrations;
- fragile public APIs;
- confused subsystem boundaries.

Implement coherent improvements, validate, then reassess.

## Wave C — Subsystem Health

Move through high-value subsystems that actually exist.

Possible boundaries include:

- core domain logic;
- user/account state;
- persistence;
- networking;
- UI architecture;
- database access;
- API layer;
- resource loading;
- events or messaging;
- background work;
- configuration;
- external integrations.

Clean meaningful debt.

Validate each coherent slice.

## Wave D — Simplification

Search for:

- obsolete abstractions;
- unnecessary wrappers;
- repeated helpers;
- excessive indirection;
- fragmented logic;
- unnecessarily complicated APIs;
- old compatibility layers;
- unused dependencies.

Simplify where evidence supports it.

## Wave E — Residue

Search for lower-risk remaining debt:

- dead code;
- obsolete utilities;
- debug remnants;
- stale comments;
- excessive logging;
- misleading names;
- easy local inconsistencies;
- tiny obsolete compatibility pieces.

Do not spend disproportionate effort on microscopic issues.

---

# Reassess After Every Wave

Ask:

- What important engineering problems remain?
- Did previous changes expose deeper root causes?
- Did a refactor make another abstraction obsolete?
- Did a migration leave old callers behind?
- Did separate changes create inconsistent patterns?
- Is state ownership clearer?
- Are dependencies simpler?
- Is meaningful duplication lower?
- Did the new architecture introduce unnecessary concepts?
- Are public surfaces smaller or clearer?
- Did risk move elsewhere?
- What change now provides the greatest engineering value?
- Is remaining work worth the regression risk?

Reprioritize based on current evidence.

Do not mechanically follow an outdated initial plan.

---

# Regression Thinking

Whenever shared code changes, determine the dependency surface.

Do not assume a local diff has local impact.

A state-management change may affect:

- domain behavior;
- UI;
- networking;
- persistence;
- APIs;
- background jobs.

A lifecycle change may affect many object types.

A shared utility migration may affect the entire project.

A public type migration may affect dynamically loaded code.

An API simplification may affect tests, tools, plugins, integrations, or external consumers.

Search for affected consumers before declaring shared changes complete.

---

# Continuous Validation

Validation should be continuous and proportionate to risk.

After meaningful changes use the project's relevant:

- compilation;
- build;
- tests;
- integration tests;
- end-to-end tests;
- type checking;
- linting;
- static analysis;
- schema checks;
- runtime smoke tests;
- reference searches;
- application-specific checks.

Do not wait until the end to discover that an early migration broke half the project.

Use focused validation during implementation.

Run broader validation periodically after substantial shared changes.

Do not repeatedly run expensive whole-project checks purely for ceremony.

---

# Independent Review of High-Risk Changes

Where practical, review high-risk changes with fresh context rather than relying only on the implementation perspective.

This is especially valuable for:

- persistence;
- serialization;
- networking;
- concurrency;
- authoritative state;
- lifecycle;
- large architectural refactors;
- broad API migrations;
- major deletions;
- difficult cross-system work.

Reviewers should actively ask:

> **How could this implementation be wrong, incomplete, unnecessarily complex, or behaviorally incompatible?**

Search for:

- regressions;
- missed consumers;
- incorrect assumptions;
- hidden state copies;
- broken compatibility;
- lifecycle leaks;
- race conditions;
- incomplete migrations;
- unjustified abstraction;
- unnecessary concepts;
- error-handling regressions;
- performance regressions.

Do not seek approval.

Seek defects.

---

# Anti-Overengineering Review

Before completion, inspect what **this cleanup itself introduced**.

Ask:

- Did we add layers that are not earning their complexity?
- Did we create interfaces with one implementation and no real boundary value?
- Did we split modules too aggressively?
- Did we create generic frameworks for isolated behavior?
- Did we introduce excessive indirection?
- Did we replace obvious direct relationships with unnecessary event machinery?
- Did we create configuration nobody needs?
- Did we introduce unnecessary dependencies?
- Did we merely move complexity rather than remove it?
- Did we replace one god object with many tightly coupled fragments?
- Are there temporary migration adapters that can already be removed?

A technical-debt cleanup that creates new technical debt is a failure.

Prefer deleting unnecessary concepts before adding more abstractions.

---

# Final Cross-System Review

Before finishing, explicitly inspect whether the pass introduced:

- regressions;
- architectural inconsistencies;
- duplicate solutions;
- incomplete migrations;
- dead compatibility paths;
- unused abstractions;
- new circular dependencies;
- hidden state copies;
- lifecycle problems;
- performance regressions;
- unsafe API changes;
- type regressions;
- error-handling regressions;
- new warnings;
- temporary hacks;
- unintended product behavior changes.

Repair justified issues.

Then run final validation.

---

# Completion Standard

The cleanup is complete when, to the degree available evidence and validation can establish:

1. intended product behavior remains intact except for intentional bug fixes;
2. the project builds and runs as expected;
3. relevant validation passes apart from documented pre-existing failures;
4. no known regressions introduced by the pass remain;
5. meaningful correctness issues discovered during the pass have been resolved;
6. state ownership is clearer;
7. subsystem ownership is clearer;
8. competing sources of truth are reduced;
9. hidden dependencies are reduced;
10. harmful coupling is reduced;
11. circular dependencies are reduced where safely actionable;
12. meaningful duplication is reduced;
13. confirmed dead code is reduced;
14. lifecycle and resource handling is clearer and safer;
15. dependency direction is easier to understand;
16. important API inconsistencies are reduced;
17. justified oversized systems have been improved;
18. incomplete migrations discovered in scope have been completed where worthwhile;
19. unnecessary abstractions and indirection are reduced;
20. relevant error handling is more reliable;
21. type and boundary safety is improved where it materially matters;
22. structural performance problems discovered in scope are corrected where justified;
23. future changes are easier and safer to make;
24. the project contains fewer concepts a developer must understand to accomplish ordinary work;
25. remaining technical debt is low-value, speculative, disproportionately risky, or better suited to another specialized pass.

The objective is not:

> **maximum refactoring**

It is:

> **the simplest, safest, most coherent version of the same project that can be justified by the available evidence.**

---

# Final Report

When complete, provide a concise engineering report.

## 1. Overall Result

Summarize the most meaningful improvements to project health.

## 2. Major Problems Found

Describe concrete problems that actually existed.

Do not list hypothetical smells.

## 3. Correctness and Stability

Summarize meaningful:

- bugs;
- state problems;
- lifecycle issues;
- race conditions;
- resource issues;
- error-handling problems;

that were actually fixed.

## 4. Architecture and Ownership

Explain meaningful changes to:

- subsystem responsibility;
- state authority;
- dependency direction;
- module boundaries;
- public surfaces.

## 5. Simplification

Summarize important:

- duplication removed;
- obsolete abstractions removed;
- indirection reduced;
- dead code removed;
- incomplete migrations completed;
- APIs simplified.

## 6. Performance

Include only meaningful structural performance improvements actually implemented.

Omit this section if none were made.

## 7. Validation

State exactly what was run and the result.

Distinguish:

- pre-existing failures;
- failures introduced and subsequently corrected;
- unresolved environmental limitations.

## 8. Deliberately Unchanged

Mention significant suspicious areas intentionally preserved because:

- evidence was insufficient;
- compatibility was unclear;
- risk exceeded value;
- the issue was outside scope.

## 9. Remaining Technical Debt

List only genuinely worthwhile remaining engineering work.

Do not pad the report with:

- formatting;
- tiny renames;
- stylistic preferences;
- microscopic cleanup.

## 10. Out-of-Scope Findings

Briefly list worthwhile findings that belong to another specialized pass.

Do not implement them here.

---

# Final Directive

**Think globally. Investigate concretely. Simplify deliberately. Preserve behavior. Implement fully. Validate continuously.**

Do not rewrite code merely for aesthetics.

Do not introduce architecture merely because it looks sophisticated.

Do not preserve harmful architecture merely because fixing it requires effort.

Do not accidentally redesign the product.

Do not manufacture problems.

Do not leave half-migrations behind.

Do not stop after superficial cleanliness.

Continue the:

> **investigate → root cause → implement → validate → reassess**

cycle while clear, material, safely actionable engineering improvements remain.

Leave behind a:

> **simpler, safer, clearer, less coupled, less duplicated, more coherent, more maintainable version of the same project.**