How the detect_changes Tool in GitNexus Maps Git Diffs to Affected Processes

The detect_changes tool in GitNexus analyzes git diffs by first building a safe file list from the requested scope, then querying the knowledge graph to map changed files to indexed symbols, and finally tracing STEP_IN_PROCESS relationships to identify exactly which business processes are impacted and at which step.

The detect_changes tool serves as GitNexus’s pre-commit impact analysis engine, transforming raw git diffs into actionable intelligence about affected business processes. By leveraging the indexed knowledge graph and STEP_IN_PROCESS relationships implemented in the local-backend.ts module, the tool bridges the gap between code changes and process-level impact assessment.

Three-Stage Architecture

The detectChanges function in src/mcp/local/local-backend.ts operates through three distinct logical stages to convert git output into process impact data.

Stage 1: Building the Git Diff

The tool constructs a safe git diff command based on the requested scope parameter. The implementation uses execFileSync with explicit argument arrays to prevent shell injection.

// From src/mcp/local/local-backend.ts#L52-L68
switch (scope) {
  case 'unstaged':
    diffArgs = ['diff', '--name-only'];
    break;
  case 'staged':
    diffArgs = ['diff', '--staged', '--name-only'];
    break;
  case 'all':
    diffArgs = ['diff', 'HEAD', '--name-only'];
    break;
  case 'compare':
    diffArgs = ['diff', base_ref, '--name-only'];
    break;
}

The raw output is split into the changedFiles array. If no files changed, the tool returns immediately with changed_count: 0 and risk_level: 'none'.

Stage 2: File-to-Symbol Mapping

Each file path is normalized to use / separators and queried against the knowledge graph. The Cypher query searches for any node whose filePath property contains the changed file path.

// From src/mcp/local/local-backend.ts#L88-L106
const query = `
  MATCH (n)
  WHERE n.filePath CONTAINS $filePath
  RETURN n.id as id, n.name as name, n.type as type, n.filePath as filePath
  LIMIT 20
`;

The results populate the changedSymbols array with objects containing id, name, type, filePath, and a static change_type: 'Modified'. These symbols represent the concrete code elements (functions, classes, methods) affected by the diff.

Stage 3: Process Tracing and Risk Assessment

For each changed symbol, the tool traces STEP_IN_PROCESS relationships to identify impacted business processes. The Cypher query locates all processes that contain the symbol and extracts the specific step number.

// From src/mcp/local/local-backend.ts#L111-L140
const processQuery = `
  MATCH (n {id: $nodeId})-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
  RETURN p.id as processId, p.name as processName, p.type as processType,
         p.stepCount as stepCount, r.step as step
`;

Results are accumulated in a Map<string, any> called affectedProcesses. For each process discovered, the tool builds a changed_steps array that records which symbol caused the impact and at which step number it appears. Duplicate process entries are merged to ensure unique process listings.

The final risk level is calculated based on the total count of distinct affected processes:

const risk = processCount === 0 ? 'low'
             : processCount <= 5 ? 'medium'
             : processCount <= 15 ? 'high'
             : 'critical';

Implementation Details

Scope Handling and Safety

The tool supports four distinct analysis scopes defined in src/mcp/tools.ts (lines 31-49):

  • unstaged: Working directory changes not yet staged (default)
  • staged: Changes in the git index ready for commit
  • all: All changes since the last commit (HEAD)
  • compare: Changes between current state and a specific base_ref

The implementation strictly avoids shell interpolation by passing arguments as arrays to execFileSync, mitigating injection risks when handling file paths or branch names.

Knowledge Graph Queries

The mapping relies on two critical Cypher query patterns:

  1. File containment: MATCH (n) WHERE n.filePath CONTAINS $filePath — flexible matching for partial paths
  2. Process membership: MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process) — explicit relationship traversal

These queries execute against the Neo4j-backed knowledge graph maintained by the GitNexus backend, with a LIMIT 20 clause on symbol lookups to prevent excessive memory consumption on large diffs.

Working with the Tool

CLI Usage

Invoke the tool through the GitNexus CLI using the gitnexus_detect_changes command:

// Pre-commit: analyze unstaged changes
gitnexus_detect_changes({ scope: 'unstaged' })

// Compare feature branch against main
gitnexus_detect_changes({ scope: 'compare', base_ref: 'main' })

The CLI handler in src/cli/eval-server.ts formats results as markdown tables for terminal display.

Programmatic API

Integrate directly with the Node.js backend for custom workflows:

import { Backend } from '@gitnexus/mcp'

async function analyzeImpact() {
  const backend = new Backend()
  const result = await backend.callTool('detect_changes', {
    scope: 'staged'
  })
  
  console.log(`Risk Level: ${result.summary.risk_level}`)
  console.table(result.affected_processes)
}

Interpreting Results

The tool returns a structured JSON object with three top-level keys:

{
  "summary": {
    "changed_count": 3,
    "affected_count": 2,
    "changed_files": 2,
    "risk_level": "medium"
  },
  "changed_symbols": [
    {
      "name": "UserService.login",
      "type": "Function",
      "filePath": "src/auth/userService.ts",
      "change_type": "Modified"
    }
  ],
  "affected_processes": [
    {
      "id": "proc-42",
      "name": "UserLogin",
      "process_type": "workflow",
      "step_count": 7,
      "changed_steps": [
        { "symbol": "UserService.login", "step": 3 }
      ]
    }
  ]
}

The changed_steps array provides precise traceability, indicating exactly which symbol impacts which step in each process. This enables targeted code reviews and selective context gathering via complementary GitNexus tools.

Summary

  • The detect_changes tool in GitNexus executes a three-stage pipeline: git diff construction, file-to-symbol mapping via knowledge graph queries, and process tracing through STEP_IN_PROCESS relationships.
  • Safety mechanisms include execFileSync with array arguments to prevent shell injection, and a LIMIT 20 clause on symbol lookups to control resource usage.
  • Risk assessment categorizes impact as low, medium, high, or critical based on the count of distinct affected processes (0, ≤5, ≤15, >15 respectively).
  • Precise traceability is achieved through the changed_steps array, which records exactly which symbol affects which step in each impacted process.

Frequently Asked Questions

How does the detect_changes tool handle different git states like staged vs unstaged files?

The tool accepts a scope parameter that supports four distinct values: unstaged (default), staged, all, and compare. Based on the scope, the tool constructs the appropriate git diff command—using --staged for staged changes, HEAD for all changes since the last commit, or a specific base_ref for comparison scenarios. This logic is implemented in the switch statement within src/mcp/local/local-backend.ts lines 52-68.

What Cypher queries does the detect_changes tool use to find affected processes?

The tool executes two primary Cypher query patterns against the Neo4j knowledge graph. First, it uses MATCH (n) WHERE n.filePath CONTAINS $filePath to locate symbols within changed files, limiting results to 20 per file. Second, for each changed symbol, it queries MATCH (n {id: $nodeId})-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process) to trace STEP_IN_PROCESS relationships and identify exactly which processes contain the modified code and at which step.

How is the risk level calculated in the detect_changes tool?

The risk level is determined by a simple threshold-based heuristic applied to the count of distinct affected processes discovered during analysis. The logic assigns low risk for zero affected processes, medium for 1-5 processes, high for 6-15 processes, and critical for more than 15 processes. This calculation appears in src/mcp/local/local-backend.ts and provides developers with an immediate quantitative sense of change magnitude.

Can the detect_changes tool be used programmatically outside of the CLI?

Yes, the tool exposes a programmatic API through the GitNexus MCP backend. Developers can import the Backend class from @gitnexus/mcp and invoke backend.callTool('detect_changes', { scope: 'staged' }) to receive the structured JSON result containing the summary, changed symbols, and affected processes. This enables integration into custom CI/CD pipelines, pre-commit hooks, or automated testing workflows without requiring CLI interaction.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →