# Existing Codebase — Archaeology & Evolution Agent Prompt Pack > **Source material:** *Appendix 2: Applying Vibe Coding to an Existing Codebase* (Archaeology Pattern + Evolution workflow). A sequential set of prompts for driving an AI coding agent through a structured analysis ("archaeology") and improvement ("evolution") workflow on an existing codebase. ## How to use - Run the prompts **in order** (01 → 14). - Copy each prompt **verbatim** into your coding agent while it is operating in the **repository root**. - **Do not skip the archaeology phases** — they materially reduce regressions and accidental "simplification" of deliberate design decisions. - Begin every session by applying the [Meta Prompt](#meta-prompt-apply-to-every-step), then run the numbered phase you are on. ### Phase overview | # | Phase | Primary deliverable(s) | |----|-------|------------------------| | 01 | Archaeology — Context Fill + Non-technical Summary | `devdocs/archaeology/small_summary.md` | | 02 | Archaeology — Architecture + Deployment Intro | `devdocs/archaeology/intro2codebase.md`, `intro2deployment.md` | | 03 | Archaeology — Deep Trace Analysis | `devdocs/archaeology/traces/trace_*.md` | | 04 | Archaeology — "5 Things" Improvement List | `devdocs/archaeology/5_things_or_not.md` | | 05 | Archaeology — Concept Inventory + Missing Concepts | `devdocs/archaeology/concepts/*.md` | | 06 | Archaeology — Code-Inferred Foundations | `devdocs/archaeology/foundations/*.md` | | 07 | Standard Analysis — Doc-Inferred Foundations | `devdocs/foundations/*.md` | | 08 | Standard Analysis — Architecture Archaeology | `devdocs/archaeology/architecture_analysis.md`, `module_discovery.md` | | 09 | Standard Analysis — Concept Mapping | `devdocs/archaeology/concept_mappings.md` | | 10 | Evolution — Gap Analysis | `devdocs/evolution/gap_analysis.md` | | 11 | Evolution — Gap Closure Strategy | `devdocs/evolution/gap_closure_plan.md` | | 12 | Evolution — Baseline Smoke Tests | `smoke_tests/check_what_is_working/*` | | 13 | Evolution — Codebase Cleanup Inventory | `devdocs/archaeology/cleanup_inventory.md` | | 14 | Evolution — Strategic Refactoring + Roadmap | `devdocs/evolution/refactoring_opportunities.md`, `implementation_roadmap.md` | --- ## Meta Prompt (apply to every step) > You are an AI coding agent operating in the repository root of an existing > codebase. Treat the current working tree as the sole source of truth. > > **Global rules:** > > 1. **Prefer code over docs.** If docs conflict with code, treat code behavior > as authoritative and explicitly document the discrepancy. > 2. **Do not delete or "simplify" anything** until you've documented what it > does and why it exists. > 3. **Reuse before you create.** Before creating new files, search for existing > equivalents and reuse/extend them. Avoid duplicate models, utilities, > abstractions, configuration, or documentation. > 4. **Keep core logic deterministic and testable.** Do not introduce direct > system time calls, unseeded randomness, environment-dependent behavior, or > nondeterministic side effects into core logic unless the existing > architecture already provides an approved abstraction. If you need time, > IDs, randomness, external IO, or environment state, use existing > providers/generators/configuration points, or introduce them via dependency > injection. > 5. **Every proposed refactor must include:** (a) exact file paths, (b) risk > assessment, (c) rollback plan, and (d) verification steps. > 6. **Keep changes incremental and reviewable.** Each step should result in a > coherent commit-sized diff. > > **When a prompt asks you to "create a file", you must:** > > - Create the directory path if missing. > - Write the file content in full. > - Ensure internal links and filenames are consistent. > - Keep tone concise and engineer-friendly. --- ## 01 — Archaeology · Phase 1: Context Fill + Non-technical Summary > Read the codebase and explain what the project does in non-technical terms. > > **Constraints:** > > - Focus on source code, build files, configuration, scripts, and runtime entry > points — **not** existing documentation. > - Read the relevant code paths fully. Do not rely on filenames alone. > - If there are multiple applications, packages, modules, services, libraries, > or deployable units, identify which one appears to be the primary > deliverable. > > **Deliverable:** Create `devdocs/archaeology/small_summary.md` > > **Include:** > > - What the user, operator, developer, or consuming system experiences at a > high level. > - What the core workflow or "core loop" appears to be. > - What appears complete vs actively evolving. > - Any major uncertainties where the code does not make intent clear. --- ## 02 — Archaeology · Phase 2: Architecture Intro + Deployment Intro > Now explain the codebase architecture at a high level for a new engineer. > > **Cover:** > > - Main data flow paths, such as UI/API/CLI entry point → application/domain > logic → persistence/infrastructure/external services. > - Main abstractions, such as repositories, services, controllers, handlers, > use cases, workers, state machines, queues, reducers, adapters, gateways, or > agents. > - Top-level design patterns, such as dependency injection, modularisation, > layering, state management, eventing, plugin systems, monorepo structure, or > service boundaries. > - Where time, ID generation, randomness, configuration, caching, persistence, > or environment access is handled. > > **Deployment / infrastructure:** > > - Read build files, package manifests, CI configs, deployment scripts, > container files, environment templates, release workflows, and runtime > configuration. > - Explain how the system is built, run, tested, packaged, deployed, and > released. > - If there are frontend assets, backend services, scheduled jobs, workers, > local models, data packs, migrations, generated files, or bundled resources, > describe how they are shipped and updated. > > **Deliverables:** > > - `devdocs/archaeology/intro2codebase.md` > - `devdocs/archaeology/intro2deployment.md` --- ## 03 — Archaeology · Phase 3: Deep Trace Analysis (Interfaces + Module Interactions) > Identify every **INTERNAL** interface boundary and submodule-level > interaction. Exclude external libraries except where they are essential to > understanding the internal boundary. For each interaction, trace execution > end-to-end based strictly on code behavior. > > **For each trace, cover:** > > - **Entry point(s):** UI events, API routes, CLI commands, handlers, > controllers, background workers, schedulers, consumers, reducers, or use > cases. > - **Execution path:** function calls, state transitions, data transformations, > validations, and side effects. > - **Resource management:** threading, async flows, processes, memory, IO, > lifecycles, transactions, caching, pooling, cleanup. > - **Error paths:** failures, retries, fallbacks, logging, exceptions, > compensation, user-visible or operator-visible behavior. > - **Performance characteristics:** hotspots, loops, allocations, network calls, > database calls, serialization, rendering, batching, startup costs. > - **Observable effects:** state changes, logs, metrics, analytics, persistence, > network calls, files written, UI changes, emitted events. > - **Why this design:** infer rationale from patterns, repetition, constraints, > naming, comments, and surrounding code. > - **What feels incomplete / vulnerable / poor design.** > > **Deliverables:** > > - Create one file per trace under `devdocs/archaeology/traces/`. > - Use naming: `trace_01_.md`, `trace_02_.md`, etc. > > **Each trace file must have these sections:** > > 1. Entry Point > 2. Execution Path > 3. Resource Management > 4. Error Path > 5. Performance Characteristics > 6. Observable Effects > 7. Why This Design > 8. Feels Incomplete > 9. Feels Vulnerable > 10. Feels Like Bad Design --- ## 04 — Archaeology · Phase 4: "5 Things" Improvement List (with historical rationale) > Review the trace documents and identify the 5 most impactful improvements. > > **For each improvement:** > > - Explain expected benefit, such as maintainability, correctness, reliability, > reproducibility, security, UX, performance, scalability, operability, or > testability. > - Cite exact code locations using file paths and key symbols. > - Provide a plausible reason it is **NOT** already implemented, such as missing > time, hidden constraints, prior tradeoffs, legacy compatibility, deployment > risk, lack of tests, unclear ownership, or incomplete migration. > - Propose a low-risk incremental first step that is small-PR sized. > > **Deliverable:** `devdocs/archaeology/5_things_or_not.md` --- ## 05 — Archaeology · Phase 5: Concept Inventory + Missing Concepts > From code, enumerate key concepts and their implementation status. > > **Deliverables:** > > 1. `devdocs/archaeology/concepts/technical_concepts_list.md` > 2. `devdocs/archaeology/concepts/design_concepts_list.md` > 3. `devdocs/archaeology/concepts/business_lvl_concepts_list.md` > 4. `devdocs/archaeology/concepts/missing_concepts_list.md` > > **Rules:** > > - Each concept: max 3 sentences, plus "Implementation status" as > **Fully / Partial / Missing**, and pointers to files/modules. > - Start with the most central concepts; branch into sub-concepts. > - Explicitly surface implicit or undocumented concepts, including edge > handling, future-proofing, invariants, reproducibility, security > assumptions, privacy assumptions, data ownership, compliance assumptions, > operational assumptions, and integration contracts. > - If the project is a library or internal service rather than an end-user > product, interpret "design concepts" as API, workflow, or system-design > concepts. --- ## 06 — Archaeology · Phase 6: Code-Inferred Foundations Extraction > Based solely on code + `devdocs/archaeology` outputs, extract "foundations" > docs. > > **Deliverables:** > > 1. `devdocs/archaeology/foundations/project_description.md` > - What the system actually does, not what docs claim. > - Current use cases and user/operator/developer/system types implied by > code. > - Actual problems being solved. > - Primary runtime or delivery model implied by the implementation. > 2. `devdocs/archaeology/foundations/philosophy.md` > - Implicit design principles found in code. > - Consistent coding, architecture, testing, deployment, and operational > patterns. > - Architectural decisions evident in structure. > - Tradeoffs that appear deliberate. > 3. `devdocs/archaeology/foundations/known_requirements.md` > - Requirements inferred from implementations. > - Constraints visible in code, such as platform, runtime, privacy, offline > behavior, latency, scalability, reproducibility, compatibility, security, > deployment, or integration constraints. > - Security, privacy, observability, or compliance measures present, if any. > - Explicit unknowns where requirements cannot be inferred safely. --- ## 07 — Standard Analysis · Phase 7: Doc-Inferred Foundations Extraction > Now, using **NON-CODE documentation only**, extract "foundations" docs for > comparison. > > **Important:** > > - This phase must be based on documentation, **not** on prior code analysis. > - Use README files, docs folders, ADRs, architecture notes, product notes, > issue templates, contribution guides, release notes, changelogs, comments in > documentation files, and any other non-code project documentation. > - Do not allow prior code analysis to fill gaps silently. If documentation is > missing or vague, say so. > > **Deliverables:** > > 1. `devdocs/foundations/project_description.md` > 2. `devdocs/foundations/philosophy.md` > 3. `devdocs/foundations/known_requirements.md` > > Also include a short **"Docs vs Code"** delta section at the end of each file. > > **The delta should identify:** > > - Where docs and code agree. > - Where docs appear outdated. > - Where docs describe intended future state rather than current behavior. > - Where code contains behavior not documented anywhere. > - Where documentation is too vague to verify. --- ## 08 — Standard Analysis · Phase 8: Architecture Archaeology (Reconstruction) > Reconstruct architecture from code, highlighting what is solid vs what is > inconsistent. > > **Deliverables:** > > 1. `devdocs/archaeology/architecture_analysis.md` > - Trace main entry points and flows. > - Map main data models, schemas, DTOs, entities, state objects, commands, > events, or messages. > - Identify duplicated or overlapping models. > - Identify important contracts, such as interfaces, services, controllers, > reducers, handlers, adapters, repositories, job processors, APIs, queues, > plugins, or extension points. > - Identify architectural patterns used. > - Call out what does not make sense, with file pointers. > - Identify areas where architecture is implied but not enforced. > 2. `devdocs/archaeology/module_discovery.md` > - Natural module boundaries. > - Coupling/cohesion analysis. > - Dependency relationships. > - Shared utilities and libraries. > - Cross-cutting concerns. > - Where boundaries are being violated. > - Where boundaries are missing but would likely help. --- ## 09 — Standard Analysis · Phase 9: Concept Mapping > Create a mapping from concepts → implementation locations. > > **Deliverable:** `devdocs/archaeology/concept_mappings.md` > > **For each major concept:** > > - Which files/modules implement it. > - Coverage percentage: **Fully / Partial / Missing**, with an approximate > percentage. > - Why implementation diverged from an "ideal" architecture. > - What alternatives were likely considered. > - Edge cases that shaped the current design. > - Related tests, fixtures, migrations, configuration, or documentation. > - Risks caused by the current implementation shape. --- ## 10 — Evolution · Phase 10: Gap Analysis > Compare "current state" from archaeology to the "desired state" implied by > foundations, documentation, roadmap, open TODOs, tests, issues, or current > project direction. > > **Deliverable:** `devdocs/evolution/gap_analysis.md` > > **Must include:** > > 1. Concepts needing implementation. > 2. Architecture changes required. > 3. Technical debt blocking progress. > 4. What can be incrementally improved. > 5. What requires a rewrite, if anything, with justification. > > **Constraints:** > > - Be realistic. Prefer incremental improvements unless a rewrite is > unavoidable. > - Call out risks and unknowns explicitly. > - Separate "known gap" from "inferred gap". > - Do not invent product requirements that are not supported by code, docs, > tests, or explicit roadmap artifacts. > - Where desired state is unclear, propose the smallest next step that clarifies > it. --- ## 11 — Evolution · Phase 11: Gap Closure Strategy > Using `devdocs/evolution/gap_analysis.md`, create a phased plan that is > executable. > > **Deliverable:** `devdocs/evolution/gap_closure_plan.md` > > **Sections:** > > 1. **Quick wins:** immediate, low-risk. > 2. **Incremental improvements:** module-by-module or subsystem-by-subsystem. > 3. **Major refactoring:** requires planning. > 4. **Complete rewrites:** only if necessary. > > **For each phase include:** > > - Dependencies and prerequisites. > - Risk assessment and mitigation. > - Testing/verification strategy. > - Rollback plan. > - Expected developer workflow. > - Suggested commit or PR boundaries. > - Explicit non-goals. --- ## 12 — Evolution · Phase 12: Baseline Smoke Tests > Establish a working baseline with smoke tests that validate what currently > works. > > **Create:** `smoke_tests/check_what_is_working/` > > **Deliverables:** > > **A)** `smoke_tests/check_what_is_working/README.md` > > - Explain the smoke-test strategy for this project. > - Provide commands to run the most relevant existing checks, such as unit > tests, integration tests, linting, type checks, formatting checks, builds, > packaging, migrations, static analysis, security checks, or end-to-end tests. > - Explain any prerequisites, environment variables, services, fixtures, > containers, databases, emulators, browsers, or local assets required. > > **B)** `smoke_tests/check_what_is_working/test_plan.md` > > - Define 5 smoke-test areas, each with 5 focused cases, for **25 total**. > - Avoid mocks unless real components are impractical or unsafe. > - Use real components and real data flows where feasible. > - Prefer the repository's existing test framework. > - If no suitable test framework exists, create the smallest practical smoke > harness under an existing module/package/service — not a new top-level > architecture — with a clear entry point and clear run instructions. > > **C)** `smoke_tests/check_what_is_working/report.md` > > - After you create the plan, run the easiest subset of checks, such as > build + existing tests + lint/typecheck where available. > - Document: > - What works as expected. > - What is broken but acceptable, and why. > - What is broken and blocks progress. > - What could not be run, and why. > - Exact commands executed. > - Relevant error excerpts, without dumping excessive logs. > > **Constraints:** > > - Do not introduce a new testing framework if one already exists. > - Do not require paid services, production credentials, or destructive > operations for smoke tests. > - Do not mutate production data or external systems. > - Keep any added smoke-test code clearly isolated and easy to remove. --- ## 13 — Evolution · Phase 13: Codebase Cleanup Inventory > Identify candidates for removal, consolidation, or quarantine, but **do not > delete anything**. > > **Deliverable:** `devdocs/archaeology/cleanup_inventory.md` > > **Include:** > > - Unreferenced files/modules/packages/services. > - Dead code paths / unreachable functions. > - Commented-out blocks. > - Duplicate implementations. > - Abandoned features. > - Tests for non-existent or obsolete behavior. > - Orphaned config. > - Unused scripts. > - Stale generated files. > - Deprecated migrations or schemas. > - Unused assets, fixtures, mock data, or sample data. > - Anything possibly used dynamically, flagged as **"dynamic risk"**. > > **Include explicit caution notes on:** > > - Dynamic loading > - Reflection > - Plugin systems > - Runtime discovery > - Config references > - Feature flags > - Build-time generation > - Deployment scripts > - Database migrations > - Audit/compliance retention > - Legal/licensing retention > - Backwards compatibility > - Public API compatibility > > **For each cleanup candidate include:** > > - File path or symbol. > - Evidence it may be unused. > - Confidence level. > - Risk level. > - Verification step before removal. > - Suggested action: remove, consolidate, quarantine, document, or leave alone. --- ## 14 — Evolution · Phase 14: Strategic Refactoring Opportunities + Roadmap > Identify the highest-ROI refactors that enable safer, faster, and more > reliable future development. > > **Deliverables:** > > **1)** `devdocs/evolution/refactoring_opportunities.md` > > For each opportunity: > > - Current problematic pattern, with file paths. > - Proposed abstraction, pattern, module boundary, or simplification. > - Benefits, such as testability, maintainability, reproducibility, security, > performance, scalability, operability, developer experience, or release > safety. > - Effort estimate. > - Risk assessment and mitigation. > - ROI justification. > - First safe step. > - Verification strategy. > - Rollback plan. > > **2)** `devdocs/evolution/implementation_roadmap.md` > > Create a roadmap that combines: > > - Critical cleanup items from cleanup inventory. > - Essential refactors that unblock other work. > - Fixes for broken core functionality from smoke report. > - Incremental feature gaps from gap analysis. > - Documentation updates needed to prevent future drift. > > Structure into phases: > > - **Phase A:** Foundation > - **Phase B:** Core Refactoring > - **Phase C:** Gap Filling > - **Phase D:** Integration & Polish > > For each item include: > > - Specific files/modules affected. > - Dependencies: what must be done first. > - Success criteria. > - Risk level. > - Verification steps. > - Suggested PR size. > - Rollback approach. > - Owner/role suggestion if relevant, such as frontend, backend, platform, QA, > security, data, design, or DevOps. --- *End of prompt pack.*