Skip to content

Commit 2312c92

Browse files
authored
Merge pull request #48 from optave/docs/ai-agent-guide
docs: add AI Agent Guide and dogfood recommended practices
2 parents 4e6e20b + 046281a commit 2312c92

12 files changed

Lines changed: 1084 additions & 57 deletions

File tree

.claude/hooks/remind-codegraph.sh

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#!/usr/bin/env bash
2+
# remind-codegraph.sh — PreToolUse hook for Edit|Write
3+
# Reminds the agent to use codegraph before editing a file.
4+
# Only fires once per file per session (tracks in .claude/codegraph-checked.log).
5+
6+
set -euo pipefail
7+
8+
# Extract file_path from tool input
9+
INPUT="${TOOL_INPUT:-}"
10+
FILE_PATH=$(echo "$INPUT" | node -e "
11+
let d=''; process.stdin.on('data',c=>d+=c);
12+
process.stdin.on('end',()=>{
13+
try {
14+
const j=JSON.parse(d);
15+
const p = j.file_path || j.path || '';
16+
// Normalize backslashes
17+
console.log(p.replace(/\\\\/g,'/'));
18+
} catch { console.log(''); }
19+
});
20+
" 2>/dev/null)
21+
22+
if [ -z "$FILE_PATH" ]; then
23+
exit 0
24+
fi
25+
26+
# Normalize to relative path
27+
REL_PATH="$FILE_PATH"
28+
if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then
29+
REL_PATH=$(node -e "
30+
const path = require('path');
31+
const abs = path.resolve(process.argv[1]);
32+
const base = path.resolve(process.argv[2]);
33+
console.log(path.relative(base, abs).replace(/\\\\/g,'/'));
34+
" "$FILE_PATH" "$CLAUDE_PROJECT_DIR" 2>/dev/null) || REL_PATH="$FILE_PATH"
35+
fi
36+
37+
# Skip non-source files (docs, config, etc.)
38+
case "$REL_PATH" in
39+
*.md|*.json|*.yml|*.yaml|*.toml|*.txt|*.lock|*.log|*.env*) exit 0 ;;
40+
esac
41+
42+
# Check if we already reminded for this file
43+
CHECKED_LOG="${CLAUDE_PROJECT_DIR:-.}/.claude/codegraph-checked.log"
44+
if [ -f "$CHECKED_LOG" ] && grep -qF "$REL_PATH" "$CHECKED_LOG" 2>/dev/null; then
45+
exit 0
46+
fi
47+
48+
# Record that we've reminded for this file
49+
mkdir -p "$(dirname "$CHECKED_LOG")"
50+
echo "$REL_PATH" >> "$CHECKED_LOG"
51+
52+
# Check if graph exists
53+
if [ ! -f "${CLAUDE_PROJECT_DIR:-.}/.codegraph/graph.db" ]; then
54+
exit 0
55+
fi
56+
57+
# Inject reminder as additionalContext
58+
cat <<HOOK_OUTPUT
59+
{
60+
"hookSpecificOutput": {
61+
"hookEventName": "PreToolUse",
62+
"permissionDecision": "allow",
63+
"additionalContext": "[codegraph reminder] You are about to edit ${REL_PATH}. Did you run codegraph first? Before editing, always: (1) 'node src/cli.js where <name>' to locate the symbol, (2) 'node src/cli.js explain ${REL_PATH}' to understand the file, (3) 'node src/cli.js context <name> -T' for full context, (4) 'node src/cli.js fn-impact <name> -T' to check blast radius. If you already did this, proceed."
64+
}
65+
}
66+
HOOK_OUTPUT

.claude/settings.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@
3535
"timeout": 10
3636
}
3737
]
38+
},
39+
{
40+
"matcher": "Edit|Write",
41+
"hooks": [
42+
{
43+
"type": "command",
44+
"command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/remind-codegraph.sh\"",
45+
"timeout": 5
46+
}
47+
]
3848
}
3949
],
4050
"PostToolUse": [

.github/workflows/codegraph-impact.yml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,15 @@ jobs:
1111
with:
1212
node-version: '22'
1313
- run: npm install
14+
- uses: actions/cache@v4
15+
with:
16+
path: .codegraph/
17+
key: codegraph-${{ hashFiles('src/**', 'package.json') }}
18+
restore-keys: codegraph-
1419
- run: npx codegraph build
1520
- name: Run impact analysis
1621
run: |
17-
npx codegraph diff-impact --ref origin/${{ github.base_ref }} --json > impact.json || echo '{"affectedFiles":[],"summary":null}' > impact.json
22+
npx codegraph diff-impact --ref origin/${{ github.base_ref }} --json -T > impact.json || echo '{"affectedFiles":[],"summary":null}' > impact.json
1823
- name: Comment on PR
1924
uses: actions/github-script@v8
2025
with:

.github/workflows/shield-license-compliance.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@ on:
88
- "package-lock.json"
99
pull_request:
1010
branches: [main]
11-
paths:
12-
- "package.json"
13-
- "package-lock.json"
1411
workflow_dispatch:
1512
schedule:
1613
- cron: "0 3 * * 1" # Weekly on Monday at 3 AM

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,7 @@ node_modules/
44
coverage/
55
.env
66
grammars/*.wasm
7+
.claude/session-edits.log
8+
.claude/codegraph-checked.log
79
artifacts/
810
pkg/

.husky/commit-msg

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
npx --no -- commitlint --edit $1
2+
3+
# Append codegraph impact summary if available
4+
IMPACT=$(codegraph diff-impact --staged --json -T 2>/dev/null || node src/cli.js diff-impact --staged --json -T 2>/dev/null)
5+
if [ -n "$IMPACT" ]; then
6+
SUMMARY=$(echo "$IMPACT" | node -e "
7+
let d=''; process.stdin.on('data',c=>d+=c);
8+
process.stdin.on('end',()=>{
9+
try {
10+
const j=JSON.parse(d);
11+
if(j.summary && j.summary.functionsChanged > 0)
12+
console.log('Impact: '+j.summary.functionsChanged+' functions changed, '+(j.summary.totalAffected||j.summary.callersAffected||0)+' affected');
13+
} catch {}
14+
});
15+
" 2>/dev/null)
16+
if [ -n "$SUMMARY" ]; then
17+
echo "" >> "$1"
18+
echo "$SUMMARY" >> "$1"
19+
fi
20+
fi

.husky/pre-commit

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
npm run lint
2+
codegraph build 2>/dev/null || node src/cli.js build . 2>/dev/null || true

.husky/pre-push

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
IMPACT=$(codegraph diff-impact origin/main --json -T 2>/dev/null || node src/cli.js diff-impact origin/main --json -T 2>/dev/null)
2+
if [ -n "$IMPACT" ]; then
3+
AFFECTED=$(echo "$IMPACT" | node -e "
4+
let d=''; process.stdin.on('data',c=>d+=c);
5+
process.stdin.on('end',()=>{
6+
try { console.log(JSON.parse(d).summary?.totalAffected||0); }
7+
catch { console.log(0); }
8+
});
9+
")
10+
if [ "$AFFECTED" -gt 50 ]; then
11+
echo "Warning: pushing changes that affect $AFFECTED functions"
12+
echo "Run 'codegraph diff-impact origin/main -T' to review"
13+
fi
14+
fi

CLAUDE.md

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
44

5+
> **Use codegraph before editing code.** This project has a pre-built dependency graph at `.codegraph/graph.db`. Before modifying any function or file, run `node src/cli.js where <name>` to locate it, `node src/cli.js explain <target>` to understand the structure, `node src/cli.js context <name> -T` to gather full context, and `node src/cli.js fn-impact <name> -T` to check blast radius. After staging changes, run `node src/cli.js diff-impact --staged -T` to verify impact. This saves tokens, prevents blind edits, and catches breakage before it happens. See the [Dogfooding](#dogfooding--codegraph-on-itself) section for the full command reference.
6+
57
## Project Overview
68

79
Codegraph (`@optave/codegraph`) is a local code dependency graph CLI. It parses codebases with tree-sitter (WASM), builds function-level dependency graphs stored in SQLite, and supports semantic search with local embeddings. No cloud services required.
@@ -97,18 +99,34 @@ The workflow can be overridden with a specific version via the `version-override
9799

98100
## Dogfooding — codegraph on itself
99101

100-
Codegraph is **our own tool**. Use it to analyze this repository before making changes:
102+
Codegraph is **our own tool**. Use it to analyze this repository before making changes. If codegraph reports an error, crashes, or produces wrong results when analyzing itself, **fix the bug in the codebase** — don't just work around it.
103+
104+
### Before modifying code, always:
105+
1. `node src/cli.js where <name>` — find where the symbol lives
106+
2. `node src/cli.js explain <file-or-function>` — understand the structure
107+
3. `node src/cli.js context <name> -T` — get full context (source, deps, callers)
108+
4. `node src/cli.js fn-impact <name> -T` — check blast radius before editing
109+
110+
### After modifying code:
111+
5. `node src/cli.js diff-impact --staged -T` — verify impact before committing
101112

113+
### Other useful commands
102114
```bash
103-
node src/cli.js build . # Build/update the graph
115+
node src/cli.js build . # Build/update the graph (incremental)
116+
node src/cli.js map --limit 20 # Module overview & most-connected nodes
117+
node src/cli.js stats # Graph health and quality score
118+
node src/cli.js fn <name> -T # Function call chain (callers + callees)
119+
node src/cli.js deps src/<file>.js # File-level imports and importers
120+
node src/cli.js diff-impact main # Impact of current branch vs main
104121
node src/cli.js cycles # Check for circular dependencies
105-
node src/cli.js map --limit 20 # Module overview & coupling hotspots
106-
node src/cli.js diff-impact main # See impact of current branch changes
107-
node src/cli.js fn <name> # Trace function-level dependency chains
108-
node src/cli.js deps src/<file>.js # See what imports/depends on a file
122+
node src/cli.js search "<query>" # Semantic search (requires `embed` first)
109123
```
110124

111-
If codegraph reports an error, crashes, or produces wrong results when analyzing itself, **fix the bug in the codebase** — don't just work around it. This is the best way to find and resolve real issues.
125+
### Flags
126+
- `-T` / `--no-tests` — exclude test files (use by default)
127+
- `-j` / `--json` — JSON output for programmatic use
128+
- `-f, --file <path>` — scope to a specific file (partial match)
129+
- `-k, --kind <kind>` — filter by symbol kind (function, method, class, etc.)
112130

113131
## Parallel Sessions
114132

README.md

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ Most code graph tools make you choose: **fast local analysis with no AI, or powe
9393
| **** | **Always-fresh graph** | Three-tier change detection: journal (O(changed)) → mtime+size (O(n) stats) → hash (O(changed) reads). Sub-second rebuilds even on large codebases. Competitors re-index everything from scratch; Merkle-tree approaches still require O(n) filesystem scanning |
9494
| **🔓** | **Zero-cost core, LLM-enhanced when you want** | Full graph analysis with no API keys, no accounts, no cost. Optionally bring your own LLM provider for richer embeddings and AI-powered search — your code only goes to the provider you already chose |
9595
| **🔬** | **Function-level, not just files** | Traces `handleAuth()``validateToken()``decryptJWT()` and shows 14 callers across 9 files break if `decryptJWT` changes |
96-
| **🤖** | **Built for AI agents** | 13-tool [MCP server](https://modelcontextprotocol.io/) — AI assistants query your graph directly. Single-repo by default, your code doesn't leak to other projects |
96+
| **🤖** | **Built for AI agents** | 17-tool [MCP server](https://modelcontextprotocol.io/) — AI assistants query your graph directly. Single-repo by default, your code doesn't leak to other projects |
9797
| **🌐** | **Multi-language, one CLI** | JS/TS + Python + Go + Rust + Java + C# + PHP + Ruby + HCL in a single graph — no juggling Madge, pyan, and cflow |
9898
| **💥** | **Git diff impact** | `codegraph diff-impact` shows changed functions, their callers, and full blast radius — ships with a GitHub Actions workflow |
9999
| **🧠** | **Semantic search** | Local embeddings by default, LLM-powered embeddings when opted in — multi-query with RRF ranking via `"auth; token; JWT"` |
@@ -132,7 +132,7 @@ Here is a cold, analytical breakdown to help you decide which tool fits your wor
132132
| Aspect | Optave Codegraph | Narsil-MCP |
133133
| :--- | :--- | :--- |
134134
| **Philosophy** | Lean, deterministic, AI-optimized | Comprehensive, feature-dense |
135-
| **AI Tool Count** | 13 focused tools | 90 distinct tools |
135+
| **AI Tool Count** | 17 focused tools | 90 distinct tools |
136136
| **Language Support** | 11 languages | 32 languages |
137137
| **Primary Interface** | CLI-first with MCP integration | MCP-first (CLI is secondary) |
138138
| **Supply Chain Risk** | Low (minimal dependency tree) | Higher (requires massive dependency graph for embedded ML/scanners) |
@@ -141,7 +141,7 @@ Here is a cold, analytical breakdown to help you decide which tool fits your wor
141141
#### Choose Codegraph if:
142142

143143
* **You need the fastest possible incremental rebuilds.** Codegraph’s three-tier change detection (journal → mtime+size → hash) achieves true O(changed) when the watcher is running — only touched files are processed. Narsil’s Merkle trees still require O(n) filesystem scanning to recompute hashes on every rebuild, even when nothing changed. On a 3,000-file project, this is the difference between near-instant and noticeable.
144-
* **You want to optimize AI agent reasoning.** Large Language Models degrade in performance and hallucinate when overwhelmed with choices. Codegraph’s tight 13-tool surface area ensures agents quickly understand their capabilities without wasting context window tokens.
144+
* **You want to optimize AI agent reasoning.** Large Language Models degrade in performance and hallucinate when overwhelmed with choices. Codegraph’s tight 17-tool surface area ensures agents quickly understand their capabilities without wasting context window tokens.
145145
* **You are concerned about supply chain attacks.** To support 90 tools, SBOMs, and neural embeddings, a tool must pull in a massive dependency tree. Codegraph keeps its dependencies minimal, dramatically reducing the risk of malicious code sneaking onto your machine.
146146
* **You want deterministic blast-radius checks.** Features like `diff-impact` are built specifically to tell you exactly how a changed function cascades through your codebase before you merge a PR.
147147
* **You value a strong standalone CLI.** You want to query your code graph locally without necessarily spinning up an AI agent.
@@ -190,7 +190,7 @@ codegraph deps src/index.ts # file-level import/export map
190190
| 📤 | **Export** | DOT (Graphviz), Mermaid, and JSON graph export |
191191
| 🧠 | **Semantic search** | Embeddings-powered natural language search with multi-query RRF ranking |
192192
| 👀 | **Watch mode** | Incrementally update the graph as files change |
193-
| 🤖 | **MCP server** | 13-tool MCP server for AI assistants; single-repo by default, opt-in multi-repo |
193+
| 🤖 | **MCP server** | 17-tool MCP server for AI assistants; single-repo by default, opt-in multi-repo |
194194
| 🔒 | **Your code, your choice** | Zero-cost core with no API keys. Optionally enhance with your LLM provider — your code only goes where you send it |
195195

196196
## 📦 Commands
@@ -391,7 +391,7 @@ Metrics are normalized per file for cross-version comparability. Times above are
391391

392392
### MCP Server
393393

394-
Codegraph includes a built-in [Model Context Protocol](https://modelcontextprotocol.io/) server with 13 tools, so AI assistants can query your dependency graph directly:
394+
Codegraph includes a built-in [Model Context Protocol](https://modelcontextprotocol.io/) server with 17 tools, so AI assistants can query your dependency graph directly:
395395

396396
```bash
397397
codegraph mcp # Single-repo mode (default) — only local project
@@ -405,20 +405,35 @@ codegraph mcp --repos a,b # Multi-repo with allowlist
405405

406406
### CLAUDE.md / Agent Instructions
407407

408-
Add this to your project's `CLAUDE.md` to help AI agents use codegraph:
408+
Add this to your project's `CLAUDE.md` to help AI agents use codegraph (full template in the [AI Agent Guide](docs/ai-agent-guide.md#claudemd-template)):
409409

410410
```markdown
411411
## Code Navigation
412412

413413
This project uses codegraph. The database is at `.codegraph/graph.db`.
414414

415-
- **Before modifying a function**: `codegraph fn <name> --no-tests`
416-
- **Before modifying a file**: `codegraph deps <file>`
417-
- **To assess PR impact**: `codegraph diff-impact --no-tests`
418-
- **To find entry points**: `codegraph map`
419-
- **To trace breakage**: `codegraph fn-impact <name> --no-tests`
420-
421-
Rebuild after major structural changes: `codegraph build`
415+
### Before modifying code, always:
416+
1. `codegraph where <name>` — find where the symbol lives
417+
2. `codegraph explain <file-or-function>` — understand the structure
418+
3. `codegraph context <name> -T` — get full context (source, deps, callers)
419+
4. `codegraph fn-impact <name> -T` — check blast radius before editing
420+
421+
### After modifying code:
422+
5. `codegraph diff-impact --staged -T` — verify impact before committing
423+
424+
### Other useful commands
425+
- `codegraph build .` — rebuild the graph (incremental by default)
426+
- `codegraph map` — module overview
427+
- `codegraph fn <name> -T` — function call chain
428+
- `codegraph deps <file>` — file-level dependencies
429+
- `codegraph search "<query>"` — semantic search (requires `codegraph embed`)
430+
- `codegraph cycles` — check for circular dependencies
431+
432+
### Flags
433+
- `-T` / `--no-tests` — exclude test files (use by default)
434+
- `-j` / `--json` — JSON output for programmatic use
435+
- `-f, --file <path>` — scope to a specific file
436+
- `-k, --kind <kind>` — filter by symbol kind
422437

423438
### Semantic search
424439

@@ -456,6 +471,8 @@ See **[docs/recommended-practices.md](docs/recommended-practices.md)** for integ
456471
- **Developer workflow** — watch mode, explore-before-you-edit, semantic search
457472
- **Secure credentials**`apiKeyCommand` with 1Password, Bitwarden, Vault, macOS Keychain, `pass`
458473

474+
For AI-specific integration, see the **[AI Agent Guide](docs/ai-agent-guide.md)** — a comprehensive reference covering the 6-step agent workflow, complete command-to-MCP mapping, Claude Code hooks, and token-saving patterns.
475+
459476
## 🔁 CI / GitHub Actions
460477

461478
Codegraph ships with a ready-to-use GitHub Actions workflow that comments impact analysis on every pull request.

0 commit comments

Comments
 (0)