# Prompt: Reverse-Engineer a Comprehensive PRD from a Code Repository > Usage: fill in the `INPUTS` block, paste the whole thing as your first message in a > session that has filesystem/repo access. The output is designed to be fed into a > follow-on "review and test plan" prompt, so the ID scheme and evidence pointers > matter — don't strip them. --- ## INPUTS - **Repository path / URL:** `{{REPO_PATH}}` - **Product or system name:** `{{PRODUCT_NAME}}` - **Intended PRD audience:** `{{AUDIENCE}}` (e.g. new engineers joining, a client, an auditor, future-me) - **Known context I already have:** `{{EXTRA_CONTEXT}}` (may be "none") - **Out of scope:** `{{EXCLUSIONS}}` (vendored deps, generated code, submodules — may be "none") - **Depth:** `{{DEPTH}}` — one of `survey` (half-day read), `standard`, or `exhaustive` (every module) --- ## ROLE You are a staff-level engineer performing a documentation archaeology exercise. You have been handed a codebase with no reliable product documentation and asked to reconstruct the Product Requirements Document that *would have produced this system*. You are documenting the system **as built**, not as anyone wishes it were built. You are not refactoring, not fixing bugs, and not writing code. Your only deliverable is the PRD. ## GROUNDING RULES (non-negotiable) 1. **Evidence or nothing.** Every functional claim must cite at least one concrete artifact: `path/to/file.rs:120-148`, a route definition, a schema, a migration, a test name, a CI job, an env var. If you cannot cite it, it does not go in the PRD as a fact. 2. **Three-tier labeling.** Tag every non-obvious statement: - `[OBSERVED]` — directly readable from the code, config, or tests. - `[INFERRED]` — a reasonable conclusion from observed evidence; state the inference chain in one clause. - `[UNKNOWN]` — the code does not answer this. Say so plainly and add it to Open Questions. 3. **No invented rationale.** Do not write "this was designed for scalability" unless a comment, ADR, commit message, or benchmark says so. Absence of stated rationale is itself a finding. 4. **Docs are claims, not truth.** When README/docs/comments contradict the code, the code wins and the contradiction is recorded in the Discrepancies section. 5. **Preserve ambiguity.** Where two readings of the behavior are equally supported, present both rather than picking one silently. 6. **Dead code is a finding.** Unreferenced modules, disabled feature flags, and commented-out routes get recorded — the test plan needs to know what not to test. ## INVESTIGATION PROTOCOL Work the phases in order. Do not begin writing the PRD until Phase 3 is complete. Announce each phase transition with a one-line status so I can interrupt. ### Phase 1 — Reconnaissance (breadth before depth) Build a map before reading implementation: - Repo layout: top two or three directory levels, workspace/monorepo members, build targets. - Manifests and lockfiles: languages, runtimes, minimum versions, direct dependencies and what each one implies about capability (an HTTP framework implies a server; a queue client implies async work; an auth library implies an identity model). - Entry points: `main`, server bootstrap, CLI definitions, background workers, cron/scheduler registrations, lambda handlers. - Public surface: HTTP routes, RPC/gRPC services, GraphQL schema, CLI subcommands, exported library API, event topics consumed and produced, webhooks. - Persistence: schema files, migrations (read them in order — they encode history), ORM models, cache keys, blob layout. - Configuration: every environment variable, config file key, feature flag, secret name, and its default. Defaults reveal intended deployment shape. - Operational surface: Dockerfiles, compose files, k8s manifests, Terraform, CI workflows, health/readiness endpoints, metrics and log statements. - Existing tests: what is covered tells you what the authors considered risky. - History: recent commit messages, release notes, CHANGELOG, ADRs, issue/PR templates. Produce a **Repository Map** artifact at the end of this phase and pause for my confirmation before proceeding. ### Phase 2 — Deep read (behavior extraction) For each subsystem identified in Phase 1, trace behavior end to end rather than reading files alphabetically. Follow at least these traces: - The primary happy-path request or job, from ingress to persistence to response. - Authentication and authorization: who can call what, where the check lives, what happens on failure. - Every error and failure path you can find: retries, timeouts, circuit breakers, dead-letter handling, partial-failure semantics, idempotency guarantees. - State machines and lifecycle transitions for the core domain objects. - Validation rules and their exact constraints (lengths, formats, ranges, uniqueness). - External integrations: what is called, with what contract, and what happens when it is down. - Concurrency: locking, transactions, isolation levels, background job ordering assumptions. Capture business rules as you find them, in the code's own terms. Domain vocabulary from identifiers and comments becomes the PRD glossary — do not translate it into generic language. ### Phase 3 — Synthesis Before drafting, resolve: - What problem does this system solve, and for whom? Derive from the domain model and the operations exposed, not from marketing text. - What are the actors/personas, evidenced by roles, permission checks, or distinct API clients? - What are the invariants the system tries never to violate? - Where is the complexity concentrated, and what does that concentration imply about the requirements that drove it? - What is deliberately *not* handled (missing endpoints, TODOs, explicit `unimplemented!`, unhandled cases)? ### Phase 4 — Write the PRD Use the template below verbatim for structure and numbering. ## PRD OUTPUT TEMPLATE Write in clear prose paragraphs. Use tables only for requirement registers, data dictionaries, and configuration references. Every requirement gets a stable ID; IDs are permanent and never renumbered. **ID scheme:** | Prefix | Meaning | |--------|---------| | `FR-###` | Functional requirement | | `NFR-###` | Non-functional requirement (performance, security, reliability, operability) | | `DR-###` | Data requirement (entity, field, constraint, retention) | | `IR-###` | Integration requirement (external system contract) | | `CR-###` | Constraint (platform, regulatory, architectural, backward-compat) | | `BR-###` | Business rule / invariant | | `OQ-###` | Open question | | `DX-###` | Discrepancy between code and documentation | --- ### 1. Document Control Source repository, commit SHA or ref reviewed, date, depth setting used, coverage statement (which directories were read in full, which were sampled, which were skipped and why). ### 2. Executive Summary Three to five paragraphs: what the system is, what it does, who uses it, how it is deployed, and the three most important things a reader should understand before touching it. ### 3. Problem Statement and Goals The problem the system addresses, inferred goals, and explicit non-goals. Label inference level throughout. ### 4. Users, Actors, and Personas Every distinct caller: human roles, service accounts, automated clients, administrators. For each, cite the evidence (permission constant, role enum, API key scope, separate ingress). ### 5. System Context Where this system sits: upstream producers, downstream consumers, external services, data sources. Include a Mermaid context diagram. ### 6. Functional Requirements The core of the document. Group by subsystem or user-facing capability. For each requirement: > **FR-001 — ** > **Description:** what the system does, in behavioral terms. > **Trigger:** what initiates it. > **Preconditions:** what must be true first. > **Behavior:** the actual logic, including branches. > **Outputs and side effects:** responses, persisted state, emitted events, notifications. > **Error handling:** each failure mode and the resulting behavior. > **Evidence:** `path:lines`, route/handler name, test names. > **Confidence:** OBSERVED | INFERRED | PARTIAL > **Related:** other IDs. Be exhaustive rather than elegant. A requirement per meaningful behavior, not per file. ### 7. Business Rules and Invariants `BR-###` entries: the domain rules the code enforces, including validation constraints, state transition legality, uniqueness and ordering guarantees, and monetary/time/unit rules. Note where enforcement lives (database constraint vs application check vs client-side only) — this distinction is critical for the test plan. ### 8. Data Requirements Entity-by-entity data dictionary: fields, types, nullability, defaults, constraints, relationships, indexes. Then lifecycle: creation, mutation paths, soft/hard deletion, retention, archival, PII classification if identifiable. Note migration history where it reveals intent. Include a Mermaid ER diagram. ### 9. Interface Specifications Every external surface, fully specified: method, path, params, request/response shapes, status codes, auth requirements, rate limits, pagination, versioning. Same treatment for CLI commands, events, and exported library APIs. ### 10. Integration Requirements `IR-###` per external dependency: what is called, contract, auth mechanism, failure behavior, timeout and retry policy, and what degrades if it is unavailable. ### 11. Non-Functional Requirements `NFR-###` covering performance (with any evidenced targets, timeouts, pool sizes, batch sizes), scalability and statefulness, availability and degradation, security (authn/authz model, secret handling, input validation, transport security), observability (logs, metrics, traces, health checks), and maintainability. Where a value appears in code as a constant or config default, cite it; where no target exists, mark `[UNKNOWN]` — do not invent SLAs. ### 12. Constraints and Assumptions `CR-###`: platform and runtime requirements, architectural constraints, backward-compatibility obligations, licensing, regulatory signals, and the assumptions the code makes about its environment (clock, ordering, network reachability, single vs multi-instance). ### 13. Operational Requirements Deployment topology, configuration reference table (every var: name, purpose, default, required?, secret?), startup and shutdown behavior, migration procedure, backup/restore if evidenced, and runbook-relevant failure modes. ### 14. Current Implementation State What is complete, partial, stubbed, deprecated, dead, or flag-disabled. TODO/FIXME inventory with locations. Known limitations visible in the code. ### 15. Discrepancies `DX-###`: every place documentation, comments, naming, or tests disagree with actual behavior. State both claims and which one the code supports. ### 16. Open Questions `OQ-###`: what the codebase cannot answer, why it matters, who or what could answer it, and the risk of proceeding without the answer. Rank by impact. ### 17. Glossary Domain terms as the code uses them, with definitions derived from usage. ### 18. Traceability Appendix A single table mapping every requirement ID to its primary evidence location and to any existing test that appears to exercise it (or `NONE` where no test was found). This table is the input contract for the downstream test-plan prompt — make it complete and machine-readable. --- ## SELF-CHECK BEFORE DELIVERING Verify and report explicitly: - Every requirement ID is unique, cited, and confidence-labeled. - No requirement asserts intent without a documented source. - The traceability appendix contains every ID that appears in the body, and no others. - Coverage statement in §1 honestly reflects what you did and did not read. - Every `[UNKNOWN]` has a corresponding `OQ-###`. - Every `NONE` in the traceability table is a genuine gap, not a search failure. Then state, in one paragraph, the three areas of the PRD you are least confident about and what additional access or context would raise that confidence. ## INTERACTION RULES - Pause after Phase 1 for confirmation; otherwise work continuously. - Ask questions only when the answer would change the structure of the PRD — batch small clarifications into the Open Questions section instead of interrupting. - If the repository is too large for the chosen depth, say so, propose a prioritized subset, and wait rather than silently sampling. - Write the final PRD to a file rather than inline in chat.