diff --git a/.claude/skills/gitnexus/debugging/SKILL.md b/.claude/skills/gitnexus/debugging/SKILL.md index b18d2392f..316b0aa3e 100644 --- a/.claude/skills/gitnexus/debugging/SKILL.md +++ b/.claude/skills/gitnexus/debugging/SKILL.md @@ -5,78 +5,64 @@ description: Trace bugs through call chains using knowledge graph # Debugging with GitNexus -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → gitnexus_analyze({repo: "my-app"}) -2. gitnexus_search({query: "...", repo: "my-app"}) → Find code related to error -3. gitnexus_explore({name, type: "symbol", repo: "my-app"}) → Get callers and callees -4. READ gitnexus://repo/my-app/process/{name} → Trace execution flow -``` - ## When to Use - "Why is this function failing?" - "Trace where this error comes from" - "Who calls this method?" -- "Debug the payment issue" +- "This endpoint returns 500" +- Investigating bugs, errors, or unexpected behavior + +## Workflow -## Workflow Checklist ``` -Bug Investigation: -- [ ] READ gitnexus://repos to find the right repo -- [ ] Understand the symptom (error message, behavior) -- [ ] gitnexus_search to find related code +1. gitnexus_search({query: ""}) → Find related code +2. gitnexus_explore({name: "", type: "symbol"}) → See callers/callees +3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow +4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] Understand the symptom (error message, unexpected behavior) +- [ ] gitnexus_search for error text or related code - [ ] Identify the suspect function -- [ ] gitnexus_explore to see callers/callees -- [ ] READ gitnexus://repo/{name}/process/{name} if suspect is in a process -- [ ] READ gitnexus://repo/{name}/schema for Cypher query help -- [ ] gitnexus_cypher for custom traces +- [ ] gitnexus_explore to see callers and callees +- [ ] Trace execution flow via process resource if applicable +- [ ] gitnexus_cypher for custom call chain traces if needed +- [ ] Read source files to confirm root cause ``` -## Resource Reference +## Debugging Patterns -### gitnexus://repo/{name}/schema -Graph schema for writing Cypher queries: -```yaml -nodes: [Function, Class, Method, File, Community, Process] -relationships: [CALLS, IMPORTS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS] -example_queries: - find_callers: | - MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "X"}) - RETURN caller.name +| Symptom | GitNexus Approach | +|---------|-------------------| +| Error message | `gitnexus_search` for error text → `explore` throw sites | +| Wrong return value | `explore` the function → trace callees for data flow | +| Intermittent failure | `explore` → look for external calls, async deps | +| Performance issue | `explore` → find symbols with many callers (hot paths) | +| Recent regression | `gitnexus_impact` on recently changed symbols | + +## Tools + +**gitnexus_search** — find code related to error: +``` +gitnexus_search({query: "payment validation error", depth: "full"}) +→ validatePayment, handlePaymentError, PaymentException ``` -### gitnexus://repo/{name}/process/{processName} -Trace execution flow to find where bug might occur: -```yaml -name: CheckoutFlow -trace: - 1: handleCheckout - 2: validateCart - 3: processPayment ← bug here? - 4: sendConfirmation +**gitnexus_explore** — full context for a suspect: ``` - -## Tool Reference - -### gitnexus_search -Find code related to error or symptom: -``` -gitnexus_search({query: "payment validation error", depth: "full", repo: "my-app"}) -``` - -### gitnexus_explore -Get symbol context: -``` -gitnexus_explore({name: "validatePayment", type: "symbol", repo: "my-app"}) +gitnexus_explore({name: "validatePayment", type: "symbol"}) → Callers: processCheckout, webhookHandler -→ Callees: verifyCard, fetchRates +→ Callees: verifyCard, fetchRates (external API!) +→ Cluster: Payment ``` -### gitnexus_cypher -Custom graph queries for tracing: +**gitnexus_cypher** — custom call chain traces: ```cypher -// Trace call chain (2 hops) MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) RETURN [n IN nodes(path) | n.name] AS chain ``` @@ -84,23 +70,14 @@ RETURN [n IN nodes(path) | n.name] AS chain ## Example: "Payment endpoint returns 500 intermittently" ``` -1. gitnexus_search({query: "payment error handling", repo: "my-app"}) +1. gitnexus_search({query: "payment error handling"}) → validatePayment, handlePaymentError, PaymentException -2. gitnexus_explore({name: "validatePayment", type: "symbol", repo: "my-app"}) +2. gitnexus_explore({name: "validatePayment", type: "symbol"}) → Callees: verifyCard, fetchRates (external API!) 3. READ gitnexus://repo/my-app/process/CheckoutFlow - → Step 3: validatePayment → calls external API + → Step 3: validatePayment → calls fetchRates (external) 4. Root cause: fetchRates calls external API without proper timeout ``` - -## Debugging Patterns - -| Symptom | Approach | -|---------|----------| -| Error message | Search for error text, trace throw sites | -| Wrong return value | Trace data flow through callees | -| Intermittent failure | Look for external calls, timeouts | -| Performance issue | Find hot paths via callers count | diff --git a/.claude/skills/gitnexus/exploring/SKILL.md b/.claude/skills/gitnexus/exploring/SKILL.md index 46e69bb2a..70a74b0fb 100644 --- a/.claude/skills/gitnexus/exploring/SKILL.md +++ b/.claude/skills/gitnexus/exploring/SKILL.md @@ -3,124 +3,71 @@ name: gitnexus-exploring description: Navigate unfamiliar code using GitNexus knowledge graph --- -# Exploring Codebases - -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos (use repo param if multiple) -1. If "Index is stale" → gitnexus_analyze({repo: "my-app"}) -2. READ gitnexus://repo/{name}/context → Get codebase overview (~150 tokens) -3. READ gitnexus://repo/{name}/clusters → See all functional clusters -4. READ gitnexus://repo/{name}/cluster/{name} → Deep dive on specific cluster -``` +# Exploring Codebases with GitNexus ## When to Use - "How does authentication work?" - "What's the project structure?" - "Show me the main components" - "Where is the database logic?" +- Understanding code you haven't seen before + +## Workflow -## Workflow Checklist ``` -Exploration Progress: -- [ ] READ gitnexus://repos to discover available repos -- [ ] READ gitnexus://repo/{name}/context for codebase overview -- [ ] READ gitnexus://repo/{name}/clusters to list all clusters -- [ ] Identify the relevant cluster by name -- [ ] READ gitnexus://repo/{name}/cluster/{name} for cluster details -- [ ] Use gitnexus_explore for specific symbols +1. READ gitnexus://repos → Discover indexed repos +2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness +3. READ gitnexus://repo/{name}/clusters → See all functional areas +4. READ gitnexus://repo/{name}/cluster/{name} → Drill into relevant cluster +5. gitnexus_explore({name, type: "symbol"}) → Deep dive on specific symbol ``` -## Resource Reference +> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal. -### gitnexus://repos -Discover all indexed repositories. **Read first.** -```yaml -repos: - - name: "my-app" - path: "/home/user/my-app" - files: 42 - symbols: 918 +## Checklist + +``` +- [ ] READ gitnexus://repos +- [ ] READ gitnexus://repo/{name}/context +- [ ] READ gitnexus://repo/{name}/clusters +- [ ] Identify the relevant cluster +- [ ] READ gitnexus://repo/{name}/cluster/{name} +- [ ] gitnexus_explore for key symbols +- [ ] Read source files for implementation details ``` -### gitnexus://repo/{name}/context -Codebase overview for a specific repo. -```yaml -project: my-app -stats: - files: 42 - symbols: 918 - clusters: 12 - processes: 45 -tools_available: [list_repos, search, explore, impact, overview, cypher] -``` +## Resources -### gitnexus://repo/{name}/clusters -All functional clusters with cohesion scores. -```yaml -clusters: - - name: "Auth" - symbols: 47 - cohesion: 92% - - name: "Database" - symbols: 32 - cohesion: 88% -``` +| Resource | What you get | +|----------|-------------| +| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) | +| `gitnexus://repo/{name}/clusters` | All clusters with cohesion scores (~300 tokens) | +| `gitnexus://repo/{name}/cluster/{name}` | Cluster members with file paths (~500 tokens) | +| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) | -### gitnexus://repo/{name}/cluster/{clusterName} -Members of a specific cluster. -```yaml -name: Auth -symbols: 47 -cohesion: 92% -members: - - name: validateUser - type: Function - file: src/auth/validator.ts -``` +## Tools -### gitnexus://repo/{name}/process/{processName} -Full execution trace. -```yaml -name: LoginFlow -type: cross_community -steps: - 1: handleLogin (src/auth/handler.ts) - 2: validateUser (src/auth/validator.ts) - 3: createSession (src/auth/session.ts) +**gitnexus_explore** — symbol context with callers/callees: ``` - -## Tool Reference (When Resources Aren't Enough) - -### gitnexus_explore -For detailed symbol context with callers/callees: -``` -gitnexus_explore({name: "validateUser", type: "symbol", repo: "my-app"}) +gitnexus_explore({name: "validateUser", type: "symbol"}) → Callers: loginHandler, apiMiddleware → Callees: checkToken, getUserById +→ Cluster: Auth (92% cohesion) ``` -### gitnexus_search -For finding code by query: +**gitnexus_search** — find code by query when you don't know the cluster: ``` -gitnexus_search({query: "payment validation", depth: "full", repo: "my-app"}) +gitnexus_search({query: "payment validation", depth: "full"}) ``` ## Example: "How does payment processing work?" ``` -1. READ gitnexus://repos - → Repos: my-app (918 symbols) - -2. READ gitnexus://repo/my-app/context - → 918 symbols, 12 clusters - -3. READ gitnexus://repo/my-app/clusters - → Clusters: Auth, Payment, Database, API... - -4. READ gitnexus://repo/my-app/cluster/Payment - → Members: processPayment, validateCard, PaymentService - -5. READ gitnexus://repo/my-app/process/CheckoutFlow - → handleCheckout → validateCart → processPayment → sendConfirmation +1. READ gitnexus://repo/my-app/context → 918 symbols, 12 clusters +2. READ gitnexus://repo/my-app/clusters → Auth, Payment, Database, API... +3. READ gitnexus://repo/my-app/cluster/Payment → processPayment, validateCard, PaymentService +4. gitnexus_explore({name: "processPayment", type: "symbol"}) + → Callers: checkoutHandler, webhookHandler + → Callees: validateCard, chargeStripe, saveTransaction +5. Read src/payments/processor.ts for implementation details ``` diff --git a/.claude/skills/gitnexus/impact-analysis/SKILL.md b/.claude/skills/gitnexus/impact-analysis/SKILL.md index 32a3ea0c2..7cedd2b97 100644 --- a/.claude/skills/gitnexus/impact-analysis/SKILL.md +++ b/.claude/skills/gitnexus/impact-analysis/SKILL.md @@ -3,74 +3,64 @@ name: gitnexus-impact-analysis description: Analyze blast radius before making code changes --- -# Impact Analysis - -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → gitnexus_analyze({repo: "my-app"}) -2. gitnexus_impact({target, direction: "upstream", repo: "my-app"}) → What depends on this -3. READ gitnexus://repo/my-app/clusters → Check affected areas -4. READ gitnexus://repo/my-app/processes → Affected execution flows -``` +# Impact Analysis with GitNexus ## When to Use - "Is it safe to change this function?" - "What will break if I modify X?" - "Show me the blast radius" - "Who uses this code?" +- Before making non-trivial code changes + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this +2. READ gitnexus://repo/{name}/clusters → Check which areas are affected +3. READ gitnexus://repo/{name}/processes → Check affected execution flows +4. Assess risk and report to user +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents +- [ ] Review d=1 items first (these WILL BREAK) +- [ ] Check high-confidence (>0.8) dependencies +- [ ] READ clusters to understand which areas are affected +- [ ] Count affected clusters (cross-cutting = higher risk) +- [ ] READ processes to check affected execution flows +- [ ] Assess risk level and report to user +``` ## Understanding Output | Depth | Risk Level | Meaning | |-------|-----------|---------| -| d=1 | WILL BREAK | Direct callers/importers | +| d=1 | **WILL BREAK** | Direct callers/importers | | d=2 | LIKELY AFFECTED | Indirect dependencies | | d=3 | MAY NEED TESTING | Transitive effects | -## Workflow Checklist -``` -Impact Analysis: -- [ ] READ gitnexus://repos to find the right repo -- [ ] gitnexus_impact(target, "upstream", repo) to find dependents -- [ ] READ gitnexus://repo/{name}/clusters to understand affected areas -- [ ] Check high-confidence (>0.8) dependencies first -- [ ] Count affected clusters (cross-cutting = higher risk) -- [ ] If >10 processes affected, consider splitting change -``` +## Risk Assessment -## Resource Reference +| Affected | Risk | +|----------|------| +| <5 symbols, 1 cluster | LOW | +| 5-15 symbols, 1-2 clusters | MEDIUM | +| >15 symbols or 3+ clusters | HIGH | +| Critical path (auth, payments) | CRITICAL | -### gitnexus://repo/{name}/clusters -Check which clusters might be affected: -```yaml -clusters: - - name: Auth - symbols: 47 - - name: API - symbols: 32 -``` +## Tools -### gitnexus://repo/{name}/processes -Find which processes touch the target: -```yaml -processes: - - name: LoginFlow - type: cross_community - steps: 5 -``` - -## Tool Reference - -### gitnexus_impact -Analyze blast radius: +**gitnexus_impact** — the primary tool: ``` gitnexus_impact({ target: "validateUser", direction: "upstream", minConfidence: 0.8, - maxDepth: 3, - repo: "my-app" + maxDepth: 3 }) → d=1 (WILL BREAK): @@ -84,34 +74,15 @@ gitnexus_impact({ → Risk: MEDIUM (3 processes) ``` -## Risk Assessment - -| Affected | Risk | -|----------|------| -| <5 symbols, 1 cluster | LOW | -| 5-15 symbols, 1-2 clusters | MEDIUM | -| >15 symbols or 3+ clusters | HIGH | -| Critical path (auth, payments) | CRITICAL | - -## Pre-Change Checklist -``` -Before Committing: -- [ ] Run impact analysis -- [ ] Review all d=1 (WILL BREAK) items -- [ ] Verify test coverage for affected processes -- [ ] If risk > MEDIUM, get code review -- [ ] If cross-cluster, coordinate with other teams -``` - ## Example: "What breaks if I change validateUser?" ``` -1. gitnexus_impact({target: "validateUser", direction: "upstream", repo: "my-app"}) - → d=1: loginHandler, apiMiddleware - → d=2: authRouter, sessionManager +1. gitnexus_impact({target: "validateUser", direction: "upstream"}) + → d=1: loginHandler, apiMiddleware (WILL BREAK) + → d=2: authRouter, sessionManager (LIKELY AFFECTED) 2. READ gitnexus://repo/my-app/clusters - → Auth and API clusters affected + → Auth and API clusters affected (2 clusters) -3. Decision: 2 direct callers, 2 clusters = MEDIUM risk +3. Risk: 2 direct callers, 2 clusters = MEDIUM ``` diff --git a/.claude/skills/gitnexus/refactoring/SKILL.md b/.claude/skills/gitnexus/refactoring/SKILL.md index 1f9b71604..f98c4b34e 100644 --- a/.claude/skills/gitnexus/refactoring/SKILL.md +++ b/.claude/skills/gitnexus/refactoring/SKILL.md @@ -5,116 +5,98 @@ description: Plan safe refactors using blast radius and dependency mapping # Refactoring with GitNexus -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → gitnexus_analyze({repo: "my-app"}) -2. gitnexus_impact({target, direction: "upstream", repo: "my-app"}) → Map all dependents -3. READ gitnexus://repo/my-app/schema → Understand graph structure -4. gitnexus_cypher({query: "...", repo: "my-app"}) → Find all references -``` - ## When to Use - "Rename this function safely" - "Extract this into a module" - "Split this service" -- "Refactor without breaking things" +- "Move this to a new file" +- Any task involving renaming, extracting, splitting, or restructuring code + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents +2. gitnexus_search({query: "X"}) → Find string/dynamic references +3. READ gitnexus://repo/{name}/cluster/{name} → Check cohesion impact +4. Plan update order: interfaces → implementations → callers → tests +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. ## Checklists ### Rename Symbol ``` -Rename Refactoring: -- [ ] gitnexus_impact({target: oldName, direction: "upstream", repo: "my-app"}) — find all callers -- [ ] gitnexus_search({query: oldName, repo: "my-app"}) — find string literals -- [ ] Check for reflection/dynamic references -- [ ] Update in order: interface → implementation → usages +- [ ] gitnexus_impact({target: oldName, direction: "upstream"}) — find all callers +- [ ] gitnexus_search({query: oldName}) — find string literals and dynamic references +- [ ] Check for reflection/dynamic invocation patterns +- [ ] Plan update order: interface → implementation → callers → tests +- [ ] Update all d=1 (WILL BREAK) items - [ ] Run tests for affected processes ``` ### Extract Module ``` -Extract Module: -- [ ] gitnexus_explore({name: target, type: "symbol", repo: "my-app"}) — map dependencies -- [ ] gitnexus_impact({target, direction: "upstream", repo: "my-app"}) — find callers -- [ ] READ gitnexus://repo/my-app/cluster/{name} — check cohesion +- [ ] gitnexus_explore({name: target, type: "symbol"}) — map internal dependencies +- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers +- [ ] READ cluster resource — check if extraction preserves cohesion - [ ] Define new module interface -- [ ] Update imports across affected files +- [ ] Extract code, update imports +- [ ] Run tests for affected processes ``` -### Split Function +### Split Function/Service ``` -Split Function: -- [ ] gitnexus_explore({name: target, type: "symbol", repo: "my-app"}) — understand callees -- [ ] Group related logic -- [ ] gitnexus_impact — verify callers won't break -- [ ] Create new functions +- [ ] gitnexus_explore({name: target, type: "symbol"}) — understand all callees +- [ ] Group callees by responsibility/domain +- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update +- [ ] Create new functions/services - [ ] Update callers +- [ ] Run tests for affected processes ``` -## Resource Reference +## Tools -### gitnexus://repo/{name}/schema -Graph structure for Cypher queries: -```yaml -nodes: [Function, Class, Method, Community, Process] -relationships: [CALLS, IMPORTS, EXTENDS, MEMBER_OF] - -example_queries: - find_callers: | - MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "X"}) - RETURN caller.name +**gitnexus_impact** — map all dependents first: +``` +gitnexus_impact({target: "validateUser", direction: "upstream"}) +→ d=1: loginHandler, apiMiddleware, testUtils +→ Affected Processes: LoginFlow, TokenRefresh ``` -### gitnexus://repo/{name}/cluster/{clusterName} -Check if extraction preserves cohesion: -```yaml -name: Payment -cohesion: 92% -members: [processPayment, validateCard, PaymentService] +**gitnexus_search** — find string/dynamic references impact() might miss: +``` +gitnexus_search({query: "validateUser"}) +→ Found in: config.json (dynamic reference!), test fixtures ``` -## Tool Reference - -### Finding all references +**gitnexus_cypher** — custom reference queries: ```cypher MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) -RETURN caller.name, caller.filePath -ORDER BY caller.filePath +RETURN caller.name, caller.filePath ORDER BY caller.filePath ``` -### Finding imports of a module -```cypher -MATCH (importer)-[:CodeRelation {type: 'IMPORTS'}]->(f:File {name: "utils.ts"}) -RETURN importer.name, importer.filePath -``` - -## Example: Safely Rename `validateUser` to `authenticateUser` - -``` -1. gitnexus_impact({target: "validateUser", direction: "upstream", repo: "my-app"}) - → loginHandler, apiMiddleware, testUtils - -2. gitnexus_search({query: "validateUser", repo: "my-app"}) - → Found in: config.json (dynamic reference!) - -3. READ gitnexus://repo/my-app/processes - → LoginFlow, TokenRefresh, APIGateway - -4. Plan update order: - 1. Update declaration in auth.ts - 2. Update config.json string reference - 3. Update loginHandler - 4. Update apiMiddleware - 5. Run tests for LoginFlow, TokenRefresh -``` - -## Refactoring Safety Rules +## Risk Rules | Risk Factor | Mitigation | |-------------|------------| | Many callers (>5) | Update in small batches | -| Cross-cluster | Coordinate with other teams | -| String references | Search for dynamic usage | -| Reflection | Check for dynamic invocation | -| External exports | May break downstream repos | +| Cross-cluster refs | Coordinate with affected areas | +| String/dynamic refs | `gitnexus_search` to find them | +| External/public API | Version and deprecate properly | + +## Example: Rename `validateUser` to `authenticateUser` + +``` +1. gitnexus_impact({target: "validateUser", direction: "upstream"}) + → d=1: loginHandler, apiMiddleware, testUtils + +2. gitnexus_search({query: "validateUser"}) + → Found in: config.json (dynamic reference!) + +3. Plan update order: + 1. Update declaration in src/auth/validator.ts + 2. Update config.json string reference + 3. Update loginHandler, apiMiddleware, testUtils + 4. Run tests for LoginFlow, TokenRefresh +``` diff --git a/AGENTS.md b/AGENTS.md index 053c0ece6..a9fbc688a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,87 +1,61 @@ # AI Agent Rules -Follow .gitnexus/RULES.md for all project context and coding guidelines. - -This project uses GitNexus MCP for code intelligence. See .gitnexus/RULES.md for available tools and best practices. - # GitNexus MCP -This project is indexed as **GitnexusV2** by GitNexus, providing AI agents with deep code intelligence. +This project is indexed by GitNexus as **GitnexusV2** (940 symbols, 2298 relationships, 13 clusters, 67 processes). -## Project: GitnexusV2 +GitNexus provides a knowledge graph over this codebase — clusters, call chains, blast radius, execution flows, and semantic search. -| Metric | Count | -|--------|-------| -| Files | 147 | -| Symbols | 940 | -| Relationships | 2298 | -| Clusters | 13 | -| Processes | 67 | +## Always Start Here -> **Staleness:** If the index is out of date, run `gitnexus_analyze({repo: "GitnexusV2"})` to refresh. The `gitnexus://repo/GitnexusV2/context` resource will warn you when the index is stale. +For any task involving code understanding, debugging, impact analysis, or refactoring, you must: -## Quick Start +1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness +2. **Match your task to a skill below** and **read that skill file** +3. **Follow the skill's workflow and checklist** -``` -1. READ gitnexus://repos → Discover all indexed repos -2. READ gitnexus://repo/GitnexusV2/context → Get codebase overview (~150 tokens) -3. READ gitnexus://repo/GitnexusV2/clusters → See all functional clusters -4. gitnexus_search({query: "...", repo: "GitnexusV2"}) → Find code by query -``` +> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first. -## Available Resources +## Skills -| Resource | Purpose | +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/refactoring/SKILL.md` | + +## Tools Reference + +| Tool | What it gives you | +|------|-------------------| +| `search` | Semantic + keyword code search with cluster context | +| `explore` | Symbol deep dive — callers, callees, cluster membership, processes | +| `impact` | Blast radius — what breaks at depth 1/2/3 with confidence scores | +| `overview` | All clusters and processes at a glance | +| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) | +| `list_repos` | Discover indexed repos | + +## Resources Reference + +Lightweight reads (~100-500 tokens) for navigation: + +| Resource | Content | |----------|---------| -| `gitnexus://repos` | List all indexed repositories | -| `gitnexus://repo/GitnexusV2/context` | Codebase stats, tools, and resources overview | -| `gitnexus://repo/GitnexusV2/clusters` | All clusters with symbol counts and cohesion | -| `gitnexus://repo/GitnexusV2/cluster/{name}` | Cluster members and details | -| `gitnexus://repo/GitnexusV2/processes` | All execution flows with types | -| `gitnexus://repo/GitnexusV2/process/{name}` | Full process trace with steps | -| `gitnexus://repo/GitnexusV2/schema` | Graph schema for Cypher queries | - -## Available Tools - -| Tool | Purpose | When to Use | -|------|---------|-------------| -| `list_repos` | Discover indexed repos | First step with multiple repos | -| `search` | Semantic + keyword search | Finding code by query | -| `overview` | List clusters & processes | Understanding architecture | -| `explore` | Deep dive on symbol/cluster/process | Detailed investigation | -| `impact` | Blast radius analysis | Before making changes | -| `cypher` | Raw graph queries | Complex analysis | -| `analyze` | Re-index repository | When index is stale or after major code changes | - -> **Multi-repo:** When multiple repos are indexed, pass `repo: "GitnexusV2"` to target this project. - -## Workflow Examples - -### Exploring the Codebase -``` -READ gitnexus://repos → Discover repos -READ gitnexus://repo/GitnexusV2/context → Stats and overview (check for staleness) -READ gitnexus://repo/GitnexusV2/clusters → Find relevant cluster by name -READ gitnexus://repo/GitnexusV2/cluster/{name} → See members of that cluster -gitnexus_explore({name: "", type: "symbol", repo: "GitnexusV2"}) -``` - -### Planning a Change -``` -gitnexus_search({query: "", repo: "GitnexusV2"}) -gitnexus_impact({target: "", direction: "upstream", repo: "GitnexusV2"}) -READ gitnexus://repo/GitnexusV2/processes → Check affected execution flows -``` +| `gitnexus://repo/{name}/context` | Stats, staleness check | +| `gitnexus://repo/{name}/clusters` | All clusters with cohesion scores | +| `gitnexus://repo/{name}/cluster/{clusterName}` | Cluster members | +| `gitnexus://repo/{name}/processes` | All execution flows | +| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace | +| `gitnexus://repo/{name}/schema` | Graph schema for Cypher | ## Graph Schema **Nodes:** File, Function, Class, Interface, Method, Community, Process - -**Relationships:** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS +**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS ```cypher -// Example: Find callers of a function MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"}) RETURN caller.name, caller.filePath ``` diff --git a/CLAUDE.md b/CLAUDE.md index 6e9550ae3..876be3fd7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,81 +1,59 @@ # GitNexus MCP -This project is indexed as **GitnexusV2** by GitNexus, providing AI agents with deep code intelligence. +This project is indexed by GitNexus as **GitnexusV2** (940 symbols, 2298 relationships, 13 clusters, 67 processes). -## Project: GitnexusV2 +GitNexus provides a knowledge graph over this codebase — clusters, call chains, blast radius, execution flows, and semantic search. -| Metric | Count | -|--------|-------| -| Files | 147 | -| Symbols | 940 | -| Relationships | 2298 | -| Clusters | 13 | -| Processes | 67 | +## Always Start Here -> **Staleness:** If the index is out of date, run `gitnexus_analyze({repo: "GitnexusV2"})` to refresh. The `gitnexus://repo/GitnexusV2/context` resource will warn you when the index is stale. +For any task involving code understanding, debugging, impact analysis, or refactoring, you must: -## Quick Start +1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness +2. **Match your task to a skill below** and **read that skill file** +3. **Follow the skill's workflow and checklist** -``` -1. READ gitnexus://repos → Discover all indexed repos -2. READ gitnexus://repo/GitnexusV2/context → Get codebase overview (~150 tokens) -3. READ gitnexus://repo/GitnexusV2/clusters → See all functional clusters -4. gitnexus_search({query: "...", repo: "GitnexusV2"}) → Find code by query -``` +> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first. -## Available Resources +## Skills -| Resource | Purpose | +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/refactoring/SKILL.md` | + +## Tools Reference + +| Tool | What it gives you | +|------|-------------------| +| `search` | Semantic + keyword code search with cluster context | +| `explore` | Symbol deep dive — callers, callees, cluster membership, processes | +| `impact` | Blast radius — what breaks at depth 1/2/3 with confidence scores | +| `overview` | All clusters and processes at a glance | +| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) | +| `list_repos` | Discover indexed repos | + +## Resources Reference + +Lightweight reads (~100-500 tokens) for navigation: + +| Resource | Content | |----------|---------| -| `gitnexus://repos` | List all indexed repositories | -| `gitnexus://repo/GitnexusV2/context` | Codebase stats, tools, and resources overview | -| `gitnexus://repo/GitnexusV2/clusters` | All clusters with symbol counts and cohesion | -| `gitnexus://repo/GitnexusV2/cluster/{name}` | Cluster members and details | -| `gitnexus://repo/GitnexusV2/processes` | All execution flows with types | -| `gitnexus://repo/GitnexusV2/process/{name}` | Full process trace with steps | -| `gitnexus://repo/GitnexusV2/schema` | Graph schema for Cypher queries | - -## Available Tools - -| Tool | Purpose | When to Use | -|------|---------|-------------| -| `list_repos` | Discover indexed repos | First step with multiple repos | -| `search` | Semantic + keyword search | Finding code by query | -| `overview` | List clusters & processes | Understanding architecture | -| `explore` | Deep dive on symbol/cluster/process | Detailed investigation | -| `impact` | Blast radius analysis | Before making changes | -| `cypher` | Raw graph queries | Complex analysis | -| `analyze` | Re-index repository | When index is stale or after major code changes | - -> **Multi-repo:** When multiple repos are indexed, pass `repo: "GitnexusV2"` to target this project. - -## Workflow Examples - -### Exploring the Codebase -``` -READ gitnexus://repos → Discover repos -READ gitnexus://repo/GitnexusV2/context → Stats and overview (check for staleness) -READ gitnexus://repo/GitnexusV2/clusters → Find relevant cluster by name -READ gitnexus://repo/GitnexusV2/cluster/{name} → See members of that cluster -gitnexus_explore({name: "", type: "symbol", repo: "GitnexusV2"}) -``` - -### Planning a Change -``` -gitnexus_search({query: "", repo: "GitnexusV2"}) -gitnexus_impact({target: "", direction: "upstream", repo: "GitnexusV2"}) -READ gitnexus://repo/GitnexusV2/processes → Check affected execution flows -``` +| `gitnexus://repo/{name}/context` | Stats, staleness check | +| `gitnexus://repo/{name}/clusters` | All clusters with cohesion scores | +| `gitnexus://repo/{name}/cluster/{clusterName}` | Cluster members | +| `gitnexus://repo/{name}/processes` | All execution flows | +| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace | +| `gitnexus://repo/{name}/schema` | Graph schema for Cypher | ## Graph Schema **Nodes:** File, Function, Class, Interface, Method, Community, Process - -**Relationships:** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS +**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS ```cypher -// Example: Find callers of a function MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"}) RETURN caller.name, caller.filePath ``` diff --git a/gitnexus/package.json b/gitnexus/package.json index d7b0718c9..381fc9749 100644 --- a/gitnexus/package.json +++ b/gitnexus/package.json @@ -1,6 +1,6 @@ { "name": "gitnexus", - "version": "1.1.6", + "version": "1.1.8", "description": "Graph-powered code intelligence for AI agents. Index any codebase, query via MCP or CLI.", "author": "Abhigyan Patwari", "license": "PolyForm-Noncommercial-1.0.0", diff --git a/gitnexus/skills/debugging.md b/gitnexus/skills/debugging.md index c2d00ba3f..316b0aa3e 100644 --- a/gitnexus/skills/debugging.md +++ b/gitnexus/skills/debugging.md @@ -5,78 +5,64 @@ description: Trace bugs through call chains using knowledge graph # Debugging with GitNexus -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → run `npx gitnexus analyze` in terminal -2. gitnexus_search({query: "...", repo: "my-app"}) → Find code related to error -3. gitnexus_explore({name, type: "symbol", repo: "my-app"}) → Get callers and callees -4. READ gitnexus://repo/my-app/process/{name} → Trace execution flow -``` - ## When to Use - "Why is this function failing?" - "Trace where this error comes from" - "Who calls this method?" -- "Debug the payment issue" +- "This endpoint returns 500" +- Investigating bugs, errors, or unexpected behavior + +## Workflow -## Workflow Checklist ``` -Bug Investigation: -- [ ] READ gitnexus://repos to find the right repo -- [ ] Understand the symptom (error message, behavior) -- [ ] gitnexus_search to find related code +1. gitnexus_search({query: ""}) → Find related code +2. gitnexus_explore({name: "", type: "symbol"}) → See callers/callees +3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow +4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] Understand the symptom (error message, unexpected behavior) +- [ ] gitnexus_search for error text or related code - [ ] Identify the suspect function -- [ ] gitnexus_explore to see callers/callees -- [ ] READ gitnexus://repo/{name}/process/{name} if suspect is in a process -- [ ] READ gitnexus://repo/{name}/schema for Cypher query help -- [ ] gitnexus_cypher for custom traces +- [ ] gitnexus_explore to see callers and callees +- [ ] Trace execution flow via process resource if applicable +- [ ] gitnexus_cypher for custom call chain traces if needed +- [ ] Read source files to confirm root cause ``` -## Resource Reference +## Debugging Patterns -### gitnexus://repo/{name}/schema -Graph schema for writing Cypher queries: -```yaml -nodes: [Function, Class, Method, File, Community, Process] -relationships: [CALLS, IMPORTS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS] -example_queries: - find_callers: | - MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "X"}) - RETURN caller.name +| Symptom | GitNexus Approach | +|---------|-------------------| +| Error message | `gitnexus_search` for error text → `explore` throw sites | +| Wrong return value | `explore` the function → trace callees for data flow | +| Intermittent failure | `explore` → look for external calls, async deps | +| Performance issue | `explore` → find symbols with many callers (hot paths) | +| Recent regression | `gitnexus_impact` on recently changed symbols | + +## Tools + +**gitnexus_search** — find code related to error: +``` +gitnexus_search({query: "payment validation error", depth: "full"}) +→ validatePayment, handlePaymentError, PaymentException ``` -### gitnexus://repo/{name}/process/{processName} -Trace execution flow to find where bug might occur: -```yaml -name: CheckoutFlow -trace: - 1: handleCheckout - 2: validateCart - 3: processPayment ← bug here? - 4: sendConfirmation +**gitnexus_explore** — full context for a suspect: ``` - -## Tool Reference - -### gitnexus_search -Find code related to error or symptom: -``` -gitnexus_search({query: "payment validation error", depth: "full", repo: "my-app"}) -``` - -### gitnexus_explore -Get symbol context: -``` -gitnexus_explore({name: "validatePayment", type: "symbol", repo: "my-app"}) +gitnexus_explore({name: "validatePayment", type: "symbol"}) → Callers: processCheckout, webhookHandler -→ Callees: verifyCard, fetchRates +→ Callees: verifyCard, fetchRates (external API!) +→ Cluster: Payment ``` -### gitnexus_cypher -Custom graph queries for tracing: +**gitnexus_cypher** — custom call chain traces: ```cypher -// Trace call chain (2 hops) MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) RETURN [n IN nodes(path) | n.name] AS chain ``` @@ -84,23 +70,14 @@ RETURN [n IN nodes(path) | n.name] AS chain ## Example: "Payment endpoint returns 500 intermittently" ``` -1. gitnexus_search({query: "payment error handling", repo: "my-app"}) +1. gitnexus_search({query: "payment error handling"}) → validatePayment, handlePaymentError, PaymentException -2. gitnexus_explore({name: "validatePayment", type: "symbol", repo: "my-app"}) +2. gitnexus_explore({name: "validatePayment", type: "symbol"}) → Callees: verifyCard, fetchRates (external API!) 3. READ gitnexus://repo/my-app/process/CheckoutFlow - → Step 3: validatePayment → calls external API + → Step 3: validatePayment → calls fetchRates (external) 4. Root cause: fetchRates calls external API without proper timeout ``` - -## Debugging Patterns - -| Symptom | Approach | -|---------|----------| -| Error message | Search for error text, trace throw sites | -| Wrong return value | Trace data flow through callees | -| Intermittent failure | Look for external calls, timeouts | -| Performance issue | Find hot paths via callers count | diff --git a/gitnexus/skills/exploring.md b/gitnexus/skills/exploring.md index cffd6c398..70a74b0fb 100644 --- a/gitnexus/skills/exploring.md +++ b/gitnexus/skills/exploring.md @@ -3,124 +3,71 @@ name: gitnexus-exploring description: Navigate unfamiliar code using GitNexus knowledge graph --- -# Exploring Codebases - -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos (use repo param if multiple) -1. If "Index is stale" → run `npx gitnexus analyze` in terminal -2. READ gitnexus://repo/{name}/context → Get codebase overview (~150 tokens) -3. READ gitnexus://repo/{name}/clusters → See all functional clusters -4. READ gitnexus://repo/{name}/cluster/{name} → Deep dive on specific cluster -``` +# Exploring Codebases with GitNexus ## When to Use - "How does authentication work?" - "What's the project structure?" - "Show me the main components" - "Where is the database logic?" +- Understanding code you haven't seen before + +## Workflow -## Workflow Checklist ``` -Exploration Progress: -- [ ] READ gitnexus://repos to discover available repos -- [ ] READ gitnexus://repo/{name}/context for codebase overview -- [ ] READ gitnexus://repo/{name}/clusters to list all clusters -- [ ] Identify the relevant cluster by name -- [ ] READ gitnexus://repo/{name}/cluster/{name} for cluster details -- [ ] Use gitnexus_explore for specific symbols +1. READ gitnexus://repos → Discover indexed repos +2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness +3. READ gitnexus://repo/{name}/clusters → See all functional areas +4. READ gitnexus://repo/{name}/cluster/{name} → Drill into relevant cluster +5. gitnexus_explore({name, type: "symbol"}) → Deep dive on specific symbol ``` -## Resource Reference +> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal. -### gitnexus://repos -Discover all indexed repositories. **Read first.** -```yaml -repos: - - name: "my-app" - path: "/home/user/my-app" - files: 42 - symbols: 918 +## Checklist + +``` +- [ ] READ gitnexus://repos +- [ ] READ gitnexus://repo/{name}/context +- [ ] READ gitnexus://repo/{name}/clusters +- [ ] Identify the relevant cluster +- [ ] READ gitnexus://repo/{name}/cluster/{name} +- [ ] gitnexus_explore for key symbols +- [ ] Read source files for implementation details ``` -### gitnexus://repo/{name}/context -Codebase overview for a specific repo. -```yaml -project: my-app -stats: - files: 42 - symbols: 918 - clusters: 12 - processes: 45 -tools_available: [list_repos, search, explore, impact, overview, cypher] -``` +## Resources -### gitnexus://repo/{name}/clusters -All functional clusters with cohesion scores. -```yaml -clusters: - - name: "Auth" - symbols: 47 - cohesion: 92% - - name: "Database" - symbols: 32 - cohesion: 88% -``` +| Resource | What you get | +|----------|-------------| +| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) | +| `gitnexus://repo/{name}/clusters` | All clusters with cohesion scores (~300 tokens) | +| `gitnexus://repo/{name}/cluster/{name}` | Cluster members with file paths (~500 tokens) | +| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) | -### gitnexus://repo/{name}/cluster/{clusterName} -Members of a specific cluster. -```yaml -name: Auth -symbols: 47 -cohesion: 92% -members: - - name: validateUser - type: Function - file: src/auth/validator.ts -``` +## Tools -### gitnexus://repo/{name}/process/{processName} -Full execution trace. -```yaml -name: LoginFlow -type: cross_community -steps: - 1: handleLogin (src/auth/handler.ts) - 2: validateUser (src/auth/validator.ts) - 3: createSession (src/auth/session.ts) +**gitnexus_explore** — symbol context with callers/callees: ``` - -## Tool Reference (When Resources Aren't Enough) - -### gitnexus_explore -For detailed symbol context with callers/callees: -``` -gitnexus_explore({name: "validateUser", type: "symbol", repo: "my-app"}) +gitnexus_explore({name: "validateUser", type: "symbol"}) → Callers: loginHandler, apiMiddleware → Callees: checkToken, getUserById +→ Cluster: Auth (92% cohesion) ``` -### gitnexus_search -For finding code by query: +**gitnexus_search** — find code by query when you don't know the cluster: ``` -gitnexus_search({query: "payment validation", depth: "full", repo: "my-app"}) +gitnexus_search({query: "payment validation", depth: "full"}) ``` ## Example: "How does payment processing work?" ``` -1. READ gitnexus://repos - → Repos: my-app (918 symbols) - -2. READ gitnexus://repo/my-app/context - → 918 symbols, 12 clusters - -3. READ gitnexus://repo/my-app/clusters - → Clusters: Auth, Payment, Database, API... - -4. READ gitnexus://repo/my-app/cluster/Payment - → Members: processPayment, validateCard, PaymentService - -5. READ gitnexus://repo/my-app/process/CheckoutFlow - → handleCheckout → validateCart → processPayment → sendConfirmation +1. READ gitnexus://repo/my-app/context → 918 symbols, 12 clusters +2. READ gitnexus://repo/my-app/clusters → Auth, Payment, Database, API... +3. READ gitnexus://repo/my-app/cluster/Payment → processPayment, validateCard, PaymentService +4. gitnexus_explore({name: "processPayment", type: "symbol"}) + → Callers: checkoutHandler, webhookHandler + → Callees: validateCard, chargeStripe, saveTransaction +5. Read src/payments/processor.ts for implementation details ``` diff --git a/gitnexus/skills/impact-analysis.md b/gitnexus/skills/impact-analysis.md index 2c283b33c..7cedd2b97 100644 --- a/gitnexus/skills/impact-analysis.md +++ b/gitnexus/skills/impact-analysis.md @@ -3,74 +3,64 @@ name: gitnexus-impact-analysis description: Analyze blast radius before making code changes --- -# Impact Analysis - -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → run `npx gitnexus analyze` in terminal -2. gitnexus_impact({target, direction: "upstream", repo: "my-app"}) → What depends on this -3. READ gitnexus://repo/my-app/clusters → Check affected areas -4. READ gitnexus://repo/my-app/processes → Affected execution flows -``` +# Impact Analysis with GitNexus ## When to Use - "Is it safe to change this function?" - "What will break if I modify X?" - "Show me the blast radius" - "Who uses this code?" +- Before making non-trivial code changes + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this +2. READ gitnexus://repo/{name}/clusters → Check which areas are affected +3. READ gitnexus://repo/{name}/processes → Check affected execution flows +4. Assess risk and report to user +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents +- [ ] Review d=1 items first (these WILL BREAK) +- [ ] Check high-confidence (>0.8) dependencies +- [ ] READ clusters to understand which areas are affected +- [ ] Count affected clusters (cross-cutting = higher risk) +- [ ] READ processes to check affected execution flows +- [ ] Assess risk level and report to user +``` ## Understanding Output | Depth | Risk Level | Meaning | |-------|-----------|---------| -| d=1 | WILL BREAK | Direct callers/importers | +| d=1 | **WILL BREAK** | Direct callers/importers | | d=2 | LIKELY AFFECTED | Indirect dependencies | | d=3 | MAY NEED TESTING | Transitive effects | -## Workflow Checklist -``` -Impact Analysis: -- [ ] READ gitnexus://repos to find the right repo -- [ ] gitnexus_impact(target, "upstream", repo) to find dependents -- [ ] READ gitnexus://repo/{name}/clusters to understand affected areas -- [ ] Check high-confidence (>0.8) dependencies first -- [ ] Count affected clusters (cross-cutting = higher risk) -- [ ] If >10 processes affected, consider splitting change -``` +## Risk Assessment -## Resource Reference +| Affected | Risk | +|----------|------| +| <5 symbols, 1 cluster | LOW | +| 5-15 symbols, 1-2 clusters | MEDIUM | +| >15 symbols or 3+ clusters | HIGH | +| Critical path (auth, payments) | CRITICAL | -### gitnexus://repo/{name}/clusters -Check which clusters might be affected: -```yaml -clusters: - - name: Auth - symbols: 47 - - name: API - symbols: 32 -``` +## Tools -### gitnexus://repo/{name}/processes -Find which processes touch the target: -```yaml -processes: - - name: LoginFlow - type: cross_community - steps: 5 -``` - -## Tool Reference - -### gitnexus_impact -Analyze blast radius: +**gitnexus_impact** — the primary tool: ``` gitnexus_impact({ target: "validateUser", direction: "upstream", minConfidence: 0.8, - maxDepth: 3, - repo: "my-app" + maxDepth: 3 }) → d=1 (WILL BREAK): @@ -84,34 +74,15 @@ gitnexus_impact({ → Risk: MEDIUM (3 processes) ``` -## Risk Assessment - -| Affected | Risk | -|----------|------| -| <5 symbols, 1 cluster | LOW | -| 5-15 symbols, 1-2 clusters | MEDIUM | -| >15 symbols or 3+ clusters | HIGH | -| Critical path (auth, payments) | CRITICAL | - -## Pre-Change Checklist -``` -Before Committing: -- [ ] Run impact analysis -- [ ] Review all d=1 (WILL BREAK) items -- [ ] Verify test coverage for affected processes -- [ ] If risk > MEDIUM, get code review -- [ ] If cross-cluster, coordinate with other teams -``` - ## Example: "What breaks if I change validateUser?" ``` -1. gitnexus_impact({target: "validateUser", direction: "upstream", repo: "my-app"}) - → d=1: loginHandler, apiMiddleware - → d=2: authRouter, sessionManager +1. gitnexus_impact({target: "validateUser", direction: "upstream"}) + → d=1: loginHandler, apiMiddleware (WILL BREAK) + → d=2: authRouter, sessionManager (LIKELY AFFECTED) 2. READ gitnexus://repo/my-app/clusters - → Auth and API clusters affected + → Auth and API clusters affected (2 clusters) -3. Decision: 2 direct callers, 2 clusters = MEDIUM risk +3. Risk: 2 direct callers, 2 clusters = MEDIUM ``` diff --git a/gitnexus/skills/refactoring.md b/gitnexus/skills/refactoring.md index 53d9e37dd..f98c4b34e 100644 --- a/gitnexus/skills/refactoring.md +++ b/gitnexus/skills/refactoring.md @@ -5,116 +5,98 @@ description: Plan safe refactors using blast radius and dependency mapping # Refactoring with GitNexus -## Quick Start -``` -0. READ gitnexus://repos → Discover indexed repos -1. If "Index is stale" → run `npx gitnexus analyze` in terminal -2. gitnexus_impact({target, direction: "upstream", repo: "my-app"}) → Map all dependents -3. READ gitnexus://repo/my-app/schema → Understand graph structure -4. gitnexus_cypher({query: "...", repo: "my-app"}) → Find all references -``` - ## When to Use - "Rename this function safely" - "Extract this into a module" - "Split this service" -- "Refactor without breaking things" +- "Move this to a new file" +- Any task involving renaming, extracting, splitting, or restructuring code + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents +2. gitnexus_search({query: "X"}) → Find string/dynamic references +3. READ gitnexus://repo/{name}/cluster/{name} → Check cohesion impact +4. Plan update order: interfaces → implementations → callers → tests +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. ## Checklists ### Rename Symbol ``` -Rename Refactoring: -- [ ] gitnexus_impact({target: oldName, direction: "upstream", repo: "my-app"}) — find all callers -- [ ] gitnexus_search({query: oldName, repo: "my-app"}) — find string literals -- [ ] Check for reflection/dynamic references -- [ ] Update in order: interface → implementation → usages +- [ ] gitnexus_impact({target: oldName, direction: "upstream"}) — find all callers +- [ ] gitnexus_search({query: oldName}) — find string literals and dynamic references +- [ ] Check for reflection/dynamic invocation patterns +- [ ] Plan update order: interface → implementation → callers → tests +- [ ] Update all d=1 (WILL BREAK) items - [ ] Run tests for affected processes ``` ### Extract Module ``` -Extract Module: -- [ ] gitnexus_explore({name: target, type: "symbol", repo: "my-app"}) — map dependencies -- [ ] gitnexus_impact({target, direction: "upstream", repo: "my-app"}) — find callers -- [ ] READ gitnexus://repo/my-app/cluster/{name} — check cohesion +- [ ] gitnexus_explore({name: target, type: "symbol"}) — map internal dependencies +- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers +- [ ] READ cluster resource — check if extraction preserves cohesion - [ ] Define new module interface -- [ ] Update imports across affected files +- [ ] Extract code, update imports +- [ ] Run tests for affected processes ``` -### Split Function +### Split Function/Service ``` -Split Function: -- [ ] gitnexus_explore({name: target, type: "symbol", repo: "my-app"}) — understand callees -- [ ] Group related logic -- [ ] gitnexus_impact — verify callers won't break -- [ ] Create new functions +- [ ] gitnexus_explore({name: target, type: "symbol"}) — understand all callees +- [ ] Group callees by responsibility/domain +- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update +- [ ] Create new functions/services - [ ] Update callers +- [ ] Run tests for affected processes ``` -## Resource Reference +## Tools -### gitnexus://repo/{name}/schema -Graph structure for Cypher queries: -```yaml -nodes: [Function, Class, Method, Community, Process] -relationships: [CALLS, IMPORTS, EXTENDS, MEMBER_OF] - -example_queries: - find_callers: | - MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "X"}) - RETURN caller.name +**gitnexus_impact** — map all dependents first: +``` +gitnexus_impact({target: "validateUser", direction: "upstream"}) +→ d=1: loginHandler, apiMiddleware, testUtils +→ Affected Processes: LoginFlow, TokenRefresh ``` -### gitnexus://repo/{name}/cluster/{clusterName} -Check if extraction preserves cohesion: -```yaml -name: Payment -cohesion: 92% -members: [processPayment, validateCard, PaymentService] +**gitnexus_search** — find string/dynamic references impact() might miss: +``` +gitnexus_search({query: "validateUser"}) +→ Found in: config.json (dynamic reference!), test fixtures ``` -## Tool Reference - -### Finding all references +**gitnexus_cypher** — custom reference queries: ```cypher MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) -RETURN caller.name, caller.filePath -ORDER BY caller.filePath +RETURN caller.name, caller.filePath ORDER BY caller.filePath ``` -### Finding imports of a module -```cypher -MATCH (importer)-[:CodeRelation {type: 'IMPORTS'}]->(f:File {name: "utils.ts"}) -RETURN importer.name, importer.filePath -``` - -## Example: Safely Rename `validateUser` to `authenticateUser` - -``` -1. gitnexus_impact({target: "validateUser", direction: "upstream", repo: "my-app"}) - → loginHandler, apiMiddleware, testUtils - -2. gitnexus_search({query: "validateUser", repo: "my-app"}) - → Found in: config.json (dynamic reference!) - -3. READ gitnexus://repo/my-app/processes - → LoginFlow, TokenRefresh, APIGateway - -4. Plan update order: - 1. Update declaration in auth.ts - 2. Update config.json string reference - 3. Update loginHandler - 4. Update apiMiddleware - 5. Run tests for LoginFlow, TokenRefresh -``` - -## Refactoring Safety Rules +## Risk Rules | Risk Factor | Mitigation | |-------------|------------| | Many callers (>5) | Update in small batches | -| Cross-cluster | Coordinate with other teams | -| String references | Search for dynamic usage | -| Reflection | Check for dynamic invocation | -| External exports | May break downstream repos | +| Cross-cluster refs | Coordinate with affected areas | +| String/dynamic refs | `gitnexus_search` to find them | +| External/public API | Version and deprecate properly | + +## Example: Rename `validateUser` to `authenticateUser` + +``` +1. gitnexus_impact({target: "validateUser", direction: "upstream"}) + → d=1: loginHandler, apiMiddleware, testUtils + +2. gitnexus_search({query: "validateUser"}) + → Found in: config.json (dynamic reference!) + +3. Plan update order: + 1. Update declaration in src/auth/validator.ts + 2. Update config.json string reference + 3. Update loginHandler, apiMiddleware, testUtils + 4. Run tests for LoginFlow, TokenRefresh +``` diff --git a/gitnexus/src/cli/ai-context.ts b/gitnexus/src/cli/ai-context.ts index c0d427afb..3ac073e6a 100644 --- a/gitnexus/src/cli/ai-context.ts +++ b/gitnexus/src/cli/ai-context.ts @@ -27,89 +27,73 @@ const GITNEXUS_START_MARKER = ''; const GITNEXUS_END_MARKER = ''; /** - * Generate the full GitNexus context content (resources-first approach) + * Generate the full GitNexus context content. + * + * Design principles (learned from real agent behavior): + * - AGENTS.md is the ROUTER — it tells the agent WHICH skill to read + * - Skills contain the actual workflows — AGENTS.md does NOT duplicate them + * - Bold **IMPORTANT** block + "Skills — Read First" heading — agents skip soft suggestions + * - One-line quick start (read context resource) gives agents an entry point + * - Tools/Resources sections are labeled "Reference" — agents treat them as lookup, not workflow */ function generateGitNexusContent(projectName: string, stats: RepoStats): string { const clusterCount = stats.clusters || stats.communities || 0; return `${GITNEXUS_START_MARKER} # GitNexus MCP -This project is indexed as **${projectName}** by GitNexus, providing AI agents with deep code intelligence. +This project is indexed by GitNexus as **${projectName}** (${stats.nodes || 0} symbols, ${stats.edges || 0} relationships, ${clusterCount} clusters, ${stats.processes || 0} processes). -## Project: ${projectName} +GitNexus provides a knowledge graph over this codebase — clusters, call chains, blast radius, execution flows, and semantic search. -| Metric | Count | -|--------|-------| -| Files | ${stats.files || 0} | -| Symbols | ${stats.nodes || 0} | -| Relationships | ${stats.edges || 0} | -| Clusters | ${clusterCount} | -| Processes | ${stats.processes || 0} | +## Always Start Here -> **Staleness:** If the index is out of date, run \`npx gitnexus analyze\` in the terminal to refresh. The \`gitnexus://repo/${projectName}/context\` resource will warn you when the index is stale. +For any task involving code understanding, debugging, impact analysis, or refactoring, you must: -## Quick Start +1. **Read \`gitnexus://repo/{name}/context\`** — codebase overview + check index freshness +2. **Match your task to a skill below** and **read that skill file** +3. **Follow the skill's workflow and checklist** -\`\`\` -1. READ gitnexus://repos → Discover all indexed repos -2. READ gitnexus://repo/${projectName}/context → Get codebase overview (~150 tokens) -3. READ gitnexus://repo/${projectName}/clusters → See all functional clusters -4. gitnexus_search({query: "...", repo: "${projectName}"}) → Find code by query -\`\`\` +> If step 1 warns the index is stale, run \`npx gitnexus analyze\` in the terminal first. -## Available Resources +## Skills -| Resource | Purpose | +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | \`.claude/skills/gitnexus/exploring/SKILL.md\` | +| Blast radius / "What breaks if I change X?" | \`.claude/skills/gitnexus/impact-analysis/SKILL.md\` | +| Trace bugs / "Why is X failing?" | \`.claude/skills/gitnexus/debugging/SKILL.md\` | +| Rename / extract / split / refactor | \`.claude/skills/gitnexus/refactoring/SKILL.md\` | + +## Tools Reference + +| Tool | What it gives you | +|------|-------------------| +| \`search\` | Semantic + keyword code search with cluster context | +| \`explore\` | Symbol deep dive — callers, callees, cluster membership, processes | +| \`impact\` | Blast radius — what breaks at depth 1/2/3 with confidence scores | +| \`overview\` | All clusters and processes at a glance | +| \`cypher\` | Raw graph queries (read \`gitnexus://repo/{name}/schema\` first) | +| \`list_repos\` | Discover indexed repos | + +## Resources Reference + +Lightweight reads (~100-500 tokens) for navigation: + +| Resource | Content | |----------|---------| -| \`gitnexus://repos\` | List all indexed repositories | -| \`gitnexus://repo/${projectName}/context\` | Codebase stats, tools, and resources overview | -| \`gitnexus://repo/${projectName}/clusters\` | All clusters with symbol counts and cohesion | -| \`gitnexus://repo/${projectName}/cluster/{name}\` | Cluster members and details | -| \`gitnexus://repo/${projectName}/processes\` | All execution flows with types | -| \`gitnexus://repo/${projectName}/process/{name}\` | Full process trace with steps | -| \`gitnexus://repo/${projectName}/schema\` | Graph schema for Cypher queries | - -## Available Tools - -| Tool | Purpose | When to Use | -|------|---------|-------------| -| \`list_repos\` | Discover indexed repos | First step with multiple repos | -| \`search\` | Semantic + keyword search | Finding code by query | -| \`overview\` | List clusters & processes | Understanding architecture | -| \`explore\` | Deep dive on symbol/cluster/process | Detailed investigation | -| \`impact\` | Blast radius analysis | Before making changes | -| \`cypher\` | Raw graph queries | Complex analysis | - -> **Re-indexing:** To refresh a stale index, run \`npx gitnexus analyze\` in the terminal. Use \`--force\` only to rebuild from scratch. This is a CLI command, not an MCP tool. - -> **Multi-repo:** When multiple repos are indexed, pass \`repo: "${projectName}"\` to target this project. - -## Workflow Examples - -### Exploring the Codebase -\`\`\` -READ gitnexus://repos → Discover repos -READ gitnexus://repo/${projectName}/context → Stats and overview (check for staleness) -READ gitnexus://repo/${projectName}/clusters → Find relevant cluster by name -READ gitnexus://repo/${projectName}/cluster/{name} → See members of that cluster -gitnexus_explore({name: "", type: "symbol", repo: "${projectName}"}) -\`\`\` - -### Planning a Change -\`\`\` -gitnexus_search({query: "", repo: "${projectName}"}) -gitnexus_impact({target: "", direction: "upstream", repo: "${projectName}"}) -READ gitnexus://repo/${projectName}/processes → Check affected execution flows -\`\`\` +| \`gitnexus://repo/{name}/context\` | Stats, staleness check | +| \`gitnexus://repo/{name}/clusters\` | All clusters with cohesion scores | +| \`gitnexus://repo/{name}/cluster/{clusterName}\` | Cluster members | +| \`gitnexus://repo/{name}/processes\` | All execution flows | +| \`gitnexus://repo/{name}/process/{processName}\` | Step-by-step trace | +| \`gitnexus://repo/{name}/schema\` | Graph schema for Cypher | ## Graph Schema **Nodes:** File, Function, Class, Interface, Method, Community, Process - -**Relationships:** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS +**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS \`\`\`cypher -// Example: Find callers of a function MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"}) RETURN caller.name, caller.filePath \`\`\` diff --git a/gitnexus/src/mcp/server.ts b/gitnexus/src/mcp/server.ts index 26450fb05..f676a1260 100644 --- a/gitnexus/src/mcp/server.ts +++ b/gitnexus/src/mcp/server.ts @@ -24,6 +24,55 @@ import { GITNEXUS_TOOLS } from './tools.js'; import type { LocalBackend } from './local/local-backend.js'; import { getResourceDefinitions, getResourceTemplates, readResource } from './resources.js'; +/** + * Next-step hints appended to tool responses. + * + * Agents often stop after one tool call. These hints guide them to the + * logical next action, creating a self-guiding workflow without hooks. + * + * Design: Each hint is a short, actionable instruction (not a suggestion). + * The hint references the specific tool/resource to use next. + */ +function getNextStepHint(toolName: string, args: Record | undefined): string { + const repo = args?.repo; + const repoParam = repo ? `, repo: "${repo}"` : ''; + const repoPath = repo || '{name}'; + + switch (toolName) { + case 'list_repos': + return `\n\n---\n**Next:** READ gitnexus://repo/{name}/context for any repo above to get its overview and check staleness.`; + + case 'search': + return `\n\n---\n**Next:** To understand a result in context, use explore({name: "", type: "symbol"${repoParam}}) to see its callers, callees, and cluster membership.`; + + case 'explore': { + const exploreType = args?.type || 'symbol'; + if (exploreType === 'symbol') { + return `\n\n---\n**Next:** If planning changes, use impact({target: "${args?.name || ''}", direction: "upstream"${repoParam}}) to check blast radius. To see execution flows, READ gitnexus://repo/${repoPath}/processes.`; + } + if (exploreType === 'cluster') { + return `\n\n---\n**Next:** To drill into a specific symbol, use explore({name: "", type: "symbol"${repoParam}}). To see execution flows, READ gitnexus://repo/${repoPath}/processes.`; + } + if (exploreType === 'process') { + return `\n\n---\n**Next:** To explore any step in detail, use explore({name: "", type: "symbol"${repoParam}}).`; + } + return ''; + } + + case 'overview': + return `\n\n---\n**Next:** To drill into a cluster, READ gitnexus://repo/${repoPath}/cluster/{name} or use explore({name: "", type: "cluster"${repoParam}}).`; + + case 'impact': + return `\n\n---\n**Next:** Review d=1 items first (WILL BREAK). To check affected execution flows, READ gitnexus://repo/${repoPath}/processes.`; + + case 'cypher': + return `\n\n---\n**Next:** To explore a result symbol, use explore({name: "", type: "symbol"${repoParam}}). For schema reference, READ gitnexus://repo/${repoPath}/schema.`; + + default: + return ''; + } +} + export async function startMCPServer(backend: LocalBackend): Promise { const server = new Server( { @@ -102,18 +151,20 @@ export async function startMCPServer(backend: LocalBackend): Promise { })), })); - // Handle tool calls + // Handle tool calls — append next-step hints to guide agent workflow server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { const result = await backend.callTool(name, args); + const resultText = typeof result === 'string' ? result : JSON.stringify(result, null, 2); + const hint = getNextStepHint(name, args as Record | undefined); return { content: [ { type: 'text', - text: typeof result === 'string' ? result : JSON.stringify(result, null, 2), + text: resultText + hint, }, ], }; diff --git a/gitnexus/src/mcp/tools.ts b/gitnexus/src/mcp/tools.ts index 07f8cb2c7..c4314638c 100644 --- a/gitnexus/src/mcp/tools.ts +++ b/gitnexus/src/mcp/tools.ts @@ -27,7 +27,9 @@ export const GITNEXUS_TOOLS: ToolDefinition[] = [ description: `List all indexed repositories available to GitNexus. Returns each repo's name, path, indexed date, last commit, and stats. -Use this to discover which repos are available before querying. + +WHEN TO USE: First step when multiple repos are indexed, or to discover available repos. +AFTER THIS: READ gitnexus://repo/{name}/context for the repo you want to work with. When multiple repos are indexed, you MUST specify the "repo" parameter on other tools (search, explore, impact, etc.) to target the correct one.`, @@ -42,7 +44,10 @@ on other tools (search, explore, impact, etc.) to target the correct one.`, description: `Hybrid search (keyword + semantic) across the codebase. Returns code nodes with cluster context and optional graph connections. -BETTER THAN IDE search because: +WHEN TO USE: Finding code by concept, name, or keyword. Use alongside grep/IDE search for richer results. +AFTER THIS: Use explore() on interesting results to see callers/callees and cluster membership. + +Complements grep/IDE search by adding: - Cluster context (which functional area each result belongs to) - Relationship data (callers/callees with depth=full) - Hybrid ranking (BM25 + semantic via Reciprocal Rank Fusion) @@ -63,6 +68,9 @@ RETURNS: Array of {name, type, filePath, cluster?, connections[]?, fusedScore, s name: 'cypher', description: `Execute Cypher query against the code knowledge graph. +WHEN TO USE: Complex structural queries that search/explore can't answer. READ gitnexus://repo/{name}/schema first for the full schema. +AFTER THIS: Use explore() on result symbols for deeper context. + SCHEMA: - Nodes: File, Folder, Function, Class, Interface, Method, Community, Process - Edges via CodeRelation.type: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES, MEMBER_OF, STEP_IN_PROCESS @@ -94,13 +102,16 @@ TIPS: name: 'explore', description: `Deep dive on a symbol, cluster, or process. +WHEN TO USE: After search() to understand context, or to drill into a specific node. +AFTER THIS (symbol): Use impact() if planning changes, or READ process resource to see execution flows. +AFTER THIS (cluster): Use explore() on specific members, or READ processes resource. +AFTER THIS (process): Use explore() on individual steps for detail. + TYPE: symbol | cluster | process For SYMBOL: Shows cluster membership, process participation, callers/callees For CLUSTER: Shows members, cohesion score, processes touching it -For PROCESS: Shows step-by-step trace, clusters traversed, entry/terminal points - -Use after search to understand context of a specific node.`, +For PROCESS: Shows step-by-step trace, clusters traversed, entry/terminal points`, inputSchema: { type: 'object', properties: { @@ -115,12 +126,13 @@ Use after search to understand context of a specific node.`, name: 'overview', description: `Get codebase map showing all clusters and processes. +WHEN TO USE: Understanding overall architecture. Prefer READ gitnexus://repo/{name}/clusters resource for a lighter-weight alternative. +AFTER THIS: Drill into a specific cluster with explore({type: "cluster"}) or search() for specific code. + Returns: - All communities (clusters) with member counts and cohesion scores - All processes with step counts and types (intra/cross-community) -- High-level architectural view - -Use to understand overall codebase structure before diving deep.`, +- High-level architectural view`, inputSchema: { type: 'object', properties: { @@ -137,7 +149,8 @@ Use to understand overall codebase structure before diving deep.`, description: `Analyze the impact of changing a code element. Returns all nodes affected by modifying the target, with distance, edge type, and confidence. -USE BEFORE making changes to understand ripple effects. +WHEN TO USE: Before making code changes, especially refactoring, renaming, or modifying shared code. Shows what would be affected. +AFTER THIS: Review d=1 items (WILL BREAK). READ gitnexus://repo/{name}/processes to check affected flows. If risk > MEDIUM, warn the user. Output includes: - Affected processes (with step positions)