---
stage: enrichment
requires:
  - errors
  - examples
outputs: "{wiki_dir}/*.md (updated)"
version: 2.1.0
estimated_tokens: 2000

guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete any files"
    - "Modify any source files"
  read_only: true
---
# Stage 15: Documentation Enrichment & Verification

Revisit ALL wiki docs with full context. Verify accuracy against source code, eliminate hallucinated content, and enrich with substantive improvements.

## Prerequisites

- Stage 14 completed with examples.md generated
- Mode: `{REPOIX_MODE}` (if "cli", convert MCP calls per AGENTS.md)
- Discovery cache loaded: LIMITS, PRIMARY_LANGUAGE

## Critical Rules

| Rule | Action |
|------|--------|
| Examples required | **MUST** verify {wiki_dir}/examples.md exists |
| Update only | **NEVER** create new wiki files - ONLY update existing |
| No new README | **NEVER** create README.md or any new document |
| No new files | **NEVER** create glossary.md, maintenance.md, or ANY new files |
| Protect custom | **NEVER** modify {wiki_dir}/custom/ directory |
| Preserve content | **NEVER** remove existing content unless incorrect |
| Edit tool only | **MUST** use Edit tool (NOT Write tool) |
| **Verify before keeping** | **MUST** read source code to verify each claim |

---

{{include:ai-cache-enforcement.md}}

{{include:understand-fast-path.md}}

## Why This Stage Matters

**Problem:** Earlier stages may contain hallucinated content because:

1. AI generated docs from limited context (README, package files only)
2. Assumptions made without verifying actual source code
3. Generic patterns described that may not exist in this codebase

**Solution:** With full project context, verify EVERY claim against actual code:

- Class names, method signatures, file paths
- Architectural patterns described
- Error handling behavior
- Integration patterns
- Configuration options

| Stage | Context Available | Potential Issues |
|-------|-------------------|------------------|
| 02-03 | README only | May describe patterns not in code |
| 04-06 | Components | May miss actual implementation details |
| 07-09 | API, models | May have incorrect signatures |
| 10-14 | Full context | Can now verify everything |

---

## Step 1: Verify Previous Stage

```bash
civyk-hatch deepwiki-update-state verify-stage --stage=15-enrichment --wiki-dir={wiki_dir}
```

---

## Step 2: Initialize Progress Tracking

**Track enrichment, verification, AND See Also for each document:**

```text
ENRICHMENT_TRACKER = {
  "quickstart.md":         { verified: false, enriched: false, see_also: false, fixes: 0 },
  "overview.md":           { verified: false, enriched: false, see_also: false, fixes: 0 },
  "diagrams.md":           { verified: false, enriched: false, see_also: false, fixes: 0 },
  "flows/README.md":       { verified: false, enriched: false, see_also: false, fixes: 0 },
  "components/README.md":  { verified: false, enriched: false, see_also: false, fixes: 0 },
  "api.md":                { verified: false, enriched: false, see_also: false, fixes: 0 },
  "models.md":             { verified: false, enriched: false, see_also: false, fixes: 0 },
  "configuration/README.md": { verified: false, enriched: false, see_also: false, fixes: 0 },
  "dependencies.md":       { verified: false, enriched: false, see_also: false, fixes: 0 },
  "decisions.md":          { verified: false, enriched: false, see_also: false, fixes: 0 },
  "errors.md":             { verified: false, enriched: false, see_also: false, fixes: 0 },
  "examples.md":           { verified: false, enriched: false, see_also: false, fixes: 0 }
}

# Update after each document:
[x] quickstart.md      - VERIFIED, enriched, See Also [OK], 0 fixes   (1/12)
[x] overview.md        - VERIFIED, enriched, See Also [OK], 3 fixes   (2/12)
[>] diagrams.md        - verifying against code...                  (3/12)
[ ] flows/README.md    - pending                                    (4/12)
```

---

## Step 3: Load Discovery Cache

```bash
civyk-hatch deepwiki-update-state show --wiki-dir={wiki_dir}
# Extract: LIMITS = discovery_cache.project_size.limits
# Extract: PRIMARY_LANGUAGE = discovery_cache.file_patterns.languages.primary
```

---

## Step 4: Recall Cached Understanding

Before verifying documents against source code, recall understanding from earlier stages (04-14):

```text
# Project and component-level understanding from earlier stages
understand(action="recall", target="project")
understand(action="recall", target="<component_path>")

# For each source file to verify against: use understand-fast-path
# (recall before read, store after analysis)
```

**Benefits:** Stages 04-14 already analyzed most files. Enrichment can recall instead of re-reading, dramatically reducing token usage.

---

## Step 5: Load Full Context for Verification

```text
# Business context - use understand-fast-path (recall before read)
understand(action="recall", target="{wiki_dir}/business-context.json")
# IF not cached: Read file, then store understanding

# Project structure - recall cached project understanding
understand(action="recall", target="project")
# IF not cached: run discovery below
architecture(action="components")
architecture(action="dependencies")
architecture(action="endpoints", limit=200)
context(action="task", task="documentation verification and enrichment", token_budget=3000)

# Get actual symbol names for verification
search(action="symbols", query="%Service%", kind="class", limit=50)
search(action="symbols", query="%Controller%", kind="class", limit=50)
search(action="symbols", query="%Repository%", kind="class", limit=50)
```

---

## Step 6: Verify & Enrich Each Document

**CRITICAL: For EACH wiki document, follow this process:**

### 6.1 Read Document & Extract Claims

```text
Read file: {wiki_dir}/[document].md

# Extract all verifiable claims:
- Class/interface names mentioned
- File paths referenced
- Method signatures described
- Architectural patterns claimed
- Configuration options listed
- Error types mentioned
```

### 6.2 Verify Against Source Code (Use Cached Understanding)

**For EACH claim, check cache FIRST, then verify:**

```text
# Example verification workflow for overview.md:

# Claim: "AuthService handles authentication"
# FIRST: Check cached understanding
understand(action="recall", target="src/services/auth.py")
# IF found AND fresh: Verify claim against cached key_points
# IF not found: search and read as below

search(action="symbols", query="AuthService", kind="class")
# If found: symbol(action="detail", fqn="...AuthService") - verify behavior
# If NOT found: This is hallucinated - MUST correct

# After verification, store understanding if not cached:
understand(action="store",
  scope="file",
  target="src/services/auth.py",
  purpose="Authentication service handling login/logout",
  importance="critical",
  key_points=["JWT tokens", "OAuth support"],
  gotchas=["Token expiry handling"],
  analysis="<detailed_logic_and_flow_explanation>",
  related_to=["UserRepository", "TokenService"]
)

# Claim: "Uses Repository pattern"
search(action="symbols", query="%Repository%", kind="class")
# Verify actual pattern used, correct if different

# Claim: "Configuration in config/settings.py"
files(pattern="**/config/**")
files(pattern="**/settings*")
# Verify actual config location
```

### 6.3 Fix Hallucinated Content

| Issue Found | Action |
|-------------|--------|
| Class doesn't exist | Replace with actual class or remove |
| Wrong file path | Correct to actual path |
| Wrong method signature | Read source, fix signature |
| Pattern not used | Describe actual pattern |
| Feature doesn't exist | Remove or mark as "not implemented" |

### 6.4 Enrich with Verified Content

After verification, ADD substantive improvements:

**Add missing implementation details:**

```text
# Read actual implementation
file(action="symbols", path="src/services/auth.py")
Read file: src/services/auth.py (lines with key logic)

# Add to docs:
- Actual method signatures with parameters
- Real error handling behavior
- Actual configuration options used
- True integration patterns
```

### 6.5 Update Cross-References

**IMPORTANT:** Add/update cross-references to connect related documentation:

**Types of cross-references to add:**

| From Document | Link To |
|---------------|---------|
| overview.md | Component docs, flow docs, architecture |
| flows/*.md | Component docs, API endpoints, error handling |
| components/*.md | Related flows, models used, config needed |
| api.md | Flow docs that use endpoints, error types |
| models.md | Components that use models, API responses |
| errors.md | Flows where errors occur, handling code |

**Add "See Also" sections to every document:**

```markdown
## See Also

- **Flows**: [Authentication](flows/authentication.md)
- **Components**: [AuthService](components/auth-service.md)
- **API**: [POST /auth/login](api.md#post-authlogin)
- **Errors**: [AuthError](errors.md#autherror)
```

**Add inline links throughout content:**

```markdown
The [AuthService](components/auth-service.md) validates credentials
and returns a [JWT token](flows/authentication.md#token-generation).
Errors are handled by [AuthError](errors.md#autherror).
```

---

## Step 7: Document-Specific Verification Checklist

| Document | Key Verifications |
|----------|-------------------|
| overview.md | Architecture claims, tech stack, main components exist |
| diagrams.md | Component names match code, relationships accurate |
| flows/*.md | Function calls exist, sequence accurate, error paths real |
| components/*.md | Classes exist, methods match signatures, dependencies correct |
| api.md | Routes exist, parameters match, response types accurate |
| models.md | Classes exist, fields match, relationships accurate |
| configuration/*.md | Files exist, options are real, defaults correct |
| dependencies.md | Packages used, versions match, integration accurate |
| errors.md | Error classes exist, handling matches code |
| examples.md | Code snippets work, imports valid |

---

## Step 8: Consistency Check

Ensure across all documents:

- Entity names match actual code exactly
- API paths match actual routes (verify with grep/search)
- Component names are spelled correctly
- Internal links resolve to existing files
- No orphaned references to non-existent code

---

## Step 9: Complete Stage

```bash
civyk-hatch deepwiki-update-state stage --stage=15-enrichment --status=completed --artifacts="{wiki_dir}/overview.md,{wiki_dir}/architecture/diagrams.md,{wiki_dir}/flows/README.md,{wiki_dir}/components/README.md,{wiki_dir}/api.md,{wiki_dir}/models.md" --wiki-dir={wiki_dir}
```

---

## Output Format

```text
===========================================================
  STAGE COMPLETE: 15-enrichment

  Documents verified: {count}
  Documents enriched: {count}
  Hallucinations fixed: {count}
  Cross-references added: {count}
  See Also sections added: {count}
  Content improvements: {count}

  Verification Summary:
  - overview.md: VERIFIED [OK], See Also [OK] (2 fixes)
  - diagrams.md: VERIFIED [OK], See Also [OK] (1 fix)
  - api.md: VERIFIED [OK], See Also [OK] (3 fixes - wrong signatures corrected)
  ...

  Next: Run {next_command}
===========================================================
```

---

## Anti-Hallucination Checklist

Before marking complete, confirm:

- [ ] Every class name mentioned exists in codebase
- [ ] Every file path referenced is valid
- [ ] Every method signature matches actual code
- [ ] Every architectural pattern claimed is actually used
- [ ] Every configuration option described is real
- [ ] Every error type listed exists
- [ ] No generic/assumed content remains unverified
- [ ] Every document has a "See Also" section with valid links

---

## Edge Cases

| Scenario | Action |
|----------|--------|
| Claim can't be verified | Read more source code until verified |
| Class name was hallucinated | Replace with actual class or remove section |
| Pattern doesn't exist | Describe what actually exists |
| Large doc set (>30 files) | Prioritize core documents, verify all |
| Conflicting information | Source code is truth - fix docs |

---

## Next Stage

Run `{next_command}` - CLI auto-detects current stage and emits next prompt.
