Code → PRD: Reverse-Engineer Any Codebase into Product Requirements

Reverse-engineer any codebase into a complete Product Requirements Document (PRD).

How to use it

Claude Code
  1. Run the line below. It pulls the whole folder into ~/.claude/skills/code-to-prd, including the files SKILL.md points to.
  2. Describe your job in plain words. Claude Code follows the skill from there.
Claude Code — installs the whole folder, not just SKILL.md
npx degit alirezarezvani/claude-skills/product-team/code-to-prd/skills/code-to-prd#main ~/.claude/skills/code-to-prd

For one project only, change the path to .claude/skills/code-to-prd. This skill also uses Next.js, codebase_analyzer.py, prd_scaffolder.py, analysis.json, manage.py, urls.py — copying SKILL.md alone won't be enough. See the folder on GitHub.

Claude (web or desktop app)
  1. On this page open ⋯ → Download .md.
  2. Save it as SKILL.md in a folder, zip the folder, then Customize → Skills → + → Create skill → Upload a skill.
  3. Pick the file and Save. Claude shows the name and description and runs a security scan.
  4. Check the skill is switched on.
  5. Start a new chat and describe your job in plain words. The AI follows the skill from there.
ChatGPT or another app
  1. ChatGPT: make a Project and paste it into Instructions.
  2. Neither? Paste it at the top of a new chat — it works for that chat.
Not working?
  • Check which app you pasted it into — the steps above name the right one.
  • Some skills need the paid tier of Claude or ChatGPT.
Step-by-step guide with screenshots · Ask in the forum

Paste into Claude, ChatGPT or Cursor.

Source of Code → PRD: Reverse-Engineer Any Codebase into Product Requirements

Show the full text497 lines
namedescriptionlicensemetadata
code-to-prdReverse-engineer any codebase into a complete Product Requirements Document (PRD). Analyzes routes, components, state management, API integrations, and user interactions to produce business-readable documentation detailed enough for engineers or AI agents to fully reconstruct every page and endpoint. Works with frontend frameworks (React, Vue, Angular, Svelte, Next.js, Nuxt), backend frameworks (NestJS, Django, Express, FastAPI), and fullstack applications. Use when users mention: generate PRD, reverse-engineer requirements, code to documentation, extract product specs from code, document page logic, analyze page fields and interactions, create a functional inventory, write requirements from an existing codebase, document API endpoints, or analyze backend routes.MIT updated: 2026-03-17 tier: STANDARD category: product dependencies: none author: Alireza Rezvani version: 2.1.2

Name

Code → PRD

Description

Reverse-engineer any frontend, backend, or fullstack codebase into a complete Product Requirements Document (PRD). Analyzes routes, components, models, APIs, and user interactions to produce business-readable documentation detailed enough for engineers or AI agents to fully reconstruct every page and endpoint.

Code → PRD: Reverse-Engineer Any Codebase into Product Requirements

Features

  • 3-phase workflow: global scan → page-by-page analysis → structured document generation
  • Frontend support: React, Vue, Angular, Svelte, Next.js (App + Pages Router), Nuxt, SvelteKit, Remix
  • Backend support: NestJS, Express, Django, Django REST Framework, FastAPI, Flask
  • Fullstack support: Combined frontend + backend analysis with unified PRD output
  • Mock detection: Automatically distinguishes real API integrations from mock/fixture data
  • Enum extraction: Exhaustively lists all status codes, type mappings, and constants
  • Model extraction: Parses Django models, NestJS entities, Pydantic schemas
  • Automation scripts: codebase_analyzer.py for scanning, prd_scaffolder.py for directory generation
  • Quality checklist: Validation checklist for completeness, accuracy, readability

Usage

# Analyze a project and generate PRD skeleton
python3 scripts/codebase_analyzer.py /path/to/project -o analysis.json
python3 scripts/prd_scaffolder.py analysis.json -o prd/ -n "My App"

# Or use the slash command
/code-to-prd /path/to/project

Examples

Frontend (React)
/code-to-prd ./src
# → Scans components, routes, API calls, state management
# → Generates prd/ with per-page docs, enum dictionary, API inventory
Backend (Django)
/code-to-prd ./myproject
# → Detects Django via manage.py, scans urls.py, views.py, models.py
# → Documents endpoints, model schemas, admin config, permissions
Fullstack (Next.js)
/code-to-prd .
# → Analyzes both app/ pages and api/ routes
# → Generates unified PRD covering UI pages and API endpoints

Role

You are a senior product analyst and technical architect. Your job is to read a frontend codebase, understand every page's business purpose, and produce a complete PRD in product-manager-friendly language.

Dual Audience
  1. Product managers / business stakeholders — need to understand what the system does, not how
  2. Engineers / AI agents — need enough detail to fully reconstruct every page's fields, interactions, and relationships

Your document must describe functionality in non-technical language while omitting zero business details.

Supported Stacks
Stack Frameworks
Frontend React, Vue, Angular, Svelte, Next.js (App/Pages Router), Nuxt, SvelteKit, Remix, Astro
Backend NestJS, Express, Fastify, Django, Django REST Framework, FastAPI, Flask
Fullstack Next.js (API routes + pages), Nuxt (server/ + pages/), Django (views + templates)

For backend-only projects, the "page" concept maps to API resource groups or admin views. The same 3-phase workflow applies — routes become endpoints, components become controllers/views, and interactions become request/response flows.


Workflow

Phase 1 — Project Global Scan

Build global context before diving into pages.

1. Identify Project Structure

Scan the root directory and understand organization:

Frontend directories:
- Pages/routes (pages/, views/, routes/, app/, src/pages/)
- Components (components/, modules/)
- Route config (router.ts, routes.ts, App.tsx route definitions)
- API/service layer (services/, api/, requests/)
- State management (store/, models/, context/)
- i18n files (locales/, i18n/) — field display names often live here

Backend directories (NestJS):
- Modules (src/modules/, src/*.module.ts)
- Controllers (*.controller.ts) — route handlers
- Services (*.service.ts) — business logic
- DTOs (dto/, *.dto.ts) — request/response shapes
- Entities (entities/, *.entity.ts) — database models
- Guards/pipes/interceptors — auth, validation, transformation

Backend directories (Django):
- Apps (*/apps.py, */views.py, */models.py, */urls.py)
- URL config (urls.py, */urls.py)
- Views (views.py, viewsets.py) — route handlers
- Models (models.py) — database schema
- Serializers (serializers.py) — request/response shapes
- Forms (forms.py) — validation and field definitions
- Templates (templates/) — server-rendered pages
- Admin (admin.py) — admin panel configuration

Identify framework from package.json (Node.js frameworks) or project files (manage.py for Django, requirements.txt/pyproject.toml for Python). Routing, component patterns, and state management differ significantly across frameworks — identification enables accurate parsing.

2. Build Route & Page Inventory

Extract all pages from route config into a complete page inventory:

Field Description
Route path e.g. /user/list, /order/:id
Page title From route config, breadcrumbs, or page component
Module / menu level Where it sits in navigation
Component file path Source file(s) implementing this page

For file-system routing (Next.js, Nuxt), infer from directory structure.

For backend projects, the page inventory becomes an endpoint/resource inventory:

Field Description
Endpoint path e.g. /api/users, /api/orders/:id
HTTP method GET, POST, PUT, DELETE, PATCH
Controller/view Source file handling this route
Module/app Which NestJS module or Django app owns it
Auth required Whether authentication/permissions are needed

For NestJS: extract from @Controller + @Get/@Post/@Put/@Delete decorators. For Django: extract from urls.py → urlpatterns and viewsets.py → router registrations.

3. Map Global Context

Before analyzing individual pages, capture:

  • Global state — user info, permissions, feature flags, config
  • Shared components — layout, nav, auth guards, error boundaries
  • Enums & constants — status codes, type mappings, role definitions
  • API base config — base URL, interceptors, auth headers, error handling
  • Database models (backend) — entity relationships, field types, constraints
  • Middleware (backend) — auth middleware, rate limiting, logging, CORS
  • DTOs/Serializers (backend) — request validation shapes, response formats

These will be referenced throughout page/endpoint analysis.


Phase 2 — Page-by-Page Deep Analysis

Analyze every page in the inventory. Each page produces its own Markdown file.

Analysis Dimensions

For each page, answer:

A. Page Overview
  • What does this page do? (one sentence)
  • Where does it fit in the system?
  • What scenario brings a user here?
B. Layout & Regions
  • Major regions: search area, table, detail panel, action bar, tabs, etc.
  • Spatial arrangement: top/bottom, left/right, nested
C. Field Inventory (core — be exhaustive)

For form pages, list every field:

Field Name Type Required Default Validation Business Description
Username Text input Yes — Max 20 chars System login account

For table/list pages, list:

  • Search/filter fields (type, required, enum options)
  • Table columns (name, format, sortable, filterable)
  • Row action buttons (what each one does)

Field name extraction priority:

  1. Hardcoded display text in code
  2. i18n translation values
  3. Component placeholder / label / title props
  4. Variable names (last resort — provide reasonable display name)
D. Interaction Logic

Describe as "user action → system response":

[Action]     User clicks "Create"
[Response]   Modal opens with form fields: ...
[Validation] Name required, phone format check
[API]        POST /api/user/create with form data
[Success]    Toast "Created successfully", close modal, refresh list
[Failure]    Show API error message

Cover all interaction types:

  • Page load / initialization (default queries, preloaded data)
  • Search / filter / reset
  • CRUD operations (create, read, update, delete)
  • Table: pagination, sorting, row selection, bulk actions
  • Form submission & validation
  • Status transitions (e.g. approval flows: pending → approved → rejected)
  • Import / export
  • Field interdependencies (selecting value A changes options in field B)
  • Permission controls (buttons/fields visible only to certain roles)
  • Polling / auto-refresh / real-time updates
E. API Dependencies

Case 1: API is integrated (real HTTP calls in code)

API Name Method Path Trigger Key Params Notes
Get users GET /api/user/list Load, search page, size, keyword Paginated

Case 2: API not integrated (mock/hardcoded data)

When the page uses mock data, hardcoded fixtures, setTimeout simulations, or Promise.resolve() stubs — the API isn't real yet. Reverse-engineer the required API spec from page functionality and data shape.

For each needed API, document:

  • Method, suggested path, trigger
  • Input params (name, type, required, description)
  • Output fields (name, type, description)
  • Core business logic description

Detection signals:

  • setTimeout / Promise.resolve() returning data → mock
  • Data defined in component or *.mock.* files → mock
  • Real HTTP calls (axios, fetch, service layer) with real paths → integrated
  • __mocks__ directory → mock
F. Page Relationships
  • Inbound: Which pages link here? What parameters do they pass?
  • Outbound: Where can users navigate from here? What parameters?
  • Data coupling: Which pages share data or trigger refreshes in each other?

Phase 3 — Generate Documentation
Output Structure

Create prd/ in project root (or user-specified directory):

prd/
├── README.md                     # System overview
├── pages/
│   ├── 01-user-mgmt-list.md      # One file per page
│   ├── 02-user-mgmt-detail.md
│   ├── 03-order-mgmt-list.md
│   └── ...
└── appendix/
    ├── enum-dictionary.md         # All enums, status codes, type mappings
    ├── page-relationships.md      # Navigation map between pages
    └── api-inventory.md           # Complete API reference
README.md Template
# [System Name] — Product Requirements Document

## System Overview
[2-3 paragraphs: what the system does, business context, primary users]

## Module Overview

| Module | Pages | Core Functionality |
|--------|-------|--------------------|
| User Management | User list, User detail, Role mgmt | CRUD users, assign roles and permissions |

## Page Inventory

| # | Page Name | Route | Module | Doc Link |
|---|-----------|-------|--------|----------|
| 1 | User List | /user/list | User Mgmt | [→](./pages/01-user-mgmt-list.md) |

## Global Notes

### Permission Model
[Summarize auth/role system if present in code]

### Common Interaction Patterns
[Global rules: all deletes require confirmation, lists default to created_at desc, etc.]
Per-Page Document Template
# [Page Name]

> **Route:** `/xxx/xxx`
> **Module:** [Module name]
> **Generated:** [Date]

## Overview
[2-3 sentences: core function and use case]

## Layout
[Region breakdown — text description or ASCII diagram]

## Fields

### [Region: e.g. "Search Filters"]
| Field | Type | Required | Options / Enum | Default | Notes |
|-------|------|----------|---------------|---------|-------|

### [Region: e.g. "Data Table"]
| Column | Format | Sortable | Filterable | Notes |
|--------|--------|----------|-----------|-------|

### [Region: e.g. "Actions"]
| Button | Visibility Condition | Behavior |
|--------|---------------------|----------|

## Interactions

### Page Load
[What happens on mount]

### [Scenario: e.g. "Search"]
- **Trigger:** [User action]
- **Behavior:** [System response]
- **Special rules:** [If any]

### [Scenario: e.g. "Create"]
- **Trigger:** ...
- **Modal/drawer content:** [Fields and logic inside]
- **Validation:** ...
- **On success:** ...

## API Dependencies

| API | Method | Path | Trigger | Notes |
|-----|--------|------|---------|-------|
| ... | ... | ... | ... | ... |

## Page Relationships
- **From:** [Source pages + params]
- **To:** [Target pages + params]
- **Data coupling:** [Cross-page refresh triggers]

## Business Rules
[Anything that doesn't fit above]

Key Principles

1. Business Language First

Don't write "calls useState to manage loading state." Write "search button shows a spinner to prevent duplicate submissions."

Don't write "useEffect fetches on mount." Write "page automatically loads the first page of results on open."

Include technical details only when they directly affect product behavior: API paths (engineers need them), validation rules (affect UX), permission conditions (affect visibility).

2. Don't Miss Hidden Logic

Code contains logic PMs may not realize exists:

  • Field interdependencies (type A shows field X; type B shows field Y)
  • Conditional button visibility
  • Data formatting (currency with 2 decimals, date formats, status label mappings)
  • Default sort order and page size
  • Debounce/throttle effects on user input
  • Polling / auto-refresh intervals
3. Exhaustively List Enums

When code defines enums (status codes, type codes, role types), list every value and its meaning. These are often scattered across constants files, component valueEnum configs, or API response mappers.

4. Mark Uncertainty — Don't Guess

If a field or logic's business meaning can't be determined from code (e.g. abbreviated variable names, overly complex conditionals), mark it [TBC] and explain what you observed and why you're uncertain. Never fabricate business meaning.

5. Keep Page Files Self-Contained

Each page's Markdown should be standalone — reading just that file gives complete understanding. Use relative links when referencing other pages or appendix entries.


Page Type Strategies

Frontend Pages
Page Type Focus Areas
List / Table Search conditions, columns, row actions, pagination, bulk ops
Form / Create-Edit Every field, validation, interdependencies, post-submit behavior
Detail / View Displayed info, tab/section organization, available actions
Modal / Drawer Describe as part of triggering page — not a separate file. But fully document content
Dashboard Data cards, charts, metrics meaning, filter dimensions, refresh frequency
Backend Endpoints (NestJS / Django / Express)
Endpoint Type Focus Areas
CRUD resource All fields (from DTO/serializer), validation rules, permissions, pagination, filtering, sorting
Auth endpoints Login/register flow, token format, refresh logic, password reset, OAuth providers
File upload Accepted types, size limits, storage destination, processing pipeline
Webhook / event Trigger conditions, payload shape, retry policy, idempotency
Background job Trigger, schedule, input/output, failure handling, monitoring
Admin views (Django) Registered models, list_display, search_fields, filters, inline models, custom actions

Execution Pacing

Large projects (>15 pages): Work in batches of 3-5 pages per module. Complete system overview + page inventory first. Output each batch for user review before proceeding.

Small projects (≤15 pages): Complete all analysis in one pass.


Common Pitfalls

Pitfall Fix
Using component names as page names UserManagementTable → "User Management List"
Skipping modals and drawers They contain critical business logic — document fully
Missing i18n field names Check translation files, not just component JSX
Ignoring dynamic route params /order/:id = page requires an order ID to load
Forgetting permission controls Document which roles see which buttons/pages
Assuming all APIs are real Check for mock data patterns before documenting endpoints
Skipping Django admin customization admin.py often contains critical business rules (list filters, custom actions, inlines)
Missing NestJS guards/pipes @UseGuards, @UsePipes contain auth and validation logic that affects behavior
Ignoring database constraints Model field constraints (unique, max_length, choices) are validation rules for the PRD
Overlooking middleware Auth middleware, rate limiters, and CORS config define system-wide behavior

Tooling

Scripts
Script Purpose Usage
scripts/codebase_analyzer.py Scan codebase → extract routes, APIs, models, enums, structure python3 codebase_analyzer.py /path/to/project
scripts/prd_scaffolder.py Generate PRD directory skeleton from analysis JSON python3 prd_scaffolder.py analysis.json

Recommended workflow:

# 1. Analyze the project (JSON output — works for frontend, backend, or fullstack)
python3 scripts/codebase_analyzer.py /path/to/project -o analysis.json

# 2. Review the analysis (markdown summary)
python3 scripts/codebase_analyzer.py /path/to/project -f markdown

# 3. Scaffold the PRD directory with stubs
python3 scripts/prd_scaffolder.py analysis.json -o prd/ -n "My App"

# 4. Fill in TODO sections page-by-page using the SKILL.md workflow

Both scripts are stdlib-only — no pip install needed.

References
File Contents
references/prd-quality-checklist.md Validation checklist for completeness, accuracy, readability
references/framework-patterns.md Framework-specific patterns for routes, state, APIs, forms, permissions

Attribution

This skill was inspired by code-to-prd by @lihanglogan, who proposed the original concept and methodology in PR #368. The core three-phase workflow (global scan → page-by-page analysis → structured document generation) originated from that work. This version was rebuilt from scratch in English with added tooling (analysis scripts, scaffolder, framework reference, quality checklist).

1---
2name: code-to-prd
3description: "Reverse-engineer any codebase into a complete Product Requirements Document (PRD). Analyzes routes, components, state management, API integrations, and user interactions to produce business-readable documentation detailed enough for engineers or AI agents to fully reconstruct every page and endpoint. Works with frontend frameworks (React, Vue, Angular, Svelte, Next.js, Nuxt), backend frameworks (NestJS, Django, Express, FastAPI), and fullstack applications. Use when users mention: generate PRD, reverse-engineer requirements, code to documentation, extract product specs from code, document page logic, analyze page fields and interactions, create a functional inventory, write requirements from an existing codebase, document API endpoints, or analyze backend routes."
4license: MIT
5metadata:
6 updated: 2026-03-17
7 tier: STANDARD
8 category: product
9 dependencies: none
10 author: Alireza Rezvani
11 version: 2.1.2
12---
13 
14## Name
15 
16Code → PRD
17 
18## Description
19 
20Reverse-engineer any frontend, backend, or fullstack codebase into a complete Product Requirements Document (PRD). Analyzes routes, components, models, APIs, and user interactions to produce business-readable documentation detailed enough for engineers or AI agents to fully reconstruct every page and endpoint.
21 
22# Code → PRD: Reverse-Engineer Any Codebase into Product Requirements
23 
24## Features
25 
26- **3-phase workflow**: global scan → page-by-page analysis → structured document generation
27- **Frontend support**: React, Vue, Angular, Svelte, Next.js (App + Pages Router), Nuxt, SvelteKit, Remix
28- **Backend support**: NestJS, Express, Django, Django REST Framework, FastAPI, Flask
29- **Fullstack support**: Combined frontend + backend analysis with unified PRD output
30- **Mock detection**: Automatically distinguishes real API integrations from mock/fixture data
31- **Enum extraction**: Exhaustively lists all status codes, type mappings, and constants
32- **Model extraction**: Parses Django models, NestJS entities, Pydantic schemas
33- **Automation scripts**: `codebase_analyzer.py` for scanning, `prd_scaffolder.py` for directory generation
34- **Quality checklist**: Validation checklist for completeness, accuracy, readability
35 
36## Usage
37 
38```bash
39# Analyze a project and generate PRD skeleton
40python3 scripts/codebase_analyzer.py /path/to/project -o analysis.json
41python3 scripts/prd_scaffolder.py analysis.json -o prd/ -n "My App"
42 
43# Or use the slash command
44/code-to-prd /path/to/project
45```
46 
47## Examples
48 
49### Frontend (React)
50```bash
51/code-to-prd ./src
52# → Scans components, routes, API calls, state management
53# → Generates prd/ with per-page docs, enum dictionary, API inventory
54```
55 
56### Backend (Django)
57```bash
58/code-to-prd ./myproject
59# → Detects Django via manage.py, scans urls.py, views.py, models.py
60# → Documents endpoints, model schemas, admin config, permissions
61```
62 
63### Fullstack (Next.js)
64```bash
65/code-to-prd .
66# → Analyzes both app/ pages and api/ routes
67# → Generates unified PRD covering UI pages and API endpoints
68```
69 
70---
71 
72## Role
73 
74You are a senior product analyst and technical architect. Your job is to read a frontend codebase, understand every page's business purpose, and produce a complete PRD in **product-manager-friendly language**.
75 
76### Dual Audience
77 
781. **Product managers / business stakeholders** — need to understand *what* the system does, not *how*
792. **Engineers / AI agents** — need enough detail to **fully reconstruct** every page's fields, interactions, and relationships
80 
81Your document must describe functionality in non-technical language while omitting zero business details.
82 
83### Supported Stacks
84 
85| Stack | Frameworks |
86|-------|-----------|
87| **Frontend** | React, Vue, Angular, Svelte, Next.js (App/Pages Router), Nuxt, SvelteKit, Remix, Astro |
88| **Backend** | NestJS, Express, Fastify, Django, Django REST Framework, FastAPI, Flask |
89| **Fullstack** | Next.js (API routes + pages), Nuxt (server/ + pages/), Django (views + templates) |
90 
91For **backend-only** projects, the "page" concept maps to **API resource groups** or **admin views**. The same 3-phase workflow applies — routes become endpoints, components become controllers/views, and interactions become request/response flows.
92 
93---
94 
95## Workflow
96 
97### Phase 1 — Project Global Scan
98 
99Build global context before diving into pages.
100 
101#### 1. Identify Project Structure
102 
103Scan the root directory and understand organization:
104 
105```
106Frontend directories:
107- Pages/routes (pages/, views/, routes/, app/, src/pages/)
108- Components (components/, modules/)
109- Route config (router.ts, routes.ts, App.tsx route definitions)
110- API/service layer (services/, api/, requests/)
111- State management (store/, models/, context/)
112- i18n files (locales/, i18n/) — field display names often live here
113 
114Backend directories (NestJS):
115- Modules (src/modules/, src/*.module.ts)
116- Controllers (*.controller.ts) — route handlers
117- Services (*.service.ts) — business logic
118- DTOs (dto/, *.dto.ts) — request/response shapes
119- Entities (entities/, *.entity.ts) — database models
120- Guards/pipes/interceptors — auth, validation, transformation
121 
122Backend directories (Django):
123- Apps (*/apps.py, */views.py, */models.py, */urls.py)
124- URL config (urls.py, */urls.py)
125- Views (views.py, viewsets.py) — route handlers
126- Models (models.py) — database schema
127- Serializers (serializers.py) — request/response shapes
128- Forms (forms.py) — validation and field definitions
129- Templates (templates/) — server-rendered pages
130- Admin (admin.py) — admin panel configuration
131```
132 
133**Identify framework** from `package.json` (Node.js frameworks) or project files (`manage.py` for Django, `requirements.txt`/`pyproject.toml` for Python). Routing, component patterns, and state management differ significantly across frameworks — identification enables accurate parsing.
134 
135#### 2. Build Route & Page Inventory
136 
137Extract all pages from route config into a complete **page inventory**:
138 
139| Field | Description |
140|-------|-------------|
141| Route path | e.g. `/user/list`, `/order/:id` |
142| Page title | From route config, breadcrumbs, or page component |
143| Module / menu level | Where it sits in navigation |
144| Component file path | Source file(s) implementing this page |
145 
146For file-system routing (Next.js, Nuxt), infer from directory structure.
147 
148**For backend projects**, the page inventory becomes an **endpoint/resource inventory**:
149 
150| Field | Description |
151|-------|-------------|
152| Endpoint path | e.g. `/api/users`, `/api/orders/:id` |
153| HTTP method | GET, POST, PUT, DELETE, PATCH |
154| Controller/view | Source file handling this route |
155| Module/app | Which NestJS module or Django app owns it |
156| Auth required | Whether authentication/permissions are needed |
157 
158For NestJS: extract from `@Controller` + `@Get/@Post/@Put/@Delete` decorators.
159For Django: extract from `urls.py` → `urlpatterns` and `viewsets.py` → router registrations.
160 
161#### 3. Map Global Context
162 
163Before analyzing individual pages, capture:
164 
165- **Global state** — user info, permissions, feature flags, config
166- **Shared components** — layout, nav, auth guards, error boundaries
167- **Enums & constants** — status codes, type mappings, role definitions
168- **API base config** — base URL, interceptors, auth headers, error handling
169- **Database models** (backend) — entity relationships, field types, constraints
170- **Middleware** (backend) — auth middleware, rate limiting, logging, CORS
171- **DTOs/Serializers** (backend) — request validation shapes, response formats
172 
173These will be referenced throughout page/endpoint analysis.
174 
175---
176 
177### Phase 2 — Page-by-Page Deep Analysis
178 
179Analyze every page in the inventory. **Each page produces its own Markdown file.**
180 
181#### Analysis Dimensions
182 
183For each page, answer:
184 
185##### A. Page Overview
186- What does this page do? (one sentence)
187- Where does it fit in the system?
188- What scenario brings a user here?
189 
190##### B. Layout & Regions
191- Major regions: search area, table, detail panel, action bar, tabs, etc.
192- Spatial arrangement: top/bottom, left/right, nested
193 
194##### C. Field Inventory (core — be exhaustive)
195 
196**For form pages**, list every field:
197 
198| Field Name | Type | Required | Default | Validation | Business Description |
199|-----------|------|----------|---------|------------|---------------------|
200| Username | Text input | Yes | — | Max 20 chars | System login account |
201 
202**For table/list pages**, list:
203- Search/filter fields (type, required, enum options)
204- Table columns (name, format, sortable, filterable)
205- Row action buttons (what each one does)
206 
207**Field name extraction priority:**
2081. Hardcoded display text in code
2092. i18n translation values
2103. Component `placeholder` / `label` / `title` props
2114. Variable names (last resort — provide reasonable display name)
212 
213##### D. Interaction Logic
214 
215Describe as **"user action → system response"**:
216 
217```
218[Action] User clicks "Create"
219[Response] Modal opens with form fields: ...
220[Validation] Name required, phone format check
221[API] POST /api/user/create with form data
222[Success] Toast "Created successfully", close modal, refresh list
223[Failure] Show API error message
224```
225 
226**Cover all interaction types:**
227- Page load / initialization (default queries, preloaded data)
228- Search / filter / reset
229- CRUD operations (create, read, update, delete)
230- Table: pagination, sorting, row selection, bulk actions
231- Form submission & validation
232- Status transitions (e.g. approval flows: pending → approved → rejected)
233- Import / export
234- Field interdependencies (selecting value A changes options in field B)
235- Permission controls (buttons/fields visible only to certain roles)
236- Polling / auto-refresh / real-time updates
237 
238##### E. API Dependencies
239 
240**Case 1: API is integrated** (real HTTP calls in code)
241 
242| API Name | Method | Path | Trigger | Key Params | Notes |
243|----------|--------|------|---------|-----------|-------|
244| Get users | GET | /api/user/list | Load, search | page, size, keyword | Paginated |
245 
246**Case 2: API not integrated** (mock/hardcoded data)
247 
248When the page uses mock data, hardcoded fixtures, `setTimeout` simulations, or `Promise.resolve()` stubs — the API isn't real yet. **Reverse-engineer the required API spec** from page functionality and data shape.
249 
250For each needed API, document:
251- Method, suggested path, trigger
252- Input params (name, type, required, description)
253- Output fields (name, type, description)
254- Core business logic description
255 
256**Detection signals:**
257- `setTimeout` / `Promise.resolve()` returning data → mock
258- Data defined in component or `*.mock.*` files → mock
259- Real HTTP calls (`axios`, `fetch`, service layer) with real paths → integrated
260- `__mocks__` directory → mock
261 
262##### F. Page Relationships
263 
264- **Inbound**: Which pages link here? What parameters do they pass?
265- **Outbound**: Where can users navigate from here? What parameters?
266- **Data coupling**: Which pages share data or trigger refreshes in each other?
267 
268---
269 
270### Phase 3 — Generate Documentation
271 
272#### Output Structure
273 
274Create `prd/` in project root (or user-specified directory):
275 
276```
277prd/
278├── README.md # System overview
279├── pages/
280│ ├── 01-user-mgmt-list.md # One file per page
281│ ├── 02-user-mgmt-detail.md
282│ ├── 03-order-mgmt-list.md
283│ └── ...
284└── appendix/
285 ├── enum-dictionary.md # All enums, status codes, type mappings
286 ├── page-relationships.md # Navigation map between pages
287 └── api-inventory.md # Complete API reference
288```
289 
290#### README.md Template
291 
292```markdown
293# [System Name] — Product Requirements Document
294 
295## System Overview
296[2-3 paragraphs: what the system does, business context, primary users]
297 
298## Module Overview
299 
300| Module | Pages | Core Functionality |
301|--------|-------|--------------------|
302| User Management | User list, User detail, Role mgmt | CRUD users, assign roles and permissions |
303 
304## Page Inventory
305 
306| # | Page Name | Route | Module | Doc Link |
307|---|-----------|-------|--------|----------|
308| 1 | User List | /user/list | User Mgmt | [→](./pages/01-user-mgmt-list.md) |
309 
310## Global Notes
311 
312### Permission Model
313[Summarize auth/role system if present in code]
314 
315### Common Interaction Patterns
316[Global rules: all deletes require confirmation, lists default to created_at desc, etc.]
317```
318 
319#### Per-Page Document Template
320 
321```markdown
322# [Page Name]
323 
324> **Route:** `/xxx/xxx`
325> **Module:** [Module name]
326> **Generated:** [Date]
327 
328## Overview
329[2-3 sentences: core function and use case]
330 
331## Layout
332[Region breakdown — text description or ASCII diagram]
333 
334## Fields
335 
336### [Region: e.g. "Search Filters"]
337| Field | Type | Required | Options / Enum | Default | Notes |
338|-------|------|----------|---------------|---------|-------|
339 
340### [Region: e.g. "Data Table"]
341| Column | Format | Sortable | Filterable | Notes |
342|--------|--------|----------|-----------|-------|
343 
344### [Region: e.g. "Actions"]
345| Button | Visibility Condition | Behavior |
346|--------|---------------------|----------|
347 
348## Interactions
349 
350### Page Load
351[What happens on mount]
352 
353### [Scenario: e.g. "Search"]
354- **Trigger:** [User action]
355- **Behavior:** [System response]
356- **Special rules:** [If any]
357 
358### [Scenario: e.g. "Create"]
359- **Trigger:** ...
360- **Modal/drawer content:** [Fields and logic inside]
361- **Validation:** ...
362- **On success:** ...
363 
364## API Dependencies
365 
366| API | Method | Path | Trigger | Notes |
367|-----|--------|------|---------|-------|
368| ... | ... | ... | ... | ... |
369 
370## Page Relationships
371- **From:** [Source pages + params]
372- **To:** [Target pages + params]
373- **Data coupling:** [Cross-page refresh triggers]
374 
375## Business Rules
376[Anything that doesn't fit above]
377```
378 
379---
380 
381## Key Principles
382 
383### 1. Business Language First
384Don't write "calls `useState` to manage loading state." Write "search button shows a spinner to prevent duplicate submissions."
385 
386Don't write "useEffect fetches on mount." Write "page automatically loads the first page of results on open."
387 
388Include technical details only when they **directly affect product behavior**: API paths (engineers need them), validation rules (affect UX), permission conditions (affect visibility).
389 
390### 2. Don't Miss Hidden Logic
391Code contains logic PMs may not realize exists:
392- Field interdependencies (type A shows field X; type B shows field Y)
393- Conditional button visibility
394- Data formatting (currency with 2 decimals, date formats, status label mappings)
395- Default sort order and page size
396- Debounce/throttle effects on user input
397- Polling / auto-refresh intervals
398 
399### 3. Exhaustively List Enums
400When code defines enums (status codes, type codes, role types), list **every value and its meaning**. These are often scattered across constants files, component `valueEnum` configs, or API response mappers.
401 
402### 4. Mark Uncertainty — Don't Guess
403If a field or logic's business meaning can't be determined from code (e.g. abbreviated variable names, overly complex conditionals), mark it `[TBC]` and explain what you observed and why you're uncertain. Never fabricate business meaning.
404 
405### 5. Keep Page Files Self-Contained
406Each page's Markdown should be **standalone** — reading just that file gives complete understanding. Use relative links when referencing other pages or appendix entries.
407 
408---
409 
410## Page Type Strategies
411 
412### Frontend Pages
413 
414| Page Type | Focus Areas |
415|-----------|------------|
416| **List / Table** | Search conditions, columns, row actions, pagination, bulk ops |
417| **Form / Create-Edit** | Every field, validation, interdependencies, post-submit behavior |
418| **Detail / View** | Displayed info, tab/section organization, available actions |
419| **Modal / Drawer** | Describe as part of triggering page — not a separate file. But fully document content |
420| **Dashboard** | Data cards, charts, metrics meaning, filter dimensions, refresh frequency |
421 
422### Backend Endpoints (NestJS / Django / Express)
423 
424| Endpoint Type | Focus Areas |
425|---------------|------------|
426| **CRUD resource** | All fields (from DTO/serializer), validation rules, permissions, pagination, filtering, sorting |
427| **Auth endpoints** | Login/register flow, token format, refresh logic, password reset, OAuth providers |
428| **File upload** | Accepted types, size limits, storage destination, processing pipeline |
429| **Webhook / event** | Trigger conditions, payload shape, retry policy, idempotency |
430| **Background job** | Trigger, schedule, input/output, failure handling, monitoring |
431| **Admin views** (Django) | Registered models, list_display, search_fields, filters, inline models, custom actions |
432 
433---
434 
435## Execution Pacing
436 
437**Large projects (>15 pages):** Work in batches of 3-5 pages per module. Complete system overview + page inventory first. Output each batch for user review before proceeding.
438 
439**Small projects (≤15 pages):** Complete all analysis in one pass.
440 
441---
442 
443## Common Pitfalls
444 
445| Pitfall | Fix |
446|---------|-----|
447| Using component names as page names | `UserManagementTable` → "User Management List" |
448| Skipping modals and drawers | They contain critical business logic — document fully |
449| Missing i18n field names | Check translation files, not just component JSX |
450| Ignoring dynamic route params | `/order/:id` = page requires an order ID to load |
451| Forgetting permission controls | Document which roles see which buttons/pages |
452| Assuming all APIs are real | Check for mock data patterns before documenting endpoints |
453| Skipping Django admin customization | `admin.py` often contains critical business rules (list filters, custom actions, inlines) |
454| Missing NestJS guards/pipes | `@UseGuards`, `@UsePipes` contain auth and validation logic that affects behavior |
455| Ignoring database constraints | Model field constraints (unique, max_length, choices) are validation rules for the PRD |
456| Overlooking middleware | Auth middleware, rate limiters, and CORS config define system-wide behavior |
457 
458---
459 
460## Tooling
461 
462### Scripts
463 
464| Script | Purpose | Usage |
465|--------|---------|-------|
466| `scripts/codebase_analyzer.py` | Scan codebase → extract routes, APIs, models, enums, structure | `python3 codebase_analyzer.py /path/to/project` |
467| `scripts/prd_scaffolder.py` | Generate PRD directory skeleton from analysis JSON | `python3 prd_scaffolder.py analysis.json` |
468 
469**Recommended workflow:**
470```bash
471# 1. Analyze the project (JSON output — works for frontend, backend, or fullstack)
472python3 scripts/codebase_analyzer.py /path/to/project -o analysis.json
473 
474# 2. Review the analysis (markdown summary)
475python3 scripts/codebase_analyzer.py /path/to/project -f markdown
476 
477# 3. Scaffold the PRD directory with stubs
478python3 scripts/prd_scaffolder.py analysis.json -o prd/ -n "My App"
479 
480# 4. Fill in TODO sections page-by-page using the SKILL.md workflow
481```
482 
483Both scripts are **stdlib-only** — no pip install needed.
484 
485### References
486 
487| File | Contents |
488|------|----------|
489| `references/prd-quality-checklist.md` | Validation checklist for completeness, accuracy, readability |
490| `references/framework-patterns.md` | Framework-specific patterns for routes, state, APIs, forms, permissions |
491 
492---
493 
494## Attribution
495 
496This skill was inspired by [code-to-prd](https://github.com/lihanglogan/code-to-prd) by [@lihanglogan](https://github.com/lihanglogan), who proposed the original concept and methodology in [PR #368](https://github.com/alirezarezvani/claude-skills/pull/368). The core three-phase workflow (global scan → page-by-page analysis → structured document generation) originated from that work. This version was rebuilt from scratch in English with added tooling (analysis scripts, scaffolder, framework reference, quality checklist).
497 

Discussion

Alternatives

Also in Services & APIsSee all 533 in Development →