# Stage 0b: Codebase Discovery

## Purpose

Reconnaissance before architecture debate. Detect existing implementations, patterns, and constraints to prevent "solving already-solved problems" and inform Planning 1 with ground truth.

## When It Runs

After Intake, before Board. The Board receives the discovery report as input alongside the brief.

**Trigger:** Brief extracted from Intake

## Input

- Approved brief
- Target codebase path (from project config or brief)
- Board memo (business constraints)

## Composition — FIXED

| Role  | Model | Purpose                                |
| ----- | ----- | -------------------------------------- |
| Scout | Haiku | Fast read-only codebase reconnaissance |

Lightweight agent — no debate protocol, just structured inspection.

## Process

### 1. Locate Target Codebase

- Check project config for `codebase_path`
- Fallback: brief may specify target repo/module
- If no codebase identified, skip Discovery (greenfield project)

### 2. Feature Existence Check

Search for existing implementations of the requested feature:

- Grep for relevant model names in Prisma/schema files
- Grep for controller/service files matching feature name
- Check for existing routes/endpoints

**Output:** `feature_status` = { EXISTS_FULL | EXISTS_PARTIAL | NOT_FOUND | N/A }

### 3. Pattern Reconnaissance (if codebase exists)

Answer these questions via file inspection:

| Category               | Questions                                                                                            |
| ---------------------- | ---------------------------------------------------------------------------------------------------- |
| **Module structure**   | Dedicated modules per feature, or consolidated (e.g., `UsersModule` holds profile/preferences/etc.)? |
| **Global prefix**      | Is `setGlobalPrefix()` set in main.ts? What's the prefix?                                            |
| **PrismaModule**       | Is it `@Global()` or must modules import it explicitly?                                              |
| **Auth decorator**     | Where is `@CurrentUser()` defined? What type does it return? What's the shape?                       |
| **User PK type**       | UUID string or autoincrement int? Affects all FK design.                                             |
| **Validation**         | Global ValidationPipe options? `forbidNonWhitelisted`? `transform`?                                  |
| **Naming conventions** | Snake_case in DB (@map) vs camelCase in code? Table naming pattern?                                  |

### 4. Conflict Detection

- Does a model with the same name already exist?
- Are there fields that would collide with proposed fields?
- Are there existing migrations that might conflict?

### 5. Constraint Extraction

Document discovered constraints:

- "PrismaModule is @Global, no import needed"
- "Users.id is UUID string, all FKs must match"
- "Controller decorators should NOT include 'api/' prefix (global prefix set)"
- "Preferences already exist in UsersModule — this is an EXTENSION task"

## Output

Write `discovery-report.md` to the run directory containing:

```markdown
# Discovery Report

## Feature Status

- Status: [EXISTS_FULL | EXISTS_PARTIAL | NOT_FOUND | N/A]
- Existing files: [list or "none"]

## Codebase Patterns

| Pattern            | Finding                        | Evidence           |
| ------------------ | ------------------------------ | ------------------ |
| Module structure   | [dedicated/consolidated]       | [file path]        |
| Global prefix      | [yes/no]                       | [main.ts line]     |
| PrismaModule scope | [@Global/explicit import]      | [prisma.module.ts] |
| @CurrentUser shape | [interface summary]            | [decorator file]   |
| User PK type       | [UUID/int]                     | [schema.prisma]    |
| Validation config  | [options]                      | [main.ts]          |
| Naming convention  | [snake_case DB / camelCase TS] | [schema.prisma]    |

## Conflicts Detected

- [List any conflicts or "none"]

## Constraints for Planning 1

1. [Constraint derived from discovery]
2. [...]

## Revised Scope Recommendation

[If EXISTS_PARTIAL: What's already done vs. what still needs work]

## Files to Reference

[Key files the architects should read before debating]
```

## Gate: discovery-complete

### Mechanical

- [ ] `discovery-report.md` exists
- [ ] Feature status is populated
- [ ] All pattern questions answered (or marked N/A)
- [ ] Constraints section is non-empty (if codebase exists)

### Gate Reviewer

- "Did Scout actually look, or just assume?"
- "Are the constraints specific enough to guide Planning 1?"
- "If feature exists partially, is that clearly communicated?"

## Integration Points

### Board (primary consumer)

The Board reads `discovery-report.md` alongside the brief. This changes the debate:

- If feature EXISTS_FULL → Board can REJECT ("already implemented") or NEEDS REVISION ("brief scope is wrong")
- If feature EXISTS_PARTIAL → Board scopes the go/no-go to the delta work only
- If NOT_FOUND → Board debates as normal (greenfield)

This prevents the Board from rubber-stamping a brief to build something that's already there.

### Brief Analyzer (consumes Discovery)

The Brief Analyzer reads `discovery-report.md` before selecting generalists. If the feature already exists:

- May add "Extension Specialist" to the roster
- May reduce scope of certain debates
- May flag for human confirmation before proceeding

### Planning 1 (consumes Discovery)

Architects read the discovery report as context. The ADR must:

- Account for existing patterns
- Avoid redesigning solved problems
- Use discovered types/conventions

## Skip Conditions

Discovery is skipped if:

- No target codebase identified (greenfield)
- Brief explicitly marks `discovery: skip`
- Project config has `discovery: disabled`

When skipped, write minimal report:

```markdown
# Discovery Report

## Feature Status

- Status: N/A (greenfield or discovery skipped)
```

## Cost Model

~30-60 seconds wall time, ~5-10 file reads, minimal token cost (Haiku model).
Worth it to avoid Planning 1 debating hypotheticals.
