-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathenrich-context.sh
More file actions
77 lines (68 loc) · 2.29 KB
/
Copy pathenrich-context.sh
File metadata and controls
77 lines (68 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env bash
# enrich-context.sh — PreToolUse hook for Read and Grep tools
# Provides dependency context from codegraph when reading/searching files.
# Always exits 0 (informational only, never blocks).
set -euo pipefail
# Read the tool input from stdin
INPUT=$(cat)
# Extract file path and convert to relative — all in node to avoid
# bash backslash issues on Windows/Git Bash
REL_PATH=$(printf '%s' "$INPUT" | CLAUDE_PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}" node -e "
let d='';
process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>{
const o=JSON.parse(d).tool_input||{};
let p=(o.file_path||o.path||'').replace(/\\\\/g,'/');
if(!p)return;
let dir=(process.env.CLAUDE_PROJECT_DIR||'.').replace(/\\\\/g,'/');
if(p.startsWith(dir))p=p.slice(dir.length+1);
process.stdout.write(p);
});
" 2>/dev/null) || true
# Guard: no file path found
if [ -z "$REL_PATH" ]; then
exit 0
fi
# Guard: codegraph DB must exist
DB_PATH="${CLAUDE_PROJECT_DIR:-.}/.codegraph/graph.db"
if [ ! -f "$DB_PATH" ]; then
exit 0
fi
# Run codegraph deps and capture output
DEPS=""
if command -v codegraph &>/dev/null; then
DEPS=$(codegraph deps "$REL_PATH" --json -d "$DB_PATH" 2>/dev/null) || true
else
DEPS=$(npx --yes @optave/codegraph deps "$REL_PATH" --json -d "$DB_PATH" 2>/dev/null) || true
fi
# Guard: no output or error
if [ -z "$DEPS" ] || [ "$DEPS" = "null" ]; then
exit 0
fi
# Output as additionalContext so it surfaces in Claude's context
printf '%s' "$DEPS" | node -e "
let d='';
process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>{
try {
const o=JSON.parse(d);
const r=o.results?.[0]||{};
const imports=(r.imports||[]).map(i=>i.file).join(', ');
const importedBy=(r.importedBy||[]).map(i=>i.file).join(', ');
const defs=(r.definitions||[]).map(d=>d.kind+' '+d.name).join(', ');
const file=o.file||'unknown';
let ctx='[codegraph] '+file;
if(imports)ctx+='\n Imports: '+imports;
if(importedBy)ctx+='\n Imported by: '+importedBy;
if(defs)ctx+='\n Defines: '+defs;
console.log(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'allow',
additionalContext: ctx
}
}));
} catch(e) {}
});
" 2>/dev/null || true
exit 0