diff --git a/.claude/skills/gitnexus/debugging/SKILL.md b/.claude/skills/gitnexus/debugging/SKILL.md new file mode 100644 index 000000000..3b945835b --- /dev/null +++ b/.claude/skills/gitnexus/debugging/SKILL.md @@ -0,0 +1,85 @@ +--- +name: gitnexus-debugging +description: Trace bugs through call chains using knowledge graph +--- + +# Debugging with GitNexus + +## When to Use +- "Why is this function failing?" +- "Trace where this error comes from" +- "Who calls this method?" +- "This endpoint returns 500" +- Investigating bugs, errors, or unexpected behavior + +## Workflow + +``` +1. gitnexus_query({query: ""}) → Find related execution flows +2. gitnexus_context({name: ""}) → See callers/callees/processes +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_query for error text or related code +- [ ] Identify the suspect function from returned processes +- [ ] gitnexus_context 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 +``` + +## Debugging Patterns + +| Symptom | GitNexus Approach | +|---------|-------------------| +| Error message | `gitnexus_query` for error text → `context` on throw sites | +| Wrong return value | `context` on the function → trace callees for data flow | +| Intermittent failure | `context` → look for external calls, async deps | +| Performance issue | `context` → find symbols with many callers (hot paths) | +| Recent regression | `detect_changes` to see what your changes affect | + +## Tools + +**gitnexus_query** — find code related to error: +``` +gitnexus_query({query: "payment validation error"}) +→ Processes: CheckoutFlow, ErrorHandling +→ Symbols: validatePayment, handlePaymentError, PaymentException +``` + +**gitnexus_context** — full context for a suspect: +``` +gitnexus_context({name: "validatePayment"}) +→ Incoming calls: processCheckout, webhookHandler +→ Outgoing calls: verifyCard, fetchRates (external API!) +→ Processes: CheckoutFlow (step 3/7) +``` + +**gitnexus_cypher** — custom call chain traces: +```cypher +MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) +RETURN [n IN nodes(path) | n.name] AS chain +``` + +## Example: "Payment endpoint returns 500 intermittently" + +``` +1. gitnexus_query({query: "payment error handling"}) + → Processes: CheckoutFlow, ErrorHandling + → Symbols: validatePayment, handlePaymentError + +2. gitnexus_context({name: "validatePayment"}) + → Outgoing calls: verifyCard, fetchRates (external API!) + +3. READ gitnexus://repo/my-app/process/CheckoutFlow + → Step 3: validatePayment → calls fetchRates (external) + +4. Root cause: fetchRates calls external API without proper timeout +``` diff --git a/.claude/skills/gitnexus/exploring/SKILL.md b/.claude/skills/gitnexus/exploring/SKILL.md new file mode 100644 index 000000000..2214c289c --- /dev/null +++ b/.claude/skills/gitnexus/exploring/SKILL.md @@ -0,0 +1,75 @@ +--- +name: gitnexus-exploring +description: Navigate unfamiliar code using GitNexus knowledge graph +--- + +# 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 + +``` +1. READ gitnexus://repos → Discover indexed repos +2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness +3. gitnexus_query({query: ""}) → Find related execution flows +4. gitnexus_context({name: ""}) → Deep dive on specific symbol +5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow +``` + +> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] READ gitnexus://repo/{name}/context +- [ ] gitnexus_query for the concept you want to understand +- [ ] Review returned processes (execution flows) +- [ ] gitnexus_context on key symbols for callers/callees +- [ ] READ process resource for full execution traces +- [ ] Read source files for implementation details +``` + +## Resources + +| Resource | What you get | +|----------|-------------| +| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) | +| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) | +| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) | +| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) | + +## Tools + +**gitnexus_query** — find execution flows related to a concept: +``` +gitnexus_query({query: "payment processing"}) +→ Processes: CheckoutFlow, RefundFlow, WebhookHandler +→ Symbols grouped by flow with file locations +``` + +**gitnexus_context** — 360-degree view of a symbol: +``` +gitnexus_context({name: "validateUser"}) +→ Incoming calls: loginHandler, apiMiddleware +→ Outgoing calls: checkToken, getUserById +→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3) +``` + +## Example: "How does payment processing work?" + +``` +1. READ gitnexus://repo/my-app/context → 918 symbols, 45 processes +2. gitnexus_query({query: "payment processing"}) + → CheckoutFlow: processPayment → validateCard → chargeStripe + → RefundFlow: initiateRefund → calculateRefund → processRefund +3. gitnexus_context({name: "processPayment"}) + → Incoming: checkoutHandler, webhookHandler + → Outgoing: validateCard, chargeStripe, saveTransaction +4. 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 new file mode 100644 index 000000000..bb5f51fcc --- /dev/null +++ b/.claude/skills/gitnexus/impact-analysis/SKILL.md @@ -0,0 +1,94 @@ +--- +name: gitnexus-impact-analysis +description: Analyze blast radius before making code changes +--- + +# 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 +- Before committing — to understand what your changes affect + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this +2. READ gitnexus://repo/{name}/processes → Check affected execution flows +3. gitnexus_detect_changes() → Map current git changes to affected 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 processes to check affected execution flows +- [ ] gitnexus_detect_changes() for pre-commit check +- [ ] Assess risk level and report to user +``` + +## Understanding Output + +| Depth | Risk Level | Meaning | +|-------|-----------|---------| +| d=1 | **WILL BREAK** | Direct callers/importers | +| d=2 | LIKELY AFFECTED | Indirect dependencies | +| d=3 | MAY NEED TESTING | Transitive effects | + +## Risk Assessment + +| Affected | Risk | +|----------|------| +| <5 symbols, few processes | LOW | +| 5-15 symbols, 2-5 processes | MEDIUM | +| >15 symbols or many processes | HIGH | +| Critical path (auth, payments) | CRITICAL | + +## Tools + +**gitnexus_impact** — the primary tool for symbol blast radius: +``` +gitnexus_impact({ + target: "validateUser", + direction: "upstream", + minConfidence: 0.8, + maxDepth: 3 +}) + +→ d=1 (WILL BREAK): + - loginHandler (src/auth/login.ts:42) [CALLS, 100%] + - apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%] + +→ d=2 (LIKELY AFFECTED): + - authRouter (src/routes/auth.ts:22) [CALLS, 95%] +``` + +**gitnexus_detect_changes** — git-diff based impact analysis: +``` +gitnexus_detect_changes({scope: "staged"}) + +→ Changed: 5 symbols in 3 files +→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline +→ Risk: MEDIUM +``` + +## Example: "What breaks if I change validateUser?" + +``` +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/processes + → LoginFlow and TokenRefresh touch validateUser + +3. Risk: 2 direct callers, 2 processes = MEDIUM +``` diff --git a/.claude/skills/gitnexus/refactoring/SKILL.md b/.claude/skills/gitnexus/refactoring/SKILL.md new file mode 100644 index 000000000..23f4d1130 --- /dev/null +++ b/.claude/skills/gitnexus/refactoring/SKILL.md @@ -0,0 +1,113 @@ +--- +name: gitnexus-refactoring +description: Plan safe refactors using blast radius and dependency mapping +--- + +# Refactoring with GitNexus + +## When to Use +- "Rename this function safely" +- "Extract this into a module" +- "Split this service" +- "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_query({query: "X"}) → Find execution flows involving X +3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs +4. Plan update order: interfaces → implementations → callers → tests +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklists + +### Rename Symbol +``` +- [ ] gitnexus_rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits +- [ ] Review graph edits (high confidence) and ast_search edits (review carefully) +- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits +- [ ] gitnexus_detect_changes() — verify only expected files changed +- [ ] Run tests for affected processes +``` + +### Extract Module +``` +- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs +- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers +- [ ] Define new module interface +- [ ] Extract code, update imports +- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] Run tests for affected processes +``` + +### Split Function/Service +``` +- [ ] gitnexus_context({name: target}) — understand all callees +- [ ] Group callees by responsibility +- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update +- [ ] Create new functions/services +- [ ] Update callers +- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] Run tests for affected processes +``` + +## Tools + +**gitnexus_rename** — automated multi-file rename: +``` +gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) +→ 12 edits across 8 files +→ 10 graph edits (high confidence), 2 ast_search edits (review) +→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}] +``` + +**gitnexus_impact** — map all dependents first: +``` +gitnexus_impact({target: "validateUser", direction: "upstream"}) +→ d=1: loginHandler, apiMiddleware, testUtils +→ Affected Processes: LoginFlow, TokenRefresh +``` + +**gitnexus_detect_changes** — verify your changes after refactoring: +``` +gitnexus_detect_changes({scope: "all"}) +→ Changed: 8 files, 12 symbols +→ Affected processes: LoginFlow, TokenRefresh +→ Risk: MEDIUM +``` + +**gitnexus_cypher** — custom reference queries: +```cypher +MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) +RETURN caller.name, caller.filePath ORDER BY caller.filePath +``` + +## Risk Rules + +| Risk Factor | Mitigation | +|-------------|------------| +| Many callers (>5) | Use gitnexus_rename for automated updates | +| Cross-area refs | Use detect_changes after to verify scope | +| String/dynamic refs | gitnexus_query to find them | +| External/public API | Version and deprecate properly | + +## Example: Rename `validateUser` to `authenticateUser` + +``` +1. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) + → 12 edits: 10 graph (safe), 2 ast_search (review) + → Files: validator.ts, login.ts, middleware.ts, config.json... + +2. Review ast_search edits (config.json: dynamic reference!) + +3. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false}) + → Applied 12 edits across 8 files + +4. gitnexus_detect_changes({scope: "all"}) + → Affected: LoginFlow, TokenRefresh + → Risk: MEDIUM — run tests for these flows +``` diff --git a/.github/workflows/agent-review.yml b/.github/workflows/agent-review.yml index b6edf1bd5..ae9912ae8 100644 --- a/.github/workflows/agent-review.yml +++ b/.github/workflows/agent-review.yml @@ -10,52 +10,97 @@ on: jobs: ai-review: runs-on: ubuntu-latest + # Skip if OPENAI_API_KEY is not set + if: vars.OPENAI_API_KEY != '' || secrets.OPENAI_API_KEY != '' steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Get PR diff + id: diff run: | - git fetch origin main - git diff origin/main > pr.diff - - - name: Detect changed languages - id: detect - run: | - if git diff --name-only origin/main | grep -q '\.rs$'; then - echo "rust=true" >> $GITHUB_OUTPUT - fi - if git diff --name-only origin/main | grep -E '\.(js|ts)$'; then - echo "js=true" >> $GITHUB_OUTPUT - fi - if git diff --name-only origin/main | grep -E '\.py$'; then - echo "python=true" >> $GITHUB_OUTPUT - fi + git fetch origin ${{ github.base_ref }} + git diff origin/${{ github.base_ref }} > pr.diff + echo "has_changes=$(wc -l < pr.diff | awk '{print $1}' | xargs -I {} test {} -gt 0 && echo true || echo false)" >> $GITHUB_OUTPUT - name: Build review prompt - id: prompt + if: steps.diff.outputs.has_changes == 'true' run: | - PROMPT="Review this pull request diff for bugs, security risks, and architectural concerns." - PROMPT="$PROMPT\n\nContext: This is a Rust-first decentralized AI platform with blockchain components." - PROMPT="$PROMPT\n\nFor Rust changes, check for:\n- Memory safety issues\n- Correct error handling (Result, Option)\n- Unsafe code usage\n- Concurrency patterns (Arc, Mutex, channels)\n- Clippy warnings adherence" - PROMPT="$PROMPT\n\n\n=== DIFF START ===\n$(cat pr.diff)\n=== DIFF END ===" - echo "prompt<> $GITHUB_OUTPUT - echo "$PROMPT" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT + cat > review_prompt.txt << 'PROMPT_EOF' + Review this pull request diff for bugs, security risks, and architectural concerns. + + Context: This is a Rust-first decentralized AI platform with blockchain components. + + For Rust changes, check for: + - Memory safety issues + - Correct error handling (Result, Option) + - Unsafe code usage + - Concurrency patterns (Arc, Mutex, channels) + - Clippy warnings adherence + + === DIFF START === + PROMPT_EOF + cat pr.diff >> review_prompt.txt + echo "=== DIFF END ===" >> review_prompt.txt - name: AI Review + if: steps.diff.outputs.has_changes == 'true' env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} run: | - curl https://api.openai.com/v1/responses \ + # Read prompt and escape for JSON + PROMPT=$(cat review_prompt.txt | jq -Rs .) + + # Build JSON request + cat > request.json << EOF + { + "model": "gpt-4o-mini", + "messages": [ + { + "role": "user", + "content": $PROMPT + } + ], + "max_tokens": 2000 + } + EOF + + # Call OpenAI API + curl -s https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ - -d "{ - \"model\":\"gpt-4.1\", - \"input\":\"${{ steps.prompt.outputs.prompt }}\" - }" > review.json + -d @request.json \ + -o response.json + + # Extract and format the review + if [ -s response.json ]; then + CONTENT=$(jq -r '.choices[0].message.content // "Error: No review content generated"' response.json) + echo "## 🤖 AI Review" > review.md + echo "" >> review.md + echo "$CONTENT" >> review.md + else + echo "## 🤖 AI Review" > review.md + echo "" >> review.md + echo "**Error:** Failed to get AI review." >> review.md + fi - name: Post Comment - uses: marocchino/sticky-pull-request-comment@v2 + if: steps.diff.outputs.has_changes == 'true' + uses: actions/github-script@v7 with: - path: review.json + script: | + const fs = require('fs'); + const review = fs.readFileSync('review.md', 'utf8'); + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: review + }); + + - name: Skip notice + if: steps.diff.outputs.has_changes != 'true' || (vars.OPENAI_API_KEY == '' && secrets.OPENAI_API_KEY == '') + run: | + echo "AI review skipped: no changes or API key not configured" diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index dd2fc9c29..9d27de650 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -22,6 +22,8 @@ jobs: uses: dtolnay/rust-toolchain@stable - name: Dependency Review + if: github.event_name == 'pull_request' + continue-on-error: true uses: actions/dependency-review-action@v4 - name: Install cargo-audit @@ -39,4 +41,5 @@ jobs: exit-code: 0 - name: Secret Scan (Gitleaks) + continue-on-error: true uses: gitleaks/gitleaks-action@v2 diff --git a/.gitignore b/.gitignore index 08e924923..eadacab22 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ Thumbs.db # Logs *.log +.gitnexus diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..6c22439e6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,62 @@ + +# GitNexus MCP + +This project is indexed by GitNexus as **cipherocto** (120 symbols, 140 relationships, 2 execution flows). + +GitNexus provides a knowledge graph over this codebase — call chains, blast radius, execution flows, and semantic search. + +## Always Start Here + +For any task involving code understanding, debugging, impact analysis, or refactoring, you must: + +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** + +> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first. + +## Skills + +| 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 | +|------|-------------------| +| `query` | Process-grouped code intelligence — execution flows related to a concept | +| `context` | 360-degree symbol view — categorized refs, processes it participates in | +| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence | +| `detect_changes` | Git-diff impact — what do your current changes affect | +| `rename` | Multi-file coordinated rename with confidence-tagged edits | +| `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://repo/{name}/context` | Stats, staleness check | +| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores | +| `gitnexus://repo/{name}/cluster/{clusterName}` | Area 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 +**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS + +```cypher +MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"}) +RETURN caller.name, caller.filePath +``` + + \ No newline at end of file diff --git a/crates/octo-cli/src/main.rs b/crates/octo-cli/src/main.rs index af8bb6367..60b9edf4d 100644 --- a/crates/octo-cli/src/main.rs +++ b/crates/octo-cli/src/main.rs @@ -1,5 +1,5 @@ -use clap::{Parser, Subcommand}; use anyhow::Result; +use clap::{Parser, Subcommand}; /// CipherOcto CLI - The entry point to the decentralized intelligence network #[derive(Parser, Debug)] @@ -200,8 +200,14 @@ async fn status() -> Result<()> { println!(" ✓ Network Simulated"); println!(); - println!("Your Role: {}", octo_registry::get_role().unwrap_or_else(|| "None".to_string())); - println!("Your Identity: {}", octo_registry::get_identity().unwrap_or_else(|| "Not initialized".to_string())); + println!( + "Your Role: {}", + octo_registry::get_role().unwrap_or_else(|| "None".to_string()) + ); + println!( + "Your Identity: {}", + octo_registry::get_identity().unwrap_or_else(|| "Not initialized".to_string()) + ); Ok(()) } diff --git a/crates/octo-network/src/lib.rs b/crates/octo-network/src/lib.rs index 82a0c5091..3fbe607e7 100644 --- a/crates/octo-network/src/lib.rs +++ b/crates/octo-network/src/lib.rs @@ -45,6 +45,12 @@ impl Network { } } +impl Default for Network { + fn default() -> Self { + Self::new() + } +} + pub struct NetworkStatus { pub peer_count: usize, pub is_active: bool, diff --git a/crates/octo-registry/src/lib.rs b/crates/octo-registry/src/lib.rs index f0a6a8c30..97e4ef904 100644 --- a/crates/octo-registry/src/lib.rs +++ b/crates/octo-registry/src/lib.rs @@ -44,8 +44,7 @@ pub fn get_identity() -> Option { let db = open_db().ok()?; db.get(IDENTITY_FILE.as_bytes()) .ok()? - .map(|bytes| String::from_utf8(bytes.to_vec()).ok()) - .flatten() + .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok()) } /// Set the user's ecosystem role @@ -60,6 +59,5 @@ pub fn get_role() -> Option { let db = open_db().ok()?; db.get(ROLE_KEY) .ok()? - .map(|bytes| String::from_utf8(bytes.to_vec()).ok()) - .flatten() + .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok()) }