# Claude Code Hooks - Automated Testing & Code Quality Workflow

This directory contains automated hooks that enforce best practices for test-driven development and code quality in the Mawidi Codex project.

## 🔄 Hook Workflow

The hooks work together to create a seamless development workflow:

```
1. Write/Edit Code
   ↓
2. generate-tests-hook.sh (PostToolUse)
   → Detects code changes
   → Requests test generation
   → Creates marker file
   ↓
3. User writes tests (prompted by Claude)
   ↓
4. restructure-code-hook.sh (PostToolUse on test files)
   → Detects test file creation
   → Finds corresponding source file
   → Requests code restructuring
   ↓
5. check-pending-tasks.sh (UserPromptSubmit)
   → Reminds about incomplete tasks
   → Ensures tests are written
```

## 📁 Hook Files

### 1. generate-tests-hook.sh

**Trigger**: After `Edit` or `Write` tool usage on source files
**Purpose**: Automatically request test generation for new/modified code

**Features**:

- Detects TypeScript/JavaScript/React file changes
- Skips test files (prevents recursion)
- Skips config/docs/non-code files
- Creates marker file for tracking
- Outputs system message prompting test creation

**File Patterns Monitored**: `*.ts`, `*.tsx`, `*.js`, `*.jsx`
**File Patterns Ignored**: `*.test.*`, `*.spec.*`, `__tests__/*`, `tests/*`, `*.md`, `*.json`, `*.yml`, `*.env*`

### 2. restructure-code-hook.sh

**Trigger**: After `Edit` or `Write` tool usage on test files
**Purpose**: Request code restructuring after tests are in place

**Features**:

- Detects test file creation/modification
- Maps test files to source files
- Supports multiple test patterns (`__tests__/`, `tests/`, `.test.`, `.spec.`)
- Only triggers when corresponding source file exists
- Requests safe refactoring with documentation

**Test File Patterns**:

- `__tests__/path/to/file.test.ts` → `path/to/file.ts`
- `tests/feature.spec.ts` → `app/feature.ts` or `lib/feature.ts` or `components/feature.ts`

### 3. check-pending-tasks.sh

**Trigger**: On user prompt submission
**Purpose**: Remind about pending test generation tasks

**Features**:

- Scans for marker files from test generation hook
- Lists files needing tests
- Auto-cleans markers older than 1 hour
- Non-intrusive (only shows when tasks pending)

### 4. ai-code-review-hook.sh

**Trigger**: `PostToolUse` (Edit|Write) and `Stop` events
**Purpose**: Automatically trigger AI code review when Claude finishes work

**Features**:

- **PostToolUse**: Queues modified source files for review
- **Stop**: When Claude completes work, prompts for AI code review
- Integrates with ai-code-review skill using Gemini and Codex MCPs
- Filters out test files, node_modules, and non-code files
- Uses `/tmp/claude_code_review/` for queue storage

**MCP Servers Used**:

- `mcp__gemini-cli__ask-gemini` (gemini-2.5-flash) - Broad pattern analysis
- `mcp__codex-mcp__prompt_engine` - CAGEERF methodology review
- `mcp__codex__codex` - Deep logic verification

**File Patterns Monitored**: `*.ts`, `*.tsx`, `*.js`, `*.jsx`, `*.py`, `*.go`, `*.rs`, `*.java`, `*.sql`, `*.prisma`
**File Patterns Ignored**: `*.test.*`, `*.spec.*`, `node_modules/*`, `.next/*`, `.git/*`

### 5. task-complete-review-hook.sh

**Trigger**: `PostToolUse` (TodoWrite) - when tasks are marked as completed
**Purpose**: Automatically send completed work to Gemini and Codex MCP for improvement suggestions

**Features**:

- **File Tracking**: Queues files as they are modified during task execution
- **Task Completion Detection**: Monitors TodoWrite for completed task status
- **Dual AI Review**: Sends files to both Gemini and Codex MCPs for comprehensive suggestions
- **File Content Sharing**: Includes actual file contents in review request
- **Smart Filtering**: Skips test files, node_modules, large files
- Uses `/tmp/claude_task_review/` for queue storage

**MCP Servers Used**:

- `mcp__gemini-cli__ask-gemini` - Fast analysis for code quality, performance, security
- `mcp__codex__codex` - Deep analysis for architecture, edge cases, maintainability

**Workflow**:

1. As Claude edits/writes files, they are queued for review
2. When TodoWrite marks a task as "completed", the hook triggers
3. Collects all modified files (up to 10) with their content
4. Outputs a system message prompting AI review
5. User can accept to run the dual MCP review

**File Patterns Monitored**: `*.ts`, `*.tsx`, `*.js`, `*.jsx`, `*.py`, `*.go`, `*.rs`, `*.java`, `*.sql`, `*.prisma`, `*.sh`, `*.mjs`, `*.cjs`
**File Patterns Ignored**: `node_modules/*`, `.next/*`, `.git/*`, `dist/*`, `build/*`, `coverage/*`

## ⚙️ Configuration

Hooks are configured in `.claude/settings.json`:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/file-watcher-hook.sh"
          },
          {
            "type": "command",
            "command": ".claude/hooks/generate-tests-hook.sh",
            "timeout": 30
          },
          {
            "type": "command",
            "command": ".claude/hooks/restructure-code-hook.sh",
            "timeout": 30
          },
          {
            "type": "command",
            "command": ".claude/hooks/ai-code-review-hook.sh",
            "timeout": 10
          },
          {
            "type": "command",
            "command": ".claude/hooks/task-complete-review-hook.sh",
            "timeout": 10
          }
        ]
      },
      {
        "matcher": "TodoWrite",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/task-complete-review-hook.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/check-pending-tasks.sh",
            "timeout": 15
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/ai-code-review-hook.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
```

## 🎯 Expected Behavior

### When You Create/Edit a Feature File

1. **Immediate Response**: Hook detects change and shows:

   ```
   📝 Code change detected in lib/services/booking.ts. Tests should be generated to ensure reliability.
   ```

2. **Claude Prompts You**:

   ```
   I notice you've created/modified lib/services/booking.ts.
   Should I write comprehensive tests for this feature to ensure it runs well in the future?
   ```

3. **You Approve**: Claude writes tests in `__tests__/lib/services/booking.test.ts`

4. **Restructuring Triggered**: After test file is written:

   ```
   ✅ Tests created for lib/services/booking.ts. Code can now be safely restructured and documented.
   ```

5. **Claude Offers Refactoring**:
   ```
   Now that tests are in place, should I restructure the code in lib/services/booking.ts
   into a well-documented and easy-to-change version? The tests will ensure nothing breaks.
   ```

### If You Skip Test Creation

When you submit your next prompt, you'll see:

```
⚠️  Pending Tasks:

🧪 Test Generation Needed:
  - lib/services/booking.ts
  - components/NewFeature.tsx

Should I write comprehensive tests for these files to ensure reliability?
```

## 🔧 Customization

### Adjust File Patterns

Edit `generate-tests-hook.sh` to change which files trigger test generation:

```bash
# Only proceed for TypeScript/JavaScript/React files
if [[ ! "$FILE_PATH" =~ \.(ts|tsx|js|jsx)$ ]]; then
  exit 0
fi
```

### Change Test File Mapping

Edit `restructure-code-hook.sh` to modify how test files map to source files:

```bash
if [[ "$FILE_PATH" == *"__tests__/"* ]]; then
  SOURCE_FILE=$(echo "$FILE_PATH" | sed 's|__tests__/||' | sed 's|\.test\.||')
fi
```

### Disable Specific Hooks

Comment out hooks in `settings.json`:

```json
{
  "hooks": [
    // {
    //   "type": "command",
    //   "command": ".claude/hooks/generate-tests-hook.sh"
    // }
  ]
}
```

## 🐛 Debugging

### Enable Verbose Output

Add debug logging to any hook script:

```bash
# At top of script, after set -euo pipefail
echo "[DEBUG] Tool: $TOOL_NAME, File: $FILE_PATH" >&2
```

### Check Hook Execution

View hook execution in Claude Code verbose mode or check stderr:

```bash
# Run hook manually for testing
echo '{"tool_name":"Write","input":{"file_path":"test.ts"}}' | .claude/hooks/generate-tests-hook.sh
```

### Check Marker Files

See pending tasks:

```bash
ls -lh /tmp/claude_code_needs_tests_*.marker
cat /tmp/claude_code_needs_tests_*.marker
```

### Clean Markers

Remove all pending task markers:

```bash
rm -f /tmp/claude_code_needs_tests_*.marker
```

## 📊 Benefits

- **Automatic Test Coverage**: Never forget to write tests for new features
- **Safe Refactoring**: Only restructure code after tests are in place
- **Code Quality**: Ensures well-documented, maintainable code
- **Consistent Workflow**: Enforces TDD best practices automatically
- **Non-Blocking**: All hooks are informational, never block development
- **Smart Filtering**: Ignores tests, configs, docs to prevent noise

## 🚀 Getting Started

1. **Restart Claude Code**: Hooks are loaded at startup
2. **Create a new feature**: Edit or write a new `.ts` file
3. **Watch the magic**: Claude will prompt you to write tests
4. **Write tests**: Claude generates comprehensive tests
5. **Refactor**: Claude offers to restructure the code
6. **Done**: Well-tested, well-documented feature complete!

## 📝 Notes

- Hooks run in parallel for performance
- Marker files auto-cleanup after 1 hour
- All hooks are non-blocking (exit 0)
- JSON output format ensures proper Claude integration
- `jq` required for JSON parsing (install: `brew install jq`)

## 🔗 Related Documentation

- Claude Code Hooks Guide: https://code.claude.com/docs/en/hooks-guide.md
- Testing System: `../../TESTING_SYSTEM_SUMMARY.md`
- MCP Code Execution: `../mcp/README.md`
