diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f1ce551..18d8a50 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -394,26 +394,31 @@ "category": "development" }, { - "name": "agenthub", - "source": "./engineering/agenthub", - "description": "Multi-agent collaboration — spawn N parallel subagents that compete on code optimization, content drafts, research approaches, or any task that benefits from diverse solutions. 7 slash commands (/hub:init, /hub:spawn, /hub:status, /hub:eval, /hub:merge, /hub:board, /hub:run), agent templates, DAG-based orchestration, LLM judge mode, message board coordination.", + "name": "code-to-prd", + "source": "./product-team/code-to-prd", + "description": "Reverse-engineer any codebase into a complete PRD. Frontend (React, Vue, Angular, Next.js), backend (NestJS, Django, Express, FastAPI), and fullstack. 2 Python scripts (codebase_analyzer, prd_scaffolder), 2 reference guides, /code-to-prd slash command.", "version": "2.1.2", "author": { "name": "Alireza Rezvani" }, "keywords": [ - "multi-agent", - "collaboration", - "parallel", - "git-dag", - "orchestration", - "competition", - "worktree", - "content-generation", - "research", - "optimization" + "prd", + "product-requirements", + "reverse-engineering", + "frontend", + "backend", + "fullstack", + "documentation", + "code-analysis", + "react", + "vue", + "angular", + "nestjs", + "django", + "fastapi", + "express" ], - "category": "development" + "category": "product" } ] } diff --git a/commands/code-to-prd.md b/commands/code-to-prd.md new file mode 100644 index 0000000..1bace0d --- /dev/null +++ b/commands/code-to-prd.md @@ -0,0 +1,78 @@ +--- +name: code-to-prd +description: Reverse-engineer a frontend codebase into a PRD. Usage: /code-to-prd [path] +--- + +# /code-to-prd + +Reverse-engineer a frontend codebase into a complete Product Requirements Document. + +## Usage + +```bash +/code-to-prd # Analyze current project +/code-to-prd ./src # Analyze specific directory +/code-to-prd /path/to/project # Analyze external project +``` + +## What It Does + +1. **Scan** — Run `codebase_analyzer.py` to detect framework, routes, APIs, enums, and project structure +2. **Scaffold** — Run `prd_scaffolder.py` to create `prd/` directory with README.md, per-page stubs, and appendix files +3. **Analyze** — Walk through each page following the Phase 2 workflow: fields, interactions, API dependencies, page relationships +4. **Generate** — Produce the final PRD with all pages, enum dictionary, API inventory, and page relationship map + +## Steps + +### Step 1: Analyze + +Determine the project path (default: current directory). Run the frontend analyzer: + +```bash +python3 {skill_path}/scripts/codebase_analyzer.py {project_path} -o .code-to-prd-analysis.json +``` + +Display a summary of findings: framework, page count, API count, enum count. + +### Step 2: Scaffold + +Generate the PRD directory skeleton: + +```bash +python3 {skill_path}/scripts/prd_scaffolder.py .code-to-prd-analysis.json -o prd/ +``` + +### Step 3: Fill + +For each page in the inventory, follow the SKILL.md Phase 2 workflow: +- Read the page's component files +- Document fields, interactions, API dependencies, page relationships +- Fill in the corresponding `prd/pages/` stub + +Work in batches of 3-5 pages for large projects (>15 pages). Ask the user to confirm after each batch. + +### Step 4: Finalize + +Complete the appendix files: +- `prd/appendix/enum-dictionary.md` — all enums and status codes found +- `prd/appendix/api-inventory.md` — consolidated API reference +- `prd/appendix/page-relationships.md` — navigation and data coupling map + +Clean up the temporary analysis file: +```bash +rm .code-to-prd-analysis.json +``` + +## Output + +A `prd/` directory containing: +- `README.md` — system overview, module map, page inventory +- `pages/*.md` — one file per page with fields, interactions, APIs +- `appendix/*.md` — enum dictionary, API inventory, page relationships + +## Skill Reference + +- `product-team/code-to-prd/SKILL.md` +- `product-team/code-to-prd/scripts/codebase_analyzer.py` +- `product-team/code-to-prd/scripts/prd_scaffolder.py` +- `product-team/code-to-prd/references/prd-quality-checklist.md` diff --git a/product-team/code-to-prd/.claude-plugin/plugin.json b/product-team/code-to-prd/.claude-plugin/plugin.json new file mode 100644 index 0000000..9c9461a --- /dev/null +++ b/product-team/code-to-prd/.claude-plugin/plugin.json @@ -0,0 +1,13 @@ +{ + "name": "code-to-prd", + "description": "Reverse-engineer any codebase into a complete Product Requirements Document (PRD). Analyzes routes, components, models, APIs, and interactions for frontend (React, Vue, Angular, Next.js), backend (NestJS, Django, Express, FastAPI), and fullstack applications.", + "version": "2.1.2", + "author": { + "name": "Alireza Rezvani", + "url": "https://alirezarezvani.com" + }, + "homepage": "https://github.com/alirezarezvani/claude-skills/tree/main/product-team/code-to-prd", + "repository": "https://github.com/alirezarezvani/claude-skills", + "license": "MIT", + "skills": "./" +} diff --git a/product-team/code-to-prd/README.md b/product-team/code-to-prd/README.md new file mode 100644 index 0000000..12485fd --- /dev/null +++ b/product-team/code-to-prd/README.md @@ -0,0 +1,58 @@ +# Code → PRD + +Reverse-engineer any codebase into a complete Product Requirements Document (PRD). + +## Quick Start + +```bash +# One command +/code-to-prd /path/to/project + +# Or step by step +python3 scripts/codebase_analyzer.py /path/to/project -o analysis.json +python3 scripts/prd_scaffolder.py analysis.json -o prd/ -n "My App" +``` + +## Supported Frameworks + +| Stack | Frameworks | +|-------|-----------| +| Frontend | React, Vue, Angular, Svelte, Next.js, Nuxt, SvelteKit, Remix | +| Backend | NestJS, Express, Django, DRF, FastAPI, Flask | +| Fullstack | Next.js (pages + API), Nuxt (pages + server), Django (views + templates) | + +## What It Generates + +``` +prd/ +├── README.md # System overview +├── pages/ +│ ├── 01-user-mgmt-list.md # Per-page/endpoint docs +│ └── ... +└── appendix/ + ├── enum-dictionary.md # All enums and status codes + ├── api-inventory.md # Complete API reference + └── page-relationships.md # Navigation and data coupling +``` + +## Scripts + +| Script | Purpose | +|--------|---------| +| `codebase_analyzer.py` | Scan codebase → extract routes, APIs, models, enums | +| `prd_scaffolder.py` | Generate PRD directory skeleton from analysis JSON | + +Both are stdlib-only — no pip install needed. Run `--help` for full usage. + +## References + +- `references/framework-patterns.md` — Route, state, API, form, and model patterns per framework +- `references/prd-quality-checklist.md` — Validation checklist for completeness and accuracy + +## Attribution + +Inspired by [code-to-prd](https://github.com/lihanglogan/code-to-prd) by [@lihanglogan](https://github.com/lihanglogan). + +## License + +MIT diff --git a/product-team/code-to-prd/SKILL.md b/product-team/code-to-prd/SKILL.md new file mode 100644 index 0000000..3014a0a --- /dev/null +++ b/product-team/code-to-prd/SKILL.md @@ -0,0 +1,507 @@ +--- +Name: code-to-prd +Tier: STANDARD +Category: product +Dependencies: none +Author: Alireza Rezvani +Version: 2.1.2 +name: code-to-prd +description: | + 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. + + Trigger 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. +license: MIT +metadata: + updated: 2026-03-17 +--- + +## 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 + +```bash +# 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) +```bash +/code-to-prd ./src +# → Scans components, routes, API calls, state management +# → Generates prd/ with per-page docs, enum dictionary, API inventory +``` + +### Backend (Django) +```bash +/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) +```bash +/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 + +```markdown +# [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 + +```markdown +# [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:** +```bash +# 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](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). diff --git a/product-team/code-to-prd/assets/sample-analysis.json b/product-team/code-to-prd/assets/sample-analysis.json new file mode 100644 index 0000000..7438f6d --- /dev/null +++ b/product-team/code-to-prd/assets/sample-analysis.json @@ -0,0 +1,81 @@ +{ + "project": { + "root": "/path/to/my-app", + "name": "my-app", + "framework": "next", + "detected_frameworks": ["next", "react"], + "key_dependencies": { + "next": "14.1.0", + "react": "18.2.0", + "tailwindcss": "3.4.1", + "axios": "1.6.5", + "@tanstack/react-query": "5.17.0" + }, + "stack_type": "fullstack" + }, + "structure": { + "total_files": 87, + "components": { + "components": 42, + "modules": 35 + }, + "route_dirs": ["/path/to/my-app/app"], + "api_dirs": ["/path/to/my-app/app/api"], + "state_dirs": ["/path/to/my-app/src/store"], + "i18n_dirs": [], + "controller_dirs": [], + "model_dirs": [], + "dto_dirs": [] + }, + "routes": { + "count": 8, + "frontend_pages": [ + {"path": "/", "source": "app/page.tsx", "filesystem": true}, + {"path": "/dashboard", "source": "app/dashboard/page.tsx", "filesystem": true}, + {"path": "/users", "source": "app/users/page.tsx", "filesystem": true}, + {"path": "/users/:id", "source": "app/users/[id]/page.tsx", "filesystem": true}, + {"path": "/settings", "source": "app/settings/page.tsx", "filesystem": true} + ], + "backend_endpoints": [ + {"path": "/api/users", "method": "GET", "source": "app/api/users/route.ts", "type": "backend"}, + {"path": "/api/users", "method": "POST", "source": "app/api/users/route.ts", "type": "backend"}, + {"path": "/api/users/:id", "method": "GET", "source": "app/api/users/[id]/route.ts", "type": "backend"} + ], + "pages": [] + }, + "apis": { + "total": 5, + "integrated": 4, + "mock": 1, + "endpoints": [ + {"path": "/api/users", "method": "GET", "source": "services/user.ts", "integrated": true, "mock_detected": false}, + {"path": "/api/users", "method": "POST", "source": "services/user.ts", "integrated": true, "mock_detected": false}, + {"path": "/api/users/:id", "method": "GET", "source": "services/user.ts", "integrated": true, "mock_detected": false}, + {"path": "/api/users/:id", "method": "PUT", "source": "services/user.ts", "integrated": true, "mock_detected": false}, + {"path": "/api/dashboard/stats", "method": "GET", "source": "services/dashboard.ts", "integrated": false, "mock_detected": true} + ] + }, + "enums": { + "count": 2, + "definitions": [ + {"name": "UserRole", "type": "enum", "values": {"ADMIN": "admin", "USER": "user", "MANAGER": "manager"}, "source": "types/user.ts"}, + {"name": "STATUS_MAP", "type": "constant_map", "values": {"active": "Active", "inactive": "Inactive", "suspended": "Suspended"}, "source": "constants/status.ts"} + ] + }, + "models": { + "count": 0, + "definitions": [] + }, + "summary": { + "pages": 5, + "backend_endpoints": 3, + "api_endpoints": 5, + "api_integrated": 4, + "api_mock": 1, + "enums": 2, + "models": 0, + "has_i18n": false, + "has_state_management": true, + "stack_type": "fullstack" + } +} diff --git a/product-team/code-to-prd/expected_outputs/sample-enum-dictionary.md b/product-team/code-to-prd/expected_outputs/sample-enum-dictionary.md new file mode 100644 index 0000000..07908ca --- /dev/null +++ b/product-team/code-to-prd/expected_outputs/sample-enum-dictionary.md @@ -0,0 +1,25 @@ +# Enum Dictionary + +All enums, status codes, and constant mappings found in the codebase. + +## UserRole + +**Source:** `types/user.ts` +**Type:** TypeScript enum + +| Value | Label | Description | +|-------|-------|-------------| +| `admin` | Admin | Full system access, can manage all users | +| `manager` | Manager | Can view and edit users, cannot delete | +| `user` | User | Read-only access | + +## STATUS_MAP + +**Source:** `constants/status.ts` +**Type:** Constant map + +| Key | Display Value | Color | Description | +|-----|--------------|-------|-------------| +| `active` | Active | Green | Normal active account | +| `inactive` | Inactive | Gray | Account disabled by user | +| `suspended` | Suspended | Red | Account suspended by admin | diff --git a/product-team/code-to-prd/expected_outputs/sample-page-user-list.md b/product-team/code-to-prd/expected_outputs/sample-page-user-list.md new file mode 100644 index 0000000..569173e --- /dev/null +++ b/product-team/code-to-prd/expected_outputs/sample-page-user-list.md @@ -0,0 +1,83 @@ +# User List + +> **Route:** `/users` +> **Module:** User Management +> **Generated:** 2026-03-17 + +## Overview + +Displays all system users in a searchable, paginated table. Supports creating, editing, and deleting users. Only ADMIN and MANAGER roles can access this page. + +## Layout + +- **Top bar**: Search input + "Create User" button +- **Main area**: Data table with pagination +- **Modal**: Create/Edit user form (triggered by buttons) + +## Fields + +### Search Filters + +| Field | Type | Required | Options | Default | Notes | +|-------|------|----------|---------|---------|-------| +| Keyword | Text input | No | — | — | Searches name and email | +| Role | Select dropdown | No | Admin, Manager, User | All | Filters by role | +| Status | Select dropdown | No | Active, Inactive, Suspended | All | Filters by status | + +### Data Table + +| Column | Format | Sortable | Filterable | Notes | +|--------|--------|----------|-----------|-------| +| Name | Text | Yes | No | Full name | +| Email | Text (link) | Yes | No | Clickable → opens detail | +| Role | Badge | No | Yes | Color-coded by role | +| Status | Badge | No | Yes | Green=active, Red=suspended | +| Created | Date (YYYY-MM-DD) | Yes | No | — | +| Actions | Buttons | No | No | Edit, Delete | + +### Actions + +| Button | Visibility | Behavior | +|--------|-----------|----------| +| Create User | ADMIN, MANAGER | Opens create modal | +| Edit | ADMIN, MANAGER | Opens edit modal with prefilled data | +| Delete | ADMIN only | Confirmation dialog → soft delete | + +## Interactions + +### Page Load +- Fetches first page of users via `GET /api/users?page=1&size=20` +- Default sort: `created_at` descending + +### Search +- **Trigger:** User types in search field (300ms debounce) +- **Behavior:** Re-fetches users with `keyword` param, resets to page 1 +- **Special rules:** Minimum 2 characters to trigger search + +### Create User +- **Trigger:** Click "Create User" button +- **Modal content:** Name (required, max 50), Email (required, email format), Role (required, select), Status (default: Active) +- **Validation:** Name required + max length, Email required + format check +- **API:** `POST /api/users` with form data +- **On success:** Toast "User created", close modal, refresh list +- **On failure:** Show API error below form + +### Delete User +- **Trigger:** Click "Delete" button on row +- **Behavior:** Confirmation dialog "Are you sure you want to delete {name}?" +- **API:** `DELETE /api/users/:id` +- **On success:** Toast "User deleted", refresh list + +## API Dependencies + +| API | Method | Path | Trigger | Notes | +|-----|--------|------|---------|-------| +| List users | GET | /api/users | Load, search, paginate | Params: page, size, keyword, role, status | +| Create user | POST | /api/users | Submit create form | Body: name, email, role | +| Delete user | DELETE | /api/users/:id | Confirm delete | — | + +## Page Relationships + +- **From:** Dashboard (click "View Users" link) +- **To:** User Detail (click email or row) +- **Data coupling:** Creating/deleting a user triggers dashboard stats refresh diff --git a/product-team/code-to-prd/expected_outputs/sample-prd-readme.md b/product-team/code-to-prd/expected_outputs/sample-prd-readme.md new file mode 100644 index 0000000..1f5e315 --- /dev/null +++ b/product-team/code-to-prd/expected_outputs/sample-prd-readme.md @@ -0,0 +1,43 @@ +# My App — Product Requirements Document + +## System Overview + +My App is a user management platform for internal teams. It provides CRUD operations for users, a dashboard with key metrics, and system settings. Built with Next.js 14 (App Router) and Tailwind CSS. + +## Module Overview + +| Module | Pages | Core Functionality | +|--------|-------|--------------------| +| Dashboard | Dashboard | Key metrics, activity feed | +| User Management | User list, User detail | CRUD users, role assignment | +| Settings | Settings | System configuration | + +## Page Inventory + +| # | Page Name | Route | Module | Doc Link | +|---|-----------|-------|--------|----------| +| 1 | Home | / | — | [→](./pages/01-home.md) | +| 2 | Dashboard | /dashboard | Dashboard | [→](./pages/02-dashboard.md) | +| 3 | User List | /users | User Mgmt | [→](./pages/03-user-list.md) | +| 4 | User Detail | /users/:id | User Mgmt | [→](./pages/04-user-detail.md) | +| 5 | Settings | /settings | Settings | [→](./pages/05-settings.md) | + +## API Inventory + +| # | Method | Path | Status | Notes | +|---|--------|------|--------|-------| +| 1 | GET | /api/users | Integrated | Paginated list | +| 2 | POST | /api/users | Integrated | Create user | +| 3 | GET | /api/users/:id | Integrated | User detail | +| 4 | PUT | /api/users/:id | Integrated | Update user | +| 5 | GET | /api/dashboard/stats | Mock | Dashboard metrics | + +## Global Notes + +### Permission Model +Role-based access: ADMIN (full access), MANAGER (read + edit), USER (read-only). + +### Common Interaction Patterns +- All delete operations require confirmation modal +- Lists default to `created_at` descending, 20 items per page +- Form validation shows inline errors below each field diff --git a/product-team/code-to-prd/references/framework-patterns.md b/product-team/code-to-prd/references/framework-patterns.md new file mode 100644 index 0000000..549a67f --- /dev/null +++ b/product-team/code-to-prd/references/framework-patterns.md @@ -0,0 +1,228 @@ +# Framework-Specific Patterns + +Quick reference for identifying routes, components, state, and APIs across frontend and backend frameworks. + +## React (CRA / Vite) + +| Aspect | Where to Look | +|--------|--------------| +| Routes | `react-router-dom` — `` or `createBrowserRouter` | +| Components | `.tsx` / `.jsx` files, default exports | +| State | Redux (`store/`), Zustand, Jotai, Recoil, React Context | +| API | `axios`, `fetch`, TanStack Query (`useQuery`), SWR (`useSWR`) | +| Forms | React Hook Form, Formik, Ant Design Form, custom `useState` | +| i18n | `react-i18next`, `react-intl` | + +## Next.js (App Router) + +| Aspect | Where to Look | +|--------|--------------| +| Routes | `app/` directory — `page.tsx` = route, folders = segments | +| Layouts | `layout.tsx` per directory | +| Loading | `loading.tsx`, `error.tsx`, `not-found.tsx` | +| API routes | `app/api/` or `pages/api/` (Pages Router) | +| Server actions | `"use server"` directive | +| Middleware | `middleware.ts` at root | + +## Next.js (Pages Router) + +| Aspect | Where to Look | +|--------|--------------| +| Routes | `pages/` directory — filename = route | +| Data fetching | `getServerSideProps`, `getStaticProps`, `getStaticPaths` | +| API routes | `pages/api/` | + +## Vue 3 + +| Aspect | Where to Look | +|--------|--------------| +| Routes | `vue-router` — `routes` array in `router/index.ts` | +| Components | `.vue` SFCs (`