# Refresh and Audit Project Documentation

**Purpose**: Intelligently detect code changes and update documentation to reflect current implementation.

**CRITICAL**: Not every code change requires documentation updates. Only update documentation when:
- Implementation patterns have actually changed
- New architectural decisions were made
- Critical information is missing or incorrect
- Non-obvious behaviors have been introduced

If documentation accurately reflects the current codebase, no changes are needed.

---

## Additional user's input
Additional context/input from user: $ARGUMENTS. Might be empty by default.

---

## Workflow Overview

This command supports two modes based on documentation type:

**🚀 Smart Mode (Codemie Docs)**:
- Detects `.codemie/guides/` directory
- Uses git to identify changed files
- Maps changes to affected guide categories
- Updates only impacted guides (selective)
- Fast and efficient for regular updates

**📋 Traditional Mode (All Documentation)**:
- Works with any documentation structure
- Comprehensive audit of all docs
- Reviews all guides vs implementation
- Updates as needed
- Thorough for major refactors

**Decision Flow**:
```
Step 1: Discover docs
  ├─ Codemie docs found → Step 2A (Smart Mode)
  └─ Other docs found → Step 2B (Traditional Mode)
```

User can override and request full audit at any point.

---

## Step 1: Discover What Documentation Exists

Identify documentation systems in this project:

**A. Codemie-Generated Documentation** (if present):
- `CLAUDE.md` in project root
- `.codemie/guides/` directory with structured guides
- Check if generated by `/codemie-init` (mentions template structure)

**B. Structured Guides** (if present):
- `docs/`, `.claude/guides/`, `documentation/`
- Look for topical organization (architecture, development, testing, etc.)

**C. CLAUDE.md Files** (if present):
- Root `CLAUDE.md` (project overview)
- Component-specific `CLAUDE.md` in subdirectories
- Common in: `src/`, `lib/`, feature directories

**D. Other Documentation**:
- `README.md`, `CONTRIBUTING.md`, `ARCHITECTURE.md`
- Wiki, Confluence, or external docs (mentioned in README)

**Note**: Projects may have any combination of these, or none at all.

**Decision Point**:
- ✅ Codemie docs found → Use smart change detection (Step 2A)
- ✅ Other docs found → Use traditional audit (Step 2B)

---

## Step 2A: Smart Change Detection (For Codemie Docs)

**Use this workflow when `.codemie/guides/` exists**

### Step 2A.1: Detect Changed Files

**Ask user** which timeframe to analyze:
- Recent uncommitted changes (default)
- Last N commits (e.g., 5, 10)
- Changes since specific date
- All changes (comprehensive audit)

**Git Commands**:
```bash
# Option 1: Uncommitted changes
git status --short
git diff HEAD --name-only

# Option 2: Last N commits
git diff HEAD~5 HEAD --name-only

# Option 3: Since date
git log --since="2 weeks ago" --name-only --pretty=format: | sort -u

# Option 4: All staged/unstaged
git diff --name-only && git diff --cached --name-only
```

**Filter relevant changes** (exclude):
- Test files (unless testing patterns changed)
- Build artifacts, dependencies
- Documentation files themselves
- Config files (unless tools changed)

**Output**: List of changed source files

**Decision Point**:
- ✅ Changes detected → Continue to Step 2A.2
- ❌ No changes → Skip to Step 6 (validation only)

---

### Step 2A.2: Map Changes to Guide Categories

**For each changed file**, determine which guides are affected:

| Changed File Pattern | Affected Guide Category | Example Guides |
|----------------------|-------------------------|----------------|
| `src/api/`, `routes/`, `controllers/` | API Development | api/api-patterns.md |
| `src/models/`, `repositories/`, `schemas/` | Data & Database | data/database-patterns.md |
| `src/services/`, `domain/`, `business/` | Architecture | architecture/architecture.md |
| `src/components/`, `ui/`, `views/` | Development Practices | development/frontend-patterns.md |
| `src/utils/errors.`, `exceptions/` | Development Practices | development/error-handling.md |
| `src/utils/logger.`, `logging/` | Development Practices | development/logging.md |
| `src/auth/`, `security/`, `middleware/auth` | Security | security/security-patterns.md |
| `tests/`, `*.test.`, `*.spec.` | Testing | testing/testing-patterns.md |
| `src/integrations/`, `clients/`, `adapters/` | Integrations | integration/external-integrations.md |
| Root directory changes (new folders) | Architecture | architecture/architecture.md |

**Assess impact**:
- **High impact**: Multiple files in same category changed
- **Low impact**: Single file changed
- **No impact**: Only tests changed, no pattern shifts

**List existing guides**:
```bash
find .codemie/guides -name "*.md" -type f
```

**Cross-reference**:
- Guide exists + impacted → Update candidate
- Guide exists + not impacted → Skip
- Guide missing + impacted → Note for user

**Present to user**:
```
📊 Change Impact Analysis

🔴 HIGH IMPACT (multiple files, pattern changes):
   ✏️ api/api-patterns.md (3 files changed)
   ✏️ security/security-patterns.md (2 files changed)

🟡 LOW IMPACT (single file, minor updates):
   ✏️ development/development-practices.md (1 file)

⏭️ SKIPPED (no pattern changes):
   - testing/testing-patterns.md
   - data/database-patterns.md

Proceed with selective update? (Yes / Full Audit / Cancel)
```

**Decision Point**:
- User selects "Yes" → Continue to Step 3A (selective update)
- User selects "Full Audit" → Jump to Step 2B (traditional audit)
- User selects "Cancel" → Exit

---

## Step 2B: Traditional Audit (For All Documentation)

**Use this workflow for non-Codemie docs or when user requests full audit**

Before reviewing documentation, understand what changed:

1. **Check recent commits**: `git log --oneline -10`
2. **Check current changes**: `git status` and `git diff`
3. **Identify impact areas**:
   - Did architectural patterns change?
   - Were new components/modules added?
   - Did core approaches evolve (error handling, testing, etc.)?
   - Were security practices updated?
   - Did integrations or APIs change?

**Decision Point**: If changes are minor (bug fixes, typos, small refactors), documentation likely doesn't need updates. Only proceed if changes affect patterns, architecture, or critical knowledge.

---

## Step 3A: Selective Update (For Codemie Docs)

**For each guide identified in Step 2A.2**:

### Step 3A.1: Analyze Changed Code

**For files mapped to this guide**:
1. Read the changed files
2. Identify what patterns changed (new, modified, or removed)
3. Extract updated code examples (5-15 lines max)
4. Note file paths with line numbers

### Step 3A.2: Compare Current Guide vs Code

**Load current guide**:
```bash
Read .codemie/guides/[category]/[guide].md
```

**Load template** (for structural reference):
```bash
Read ${CLAUDE_PLUGIN_ROOT}/claude-templates/templates/guides/[category]/[template].md.template
```

**Check**:
- [ ] Are documented patterns still used?
- [ ] Are code examples still accurate?
- [ ] Are file references still valid?
- [ ] Are new patterns present that should be documented?
- [ ] Are any documented patterns now obsolete?

### Step 3A.3: Execute Selective Updates

**Determine update scope**:

| Finding | Action |
|---------|--------|
| Code example outdated | Update specific example, preserve structure |
| Pattern evolved | Update pattern description and example |
| New pattern introduced | Add new pattern section (if space allows) |
| Pattern removed | Remove or mark as deprecated |
| File path changed | Update reference path |
| Everything accurate | Skip update (no changes needed) |

**Update strategy**:
- ✅ Use Edit tool for selective updates (NOT Write)
- ✅ Update specific sections that changed
- ✅ Preserve guide structure (maintain template alignment)
- ✅ Keep existing examples that are still valid
- ✅ Update file:line references
- ❌ Don't rewrite entire guide
- ❌ Don't change structure unnecessarily

**Validate size**:
```bash
wc -l .codemie/guides/[category]/[guide].md  # Must be ≤400 lines
```

If exceeded → Condense: remove redundant examples, use tables, tighten prose.

**Skip to Step 6** (validation) after updating impacted guides.

---

## Step 3B: Traditional Audit of Structured Guides

**Use for non-Codemie docs or full audit mode**

For each guide/doc file that exists:

**Review Process**:
1. Load the content
2. Compare documented patterns against actual implementation
3. Check if described approaches still match the codebase
4. Identify outdated, incorrect, or missing information

**Update Only If**:
- [ ] Pattern described no longer matches implementation
- [ ] New pattern emerged that should be documented
- [ ] Critical information is missing or incorrect
- [ ] Examples reference deleted/renamed code
- [ ] Security or architectural decisions changed

**Common Documentation Topics** (adapt to your project):
- Architecture and system design
- Error handling and logging patterns
- Testing strategies and setup
- Security practices
- API patterns and conventions
- Database/data patterns
- Development workflow
- Deployment and operations

---

## Step 4: Audit CLAUDE.md Files (if present)

For each CLAUDE.md file:

**Find CLAUDE.md Files**:
```bash
find . -name "CLAUDE.md" -not -path "*/node_modules/*" -not -path "*/.git/*"
```

**Review Process**:
1. Load current content
2. Compare against actual implementation in that directory
3. Check if file structure/organization changed
4. Identify outdated, incorrect, or missing information

**Update Only If**:
- [ ] Module purpose or responsibility changed
- [ ] Key architectural decisions evolved
- [ ] Important implementation details missing
- [ ] Documented patterns no longer used
- [ ] New gotchas or non-obvious behaviors introduced

**Typical CLAUDE.md Content** (adapt to project style):
- Purpose and responsibility of module
- Key architectural decisions
- Important implementation details
- Common patterns used
- Non-obvious behaviors or gotchas
- Integration points with other modules

---

## Step 5: Determine What Needs Updating (Traditional Mode)

Categorize findings:

**Definitely Update**:
- Documented pattern now incorrect
- Missing critical information for understanding
- Security or architectural approach changed
- Examples reference non-existent code
- Misleading or confusing content

**Probably Update**:
- New project-wide pattern should be documented
- Testing strategy evolved
- Integration points changed
- Important context missing

**No Update Needed**:
- Bug fixes that don't affect patterns
- Code refactoring maintaining same approach
- Typo fixes or variable renames
- Documentation already accurate
- Changes are self-evident from code

---

## Step 6: Execute Updates

**For Codemie Docs** (if using selective update from Step 3A):
- Updates already completed in Step 3A.3
- Skip to Step 7 (validation)

**For Traditional Audit** (if using Step 3B-5):
- Continue with updates below

Only modify files where changes are actually needed:

**For Structured Guides**:
1. Edit specific sections that are outdated
2. Update code examples if references changed
3. Add new patterns only if broadly applicable
4. Remove obsolete information
5. Keep content focused and concise

**For CLAUDE.md Files**:
1. Verify technical claims against current code
2. Update specific sections that changed
3. Add new critical information
4. Remove obsolete patterns
5. Ensure info is in most appropriate file

**For Codemie Guides** (if updating in traditional mode):
1. Maintain template structure from `${CLAUDE_PLUGIN_ROOT}/claude-templates/`
2. Update specific sections that are outdated
3. Preserve existing valid examples
4. Keep guides within size limits (200-400 lines)
5. Update file:line references if paths changed

**Content Placement**:
- **Broad patterns** (used across project) → Root docs or main CLAUDE.md
- **Component-specific** (local to one area) → Component CLAUDE.md or specific guide section
- **Project-wide conventions** → Root README or CLAUDE.md
- **Module implementation details** → Module-level CLAUDE.md
- **Codemie guides** → Category-specific guides in `.codemie/guides/[category]/`

---

## Step 7: Validate Changes

Before finalizing:

**Accuracy Check**:
- [ ] All technical claims verified against current code
- [ ] Examples reference existing files/functions (check with actual file paths)
- [ ] Patterns match actual implementation
- [ ] No contradictions between different docs

**For Codemie Docs** (additional checks):
- [ ] All file:line references are valid
```bash
# Verify referenced files exist
grep -o '\[.*\..*:.*\]' .codemie/guides/**/*.md | while read ref; do
    file=$(echo $ref | cut -d: -f1 | tr -d '[]')
    [ -f "$file" ] || echo "Missing: $file"
done
```
- [ ] No placeholders remain ([PLACEHOLDER], FILL IN, TODO)
```bash
grep -r '\[.*\]' .codemie/guides/ | grep -v '.git'
grep -r 'FILL IN\|TODO\|PLACEHOLDER' .codemie/guides/
```
- [ ] Guide structure matches template conventions
- [ ] Size limits maintained (≤400 lines per guide)
```bash
for guide in .codemie/guides/**/*.md; do
    lines=$(wc -l < "$guide")
    [ $lines -gt 400 ] && echo "⚠️ $guide exceeds 400 lines ($lines)"
done
```
- [ ] CLAUDE.md guide references are current (if guides added/removed)

**Relevance Check**:
- [ ] Information is actionable
- [ ] Content helps future understanding
- [ ] No duplicate information across files
- [ ] No obsolete references

**Quality Check**:
- [ ] Clear and concise language
- [ ] Examples are accurate
- [ ] Proper markdown formatting
- [ ] Links work (if any)

---

## Summary Report

After completing updates, provide a summary:

**For Selective Updates (Codemie Docs)**:
```markdown
# Documentation Refresh Complete

## Updated Guides (3)

### High Impact Updates
**api/api-patterns.md** ✅
- Updated: Validation middleware pattern
- Updated: Error response format examples
- References: 3 files updated, all verified

**security/security-patterns.md** ✅
- Updated: JWT token generation example
- References: 2 files updated, all verified

### Low Impact Updates
**development/development-practices.md** ✅
- Updated: Validation helper reference
- References: 1 file updated, verified

## Skipped Guides (5)
- testing/testing-patterns.md (no pattern changes)
- data/database-patterns.md (no changes)
- architecture/architecture.md (structure unchanged)

## Validation Status
- ✅ All file references verified
- ✅ No placeholders remain
- ✅ Size limits maintained
- ✅ Template structure preserved
```

**For Traditional Audit**:
```markdown
# Documentation Audit Complete

## Files Updated
- CLAUDE.md (updated commands section)
- .codemie/guides/api/api-patterns.md (new pattern added)
- src/services/CLAUDE.md (updated integration points)

## Validation Status
- ✅ All technical claims verified
- ✅ Examples reference existing code
- ✅ No contradictions found
- ✅ Links validated
```

---

## Key Principles

**Accuracy Over Completeness**:
- Better to have less documentation that's accurate
- Don't document what's obvious from well-written code
- Focus on "why" and "gotchas", not "what" (code shows "what")

**Selective Updates**:
- Not every commit requires documentation changes
- Only update when patterns or understanding actually shifts
- If in doubt, verify against actual implementation

**Appropriate Placement**:
- Put information where it's most useful
- Avoid duplication across files
- Component-specific → component docs
- Project-wide → root docs

**Maintainability**:
- Keep documentation focused
- Remove outdated content promptly
- Cross-reference related docs
- Use examples sparingly but effectively

---

## Decision Checklist

Before making changes, ask:

1. **Which mode applies?** (Codemie docs → Smart Mode | Other docs → Traditional)
2. **Is this change needed?** (Does doc mismatch implementation?)
3. **Is it significant?** (Will this help future understanding?)
4. **Where should it go?** (Most specific applicable location)
5. **What's the scope?** (Component-specific or project-wide?)
6. **Is it accurate?** (Verified against current code?)
7. **Is it clear?** (Would someone else understand this?)

**Smart Mode Benefits**:
- Faster: Only checks changed areas
- Targeted: Updates specific guides
- Efficient: Good for regular maintenance

**Traditional Mode Benefits**:
- Comprehensive: Reviews all docs
- Thorough: Catches subtle issues
- Complete: Good for major refactors

**If unsure**: Verify implementation first, then update documentation.

**Remember**: Documentation serves the code, not vice versa. Focus on critical, non-obvious knowledge that helps future work.
