# Workflow: codebase-rebuild

Full rebuild of the `.workflow/codebase/` documentation system.

## Trigger

- Manual via `/workflow:codebase-rebuild [--force] [--skip-commit]`
- Auto-triggered by `/workflow:init` when existing code is detected
- Auto-triggered by `/workflow:map`

## Arguments

| Arg | Description | Default |
|-----|-------------|---------|
| `--force` | Clear existing codebase/ and rebuild from scratch | `false` |
| `--skip-commit` | Skip the final git commit of generated docs | `false` |

## Prerequisites

- Project source code exists (src/ or equivalent)
- `.workflow/` directory exists

---

## Workflow Steps

### Step 1: Prepare Directory Structure

```
Create (or clear if --force) .workflow/codebase/:
  doc-index.json, tech-registry/_index.md, feature-maps/_index.md, action-logs/

If exists and not --force: confirm overwrite or exit.
```

### Step 2: Scan Project Structure — Components

```
Scan source directories (src/, lib/, app/, packages/) for components.
Use project.md Tech Stack for context if available.

Classify files by naming pattern:
  Models (*model*, *entity*, *schema*), Services (*service*, *provider*),
  Controllers (*controller*, *handler*, *route*), Utils (*util*, *helper*),
  Types (*type*, *interface*, *.d.ts), Config (*config*, *constant*),
  Middleware (*middleware*, *guard*, *interceptor*), Core (*core*, *registry*, *loader*)

For each component: read files, extract exported symbols, determine type.
Build component entry:
  {
    "id": "TC-{NNN}",              // Sequential TC-001, TC-002, ...
    "name": "{PascalCase name}",
    "type": "{type}",
    "code_locations": ["{relative paths}"],
    "feature_ids": [],              // Populated in Step 3
    "symbols": ["{exported symbol names}"],
    "last_updated": "{ISO timestamp}"
  }
```

### Step 2.5: Load Project Specs

```
specs_content = maestro spec load --category arch
```

Used in Step 2-4 to produce architecture-aware documentation.

---

### Step 3: Scan Project Structure — Features

```
Group components into features by:
  directory proximity, naming patterns, import relationships, blueprint/ mapping.

For each feature group: derive name, collect component IDs, map requirements and phase.
Build feature entry:
  {
    "id": "FT-{NNN}",
    "name": "{Feature Name}",
    "status": "active",
    "requirement_ids": [],        // From .spec mapping
    "component_ids": ["TC-001", "TC-002"],
    "phase": null                 // From roadmap mapping
  }

Back-fill component.feature_ids with assigned feature IDs.
```

### Step 4: Map Requirements (if .spec exist)

```
If .workflow/blueprint/ exist: parse each SPEC-*/requirements/REQ-*.md,
match to features by keyword analysis. Build requirement entry:
  {
    "id": "REQ-{NNN}",
    "title": "{requirement title}",
    "priority": "must|should|could|wont",
    "feature_id": "FT-{NNN}",
    "status": "pending|in_progress|completed",
    "acceptance_criteria": ["{criteria}"]
  }

If no blueprint: requirements = [] (populated later by maestro-blueprint).
```

### Step 5: Record Architecture Decisions (if ADRs exist)

```
If .workflow/blueprint/*/architecture/ADR-*.md exist: parse each ADR,
map to components by keyword analysis. Build ADR entry:
  {
    "id": "ADR-{NNN}",
    "title": "{ADR title}",
    "component_ids": ["TC-{NNN}"],
    "decision": "{decision summary}",
    "rationale": "{rationale summary}"
  }

If no ADRs: architecture_decisions = [].
```

### Step 6: Write doc-index.json

```
Assemble the complete doc-index.json:

{
  "version": "1.0",
  "schema_version": "1.0",
  "project": "{project name from state.json or package.json}",
  "last_updated": "{ISO timestamp}",
  "features": [{feature entries}],
  "components": [{component entries}],
  "requirements": [{requirement entries}],
  "architecture_decisions": [{ADR entries}],
  "actions": []
}

Write to: .workflow/codebase/doc-index.json
```

### Step 7: Generate Tech Registry Docs

```
For each component (slug = lowercase-hyphenated name):

Write .workflow/codebase/tech-registry/{slug}.md:
  Header table (ID, Type, Features) + sections: Code Locations, Exported Symbols, Dependencies.
  Footer: *Auto-generated by codebase-rebuild at {timestamp}*

Write .workflow/codebase/tech-registry/_index.md:
  Summary table (ID, Name, Type, Locations) + component count footer.
```

### Step 8: Generate Feature Map Docs

```
For each feature (slug = lowercase-hyphenated name):

Write .workflow/codebase/feature-maps/{slug}.md:
  Header table (ID, Status, Phase) + sections: Requirements, Components table.
  Footer: *Auto-generated by codebase-rebuild at {timestamp}*

Write .workflow/codebase/feature-maps/_index.md:
  Summary table (ID, Name, Status, Components, Requirements) + feature count footer.
```

### Step 8.5: Update State and Project Artifacts

```
a. Update state.json: set last_codebase_rebuild and last_updated timestamps.

b. Update project.md Tech Stack (if exists):
   Compare "## Tech Stack" against detected stack from Step 2.
   If changes detected: update section + footer timestamp.
```

### Step 9: Report and Commit

```
Display summary: component/feature/requirement/ADR/file counts.
If mapper agents failed: log W001.
If not --skip-commit: suggest committing generated docs.
Suggest next: manage-status (review) or manage-codebase-refresh (incremental updates).
```

---

## Error Handling

| Error | Action |
|-------|--------|
| No source directories found | Warn and create empty doc-index.json |
| .workflow/ missing | Fail: "Run /workflow:init first" |
| File read errors | Log warning, skip file, continue scan |
| Existing codebase/ without --force | Prompt user for confirmation |

## Output Files

| File | Description |
|------|-------------|
| `.workflow/codebase/doc-index.json` | Single source of truth for all components/features/requirements |
| `.workflow/codebase/tech-registry/_index.md` | Component index |
| `.workflow/codebase/tech-registry/{slug}.md` | Per-component documentation |
| `.workflow/codebase/feature-maps/_index.md` | Feature index |
| `.workflow/codebase/feature-maps/{slug}.md` | Per-feature documentation |
| `.workflow/state.json` | Updated: last_codebase_rebuild timestamp |
| `.workflow/project.md` | Updated: Tech Stack section refreshed |
