---
name: setup-claude-project
description: Scan the project codebase and create or migrate all .claude/ configuration files (rules, skills, agents, CLAUDE.md). Run this on new projects or to migrate from legacy prompts/Agent.md setups.
argument-hint: "[optional: focus area like 'frontend' or 'backend']"
disable-model-invocation: true
---

Scan this project's codebase and create or customize `.claude/` configuration files to match the actual tech stack, conventions, and patterns in use. Confirm with the user before making changes.

CLAUDE.md must be at the project root (`./CLAUDE.md`), NOT inside `.claude/`. All other config files live inside `.claude/`.

If the project is empty or has no source code yet, tell the user the defaults will be kept as-is and stop.

## Phase 0: Detect Legacy Setup

Before creating anything, check for legacy AI configuration patterns:

### Legacy files to look for:
- `Agent.md` or `AGENT.md` — old-style monolithic AI instructions
- `memory.md` — old-style working memory (not Claude Code's `~/.claude/` memory)
- `prompts/` directory — old-style prompt templates (planning.md, building.md, bug_fixer.md, etc.)
- `.claude/commands/` — old commands format (superseded by `.claude/skills/`)
- Any root-level AI instruction files (AI.md, LLM.md, etc.)

### If legacy files exist:
1. Read each legacy file completely
2. Present findings to the user:
   ```
   I found legacy AI configuration:
   - Agent.md: [summary of what's in it — rules, conventions, workflow instructions]
   - memory.md: [summary — working notes, preferences, project state]
   - prompts/: [list files and their purpose]
   
   I'll migrate the useful content into the new .claude/ structure:
   - Rules from Agent.md → .claude/rules/
   - Workflow prompts → .claude/skills/
   - Project context → CLAUDE.md
   
   The old files can be deleted after migration. Proceed? (yes/no)
   ```
3. Extract and categorize content from legacy files:
   - **Non-negotiable rules** (input handling, forbidden actions, security) → `.claude/rules/core.md`
   - **Model/ORM conventions** → `.claude/rules/models.md`
   - **API/REST conventions** → `.claude/rules/rest.md` or `.claude/rules/api.md`
   - **Testing conventions** → `.claude/rules/testing.md`
   - **Documentation obligations** → `.claude/rules/docs.md`
   - **Performance patterns** → `.claude/rules/performance.md`
   - **Workflow prompts** (planning, building, bug fixing) → `.claude/skills/`
   - **Project description, trust order, key pointers** → `CLAUDE.md`
4. After successful migration, ask user if they want to delete the legacy files

### If no legacy files exist:
Proceed to Phase 1 — this is a fresh setup.

## Phase 1: Detect Tech Stack

Scan for package manifests, config files, and folder structure to detect: language, framework, package manager, test framework, linter/formatter, architecture pattern, and source/test directories.

**Package manifests:** `package.json`, `pyproject.toml`, `setup.py`, `setup.cfg`, `Cargo.toml`, `go.mod`, `Gemfile`, `composer.json`, `build.gradle`, `pom.xml`, `Makefile`, `Dockerfile`, `requirements.txt`

**Monorepo indicators:** `workspaces` in package.json, `pnpm-workspace.yaml`, `lerna.json`, `nx.json`, `turbo.json`, or multiple `package.json` files at depth 2+. If detected, ask which packages/apps to focus on.

**Frameworks** — detect from dependencies and config files:
- Python: Django, Flask, FastAPI, Starlette, SQLAlchemy, Celery
- JavaScript/TypeScript: React, Next.js, Vue, Nuxt, Express, NestJS, Hono
- Go: Gin, Echo, Chi, standard library
- Rust: Actix, Axum, Rocket
- Ruby: Rails, Sinatra

**Test frameworks** — detect from config files:
- `jest.config.*`, `vitest.config.*`, `pytest.ini`, `conftest.py`, `pyproject.toml [tool.pytest]`
- `playwright.config.*`, `cypress.config.*`, `.mocharc.*`
- `_test.go` files, `Cargo.toml [dev-dependencies]`, `spec/` directory

**Linter/formatter** — detect from config:
- `.eslintrc.*`, `.prettierrc.*`, `biome.json`, `ruff.toml`, `pyproject.toml [tool.ruff]`
- `tsconfig.json`, `.editorconfig`, `.rustfmt.toml`, `golangci.yml`

**Folder structure** — identify pattern (feature-based, layered, monorepo, MVC) and locate source, test, API, and config directories.

**Commit style** — check `git log --oneline -20` for commit message conventions.

## Phase 2: Present Findings

Present a summary to the user:

```
I scanned your project. Here's what I found:

**Stack**: [language] + [framework] + [CSS/UI] + [DB/ORM]
**Package manager**: [npm/pnpm/yarn/bun/pip/uv/cargo/go]
**Test framework**: [jest/vitest/pytest/go test/etc.]
**Linter/Formatter**: [eslint+prettier/ruff/clippy/etc.]
**Architecture**: [layered/feature-based/monorepo/MVC/etc.]
**Source dirs**: [list]
**Test dirs**: [list]
**Legacy AI config**: [what was found, or "none"]

Should I create/customize the .claude/ files based on this? (yes/no/corrections)
```

Incorporate any corrections before proceeding.

## Phase 3: Create Directory Structure

```
mkdir -p .claude/rules .claude/skills .claude/agents
```

## Phase 4: Create Rules

Rules load automatically. They are passive instructions Claude follows without being invoked. Use `globs:` frontmatter to scope rules to specific file paths — this saves context when working on unrelated files.

### .claude/rules/core.md (always loaded — no globs)

Non-negotiable rules for this specific project. Customize based on what you found:

```markdown
# Core Rules

These rules apply to all work in this repository. Non-negotiable.

## Input Handling
[How this project handles request input — framework-specific]

## Forbidden Actions
[Things that must never happen — migrations in library repos, type hints if not used, etc.]
[Include: Never make blind edits — read target files first]

## Security
[Security posture — fail-closed, permission model, secrets handling]

## Philosophy
[KISS, module organization, where domain logic lives, helper/utility conventions]
[Preferred data structures if the project has conventions]
[Confirm assumptions with user when uncertain]

## Trust Order
[When docs and code conflict, what takes precedence]

## Delivery Checklist
[Before closing any task — what to verify]
```

**Guidance for customizing core.md:**
- Read the codebase to find actual patterns, don't assume
- If the project uses a specific input handling pattern (request.DATA, req.body, etc.), enforce it
- If the project forbids certain practices (no type hints, no ORMs, etc.), capture those
- If there's a helpers/utils directory, add a rule to check it before writing new utilities
- Keep it short — only rules that apply everywhere

### .claude/rules/models.md (path-scoped to model directories)

Only create if the project has an ORM/database layer.

```yaml
---
globs: [path/to/models/**/*.py, path/to/models/**/*.ts, etc.]
---
```

Content should cover:
- Model inheritance patterns (base classes, mixins)
- Required fields (created/modified timestamps, etc.)
- File organization (one model per file, etc.)
- Permission/authorization metadata if applicable
- Relationship conventions (FK naming, cascade behavior)

### .claude/rules/api.md or rest.md (path-scoped to API/route directories)

Only create if the project has an API layer.

```yaml
---
globs: [path/to/api/**/*.py, path/to/routes/**/*.ts, etc.]
---
```

Content should cover:
- Input handling conventions
- URL/route patterns and naming
- Authentication/authorization decorators or middleware
- Response format (always JSON, use framework helpers, etc.)
- Error handling patterns
- CRUD patterns specific to this project

### .claude/rules/testing.md (path-scoped to test directories)

```yaml
---
globs: [tests/**/*.py, **/*.test.ts, **/*.spec.js, etc.]
---
```

Content should cover:
- Test framework and how to run tests
- Test file naming and organization
- Setup/teardown patterns
- Mocking conventions or restrictions
- Assertion requirements (descriptive messages, etc.)
- How to run specific tests vs full suite

### .claude/rules/docs.md (always loaded — no globs)

Only create if the project has documentation that needs maintaining.

Content should cover:
- Where docs live and who they're for
- When to update docs (new endpoints, config changes, etc.)
- Changelog conventions
- Multiple doc audiences if applicable

### .claude/rules/performance.md (path-scoped to source directories)

```yaml
---
globs: [src/**/*.py, src/**/*.ts, etc.]
---
```

Content should cover:
- N+1 query prevention (if ORM)
- Indexing requirements
- Pagination requirements
- Caching patterns
- Common performance anti-patterns for this stack

**Important:** Only create rules files that are relevant. A pure frontend project doesn't need models.md. A library without docs doesn't need docs.md. Less is more.

## Phase 5: Create Skills

Skills are user-invoked workflows. Each skill gets its own directory under `.claude/skills/<name>/SKILL.md`.

### .claude/skills/bug/SKILL.md — Bug Intake

```yaml
---
name: bug
description: Investigate a bug report, confirm if possible, write a structured issue file to planning/issues/
user-invocable: true
argument-hint: <description of the problem>
---
```

Workflow:
1. Parse the bug description from $ARGUMENTS (or ask user to describe it)
2. Investigate the code — read relevant files, trace the code path
3. Best-effort confirmation through code analysis. If a regression test is feasible, write and run it to demonstrate the failure
4. Write `planning/issues/<slug>.md` with standardized template:
   - Title, Type (bug), Status (open), Date, Severity
   - Description, Context, Acceptance Criteria
   - Investigation: likely root cause, confidence level, code path refs, regression test, related files
5. Stop and hand off: print file path + "Start new session, run `/design planning/issues/<slug>.md`"

Rules: Do NOT fix the bug. Investigation and documentation only.

### .claude/skills/request/SKILL.md — Feature Request Intake

```yaml
---
name: request
description: Explore codebase, clarify scope, write a structured feature request file to planning/requests/
user-invocable: true
argument-hint: <description of what you want>
---
```

Workflow:
1. Parse the feature description from $ARGUMENTS (or ask user what they want)
2. Explore codebase — what exists, what changes, constraints
3. Ask clarifying questions until scope is unambiguous (API contract, permissions, edge cases, out-of-scope)
4. Write `planning/requests/<slug>.md` with standardized template:
   - Title, Type (request), Status (open), Date, Priority
   - Description, Context, Acceptance Criteria
   - Investigation: what exists, what changes, constraints, related files, endpoints, tests required, out of scope
5. Stop and hand off: print file path + "Start new session, run `/design planning/requests/<slug>.md`"

Rules: Do NOT implement anything. Exploration and documentation only.

### .claude/skills/design/SKILL.md — Design Implementation

```yaml
---
name: design
description: Design implementation approach for an issue or request file, adds a Plan section
user-invocable: true
argument-hint: <path to issue or request file>
---
```

Workflow:
1. Read the issue/request file at $ARGUMENTS (or list open files and ask which one)
2. Deep exploration — read all related files, check for existing features/helpers
3. Design file-level plan: objective, ordered steps, design decisions, edge cases, testing, docs
4. Present plan, wait for user confirmation, iterate if needed
5. Append `## Plan` section to the file, set Status to "planned"
6. Stop and hand off: "Start new session, run `/build <file-path>`"

Rules: Do NOT implement. Planning and documentation only.

### .claude/skills/build/SKILL.md — Implement, Test, Commit

```yaml
---
name: build
description: Implement a planned issue or request — code, tests, commit, then spawn test/docs/security agents
user-invocable: true
argument-hint: <path to planned file>
---
```

Workflow:
1. Read the planned file — must have `## Plan` section
2. Read all files in scope
3. Confirm with user before building
4. Implement following the plan and rules
5. Write and run tests — fix failures in code, not tests
6. Git commit (stage specific files, never `git add -A`, never push)
7. Spawn post-build agents in parallel:
   - **test-runner** — full test suite for regressions
   - **docs-updater** — update docs based on git diff
   - **security-review** — review diff for security concerns
8. Append `## Resolution` section, move file to `planning/done/`
9. Report summary to user

Rules: Confirm before implementing. Commit but never push. Stage specific files only.

### .claude/skills/use-cases/SKILL.md — Use Case Library

```yaml
---
name: use-cases
description: Research, generate, and organize use cases for a product, feature, domain, or persona. Spawns parallel research agents to explore the codebase, docs, and context, then synthesizes findings into a structured usecases/ folder. Use when mapping what the product can do, building a use case library, generating examples for documentation or sales, or thinking through how different personas interact with the system.
user-invocable: true
argument-hint: <product, feature, or domain — e.g. "payment API" or "admin dashboard" or "the whole product">
---
```

Workflow:
1. Parse $ARGUMENTS for target scope. If vague or empty, ask:
   - What are we mapping? (specific feature / persona / whole product)
   - What's the goal? (internal docs / sales library / developer onboarding / product planning)
2. Present research plan and confirm with user before spawning agents
3. Spawn three research agents **in parallel**:
   - **use-cases-codebase-explorer** — scans routes, models, permissions, feature flags; returns a capability map grouped by domain
   - **use-cases-docs-reader** — reads READMEs, planning files, changelogs, test descriptions; returns documented user types and feature language
   - **use-cases-persona-mapper** — infers personas from auth/permission layers; returns a persona matrix with per-persona capabilities
4. Merge agent outputs into a master capability map: domain → capabilities → personas → documentation status
5. Write `usecases/` folder (see structure below)
6. Present summary and next-step suggestions

**Output structure** — organize by domain (default) or persona (when personas are very distinct):

```
usecases/
├── README.md                    ← full index: by domain, by persona, by status
├── [domain-a]/
│   ├── UC-001-[slug].md
│   └── UC-002-[slug].md
├── [domain-b]/
│   └── ...
└── cross-cutting/               ← use cases that span domains
    └── ...
```

**Each use case file**:
```markdown
---
id: UC-[NNN]
title: [Action verb + object]
domain: [e.g. Billing]
persona: [e.g. Finance admin]
status: active | planned | speculative
source: codebase | docs | inferred
priority: high | medium | low
---

# UC-[NNN]: [Title]
## Summary / Persona / Trigger / Preconditions / Steps / Outcome / Variants / Related Use Cases / Notes
```

**Source field discipline**:
- `codebase` — verified in code
- `docs` — described in documentation
- `inferred` — synthesized from patterns
- `speculative` — doesn't exist yet, but gaps suggest it should

**Rules**:
- Do not invent capabilities — mark anything unverified as `speculative`
- Titles must be action-verb phrases ("Export invoice report", not "Invoice Feature")
- Read existing `usecases/` folder before writing — extend, don't overwrite
- Confirm scope before spawning agents

**Agents to create** under `.claude/agents/`:

#### use-cases-codebase-explorer.md
```yaml
---
name: use-cases-codebase-explorer
description: Scan routes, models, permissions, and feature flags to map what the system can actually do
tools: Read, Grep, Glob, Bash
model: sonnet
---
```
Instructions: Find all entry points (API routes, CLI, background jobs). Scan models and status enums. Map the permission/role layer. Group capabilities by domain using folder structure and URL prefixes as signals. Return a structured capability map — NOT use case files.

#### use-cases-docs-reader.md
```yaml
---
name: use-cases-docs-reader
description: Read existing documentation and planning files to extract use case language, user types, and feature descriptions
tools: Read, Grep, Glob, Bash
model: sonnet
---
```
Instructions: Read README, docs/, CHANGELOG, planning/requests/, planning/done/, OpenAPI specs, and test file names. Extract: user types mentioned, feature descriptions, acceptance criteria, "as a user" language. Return a documentation summary — NOT use case files.

#### use-cases-persona-mapper.md
```yaml
---
name: use-cases-persona-mapper
description: Infer user personas from auth layers, permission models, and feature surfaces. Map what each persona can do.
tools: Read, Grep, Glob, Bash
model: sonnet
---
```
Instructions: Find role fields, permission classes, feature flags, and plan tiers. Build a persona list using the codebase's own language. Map unique and shared capabilities per persona. Identify interaction patterns between personas (approval flows, delegation, shared resources). Return a persona matrix — NOT use case files.

**Handoff message after completion**:
```
Use case library generated at usecases/

[N] use cases across [domains]:
  - [N] active (backed by existing code)
  - [N] planned (in roadmap/requests)
  - [N] speculative (gaps or opportunities)

Next steps:
  - Review speculative use cases — run /request on any worth building
  - Run /design on any use case you want to implement next
```

### .claude/skills/memory/SKILL.md — Show Memory

```yaml
---
name: memory
description: Display the current state of Claude Code project memory
user-invocable: true
---
```

Workflow:
1. Read the memory index at `~/.claude/projects/<project-path>/memory/MEMORY.md`
2. List and read all memory files in that directory
3. Present a summary table: name, type, description, content preview
4. Read-only — do not modify any memory files

## Phase 6: Create Agents

Agents run in isolated context windows with restricted tools. They are spawned by the `/build` skill after committing, and by `/use-cases` during research.

### .claude/agents/test-runner.md

```yaml
---
name: test-runner
description: Run the test suite, fix trivial errors, report complex failures
tools: Bash, Read, Edit, Grep, Glob
model: sonnet
---
```

Behavior:
1. Run the test suite (detect the right command from Phase 1: `npm test`, `pytest`, `go test ./...`, `cargo test`, `bin/run_tests`, etc.)
2. If all pass: return summary
3. If failures:
   - **Simple errors** (syntax, missing imports, typos): fix the code (NOT the test), re-run to confirm, report what was fixed
   - **Complex errors** (logic failures, assertion mismatches, infrastructure issues): do NOT fix, report test name, file:line, error, likely cause
4. Never change test expectations or test logic

### .claude/agents/docs-updater.md

```yaml
---
name: docs-updater
description: Read git diff and update project documentation to match code changes
tools: Bash, Read, Edit, Grep, Glob
model: sonnet
---
```

Behavior:
1. Run `git diff HEAD~1 --name-only` and `git diff HEAD~1`
2. Determine which docs need updating based on what changed
3. Read existing docs before editing — match style
4. Update changelog if behavior or API changed
5. Update doc indexes if new doc files added
6. Return summary of what was updated

**Customize:** List the project's doc directories and audiences. If the project has multiple doc tracks (like django_developer + web_developer), specify which changes affect which track.

### .claude/agents/security-review.md

```yaml
---
name: security-review
description: Review recent code changes for security concerns
tools: Bash, Read, Grep, Glob
model: sonnet
---
```

Behavior:
1. Run `git diff HEAD~1`
2. Check for: permission gaps, data exposure, injection risks, auth bypasses, secret leakage
3. Rate each finding: critical / warning / info
4. Return structured report with file:line references and recommended fixes
5. Read-only — do NOT make edits

**Customize:** Adjust the security checklist based on the framework. A Django project checks RestMeta permissions; a Next.js project checks middleware auth; a Go API checks handler-level auth.

### .claude/agents/use-cases-codebase-explorer.md

```yaml
---
name: use-cases-codebase-explorer
description: Scan routes, models, permissions, and feature flags to map what the system can actually do. Spawned by the use-cases skill.
tools: Read, Grep, Glob, Bash
model: sonnet
---
```

Behavior:
1. Find all entry points: API routes, CLI commands, background jobs/workers
2. Scan models and data layer: entities, status enums, key relationships
3. Map the permission/role layer: what each role unlocks
4. Group capabilities by domain using folder structure and URL prefixes as signals
5. Return a structured capability map (NOT use case files) in this format:

```
## Domain: [Name]
Files scanned: [list]
Capabilities:
- [Verb + object] — [description] — [file:line or route]
Permissions: [roles with access]
Status variants: [enums or states]

## Gaps / Observations
- [Dead code, TODOs, flags that disable things, inconsistencies]
```

### .claude/agents/use-cases-docs-reader.md

```yaml
---
name: use-cases-docs-reader
description: Read existing documentation and planning files to extract use case language, user types, and feature descriptions. Spawned by the use-cases skill.
tools: Read, Grep, Glob, Bash
model: sonnet
---
```

Behavior:
1. Read: README, docs/, CHANGELOG, planning/requests/, planning/done/, OpenAPI specs, test file names
2. Extract: user types mentioned, feature descriptions, acceptance criteria, "as a user" language
3. Flag: features in code but not in docs; personas in code but not in docs
4. Return a documentation summary (NOT use case files) covering: sources read, user types found, feature inventory, existing use case language, planning insights, gaps

### .claude/agents/use-cases-persona-mapper.md

```yaml
---
name: use-cases-persona-mapper
description: Infer user personas from auth layers, permission models, and feature surfaces. Spawned by the use-cases skill.
tools: Read, Grep, Glob, Bash
model: sonnet
---
```

Behavior:
1. Find role fields, permission classes, feature flags, plan tiers, OAuth scopes
2. Build a persona list using the codebase's own naming (use `is_staff` language, not invented names)
3. Map unique and shared capabilities per persona, with code references
4. Identify interaction patterns between personas (approval flows, delegation, shared resources)
5. Return a persona matrix (NOT use case files) with: persona definitions, capability maps, interaction matrix, gaps/questions

## Phase 7: Create CLAUDE.md

This is the project entrypoint — loaded automatically every session. Keep it concise.

```markdown
# [Project Name]

This file is loaded automatically by Claude Code.

## Project

[One-line description of what this project is]

## How to Work Here

- **Rules** are in `.claude/rules/` and load automatically. Follow them.
- **Skills** are in `.claude/skills/` — invoked with `/<name>` (e.g., `/bug`, `/request`, `/design`, `/build`, `/use-cases`, `/memory`).
- **Agents** are in `.claude/agents/` — spawned automatically by build and use-cases skills.
- See `AI_DEV.md` for the full developer workflow.
- [Any critical "read this first" pointer, like main docs or architecture guide]

## Planning

Active work is tracked as files in `planning/`:
- `planning/issues/` — open bugs
- `planning/requests/` — open feature requests
- `planning/done/` — resolved items

## Use Cases

A library of what this product can do lives in `usecases/`. Run `/use-cases` to generate or update it.

## Trust Order

When docs and code conflict:
1. [Primary authority]
2. [Secondary authority]
3. Existing code patterns
```

## Phase 8: Create AI_DEV.md

Developer guide explaining the full workflow. Include:

- Quick start with all skill invocations
- Workflow chain diagram (bug/request → plan → build → done)
- Use case workflow (use-cases → request → plan → build)
- Planning directory structure
- Skills table (name, purpose)
- Rules table (name, scope, what it covers)
- Agents table (name, purpose) — include the three use-cases agents
- File template format (progressive sections: Investigation → Plan → Resolution)

## Phase 9: Create Planning Directory

```
mkdir -p planning/issues planning/requests planning/done planning/future planning/rejected
```

Add a `.gitkeep` to each empty directory so git tracks them.

## Phase 10: Final Summary

Present to the user:

```
Setup complete. Here's what was created:

**Rules** (.claude/rules/):
- [list each rule file and its scope]

**Skills** (.claude/skills/):
- /bug — investigate and document bugs
- /request — explore and document feature requests
- /design — design implementation approach
- /build — implement, test, commit, review
- /use-cases — research and generate a use case library
- /memory — show Claude Code memory state

**Agents** (.claude/agents/):
- test-runner — run tests, fix trivial errors
- docs-updater — update docs from git diff
- security-review — review changes for security
- use-cases-codebase-explorer — map capabilities from code (spawned by /use-cases)
- use-cases-docs-reader — extract use case language from docs (spawned by /use-cases)
- use-cases-persona-mapper — build persona matrix from auth layer (spawned by /use-cases)

**Root files**:
- CLAUDE.md — project entrypoint (loaded every session)
- AI_DEV.md — developer workflow guide

**Planning**:
- planning/ directory with issues/, requests/, done/, future/, rejected/

[If migrated from legacy]: Legacy files [Agent.md, memory.md, prompts/] can now be deleted.

Start a new Claude Code session for skills to be discovered, then try:
  /use-cases          ← map what your product can do
  /bug                ← report and investigate a bug
  /request            ← capture a feature idea
```

## Important Notes

- Every rule, skill, and agent must be customized to the ACTUAL project — do not use placeholder text or generic examples. Read the code and write specific, actionable instructions.
- If you're unsure about a convention, ask the user rather than guessing.
- Rules should be concise — they load into context every session. Don't waste tokens on obvious things.
- Skills should be complete — they run workflows end-to-end.
- Agents should be focused — they run in isolated context with limited tools.
- The planning directory and file template format is project-agile — use it everywhere.
- After creating everything, remind the user to start a new session for skill discovery.
