This guide explains how to integrate Terraphim's knowledge graph capabilities with Claude through two different approaches: Hooks and Skills.
- Overview
- Approach Comparison
- Claude Code Hooks
- Claude Skills
- Codebase Evaluation
- Which Approach to Use
- Getting Started
- Advanced Integration
Terraphim provides knowledge graph-based text replacement capabilities through its terraphim-tui command-line tool. This can be integrated with Claude in two ways:
- Hooks: Automatic, transparent interception of user input
- Skills: Context-aware, conversational assistance
Both approaches use the same underlying technology:
- Knowledge Graph: Semantic relationships defined in markdown files
- Aho-Corasick Automata: Fast pattern matching (O(n + m))
- Terraphim-TUI: Command-line interface for replacements
| Feature | Claude Code Hooks | Claude Skills |
|---|---|---|
| Activation | Automatic on every prompt | Context-aware when relevant |
| User Visibility | Transparent (optional notification) | Conversational with explanation |
| Platform | Claude Code CLI only | All Claude platforms |
| Setup Location | Hook script in settings | Skill in ~/.claude/skills/ |
| User Control | Environment variables | Natural language direction |
| Execution Timing | Before Claude sees input | During Claude's response |
| Best For | Consistent enforcement | Interactive collaboration |
| Explanation | None (or minimal log) | Full context and reasoning |
| Complexity | Medium (bash scripting) | Low (markdown + optional scripts) |
| Cross-Platform | No (CLI only) | Yes (all surfaces) |
Hooks are shell commands that execute in response to events like user prompt submission. They modify input before Claude sees it.
User Input → Hook Script → Modified Input → Claude
The hook intercepts the input, processes it, and returns modified text.
#!/usr/bin/env bash
# Read user input
INPUT=$(cat)
# Process with terraphim-tui
REPLACED=$(terraphim-tui replace "$INPUT" 2>/dev/null)
# Return modified input
echo "$REPLACED"File: ~/.config/claude-code/settings.json
{
"hooks": {
"user-prompt-submit": {
"command": "bash",
"args": ["/path/to/terraphim-package-manager-hook.sh"],
"enabled": true,
"description": "Replace package manager commands with bun"
}
}
}Hooks support three operational modes:
Replace Mode (default)
export HOOK_MODE=replaceAutomatically replaces all package manager commands without notification.
Suggest Mode
export HOOK_MODE=suggestShows suggestions in stderr but keeps original input.
Passive Mode
export HOOK_MODE=passiveOnly logs what would be replaced, doesn't modify input.
✅ Use hooks when:
- You want consistent, automatic enforcement
- You don't need explanations for changes
- You're using Claude Code CLI exclusively
- You want replacements to happen transparently
- You have clear, well-defined patterns to match
❌ Don't use hooks when:
- You want Claude to explain changes
- You need context-aware decisions
- You're using multiple Claude platforms
- You want interactive control
- Patterns are complex or context-dependent
Location: examples/claude-code-hooks/
Files:
terraphim-package-manager-hook.sh- Hook scripttest-hook.sh- Test suiteclaude-settings-example.json- Configuration exampleREADME.md- Comprehensive guide
Documentation: See examples/claude-code-hooks/README.md
1. Package Manager Replacement (bun)
Knowledge Graph Files:
docs/src/kg/bun.md- Maps npm/yarn/pnpm → bundocs/src/kg/bun_install.md- Maps installation commands → bun_install
Example Replacements:
$ terraphim-tui replace "npm install && yarn test"
bun_install && bun test2. Attribution Replacement (Claude → Terraphim)
Knowledge Graph Files:
docs/src/kg/terraphim_ai.md- Maps "Claude Code" → terraphim_aidocs/src/kg/https___terraphim_ai.md- Maps Claude URLs → Terraphim URLsdocs/src/kg/generated_with_terraphim.md- Maps attribution textdocs/src/kg/noreply_terraphim.md- Maps email addresses
Example Replacements:
$ terraphim-tui replace "🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>"
🤖 Generated with [terraphim_ai](https___terraphim_ai) Co-Authored-By: terraphim_ai <noreply_terraphim>Note on Output Format: Replacement text uses filename stems, so spaces become underscores and special characters are converted (e.g., "https://terraphim.ai" → "https___terraphim_ai"). This is a fundamental design of the system where filenames serve as normalized replacement terms.
Skills are modular capabilities that extend Claude's functionality through instructions, metadata, and optional resources.
User Message → Claude Detects Context → Loads Skill → Executes Logic → Responds with Explanation
Skills use progressive disclosure:
- Metadata (always loaded, ~100 tokens)
- Instructions (loaded when triggered, <5k tokens)
- Resources (loaded on-demand, output only)
File: SKILL.md
---
name: terraphim-package-manager
description: Replace npm/yarn/pnpm with bun using knowledge graph
---
# Skill Title
## Instructions
[Step-by-step guide for Claude]
## Examples
[Concrete usage examples]terraphim-package-manager/
├── SKILL.md # Main skill definition
├── replace.sh # Helper script (optional)
├── README.md # Documentation
└── examples/ # Example files (optional)
Claude Code: Place in ~/.claude/skills/ or .claude/skills/ (project-specific)
mkdir -p ~/.claude/skills/terraphim-package-manager
cp -r examples/claude-skills/terraphim-package-manager/* \
~/.claude/skills/terraphim-package-manager/Claude.ai: Upload as zip file via Settings → Skills
cd examples/claude-skills
zip -r terraphim-package-manager.zip terraphim-package-manager/Claude API: Specify skill_id in API requests
Skills activate automatically when Claude detects relevant context:
Triggers:
- User mentions npm, yarn, or pnpm
- User asks about installation
- User shares package.json files
- User provides shell scripts with package managers
✅ Use skills when:
- You want Claude to explain changes
- You need context-aware decisions
- You're working across multiple platforms
- You want interactive control
- You need Claude to learn when to apply
❌ Don't use skills when:
- You want silent, automatic replacements
- You don't need explanations
- You're only using Claude Code CLI
- You want pre-processing before Claude sees input
- Performance is critical (skills add token overhead)
Location: examples/claude-skills/terraphim-package-manager/
Files:
SKILL.md- Skill definition with YAML frontmatterreplace.sh- Helper script for replacementsREADME.md- Complete documentationexamples/- Example package.json and scripts
Documentation: See examples/claude-skills/terraphim-package-manager/README.md
Beyond text replacement, Terraphim AI provides a powerful framework for evaluating whether AI agents improve or deteriorate codebases. This deterministic, knowledge graph-based evaluation system measures code quality before and after AI changes.
The evaluation system uses Terraphim's core capabilities to:
- Index codebases as searchable haystacks
- Build knowledge graphs for quality, security, and performance patterns
- Run standardized queries to detect issues
- Compare metrics before and after AI changes
- Generate verdicts: Improvement, Deterioration, or Neutral
- Deterministic: Aho-Corasick automata provide consistent, repeatable scoring
- Local & Private: No external API dependencies for evaluation
- Role-Based: Evaluate from multiple perspectives (security, performance, quality)
- Quantifiable: Numeric scores for objective comparison
- CI/CD Ready: Integrate with GitHub Actions, GitLab CI, etc.
# Run complete evaluation
cd examples/codebase-evaluation
./scripts/evaluate-ai-agent.sh /path/to/your/codebase
# The script will:
# 1. Create baseline evaluation
# 2. Prompt you to apply AI changes
# 3. Re-evaluate after changes
# 4. Generate verdict reportKnowledge Graph Metrics:
- Semantic matches for quality issues
- Pattern detection using Aho-Corasick
- Concept relationship density
Code Quality Metrics (Rust example):
- Clippy warnings count
- Test pass/fail rates
- Anti-pattern occurrences (unwrap, panic, etc.)
- TODO/FIXME counts
Verdict Logic:
- ✅ IMPROVEMENT: More metrics improved than deteriorated
- ❌ DETERIORATION: More metrics deteriorated than improved
- ➖ NEUTRAL: Mixed or minimal changes
1. Evaluate Pull Request from AI Agent
# Checkout baseline (main branch)
git checkout main
./scripts/baseline-evaluation.sh . "Code Reviewer"
# Checkout AI-generated PR
git checkout ai-agent-pr-123
./scripts/post-evaluation.sh . "Code Reviewer"
# Generate verdict
./scripts/compare-evaluations.sh2. Continuous Evaluation in CI/CD
# GitHub Actions example
- name: Baseline evaluation
run: ./scripts/baseline-evaluation.sh ${{ github.workspace }}
- name: Apply AI changes
run: # Your AI agent step
- name: Post-change evaluation
run: ./scripts/post-evaluation.sh ${{ github.workspace }}
- name: Generate verdict (fails on deterioration)
run: ./scripts/compare-evaluations.sh3. Multi-Role Evaluation
Evaluate from different perspectives:
# Code quality focus
./scripts/evaluate-ai-agent.sh ./codebase claude-code "Code Reviewer"
# Security focus
./scripts/evaluate-ai-agent.sh ./codebase claude-code "Security Auditor"
# Performance focus
./scripts/evaluate-ai-agent.sh ./codebase claude-code "Performance Analyst"Define custom evaluation perspectives using knowledge graphs:
Code Reviewer Role (code-quality.md):
# Code Quality
synonyms:: code smell, technical debt, refactoring opportunity, bad practiceSecurity Auditor Role (security.md):
# Security Vulnerability
synonyms:: SQL injection, XSS, CSRF, authentication flaw, command injectionPerformance Analyst Role (performance.md):
# Performance Bottleneck
synonyms:: slow code, inefficient algorithm, O(n^2) complexity, blocking operation# Codebase Evaluation Verdict
## Summary
### Clippy Warnings
| Metric | Baseline | After | Delta |
|----------|----------|-------|-------|
| Warnings | 15 | 8 | -7 |
✅ **Improvement**: Reduced warnings by 7
### Anti-Patterns
| Metric | Baseline | After | Delta |
|--------|----------|-------|-------|
| Count | 23 | 18 | -5 |
✅ **Improvement**: Removed 5 anti-patterns
## Overall Verdict
✅ **IMPROVEMENT**: The AI agent improved the codebase quality.
- ✅ Improved metrics: **3**
- ❌ Deteriorated metrics: **0**
- ➖ Neutral metrics: **1**
## Recommendations
- ✅ No critical issues found
- 📝 Review remaining 8 clippy warnings for completionCombine codebase evaluation with hooks or skills:
Hook Integration: Automatically evaluate changes before commits
# pre-commit hook
./scripts/baseline-evaluation.sh .
# ... make changes with Claude ...
./scripts/post-evaluation.sh .
./scripts/compare-evaluations.sh || exit 1Skill Integration: Ask Claude to evaluate changes
---
name: terraphim-codebase-eval
description: Evaluate code quality using Terraphim's knowledge graph system
---
When the user asks to evaluate code quality or AI changes, run:
./scripts/evaluate-ai-agent.sh <codebase>Complete documentation and scripts available:
- Design Document:
examples/codebase-evaluation/CODEBASE_EVALUATION_DESIGN.md - Quick Start Guide:
examples/codebase-evaluation/README.md - Evaluation Scripts:
examples/codebase-evaluation/scripts/ - KG Templates:
examples/codebase-evaluation/kg-templates/
- Objective Assessment: Quantifiable metrics over subjective opinions
- Early Detection: Catch quality issues before they reach production
- CI/CD Integration: Automated quality gates in pipelines
- Historical Tracking: Monitor quality trends over time
- Multi-Dimensional: Evaluate security, performance, and quality simultaneously
| Your Need | Recommended Approach |
|---|---|
| Automatic, silent replacements | Hook |
| Explanations and context | Skill |
| Claude Code CLI only | Hook |
| All Claude platforms | Skill |
| Pre-processing input | Hook |
| Interactive collaboration | Skill |
| Learning and adaptation | Skill |
| Consistent enforcement | Hook |
| Complex decision-making | Skill |
| Simple pattern matching | Hook |
You can use both simultaneously:
Hook: Automatically replace obvious patterns (npm → bun) Skill: Help with complex scenarios (migration planning, documentation updates)
Phase 1: Start with skill for learning
- Claude explains what would be replaced
- You learn the patterns
- You validate the approach
Phase 2: Add hook for automation
- Once patterns are validated, add hook
- Hook handles common cases automatically
- Skill handles edge cases
Phase 3: Optimize based on usage
- Keep hook for 95% of cases
- Use skill for remaining 5%
- Update knowledge graph based on experience
Both approaches require:
-
Terraphim-TUI built:
cargo build --release -p terraphim_tui
-
Knowledge graph files:
docs/src/kg/bun.md- Package manager synonymsdocs/src/kg/bun_install.md- Install command synonyms
-
PATH configured (optional):
export PATH="$PATH:$(pwd)/target/release"
# 1. Copy hook script
cp examples/claude-code-hooks/terraphim-package-manager-hook.sh ~/
# 2. Make executable
chmod +x ~/terraphim-package-manager-hook.sh
# 3. Configure Claude Code
mkdir -p ~/.config/claude-code
cat > ~/.config/claude-code/settings.json << 'EOF'
{
"hooks": {
"user-prompt-submit": {
"command": "bash",
"args": ["/home/user/terraphim-package-manager-hook.sh"],
"enabled": true
}
}
}
EOF
# 4. Test
echo "npm install" | ~/terraphim-package-manager-hook.sh# 1. Install skill
mkdir -p ~/.claude/skills/terraphim-package-manager
cp -r examples/claude-skills/terraphim-package-manager/* \
~/.claude/skills/terraphim-package-manager/
# 2. Make script executable
chmod +x ~/.claude/skills/terraphim-package-manager/replace.sh
# 3. Test
cd ~/.claude/skills/terraphim-package-manager
./replace.sh "npm install"
# 4. Use with Claude
# Start Claude and mention package managersUse both for maximum flexibility:
// Claude Code settings.json
{
"hooks": {
"user-prompt-submit": {
"command": "bash",
"args": ["/path/to/hook.sh"],
"enabled": true
}
}
}Plus:
# Skill for advanced scenarios
~/.claude/skills/terraphim-package-manager/Workflow:
- Hook handles simple replacements automatically
- Claude uses skill for complex cases
- User gets best of both worlds
Create domain-specific replacements:
Frontend Developer:
# React
synonyms:: vue, angular, svelteBackend Developer:
# FastAPI
synonyms:: flask, django, expressDevOps Engineer:
# Docker
synonyms:: podman, containerdCreate a workflow skill that uses the package manager skill:
---
name: full-stack-migration
description: Complete migration from npm to bun for full-stack projects
---
# Full-Stack Migration Workflow
1. Use terraphim-package-manager skill for frontend
2. Use terraphim-package-manager skill for backend
3. Update Docker files
4. Update CI/CD configuration
5. Update documentation
6. Run testsUse different Terraphim roles for different contexts:
# Frontend work
export TERRAPHIM_ROLE="Frontend Engineer"
# Backend work
export TERRAPHIM_ROLE="Backend Engineer"
# DevOps work
export TERRAPHIM_ROLE="DevOps Engineer"Each role can have its own knowledge graph and preferences.
Integrate both approaches in CI/CD:
Hook in Pre-commit:
# .git/hooks/pre-commit
#!/bin/bash
find . -name "*.sh" | while read file; do
terraphim-tui replace "$(cat $file)" > $file.new
mv $file.new $file
doneSkill in GitHub Actions:
# .github/workflows/validate.yml
- name: Check package manager usage
run: |
# Use Claude API with skill to analyze and suggest improvements
claude-api --skill terraphim-package-manager validateHook not executing:
- Check hook script path in settings.json
- Verify script is executable (
chmod +x) - Test script directly:
echo "npm install" | ./hook.sh
Skill not loading:
- Verify location (
~/.claude/skills/or.claude/skills/) - Check YAML frontmatter is valid
- Ensure
nameanddescriptionfields exist
terraphim-tui not found:
- Build:
cargo build --release -p terraphim_tui - Add to PATH:
export PATH="$PATH:$(pwd)/target/release" - Use absolute path in scripts
Replacements not working:
- Test directly:
terraphim-tui replace "npm install" 2>/dev/null - Check knowledge graph files exist:
ls docs/src/kg/bun*.md - Verify synonyms are defined:
grep "synonyms::" docs/src/kg/bun.md
Hook Performance:
- Pattern matching: ~10-50ms
- Knowledge graph loading: ~100-200ms (cached)
- Total execution: <100ms typically
Skill Performance:
- Metadata loading: ~100 tokens (always)
- Instructions loading: ~5k tokens (when triggered)
- Script execution: ~10-50ms
- Total overhead: Minimal, only loads when relevant
- ✅ Suppress stderr:
2>/dev/null - ✅ Handle errors gracefully:
|| echo "$INPUT" - ✅ Test before deploying
- ✅ Use environment variables for configuration
- ✅ Log in suggest/passive mode during testing
- ✅ Write clear descriptions that trigger appropriately
- ✅ Provide concrete examples in SKILL.md
- ✅ Keep instructions focused and actionable
- ✅ Test with actual conversations
- ✅ Audit scripts for security
- ✅ Version control knowledge graph files
- ✅ Document custom synonyms
- ✅ Test with real-world examples
- ✅ Monitor performance
- ✅ Gather user feedback and iterate
- Hooks Guide:
examples/claude-code-hooks/README.md - Skills Guide:
examples/claude-skills/terraphim-package-manager/README.md - Knowledge Graph:
docs/src/kg/PACKAGE_MANAGER_REPLACEMENT.md - Terraphim TUI:
crates/terraphim_tui/README.md
- Claude Skills Docs: https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview
- Skills Cookbook: https://github.com/anthropics/claude-cookbooks/tree/main/skills
- Claude Code: https://code.claude.com/
- Hook Tests:
examples/claude-code-hooks/test-hook.sh - Skill Examples:
examples/claude-skills/terraphim-package-manager/examples/ - Knowledge Graph:
docs/src/kg/
Improvements welcome!
Hook Improvements:
- Add more modes (audit, report, interactive)
- Support more configuration options
- Add telemetry/metrics
Skill Improvements:
- Add more examples
- Improve error messages
- Support more package managers
Knowledge Graph Improvements:
- Add more domains (databases, frameworks, tools)
- Create role-specific graphs
- Add validation and testing
This integration guide and examples are part of the Terraphim AI project and follow the same license (Apache-2.0).