terraphim-hooks
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTerraphim Hooks
Terraphim Hooks
Use this skill when setting up or using Terraphim's knowledge graph-based text replacement capabilities through hooks.
当你需要通过钩子设置或使用Terraphim基于知识图谱的文本替换功能时,可使用本技能。
Overview
概述
Terraphim hooks intercept text at key points (CLI commands, commit messages) and apply transformations using Aho-Corasick automata built from knowledge graph definitions.
Key Components:
- - CLI command for text replacement
terraphim-agent replace - PreToolUse hooks - Intercept Claude Code tool calls before execution
- Git hooks - Transform commit messages using prepare-commit-msg
Terraphim Hooks会在关键节点(CLI命令、提交信息)拦截文本,并使用基于知识图谱定义构建的Aho-Corasick自动机执行转换。
核心组件:
- - 用于文本替换的CLI命令
terraphim-agent replace - PreToolUse钩子 - 在Claude Code工具执行前拦截其调用
- Git钩子 - 使用prepare-commit-msg转换提交信息
Architecture
架构
┌─────────────────────────────────────────────────────────────────┐
│ Knowledge Graph (docs/src/kg/) │
│ ┌──────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
│ │ bun.md │ │ bun install.md │ │ terraphim ai.md │ │
│ │ synonyms:: │ │ synonyms:: │ │ synonyms:: │ │
│ │ npm, yarn, │ │ npm install, │ │ Claude Code, │ │
│ │ pnpm, npx │ │ yarn install... │ │ Claude Opus... │ │
│ └──────────────┘ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────┐
│ Aho-Corasick Automata │
│ (LeftmostLongest matching) │
└───────────────────────────────┘
│
┌───────────────┴───────────────┐
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ PreToolUse Hook │ │ Git Hook │
│ (npm → bun) │ │ (Claude → Terraphim)│
│ │ │ │
│ Input: Bash command │ │ Input: Commit msg │
│ Output: Modified │ │ Output: Modified │
└──────────────────────┘ └──────────────────────┘┌─────────────────────────────────────────────────────────────────┐
│ Knowledge Graph (docs/src/kg/) │
│ ┌──────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
│ │ bun.md │ │ bun install.md │ │ terraphim ai.md │ │
│ │ synonyms:: │ │ synonyms:: │ │ synonyms:: │ │
│ │ npm, yarn, │ │ npm install, │ │ Claude Code, │ │
│ │ pnpm, npx │ │ yarn install... │ │ Claude Opus... │ │
│ └──────────────┘ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────┐
│ Aho-Corasick Automata │
│ (LeftmostLongest matching) │
└───────────────────────────────┘
│
┌───────────────┴───────────────┐
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ PreToolUse Hook │ │ Git Hook │
│ (npm → bun) │ │ (Claude → Terraphim)│
│ │ │ │
│ Input: Bash command │ │ Input: Commit msg │
│ Output: Modified │ │ Output: Modified │
└──────────────────────┘ └──────────────────────┘For Humans
面向普通用户
Quick Start (Using Released Binary)
快速开始(使用发布的二进制文件)
bash
undefinedbash
undefinedDownload and install terraphim-agent from GitHub releases (latest version)
Download and install terraphim-agent from GitHub releases (latest version)
macOS ARM64 (Apple Silicon)
macOS ARM64 (Apple Silicon)
gh release download --repo terraphim/terraphim-ai
--pattern "terraphim-agent-aarch64-apple-darwin" --dir /tmp chmod +x /tmp/terraphim-agent-aarch64-apple-darwin mv /tmp/terraphim-agent-aarch64-apple-darwin ~/.cargo/bin/terraphim-agent
--pattern "terraphim-agent-aarch64-apple-darwin" --dir /tmp chmod +x /tmp/terraphim-agent-aarch64-apple-darwin mv /tmp/terraphim-agent-aarch64-apple-darwin ~/.cargo/bin/terraphim-agent
gh release download --repo terraphim/terraphim-ai
--pattern "terraphim-agent-aarch64-apple-darwin" --dir /tmp chmod +x /tmp/terraphim-agent-aarch64-apple-darwin mv /tmp/terraphim-agent-aarch64-apple-darwin ~/.cargo/bin/terraphim-agent
--pattern "terraphim-agent-aarch64-apple-darwin" --dir /tmp chmod +x /tmp/terraphim-agent-aarch64-apple-darwin mv /tmp/terraphim-agent-aarch64-apple-darwin ~/.cargo/bin/terraphim-agent
macOS x86_64 (Intel)
macOS x86_64 (Intel)
gh release download --repo terraphim/terraphim-ai \
gh release download --repo terraphim/terraphim-ai \
--pattern "terraphim-agent-x86_64-apple-darwin" --dir /tmp
--pattern "terraphim-agent-x86_64-apple-darwin" --dir /tmp
Linux x86_64
Linux x86_64
gh release download --repo terraphim/terraphim-ai \
gh release download --repo terraphim/terraphim-ai \
--pattern "terraphim-agent-x86_64-unknown-linux-gnu" --dir /tmp
--pattern "terraphim-agent-x86_64-unknown-linux-gnu" --dir /tmp
Note: crates.io version (cargo install terraphim_agent) is outdated (v1.0.0)
Note: crates.io version (cargo install terraphim_agent) is outdated (v1.0.0)
and missing hook/guard commands. Use GitHub releases for latest features.
and missing hook/guard commands. Use GitHub releases for latest features.
Create knowledge graph directory
Create knowledge graph directory
mkdir -p ~/.config/terraphim/docs/src/kg
mkdir -p ~/.config/terraphim/docs/src/kg
Create replacement rules (example: npm -> bun)
Create replacement rules (example: npm -> bun)
cat > ~/.config/terraphim/docs/src/kg/"bun install.md" << 'EOF'
cat > ~/.config/terraphim/docs/src/kg/"bun install.md" << 'EOF'
bun install
bun install
Install dependencies using Bun package manager.
synonyms:: npm install, yarn install, pnpm install, npm i
EOF
Install dependencies using Bun package manager.
synonyms:: npm install, yarn install, pnpm install, npm i
EOF
Create hooks directory and script
Create hooks directory and script
mkdir -p ~/.claude/hooks
cat > ~/.claude/hooks/pre_tool_use.sh << 'EOF'
#!/bin/bash
INPUT=$(cat)
cd ~/.config/terraphim 2>/dev/null || exit 0
terraphim-agent hook --hook-type pre-tool-use --json <<< "$INPUT" 2>/dev/null
EOF
chmod +x ~/.claude/hooks/pre_tool_use.sh
mkdir -p ~/.claude/hooks
cat > ~/.claude/hooks/pre_tool_use.sh << 'EOF'
#!/bin/bash
INPUT=$(cat)
cd ~/.config/terraphim 2>/dev/null || exit 0
terraphim-agent hook --hook-type pre-tool-use --json <<< "$INPUT" 2>/dev/null
EOF
chmod +x ~/.claude/hooks/pre_tool_use.sh
Test replacement
Test replacement
echo "npm install react" | ~/.claude/hooks/pre_tool_use.sh
echo "npm install react" | ~/.claude/hooks/pre_tool_use.sh
Output: {"tool_input":{"command":"bun install react"},"tool_name":"Bash"}
Output: {"tool_input":{"command":"bun install react"},"tool_name":"Bash"}
undefinedundefinedConfigure Claude Code Hook
配置Claude Code钩子
Add to :
~/.claude/settings.local.jsonjson
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/pre_tool_use.sh"
}]
}]
}
}添加以下内容到:
~/.claude/settings.local.jsonjson
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/pre_tool_use.sh"
}]
}]
}
}Alternative: Build from Source
替代方案:从源码构建
bash
undefinedbash
undefinedClone terraphim-ai repository
Clone terraphim-ai repository
git clone https://github.com/terraphim/terraphim-ai
cd terraphim-ai
git clone https://github.com/terraphim/terraphim-ai
cd terraphim-ai
Build the agent
Build the agent
cargo build -p terraphim_agent --release
cargo build -p terraphim_agent --release
Install to cargo bin
Install to cargo bin
cp target/release/terraphim-agent ~/.cargo/bin/
undefinedcp target/release/terraphim-agent ~/.cargo/bin/
undefinedCLI Usage
CLI使用方法
bash
undefinedbash
undefinedBasic replacement
Basic replacement
echo "npm install package" | terraphim-agent replace
echo "npm install package" | terraphim-agent replace
Output: bun install package
Output: bun install package
With JSON output (for programmatic use)
With JSON output (for programmatic use)
echo "npm install" | terraphim-agent replace --json
echo "npm install" | terraphim-agent replace --json
Output: {"result":"bun install","original":"npm install","replacements":1,"changed":true}
Output: {"result":"bun install","original":"npm install","replacements":1,"changed":true}
Fail-open mode (returns original on error)
Fail-open mode (returns original on error)
echo "npm install" | terraphim-agent replace --fail-open
undefinedecho "npm install" | terraphim-agent replace --fail-open
undefinedAdding Custom Replacements
添加自定义替换规则
Create markdown files in :
~/.config/terraphim/docs/src/kg/markdown
undefined在目录下创建Markdown文件:
~/.config/terraphim/docs/src/kg/markdown
undefinedreplacement term
replacement term
Description of the replacement term.
synonyms:: term_to_replace, another_term, third_term
**Important:** The heading (after `#`) becomes the replacement text. Use spaces, not underscores.
**Example - Replace pytest with cargo test:**
Create `~/.config/terraphim/docs/src/kg/cargo test.md`:
```markdownDescription of the replacement term.
synonyms:: term_to_replace, another_term, third_term
**重要提示:** 标题(`#`后的内容)将作为替换后的文本。请使用空格,不要使用下划线。
**示例:将pytest替换为cargo test**
创建`~/.config/terraphim/docs/src/kg/cargo test.md`:
```markdowncargo test
cargo test
Rust's built-in test runner using Cargo.
synonyms:: pytest, py.test, python -m pytest
undefinedRust's built-in test runner using Cargo.
synonyms:: pytest, py.test, python -m pytest
undefinedFor AI Agents
面向AI Agent
Detecting Terraphim Capabilities
检测Terraphim功能
Check for terraphim-agent availability:
bash
undefined检查terraphim-agent是否可用:
bash
undefinedCheck if agent is available
Check if agent is available
if command -v terraphim-agent >/dev/null 2>&1; then
echo "Terraphim agent available"
elif [ -x "./target/release/terraphim-agent" ]; then
AGENT="./target/release/terraphim-agent"
elif [ -x "$HOME/.cargo/bin/terraphim-agent" ]; then
AGENT="$HOME/.cargo/bin/terraphim-agent"
fi
undefinedif command -v terraphim-agent >/dev/null 2>&1; then
echo "Terraphim agent available"
elif [ -x "./target/release/terraphim-agent" ]; then
AGENT="./target/release/terraphim-agent"
elif [ -x "$HOME/.cargo/bin/terraphim-agent" ]; then
AGENT="$HOME/.cargo/bin/terraphim-agent"
fi
undefinedUsing Replacement in Hooks
在钩子中使用替换功能
PreToolUse Hook Pattern:
bash
#!/bin/bashPreToolUse钩子示例:
bash
#!/bin/bashRead JSON input
Read JSON input
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
Only process Bash commands
Only process Bash commands
[ "$TOOL_NAME" != "Bash" ] && exit 0
[ "$TOOL_NAME" != "Bash" ] && exit 0
Perform replacement with fail-open
Perform replacement with fail-open
REPLACED=$(terraphim-agent replace --fail-open <<< "$COMMAND")
REPLACED=$(terraphim-agent replace --fail-open <<< "$COMMAND")
Output modified tool_input if changed
Output modified tool_input if changed
if [ "$REPLACED" != "$COMMAND" ]; then
echo "$INPUT" | jq --arg cmd "$REPLACED" '.tool_input.command = $cmd'
fi
**Git Hook Pattern:**
```bash
#!/bin/bash
COMMIT_MSG_FILE=$1if [ "$REPLACED" != "$COMMAND" ]; then
echo "$INPUT" | jq --arg cmd "$REPLACED" '.tool_input.command = $cmd'
fi
**Git钩子示例:**
```bash
#!/bin/bash
COMMIT_MSG_FILE=$1Read original message
Read original message
ORIGINAL=$(cat "$COMMIT_MSG_FILE")
ORIGINAL=$(cat "$COMMIT_MSG_FILE")
Replace using knowledge graph
Replace using knowledge graph
REPLACED=$(terraphim-agent replace --fail-open <<< "$ORIGINAL")
REPLACED=$(terraphim-agent replace --fail-open <<< "$ORIGINAL")
Write back if changed
Write back if changed
if [ "$REPLACED" != "$ORIGINAL" ]; then
echo "$REPLACED" > "$COMMIT_MSG_FILE"
fi
undefinedif [ "$REPLACED" != "$ORIGINAL" ]; then
echo "$REPLACED" > "$COMMIT_MSG_FILE"
fi
undefinedProgrammatic Usage (Rust)
程序化使用(Rust)
rust
use terraphim_hooks::{ReplacementService, HookResult};
use terraphim_types::Thesaurus;
// Load thesaurus from knowledge graph
let thesaurus = load_thesaurus_from_kg("docs/src/kg/");
// Create replacement service
let service = ReplacementService::new(thesaurus);
// Perform replacement
let result: HookResult = service.replace_fail_open("npm install react");
// result.result == "bun install react"
// result.changed == true
// result.replacements == 1rust
use terraphim_hooks::{ReplacementService, HookResult};
use terraphim_types::Thesaurus;
// Load thesaurus from knowledge graph
let thesaurus = load_thesaurus_from_kg("docs/src/kg/");
// Create replacement service
let service = ReplacementService::new(thesaurus);
// Perform replacement
let result: HookResult = service.replace_fail_open("npm install react");
// result.result == "bun install react"
// result.changed == true
// result.replacements == 1MCP Tool Integration
MCP工具集成
The MCP tool provides the same functionality:
replace_matchesjson
{
"tool": "replace_matches",
"arguments": {
"text": "npm install react",
"role": "Default"
}
}replace_matchesjson
{
"tool": "replace_matches",
"arguments": {
"text": "npm install react",
"role": "Default"
}
}Hook Types and Use Cases
钩子类型与使用场景
| Hook Type | Trigger Point | Use Case |
|---|---|---|
| PreToolUse | Before tool execution | Transform commands (npm→bun) |
| PostToolUse | After tool execution | Validate outputs |
| prepare-commit-msg | Before commit | Transform attribution |
| pre-commit | Before commit | Block unwanted patterns |
| 钩子类型 | 触发节点 | 使用场景 |
|---|---|---|
| PreToolUse | 工具执行前 | 转换命令(如npm→bun) |
| PostToolUse | 工具执行后 | 验证输出结果 |
| prepare-commit-msg | 提交前 | 转换归属信息 |
| pre-commit | 提交前 | 拦截不想要的模式 |
Error Handling
错误处理
Hooks use fail-open semantics:
- If terraphim-agent is not found: pass through unchanged
- If replacement fails: return original text
- Errors logged to stderr only in verbose mode
Enable verbose mode:
bash
export TERRAPHIM_VERBOSE=1钩子采用故障开放语义:
- 若未找到terraphim-agent:直接返回原内容
- 若替换失败:返回原文本
- 仅在verbose模式下将错误日志输出到stderr
启用verbose模式:
bash
export TERRAPHIM_VERBOSE=1Knowledge Graph Format
知识图谱格式
Knowledge graph files use markdown with frontmatter:
markdown
undefined知识图谱文件使用带前置内容的Markdown格式:
markdown
undefinedterm_name
term_name
Optional description.
synonyms:: synonym1, synonym2, synonym3
**Matching behavior:**
- Aho-Corasick with LeftmostLongest matching
- Longer patterns match before shorter ones
- Case-sensitive by defaultOptional description.
synonyms:: synonym1, synonym2, synonym3
**匹配行为:**
- 采用Aho-Corasick算法与LeftmostLongest匹配规则
- 长模式优先于短模式匹配
- 默认区分大小写Validation
验证
Test your hooks:
bash
undefined测试你的钩子:
bash
undefinedRun test script
Run test script
./scripts/test-terraphim-hooks.sh
./scripts/test-terraphim-hooks.sh
Manual test - PreToolUse
Manual test - PreToolUse
echo '{"tool_name":"Bash","tool_input":{"command":"npm install"}}' | .claude/hooks/npm_to_bun_guard.sh
echo '{"tool_name":"Bash","tool_input":{"command":"npm install"}}' | .claude/hooks/npm_to_bun_guard.sh
Manual test - Git hook
Manual test - Git hook
echo "Claude Code generated this" | terraphim-agent replace
undefinedecho "Claude Code generated this" | terraphim-agent replace
undefinedTroubleshooting
故障排除
| Issue | Solution |
|---|---|
| Hook not triggering | Check |
| No replacement happening | Verify knowledge graph files exist in |
| Agent not found | Build with |
| Permission denied | Run |
| jq not found | Install jq: |
| 问题 | 解决方案 |
|---|---|
| 钩子未触发 | 检查 |
| 未执行替换 | 验证知识图谱文件是否存在于 |
| 找不到Agent | 使用 |
| 权限被拒绝 | 对钩子脚本执行 |
| 找不到jq | 安装jq: |
Related Skills
相关技能
- - For building custom hooks
implementation - - For validating hook behavior
testing - - For CI/CD integration with hooks
devops
- - 用于构建自定义钩子
implementation - - 用于验证钩子行为
testing - - 用于将钩子集成到CI/CD流程中
devops