commandby alinaqi

Update Code Index

Regenerates `CODE_INDEX.md` by scanning the codebase for all functions, classes, hooks, and components. Organizes by capability to prevent semantic duplication.

Installs: 0
Used in: 1 repos
Updated: 0mo ago
$npx ai-builder add command alinaqi/update-code-index

Installs to .claude/commands/update-code-index.md

# Update Code Index

Regenerates `CODE_INDEX.md` by scanning the codebase for all functions, classes, hooks, and components. Organizes by capability to prevent semantic duplication.

---

## What This Command Does

1. **Scans source files** - Finds all exported functions, classes, hooks, components
2. **Extracts docstrings** - Gets descriptions from JSDoc/docstrings
3. **Categorizes by capability** - Groups by what things DO, not where they live
4. **Generates CODE_INDEX.md** - Creates/updates the semantic index

---

## Phase 1: Detect Project Type

```bash
# Check language
ls package.json pyproject.toml 2>/dev/null

# Check source directories
ls -d src/ lib/ app/ 2>/dev/null
```

---

## Phase 2: Scan Codebase

### For TypeScript/JavaScript

Scan for exports:

```bash
# Find all exported functions
grep -rn "export function\|export const\|export class\|export default" src/ --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx"

# Find React hooks
grep -rn "export function use[A-Z]\|export const use[A-Z]" src/ --include="*.ts" --include="*.tsx"

# Find React components (PascalCase exports)
grep -rn "export function [A-Z]\|export const [A-Z].*=.*=>" src/ --include="*.tsx" --include="*.jsx"
```

### For Python

```bash
# Find all function definitions
grep -rn "^def \|^async def \|^class " src/ --include="*.py"

# Check __all__ exports
grep -rn "__all__" src/ --include="*.py"
```

---

## Phase 3: Extract Documentation

For each found export, extract:

1. **Name** - Function/class name
2. **Location** - File path and line number
3. **Description** - From JSDoc `@description` or first line of docstring
4. **Parameters** - Function signature
5. **Returns** - Return type if available

### TypeScript Example

```typescript
/**
 * Formats a date into a human-readable relative string.
 * @param date - The date to format
 * @returns Relative time string like "2 days ago"
 */
export function formatRelative(date: Date): string {
```

Extract:
- Name: `formatRelative`
- Description: "Formats a date into a human-readable relative string"
- Params: `(date: Date)`
- Returns: `string`

### Python Example

```python
def format_relative(date: datetime) -> str:
    """Formats a date into a human-readable relative string.

    Args:
        date: The date to format

    Returns:
        Relative time string like "2 days ago"
    """
```

Extract:
- Name: `format_relative`
- Description: "Formats a date into a human-readable relative string"
- Params: `(date: datetime)`
- Returns: `str`

---

## Phase 4: Categorize by Capability

Group functions by what they DO:

| Category | Keywords to Match |
|----------|-------------------|
| **Date/Time** | date, time, format, parse, duration, relative, timestamp |
| **Validation** | validate, is*, check, verify, sanitize |
| **String Operations** | string, text, format, parse, slug, truncate, capitalize |
| **API Clients** | fetch, get, post, put, delete, api, request |
| **Authentication** | auth, login, logout, session, token, user |
| **Error Handling** | error, exception, handle, catch, throw |
| **Database** | db, query, find, create, update, delete, repository |
| **Hooks (React)** | use* |
| **Components (React)** | PascalCase in .tsx/.jsx |
| **Utilities** | util, helper, common (catch-all) |

---

## Phase 5: Generate CODE_INDEX.md

Create or overwrite `CODE_INDEX.md`:

```markdown
# Code Index

*Auto-generated by /update-code-index*
*Last updated: [TIMESTAMP]*

> ⚠️ **Before writing new code, search this index first!**
> Find similar functionality? Use or extend it instead of creating new.

## Quick Stats

| Category | Count | Main Location |
|----------|-------|---------------|
| Date/Time | X | src/utils/dates.ts |
| Validation | X | src/utils/validate.ts |
| API Clients | X | src/api/*.ts |
| Hooks | X | src/hooks/*.ts |
| Components | X | src/components/*.tsx |

---

## Date/Time Operations

| Function | Location | Description | Signature |
|----------|----------|-------------|-----------|
| `formatDate()` | utils/dates.ts:15 | Formats Date to locale string | `(date: Date, opts?)` |
| `formatRelative()` | utils/dates.ts:32 | Formats as "2 days ago" | `(date: Date)` |
| ... | ... | ... | ... |

---

## Validation

| Function | Location | Description | Signature |
|----------|----------|-------------|-----------|
| `isEmail()` | utils/validate.ts:10 | Validates email format | `(email: string)` |
| ... | ... | ... | ... |

---

[Continue for each category...]
```

---

## Phase 6: Report Changes

After generating, report:

```
📊 Code Index Updated

Scanned:
• 45 TypeScript files
• 12 React components
• 8 custom hooks
• 156 exported functions

Categories:
• Date/Time: 5 functions
• Validation: 8 functions
• API Clients: 23 functions
• Hooks: 8 hooks
• Components: 12 components
• Utilities: 42 functions

New since last run:
• + fetchOrders() in api/orders.ts
• + useCart() in hooks/useCart.ts
• + OrderCard component in components/OrderCard.tsx

Possible duplicates detected:
• ⚠️ formatDate() and displayDate() - similar purpose?
• ⚠️ isValid() and validate() - review these

Updated: CODE_INDEX.md
```

---

## Handling Missing Documentation

If a function lacks documentation:

```markdown
| `myFunction()` | utils/helpers.ts:42 | ⚠️ *No description - add JSDoc* | `(a, b, c)` |
```

Report at end:

```
⚠️ 12 functions missing documentation:
• myFunction() in utils/helpers.ts:42
• anotherFunc() in services/user.ts:88
• ...

Run with --add-docs to prompt for descriptions.
```

---

## Options

```bash
# Basic update
/update-code-index

# Include private/non-exported functions
/update-code-index --include-private

# Prompt to add missing docs
/update-code-index --add-docs

# Only scan specific directory
/update-code-index src/utils

# Output as JSON (for vector DB ingestion)
/update-code-index --json > code_index.json

# Detect duplicates only (no index update)
/update-code-index --audit-only
```

---

## Audit Mode

When run with `--audit-only` or as `/audit-duplicates`:

```markdown
## Duplicate Audit Report - [DATE]

### 🔴 High Confidence Duplicates

1. **formatDate / displayDate / showDate**
   - `formatDate()` at utils/dates.ts:15
   - `displayDate()` at components/Header.tsx:42
   - `showDate()` at pages/Profile.tsx:28
   - Similarity: 89% (same logic, different names)
   - **Recommendation:** Consolidate into utils/dates.ts

2. **isEmail / validateEmail / checkEmail**
   - `isEmail()` at utils/validate.ts:10
   - `validateEmail()` at forms/signup.ts:55
   - `checkEmail()` at api/users.ts:30
   - Similarity: 95% (identical regex)
   - **Recommendation:** Use isEmail() everywhere

### 🟡 Possible Duplicates (Review)

1. **fetchUser / getUser / loadUser**
   - Different implementations but same purpose
   - May be intentional (different contexts)
   - **Action:** Document if intentional, merge if not

### 🟢 Similar But Distinct

1. **Button / IconButton / LinkButton**
   - Related components with different purposes
   - **Status:** OK - documented variants
```

---

## Integration with Vector DB

If vector DB is set up, also update embeddings:

```bash
/update-code-index --vector
```

This:
1. Generates CODE_INDEX.md (as usual)
2. Creates embeddings for each function description
3. Stores in `.chroma/` or `.lancedb/`
4. Enables semantic search: "find functions that validate user input"

---

## Suggested Workflow

### Daily
- Index auto-updates on significant code changes
- Claude checks index before writing new code

### Weekly
- Run `/update-code-index --audit-only`
- Review duplicate report
- Merge or document similar functions

### After Major Features
- Full index regeneration
- Vector DB re-embedding (if used)

---

## File Output

Creates/updates:
- `CODE_INDEX.md` - Human-readable index
- `.code-index.json` (optional) - Machine-readable for tooling

---

## Claude Instructions

When user runs `/update-code-index`:

1. Detect project type (TS/JS/Python)
2. Scan source directories
3. Extract all exports with documentation
4. Categorize by capability
5. Generate CODE_INDEX.md
6. Report stats and potential duplicates
7. Commit the updated index

After running, remind user:
> "Index updated! I'll check this before writing any new code to avoid duplicating existing functionality."

Quick Install

$npx ai-builder add command alinaqi/update-code-index

Details

Type
command
Author
alinaqi
Slug
alinaqi/update-code-index
Created
0mo ago