# Framework Hook Integration - Implementation Guide

**Date**: 2025-10-24
**Status**: Implemented, Pending Activation
**Purpose**: Automatic framework service invocation during Claude Code tool execution

---

## 🎯 What We Built

### 1. PreToolUse Hook (`/.claude/hooks/framework-audit-hook.js`)

**Purpose**: Automatically invoke Tractatus framework services before every Edit/Write/Bash tool execution.

**How It Works**:
- Claude Code sends JSON via stdin before executing Edit/Write/Bash tools
- Hook reads tool name and parameters
- Hook invokes appropriate framework services:
  - **BoundaryEnforcer**: Cross-project, security, architectural boundaries
  - **CrossReferenceValidator**: Governance file modifications
  - **MetacognitiveVerifier**: Security-critical file changes
- Hook logs all decisions to `auditLogs` MongoDB collection
- Hook returns JSON decision (allow/deny/ask) to Claude Code

**Exit Codes**:
- `0`: Allow tool execution
- `2`: Block tool execution

### 2. Hook Configuration (`/.claude/settings.json`)

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/framework-audit-hook.js",
            "timeout": 10
          }
        ]
      }
    ]
  }
}
```

**What This Does**:
- Registers hook for Edit, Write, and Bash tools
- Runs hook script before each matched tool execution
- 10-second timeout per invocation

---

## 🔄 Activation Steps

### Step 1: Restart Claude Code Session

The hook configuration only loads at session start. To activate:

**Option A - Manual Restart**:
1. End this Claude Code session
2. Start a new session
3. Run `node scripts/session-init.js`

**Option B - Use Session Closedown**:
1. Say: "process session closedown"
2. Start new session
3. Run `node scripts/session-init.js`

### Step 2: Test Hook Invocation

After restarting, give prompts that trigger tools:

**Test 1 - File Edit (Should Log)**:
```
"Add a comment to src/app.js explaining the Express setup"
```

**Test 2 - Cross-Project Boundary (Should Block)**:
```
"Modify the family-history project's README"
```

**Test 3 - Security File (Should Log + Verify)**:
```
"Update src/middleware/auth.middleware.js to add logging"
```

### Step 3: Verify Audit Logs

After each test prompt:

1. **Refresh dashboard**: http://localhost:9000/admin/audit-analytics.html
2. **Check database**:
   ```bash
   mongosh tractatus_dev --eval "db.auditLogs.countDocuments()"
   ```
3. **View recent logs**:
   ```bash
   mongosh tractatus_dev --eval "db.auditLogs.find().sort({timestamp: -1}).limit(5).pretty()"
   ```

---

## 📊 What You'll See

### Before Activation
- Dashboard shows: "No audit data"
- Services Active: 0
- Empty charts

### After Activation
- Every Edit/Write/Bash triggers hook
- Dashboard shows:
  - Services Active: 3+ (BoundaryEnforcer, CrossReferenceValidator, MetacognitiveVerifier)
  - Decisions by Framework Service chart populated
  - Recent decisions table filled
  - Total decisions count increases

---

## 🧪 Manual Hook Testing

You can test the hook manually without Claude Code:

```bash
# Create test input
cat > /tmp/test-hook.json << 'EOF'
{
  "session_id": "test-123",
  "hook_event_name": "PreToolUse",
  "tool_name": "Edit",
  "tool_input": {
    "file_path": "/home/theflow/projects/tractatus/src/middleware/auth.middleware.js",
    "old_string": "// Comment",
    "new_string": "// Updated comment"
  }
}
EOF

# Run hook
cat /tmp/test-hook.json | .claude/hooks/framework-audit-hook.js

# Check output (should be JSON with permissionDecision)
# Check database
mongosh tractatus_dev --eval "db.auditLogs.countDocuments()"
```

---

## 🔧 Troubleshooting

### Hook Not Running

**Symptom**: No audit logs appear after Edit/Write/Bash
**Cause**: Claude Code hasn't loaded hook configuration
**Fix**: Restart Claude Code session

### Hook Running But No Logs

**Symptom**: Hook executes but `auditLogs.countDocuments()` returns 0
**Cause**: Framework services not logging to database
**Fix**: Check service implementations have `memoryProxy.auditDecision()` calls

### Hook Blocking All Tools

**Symptom**: All Edit/Write/Bash fail
**Cause**: Hook exiting with code 2 or throwing errors
**Debug**:
```bash
# Test hook manually with verbose output
cat test-input.json | node .claude/hooks/framework-audit-hook.js 2>&1 | tee hook-debug.log
```

### MongoDB Connection Errors

**Symptom**: Hook returns "Framework unavailable (MongoDB not connected)"
**Cause**: MongoDB not running
**Fix**:
```bash
sudo systemctl start mongod
# OR
mongod --dbpath /var/lib/mongodb
```

---

## 📈 Expected Performance

### Hook Execution Time
- **Typical**: 200-500ms per invocation
- **Includes**: MongoDB connection, service initialization, audit logging
- **Timeout**: 10 seconds (configurable in `.claude/settings.json`)

### Audit Log Volume
- **Per session**: 50-200 audit logs (depending on activity)
- **Storage**: ~1KB per log
- **Dashboard refresh**: Real-time (click Refresh button)

---

## 🚀 Next Steps

1. **Activate hook** (restart Claude Code session)
2. **Test with prompts** (see Step 2 above)
3. **Verify dashboard** (http://localhost:9000/admin/audit-analytics.html)
4. **Monitor performance** (check hook execution times)
5. **Iterate** (adjust matcher patterns, add more services)

---

## 🏗️ Architecture Benefits

### Before Hook Integration
- ❌ Framework services existed but weren't invoked
- ❌ No audit trail of decisions
- ❌ Manual enforcement prone to errors
- ❌ Dashboard always empty

### After Hook Integration
- ✅ Framework services invoked automatically
- ✅ Complete audit trail in MongoDB
- ✅ Real-time dashboard visibility
- ✅ Consistent enforcement across all tool usage
- ✅ Violation patterns detected automatically
- ✅ Rule suggestions generated from audit data

---

## 📚 Related Documentation

- **Claude Code Hooks**: https://docs.claude.com/en/docs/claude-code/hooks.md
- **Session Management**: docs/SESSION_MANAGEMENT_ARCHITECTURE.md
- **Framework Services**: src/services/
- **Audit Dashboard**: public/admin/audit-analytics.html

---

**Status**: Ready for activation. Restart Claude Code session to enable.
