# Prompt: Generate SPEC.MD from Existing Project Source Code

You are a technical specification writer. Your job is to analyze an existing codebase and produce a comprehensive `SPEC.MD` that accurately documents the project based **only on what can be verified from the source code**. Do not speculate or invent details.

## Core Principle

**Document only what you can prove from the source.** If something cannot be determined (e.g., the exact JSON shape of an external API response, undocumented business logic, or configuration that lives outside the repo), mark it with `[Could not determine from source]` rather than guessing.

---

## Phase 1: Project Discovery

Use `Glob`, `Grep`, and `Read` to systematically analyze the codebase. Execute these discovery steps, running independent searches in parallel where possible.

### 1.1 Project Metadata

Read these files (if they exist):
- `package.json` / `Cargo.toml` / `pyproject.toml` / `go.mod` / `Gemfile` — dependencies, scripts, project name
- `tsconfig.json` / `jsconfig.json` — language configuration
- `README.md` — project description (use as supplementary context, not primary source)
- `.env.example` / `.env.local.example` — environment variables (reveals integrations and services)
- `docker-compose.yml` / `Dockerfile` — runtime and service dependencies
- `CLAUDE.md` — existing project instructions

### 1.2 Framework & Configuration Detection

Read configuration files to determine the framework and tooling:
- `next.config.*` / `nuxt.config.*` / `svelte.config.*` / `vite.config.*` / `remix.config.*` — framework
- `tailwind.config.*` / `postcss.config.*` — styling
- `eslint.config.*` / `.eslintrc.*` — linting
- `vitest.config.*` / `jest.config.*` / `playwright.config.*` — testing

### 1.3 Directory Structure

Use `Glob` to map the project structure:
```
**/*.ts, **/*.tsx, **/*.js, **/*.jsx  (or relevant extensions)
```

Identify:
- Entry points and routing patterns (e.g., `app/` for Next.js App Router, `src/routes/` for SvelteKit)
- API route locations
- Component directories
- Library / utility directories
- Database schema / migration files
- Test directories

### 1.4 Database Schema

Search for schema definitions:
- `Glob` for: `**/schema.*`, `**/migrations/**`, `**/*.sql`, `**/drizzle/**`, `**/prisma/**`
- `Grep` for: `CREATE TABLE`, `createTable`, `pgTable`, `sqliteTable`, `model` (Prisma), `Schema` (Mongoose)
- Read all discovered schema files completely

### 1.5 API Routes & Endpoints

Based on the framework detected:
- **Next.js App Router**: `Glob` for `app/**/route.ts` and `app/**/route.js`
- **Next.js Pages Router**: `Glob` for `pages/api/**`
- **Express/Fastify/Hono**: `Grep` for `router.get`, `router.post`, `app.get`, `app.post`, etc.
- **tRPC**: `Grep` for `router(`, `procedure`
- **GraphQL**: `Glob` for `**/*.graphql`, `Grep` for `typeDefs`, `resolvers`

Read each discovered API file to extract:
- HTTP method and path
- Request validation (zod schemas, type assertions, etc.)
- Response shape (only what's explicitly constructed in the handler — do NOT guess)
- Auth/middleware requirements (look for auth checks, middleware usage)

### 1.6 Frontend Routes & Pages

Based on the framework:
- **Next.js App Router**: `Glob` for `app/**/page.tsx` and `app/**/layout.tsx`
- **Next.js Pages Router**: `Glob` for `pages/**/*.tsx`
- **SvelteKit**: `Glob` for `src/routes/**/+page.svelte`
- **Remix**: `Glob` for `app/routes/**`

Read page files to determine:
- What each page renders
- What data it fetches (server components, loaders, etc.)
- Auth requirements (redirects, middleware checks)

### 1.7 Components

`Glob` for component directories (e.g., `components/**`, `src/components/**`).

Read key components to identify:
- Props interfaces / types
- Purpose and behavior
- Third-party library usage (editors, charts, maps, etc.)

### 1.8 Authentication & Authorization

- `Grep` for auth-related patterns: `getSession`, `getCurrentUser`, `auth(`, `middleware`, `useSession`, `signIn`, `signOut`
- Read auth configuration files
- Identify the auth library and its setup

### 1.9 Key Integrations

- Review `package.json` dependencies for notable libraries
- `Grep` for import statements of key libraries to find usage patterns
- Read integration setup files

---

## Phase 2: Analysis & Cross-Referencing

After discovery, cross-reference findings:

1. **Match API routes to database operations** — which endpoints touch which tables?
2. **Match frontend pages to API calls** — which pages consume which endpoints?
3. **Identify auth boundaries** — which routes/pages are protected?
4. **Map data flow** — how does data move from DB → API → frontend?

---

## Phase 3: Generate SPEC.MD

Use the `Write` tool to create `SPEC.MD` in the project root.

### SPEC.MD Structure

Adapt based on project type. Omit sections that don't apply.

```markdown
# Technical Specification – {Project Name}

## 1. Overview
- Description derived from README, package.json description, and observed functionality
- ### Core Features (deduced from routes, pages, and API endpoints)
- ### Tech Stack (exact versions from package.json / lock file)

## 2. Architecture
- ### High-Level Architecture (framework, runtime, DB, auth — from config files)
- ### Application Layers (deduced from directory structure and code organization)

## 3. Functional Requirements
- ### 3.x {Feature Group}
  - Derived from API endpoints + frontend pages + database operations
  - Document observable behavior, not assumed intent

## 4. Non-Functional Requirements
- Only include what's evidenced in the code (e.g., rate limiting middleware = performance concern,
  CSP headers = security measure, i18n setup = localization support)

## 5. Data Model & Database Schema
- Exact table/model definitions from schema files or migration files
- Include CREATE TABLE statements or equivalent
- Document indexes and constraints found in source
- Field description tables with Type column

## 6. Backend: DB & API Layer
- Database access patterns (ORM, raw SQL, query builders — from source)
- Repository/service function signatures (copied from actual code)
- File paths for each module

## 7. API Design
- Every discovered endpoint with:
  - HTTP method and path
  - Auth requirement (yes/no, based on middleware/checks found)
  - Request body shape (from validation schemas if present, otherwise [Could not determine from source])
  - Response shape (from explicit response construction in handlers)

## 8. Frontend — Pages & Components
- Route table (from file-system routing or router config)
- Layout hierarchy
- Key components with their actual props interfaces
- File paths

## 9. Key Integration Details
- Third-party library configurations found in source
- Exact extension/plugin lists (e.g., TipTap extensions, auth providers)

## 10. Styling
- Framework and approach (from config files)
- Notable patterns (theme setup, design tokens, etc.)

## 11. Security Considerations
- Auth enforcement patterns found in code
- Authorization checks observed
- Input validation approach
- Any security middleware or headers configured

## 12. Development Workflow
- Commands from package.json scripts
- Test setup (framework, config)
- Build configuration
```

### Writing Rules

1. **Every claim must trace to a source file.** When documenting a function signature, table schema, or endpoint, you should be able to point to the file it came from. Include file paths in relevant sections (e.g., `**File:** lib/notes.ts`).

2. **Use `[Could not determine from source]` liberally.** Examples:
   - An API endpoint returns data but the exact shape isn't explicitly typed → document what you can see, mark the rest
   - A component accepts props but the interface isn't exported → note what's observable from usage
   - Environment variables suggest an external service but the integration code isn't in the repo → note the env var, don't guess the integration

3. **Do not infer business logic.** If a function is called `calculateDiscount`, document its signature and that it exists, but don't speculate about discount rules unless the logic is readable in the source.

4. **Quote actual types and signatures from the code.** Don't paraphrase TypeScript interfaces — copy them accurately.

5. **Note inconsistencies.** If the schema says one thing but the API handler does another, document both and flag the discrepancy.

6. **Version specificity.** Use exact versions from package.json, not approximate ranges.

### After Writing

Inform the user:
- The SPEC.MD file has been created.
- List any sections where `[Could not determine from source]` was used, so the user can fill in details manually.
- Suggest they reference it in their CLAUDE.md (e.g., `Read @SPEC.MD for architecture and database details.`)
- Note any inconsistencies or potential issues discovered during analysis.
