Skip to content
This repository was archived by the owner on Feb 1, 2026. It is now read-only.

Commit 8b19dd5

Browse files
Spacehunterzclaude
andcommitted
Add hook templates and auto-install mechanism for new users
Problem: New users don't have sync-golden-rules hook, so golden-rules.md doesn't auto-sync with database. Solution: - Add .hooks-templates/ directory to version all hooks in git - Create install-hooks.py to copy templates to ~/.claude/hooks/ - Create verify-hooks.py to check and auto-install missing hooks - Hooks are installed automatically during setup and checkin New users now get: - Auto-syncing of golden rules (PostToolUse hook) - Seamless experience with zero manual config - Safety net via verify-hooks in checkin Installation workflow: 1. User runs setup.sh -> hooks auto-installed 2. User runs /checkin -> verify-hooks ensures they're present 3. PostToolUse hook keeps markdown and database in sync Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
1 parent 73c24aa commit 8b19dd5

4 files changed

Lines changed: 356 additions & 145 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Post-tool hook: Auto-sync golden-rules.md to database
4+
5+
Runs after every tool use. If golden-rules.md was modified, syncs to database.
6+
"""
7+
8+
import sqlite3
9+
import re
10+
from pathlib import Path
11+
import hashlib
12+
import json
13+
from datetime import datetime
14+
15+
STATE_FILE = Path.home() / '.claude/hooks/investigation-state.json'
16+
MARKDOWN_FILE = Path.home() / '.claude/emergent-learning/memory/golden-rules.md'
17+
DB_FILE = Path.home() / '.claude/emergent-learning/memory/index.db'
18+
19+
def get_file_hash(filepath):
20+
"""Get SHA256 hash of file."""
21+
try:
22+
with open(filepath, 'rb') as f:
23+
return hashlib.sha256(f.read()).hexdigest()
24+
except:
25+
return None
26+
27+
def load_state():
28+
"""Load last known state."""
29+
try:
30+
if STATE_FILE.exists():
31+
with open(STATE_FILE) as f:
32+
return json.load(f)
33+
except:
34+
pass
35+
return {}
36+
37+
def save_state(state):
38+
"""Save current state."""
39+
try:
40+
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
41+
with open(STATE_FILE, 'w') as f:
42+
json.dump(state, f)
43+
except:
44+
pass
45+
46+
def sync_golden_rules():
47+
"""Sync markdown to database."""
48+
try:
49+
# Read markdown
50+
with open(MARKDOWN_FILE) as f:
51+
content = f.read()
52+
53+
golden_titles = re.findall(r'^## \d+\. (.+)$', content, re.MULTILINE)
54+
55+
# Connect to database
56+
conn = sqlite3.connect(str(DB_FILE))
57+
cur = conn.cursor()
58+
59+
# Get all active heuristics
60+
cur.execute('SELECT id, rule, is_golden FROM heuristics WHERE status="active"')
61+
all_heuristics = cur.fetchall()
62+
63+
updates = 0
64+
for heuristic_id, rule_text, is_golden in all_heuristics:
65+
should_be_golden = any(
66+
title.lower() in rule_text.lower()
67+
for title in golden_titles
68+
)
69+
70+
if should_be_golden != bool(is_golden):
71+
cur.execute('UPDATE heuristics SET is_golden=? WHERE id=?',
72+
(1 if should_be_golden else 0, heuristic_id))
73+
updates += 1
74+
75+
conn.commit()
76+
conn.close()
77+
78+
return updates > 0
79+
except Exception as e:
80+
print(f"[WARN] Golden rules sync failed: {e}")
81+
return False
82+
83+
def run():
84+
"""Check if sync is needed and run it."""
85+
state = load_state()
86+
current_hash = get_file_hash(MARKDOWN_FILE)
87+
last_hash = state.get('golden_rules_hash')
88+
89+
# If markdown changed, sync to database
90+
if current_hash and current_hash != last_hash:
91+
if sync_golden_rules():
92+
state['golden_rules_hash'] = current_hash
93+
state['golden_rules_last_sync'] = datetime.now().isoformat()
94+
save_state(state)
95+
return "Synced golden-rules.md to database"
96+
97+
return None
98+
99+
if __name__ == '__main__':
100+
result = run()
101+
if result:
102+
print(f"[SYNC] {result}")

.hooks-templates/README.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# ELF Hook Templates
2+
3+
This directory contains templates for Claude Code hooks that enhance the ELF experience.
4+
5+
## Hooks Included
6+
7+
### PostToolUse/sync-golden-rules.py
8+
**Purpose:** Auto-sync golden-rules.md with the database after each tool use
9+
10+
**What it does:**
11+
- Detects changes to `memory/golden-rules.md`
12+
- Syncs rule definitions to the heuristics database
13+
- Keeps markdown and database in sync automatically
14+
15+
**When it runs:** After every tool execution
16+
17+
---
18+
19+
## Installation
20+
21+
### Automatic (Recommended)
22+
Hooks are installed automatically during:
23+
1. **Initial ELF setup**: `bash install.sh`
24+
2. **First checkin**: `/checkin` command
25+
3. **Manual install**: `python scripts/install-hooks.py`
26+
27+
### Manual Installation
28+
```bash
29+
# Install all hooks
30+
python ~/.claude/emergent-learning/scripts/install-hooks.py
31+
32+
# Install with verbose output
33+
python ~/.claude/emergent-learning/scripts/install-hooks.py --verbose
34+
35+
# Force reinstall existing hooks
36+
python ~/.claude/emergent-learning/scripts/install-hooks.py --force
37+
```
38+
39+
### Verification
40+
```bash
41+
# Check if all hooks are installed
42+
python ~/.claude/emergent-learning/scripts/verify-hooks.py
43+
```
44+
45+
---
46+
47+
## How Hooks Work
48+
49+
Hooks are shell scripts that run at specific points in the Claude Code workflow:
50+
51+
**Hook Locations:**
52+
- `~/.claude/hooks/PostToolUse/` - Run after tool execution
53+
- `~/.claude/hooks/PreToolUse/` - Run before tool execution
54+
- `~/.claude/hooks/UserPromptSubmit/` - Run after user message
55+
- `~/.claude/hooks/SessionEnd/` - Run at session end
56+
57+
**Exit Codes:**
58+
- `0` - Success (hook output is captured)
59+
- `1+` - Failure (hook output is not captured)
60+
61+
---
62+
63+
## For New Users
64+
65+
When you first run ELF:
66+
1. **Setup** automatically installs hooks
67+
2. **Checkin** verifies hooks are installed (safety net)
68+
3. **Auto-sync** starts working immediately
69+
70+
No manual action needed!
71+
72+
---
73+
74+
## Troubleshooting
75+
76+
**Hooks not running?**
77+
- Check they're executable: `ls -la ~/.claude/hooks/PostToolUse/`
78+
- Verify hooks directory exists: `ls ~/.claude/hooks/`
79+
- Reinstall: `python ~/.claude/emergent-learning/scripts/install-hooks.py --force`
80+
81+
**Auto-sync not working?**
82+
- Check hook was installed: `ls ~/.claude/hooks/PostToolUse/sync-golden-rules.py`
83+
- Run verify script: `python ~/.claude/emergent-learning/scripts/verify-hooks.py`
84+
- Check permissions: `chmod +x ~/.claude/hooks/PostToolUse/sync-golden-rules.py`
85+
86+
---
87+
88+
## Developing New Hooks
89+
90+
1. Create hook in `.hooks-templates/[HOOK_TYPE]/my-hook.py`
91+
2. Test locally in `~/.claude/hooks/[HOOK_TYPE]/`
92+
3. Commit to repo
93+
4. Users will auto-install on next setup/checkin
94+

0 commit comments

Comments
 (0)