to-spec — Reverse-Engineer Project Specification
Analyze an existing codebase and produce a structured SPEC document that captures what the project does, how it's built, and what contracts it exposes. The output is a living specification that could be used to rebuild the project from scratch or onboard new contributors.
When to Use
- You want a comprehensive understanding of an existing project
- Onboarding new team members who need a high-level overview
- Documenting a project that was built without a spec
- Comparing actual implementation against intended design
- Preparing for a rewrite or major refactor
- Auditing what a project actually does vs. what people think it does
The Job
- Scope confirmation — ask user what to analyze (entire repo, specific directory, or specific aspect)
- Deep scan — systematically read project structure, entry points, config, tests, and core logic
- Synthesize — produce a structured SPEC document
- Review — present to user for feedback and iteration
- Save — write final SPEC to agreed location
Step 1: Scope Confirmation
Before scanning, ask the user:
What should I analyze?
A. Entire repository (recommended for small-medium projects)
B. Specific directory or module: [path]
C. Specific aspect only (e.g., API surface, data model, auth flow)
Depth level:
1. Overview — high-level architecture + tech stack + key features (fast, ~5 min)
2. Standard — includes API contracts, data models, config, dependencies (default)
3. Deep — adds internal module interactions, error handling patterns, test coverage analysis
If the project is large (>500 files), recommend starting with Overview or a specific module.
Step 2: Deep Scan
Systematically analyze the following (adapt to what exists):
2.1 Project Identity
package.json, go.mod, Cargo.toml, pyproject.toml, pom.xml, etc.
- README, LICENSE
- Git history (first commit date, recent activity, contributor count)
2.2 Architecture
- Directory structure and organization pattern (monorepo, layered, hexagonal, etc.)
- Entry points (main files, CLI commands, server bootstrap)
- Module boundaries and dependency graph (internal)
2.3 Tech Stack
- Language(s) and version constraints
- Frameworks and major libraries
- Build tools and bundlers
- Runtime requirements (Node version, Docker, etc.)
2.4 Features & Behavior
- Route definitions / CLI commands / exported functions
- Business logic modules and their responsibilities
- Background jobs, cron tasks, event handlers
2.5 Data Model
- Database schemas, migrations, ORMs
- Key data structures and their relationships
- State management approach
2.6 API Surface
- HTTP endpoints (method, path, request/response shapes)
- GraphQL schema / gRPC protos / WebSocket events
- CLI interface (commands, flags, arguments)
- Exported library API (public functions, classes, types)
2.7 Configuration & Environment
- Environment variables and their purpose
- Config files and their schema
- Feature flags, toggles
2.8 External Dependencies
- Third-party services (databases, queues, APIs)
- Infrastructure requirements (cloud services, storage)
- Authentication/authorization providers
2.9 Testing & Quality
- Test framework and approach (unit, integration, e2e)
- Coverage patterns (what's tested, what's not)
- Linting, formatting, type checking setup
2.10 Deployment & Operations
- CI/CD configuration
- Deployment targets and strategies
- Monitoring, logging, health checks
Step 3: SPEC Document Structure
Generate the SPEC with these sections. Omit sections that don't apply.
# SPEC: [Project Name]
> Reverse-engineered specification — generated [date] from commit [short-hash]
## 1. Overview
### 1.1 Purpose
[One paragraph: what problem this project solves and for whom]
### 1.2 Key Capabilities
- [Bullet list of what the system can do, from a user's perspective]
### 1.3 Architecture Style
[e.g., "Monolithic Express.js API with React SPA frontend", "CLI tool with plugin system", "Microservices communicating over gRPC"]
---
## 2. Tech Stack
| Layer | Technology | Version |
|-------|-----------|---------|
| Language | ... | ... |
| Framework | ... | ... |
| Database | ... | ... |
| Build | ... | ... |
| Test | ... | ... |
| Deploy | ... | ... |
---
## 3. Project Structure
[Directory tree with annotations explaining each top-level directory's purpose]
---
## 4. Data Model
### 4.1 Core Entities
[For each entity: name, fields, relationships, constraints]
### 4.2 State Transitions
[If applicable: lifecycle states and valid transitions]
---
## 5. API Surface
### 5.1 [Interface Type: REST / CLI / Library / etc.]
[For each endpoint/command/function:]
| Method | Path/Command | Description | Auth |
|--------|-------------|-------------|------|
| ... | ... | ... | ... |
### 5.2 Request/Response Schemas
[Key request/response shapes with field types]
---
## 6. Configuration
| Variable / Key | Required | Default | Description |
|---------------|----------|---------|-------------|
| ... | ... | ... | ... |
---
## 7. External Dependencies
| Service | Purpose | Failure Impact |
|---------|---------|----------------|
| ... | ... | ... |
---
## 8. Business Rules & Constraints
- [Numbered list of invariants, validation rules, and business logic constraints discovered in the code]
---
## 9. Non-Functional Characteristics
### 9.1 Performance
[Observed patterns: caching, pagination, batch processing, etc.]
### 9.2 Security
[Auth mechanism, input validation patterns, secrets management]
### 9.3 Error Handling
[Error strategy: custom error types, error codes, retry policies]
---
## 10. Testing Strategy
| Type | Framework | Coverage Pattern |
|------|-----------|-----------------|
| Unit | ... | ... |
| Integration | ... | ... |
| E2E | ... | ... |
---
## 11. Known Gaps & Assumptions
- [Things that are unclear from the code alone]
- [Assumptions made during analysis]
- [Areas with no tests or documentation]
---
## 12. Appendix
### A. Dependency Graph
[Key module dependencies, import relationships]
### B. Environment Setup
[Steps to run the project locally, derived from config and scripts]
Step 4: Review & Iteration
After generating the SPEC, present it and ask:
SPEC generated. Please review:
- Are there sections that need more detail?
- Are there inaccuracies I should correct?
- Should I add/remove any sections?
- Is the depth level appropriate?
Reply OK to save, or provide feedback for iteration.
Apply feedback and re-present until user confirms.
Step 5: Save
Ask user for save location:
Where should I save the SPEC?
A. docs/SPEC.md (recommended)
B. SPEC.md (project root)
C. Custom path: [specify]
Analysis Heuristics
Identifying Purpose
- Look at README first line, package description field, CLI help text
- Check the main entry point — what does it bootstrap?
- Look at test descriptions — they often describe expected behavior in plain language
Discovering Architecture
- Map
import/require statements to build dependency graph
- Identify layers by directory naming:
controllers, services, models, routes, handlers, domain, infra
- Check for dependency injection patterns, middleware chains, plugin registrations
Extracting Business Rules
- Look for validation functions, guard clauses, assertion statements
- Check error messages — they often describe what went wrong in business terms
- Examine test assertions — they encode expected behavior
Finding API Contracts
- Route registrations (Express:
app.get(), FastAPI: @app.get(), Go: mux.HandleFunc())
- OpenAPI/Swagger files if present
- Request validation schemas (Joi, Zod, Pydantic, struct tags)
- CLI flag/argument definitions (cobra, argparse, yargs)
Detecting Data Models
- ORM model definitions (Prisma, SQLAlchemy, GORM, TypeORM)
- Migration files (in chronological order)
- Type/interface definitions for core domain objects
- Database seed files
Edge Cases
| Scenario |
Handling |
| Project has no README or documentation |
Note this in "Known Gaps"; infer purpose from code |
| Monorepo with multiple services |
Ask user which service(s) to analyze; produce one SPEC per service or a unified SPEC with clear boundaries |
| Project uses code generation |
Document the generated code's purpose but focus on the source of truth (schemas, proto files, templates) |
| Legacy project with mixed patterns |
Document all observed patterns, note inconsistencies in "Known Gaps" |
| Project is a library (no runtime) |
Focus on exported API surface, type contracts, and usage patterns from tests |
| Incomplete or broken code |
Document what exists, mark broken/incomplete areas explicitly |
| Project >1000 files |
Start with entry points and trace key flows; don't exhaustively read every file |
| Multiple languages in one repo |
Document each language's role and how they interact |
Quality Criteria
A good reverse-engineered SPEC should pass these checks:
Anti-Patterns to Avoid
- Don't invent intent. If you can't determine WHY something exists, say so. Don't fabricate rationale.
- Don't copy code into the SPEC. Describe behavior and contracts, don't paste implementations.
- Don't include transient state. The SPEC describes the system's design, not its current runtime state.
- Don't over-specify internals. Focus on boundaries, contracts, and behavior. Internal implementation details belong in code comments, not specs.
- Don't assume the README is accurate. READMEs often lag behind code. Verify claims against actual implementation.
1---2name: code-to-spec3description: Reverse-engineer a SPEC document from an existing project. Analyzes code, config, tests, and structure to produce a comprehensive specification. Triggers on: code-to-spec, reverse spec, generate spec, 逆向规格, 生成规格文档, 生成设计文档, 生成设计方案, extract spec, document this project, what does this project do.4---5
6# to-spec — Reverse-Engineer Project Specification
7
8Analyze an existing codebase and produce a structured SPEC document that captures what the project does, how it's built, and what contracts it exposes. The output is a living specification that could be used to rebuild the project from scratch or onboard new contributors.
9
10---
11
12## When to Use
13
14- You want a comprehensive understanding of an existing project
15- Onboarding new team members who need a high-level overview
16- Documenting a project that was built without a spec
17- Comparing actual implementation against intended design
18- Preparing for a rewrite or major refactor
19- Auditing what a project actually does vs. what people think it does
20
21---
22
23## The Job
24
251. **Scope confirmation** — ask user what to analyze (entire repo, specific directory, or specific aspect)
262. **Deep scan** — systematically read project structure, entry points, config, tests, and core logic
273. **Synthesize** — produce a structured SPEC document
284. **Review** — present to user for feedback and iteration
295. **Save** — write final SPEC to agreed location
30
31---
32
33## Step 1: Scope Confirmation
34
35Before scanning, ask the user:
36
37```
38What should I analyze?
39
40A. Entire repository (recommended for small-medium projects)
41B. Specific directory or module: [path]
42C. Specific aspect only (e.g., API surface, data model, auth flow)
43
44Depth level:
451. Overview — high-level architecture + tech stack + key features (fast, ~5 min)
462. Standard — includes API contracts, data models, config, dependencies (default)
473. Deep — adds internal module interactions, error handling patterns, test coverage analysis
48```
49
50If the project is large (>500 files), recommend starting with Overview or a specific module.
51
52---
53
54## Step 2: Deep Scan
55
56Systematically analyze the following (adapt to what exists):
57
58### 2.1 Project Identity
59- `package.json`, `go.mod`, `Cargo.toml`, `pyproject.toml`, `pom.xml`, etc.
60- README, LICENSE
61- Git history (first commit date, recent activity, contributor count)
62
63### 2.2 Architecture
64- Directory structure and organization pattern (monorepo, layered, hexagonal, etc.)
65- Entry points (main files, CLI commands, server bootstrap)
66- Module boundaries and dependency graph (internal)
67
68### 2.3 Tech Stack
69- Language(s) and version constraints
70- Frameworks and major libraries
71- Build tools and bundlers
72- Runtime requirements (Node version, Docker, etc.)
73
74### 2.4 Features & Behavior
75- Route definitions / CLI commands / exported functions
76- Business logic modules and their responsibilities
77- Background jobs, cron tasks, event handlers
78
79### 2.5 Data Model
80- Database schemas, migrations, ORMs
81- Key data structures and their relationships
82- State management approach
83
84### 2.6 API Surface
85- HTTP endpoints (method, path, request/response shapes)
86- GraphQL schema / gRPC protos / WebSocket events
87- CLI interface (commands, flags, arguments)
88- Exported library API (public functions, classes, types)
89
90### 2.7 Configuration & Environment
91- Environment variables and their purpose
92- Config files and their schema
93- Feature flags, toggles
94
95### 2.8 External Dependencies
96- Third-party services (databases, queues, APIs)
97- Infrastructure requirements (cloud services, storage)
98- Authentication/authorization providers
99
100### 2.9 Testing & Quality
101- Test framework and approach (unit, integration, e2e)
102- Coverage patterns (what's tested, what's not)
103- Linting, formatting, type checking setup
104
105### 2.10 Deployment & Operations
106- CI/CD configuration
107- Deployment targets and strategies
108- Monitoring, logging, health checks
109
110---
111
112## Step 3: SPEC Document Structure
113
114Generate the SPEC with these sections. Omit sections that don't apply.
115
116```markdown
117# SPEC: [Project Name]
118
119> Reverse-engineered specification — generated [date] from commit [short-hash]
120
121## 1. Overview
122
123### 1.1 Purpose
124[One paragraph: what problem this project solves and for whom]
125
126### 1.2 Key Capabilities
127- [Bullet list of what the system can do, from a user's perspective]
128
129### 1.3 Architecture Style
130[e.g., "Monolithic Express.js API with React SPA frontend", "CLI tool with plugin system", "Microservices communicating over gRPC"]
131
132---
133
134## 2. Tech Stack
135
136| Layer | Technology | Version |
137|-------|-----------|---------|
138| Language | ... | ... |
139| Framework | ... | ... |
140| Database | ... | ... |
141| Build | ... | ... |
142| Test | ... | ... |
143| Deploy | ... | ... |
144
145---
146
147## 3. Project Structure
148
149[Directory tree with annotations explaining each top-level directory's purpose]
150
151---
152
153## 4. Data Model
154
155### 4.1 Core Entities
156[For each entity: name, fields, relationships, constraints]
157
158### 4.2 State Transitions
159[If applicable: lifecycle states and valid transitions]
160
161---
162
163## 5. API Surface
164
165### 5.1 [Interface Type: REST / CLI / Library / etc.]
166
167[For each endpoint/command/function:]
168| Method | Path/Command | Description | Auth |
169|--------|-------------|-------------|------|
170| ... | ... | ... | ... |
171
172### 5.2 Request/Response Schemas
173[Key request/response shapes with field types]
174
175---
176
177## 6. Configuration
178
179| Variable / Key | Required | Default | Description |
180|---------------|----------|---------|-------------|
181| ... | ... | ... | ... |
182
183---
184
185## 7. External Dependencies
186
187| Service | Purpose | Failure Impact |
188|---------|---------|----------------|
189| ... | ... | ... |
190
191---
192
193## 8. Business Rules & Constraints
194
195- [Numbered list of invariants, validation rules, and business logic constraints discovered in the code]
196
197---
198
199## 9. Non-Functional Characteristics
200
201### 9.1 Performance
202[Observed patterns: caching, pagination, batch processing, etc.]
203
204### 9.2 Security
205[Auth mechanism, input validation patterns, secrets management]
206
207### 9.3 Error Handling
208[Error strategy: custom error types, error codes, retry policies]
209
210---
211
212## 10. Testing Strategy
213
214| Type | Framework | Coverage Pattern |
215|------|-----------|-----------------|
216| Unit | ... | ... |
217| Integration | ... | ... |
218| E2E | ... | ... |
219
220---
221
222## 11. Known Gaps & Assumptions
223
224- [Things that are unclear from the code alone]
225- [Assumptions made during analysis]
226- [Areas with no tests or documentation]
227
228---
229
230## 12. Appendix
231
232### A. Dependency Graph
233[Key module dependencies, import relationships]
234
235### B. Environment Setup
236[Steps to run the project locally, derived from config and scripts]
237```
238
239---
240
241## Step 4: Review & Iteration
242
243After generating the SPEC, present it and ask:
244
245```
246SPEC generated. Please review:
247
248- Are there sections that need more detail?
249- Are there inaccuracies I should correct?
250- Should I add/remove any sections?
251- Is the depth level appropriate?
252
253Reply OK to save, or provide feedback for iteration.
254```
255
256Apply feedback and re-present until user confirms.
257
258---
259
260## Step 5: Save
261
262Ask user for save location:
263
264```
265Where should I save the SPEC?
266
267A. docs/SPEC.md (recommended)
268B. SPEC.md (project root)
269C. Custom path: [specify]
270```
271
272---
273
274## Analysis Heuristics
275
276### Identifying Purpose
277- Look at README first line, package description field, CLI help text
278- Check the main entry point — what does it bootstrap?
279- Look at test descriptions — they often describe expected behavior in plain language
280
281### Discovering Architecture
282- Map `import`/`require` statements to build dependency graph
283- Identify layers by directory naming: `controllers`, `services`, `models`, `routes`, `handlers`, `domain`, `infra`
284- Check for dependency injection patterns, middleware chains, plugin registrations
285
286### Extracting Business Rules
287- Look for validation functions, guard clauses, assertion statements
288- Check error messages — they often describe what went wrong in business terms
289- Examine test assertions — they encode expected behavior
290
291### Finding API Contracts
292- Route registrations (Express: `app.get()`, FastAPI: `@app.get()`, Go: `mux.HandleFunc()`)
293- OpenAPI/Swagger files if present
294- Request validation schemas (Joi, Zod, Pydantic, struct tags)
295- CLI flag/argument definitions (cobra, argparse, yargs)
296
297### Detecting Data Models
298- ORM model definitions (Prisma, SQLAlchemy, GORM, TypeORM)
299- Migration files (in chronological order)
300- Type/interface definitions for core domain objects
301- Database seed files
302
303---
304
305## Edge Cases
306
307| Scenario | Handling |
308|----------|----------|
309| Project has no README or documentation | Note this in "Known Gaps"; infer purpose from code |
310| Monorepo with multiple services | Ask user which service(s) to analyze; produce one SPEC per service or a unified SPEC with clear boundaries |
311| Project uses code generation | Document the generated code's purpose but focus on the source of truth (schemas, proto files, templates) |
312| Legacy project with mixed patterns | Document all observed patterns, note inconsistencies in "Known Gaps" |
313| Project is a library (no runtime) | Focus on exported API surface, type contracts, and usage patterns from tests |
314| Incomplete or broken code | Document what exists, mark broken/incomplete areas explicitly |
315| Project >1000 files | Start with entry points and trace key flows; don't exhaustively read every file |
316| Multiple languages in one repo | Document each language's role and how they interact |
317
318---
319
320## Quality Criteria
321
322A good reverse-engineered SPEC should pass these checks:
323
324- [ ] A developer unfamiliar with the project could understand its purpose in 60 seconds
325- [ ] The tech stack section is complete enough to set up a dev environment
326- [ ] API contracts are specific enough to write a client against
327- [ ] Data models are complete enough to recreate the schema
328- [ ] Business rules are explicit (not buried in "see code")
329- [ ] Known gaps are honestly listed (don't invent what you can't determine)
330- [ ] The SPEC matches the actual code (not aspirational documentation)
331
332---
333
334## Anti-Patterns to Avoid
335
336- **Don't invent intent.** If you can't determine WHY something exists, say so. Don't fabricate rationale.
337- **Don't copy code into the SPEC.** Describe behavior and contracts, don't paste implementations.
338- **Don't include transient state.** The SPEC describes the system's design, not its current runtime state.
339- **Don't over-specify internals.** Focus on boundaries, contracts, and behavior. Internal implementation details belong in code comments, not specs.
340- **Don't assume the README is accurate.** READMEs often lag behind code. Verify claims against actual implementation.