GitNexus Knowledge Graph Engine

repository·main·Indexed 12 days ago

https://github.com/abhigyanpatwari/gitnexus

A knowledge graph engine for codebases that provides architectural context to AI agents via Model Context Protocol (MCP) tools. It indexes dependencies, call chains, and clusters to prevent breaking changes. Includes an evaluation harness for SWE-bench, an eval-server for fast tool responses, and specialized skills like gitnexus-plan for engineering planning and gitnexus-work for executing verified atomic commits.

Tokens
147.8K
Snippets
337
Records
591
Agent score
99%

What's inside GitNexus

  1. Understand Swift ingestion limitations in GitNexus

    main

    GitNexus tracks known gaps in its Swift ingestion pipeline, which can affect how accurately the knowledge graph represents Swift codebases. These gaps are categorized by priority (High, Medium, Low) and impact different aspects of code understanding such as Type Inference, Call Resolution, Symbol Extraction, Inheritance, and Module Imports.

    High Priority Gaps

    • Type Inference: Issues with if let / guard let inside for-loop bodies (unresolved calls inside for item in collection) and while let bindings.
    • Call Resolution: Difficulties with await expr / try expr wrappers, multi-hop chains (e.g., a.b.c()), and trailing closures where $0 type is not inferrable.

    Medium Priority Gaps

    • Symbol Extraction: Missing support for Enum case as callables, subscript declarations, operator overloads, deinit, and Swift 5.9+ macros.
    • Heritage / Inheritance: Incomplete tracking of multiple inheritance specifiers, generic constraints, conditional conformance, and protocol composition.
    • Export / Visibility: Nested function declarations may be incorrectly marked as exported.
    • Module / Import: @testable import, cross-package SPM imports, and @_exported import are not fully tracked.

    Low Priority Gaps

    • Type Inference: switch/case pattern binding, tuple destructuring, and SwiftUI-specific patterns like @Environment or @Query.
  2. Understand the GitNexus repository layout

    main

    GitNexus is organized as a monorepo with several distinct packages and directories:

    • gitnexus/: The core npm package. It contains the CLI, the MCP server (stdio), the HTTP API, the ingestion pipeline, the LadybugDB graph, and embeddings logic.
    • gitnexus-web/: A Vite + React client used for the graph explorer and AI chat. It communicates with the backend via the gitnexus serve HTTP API.
    • gitnexus-shared/: Contains shared TypeScript types and constants used by both the CLI and the Web client.
    • eval/: Contains evaluation harnesses for benchmarking tool usage.
    • .claude/, gitnexus-claude-plugin/, gitnexus-cursor-integration/: Contains agent skills and plugin metadata for AI integrations.
    • .github/: Contains CI workflows and composite actions (setup-gitnexus/, setup-gitnexus-web/).
  3. Overview of GitNexus Architecture and Components

    main

    GitNexus is a code intelligence tool that constructs a knowledge graph from source code. It utilizes tree-sitter AST parsing to support 12 different languages and uses KuzuDB for graph storage.

    The project is split into two primary packages:

    • gitnexus/: The core package containing the CLI and MCP (Model Context Protocol) server, written in TypeScript.
    • gitnexus-web/: The browser-based interface.

    The ingestion pipeline follows a specific sequence of phases: structureparsingimportscallsheritageprocessestype resolution.

  4. Follow Reread Rules to avoid redundant queries

    main

    To maintain efficiency, do not repeat a query or reread a source range unless one of the following conditions is met:

    1. Incompleteness: The previous result was insufficient for the current question.
    2. Change: The source is known to have changed (e.g., an edit occurred).
    3. Contradiction: Validation revealed a contradiction between the graph and the source.

    Allowed Escalations (not violations):

    • Using summaryOnly: true to perform a full drill-down on an existing impact target.
    • Retrying an ambiguous result once by narrowing with kind, file_path, or uid.
    • Re-running the same tool with a different parameter to answer a new planning question (e.g., running pdg_query with controls and then flows on the same function).

    Note: If you must repeat a query, you must record the reason for the insufficiency in the ledger. A ledger containing near-duplicate queries is considered a failure signal.

  5. How safe plan reading and writing works

    main

    GitNexus uses descriptor-anchored operations to prevent race conditions (like symlink attacks or parent directory swaps) during plan management.

    Safe Reading (read-plan):

    • The helper resolves the repository root and every parent directory of the plan as held, non-following directory descriptors (O_DIRECTORY | O_NOFOLLOW).
    • It verifies that the lexical path still matches the held descriptors before returning the receipt.
    • It is only supported on platforms that can resolve names against held descriptors (Linux via /proc/self/fd or macOS via O_DIRECTORY/O_NOFOLLOW).

    Safe Writing (write-plan):

    • Initial Write: Uses an atomic link(2) to a temporary file. This fails if the destination already exists (EEXIST), ensuring no accidental overwrites.
    • Deepen (Update) Write:
      1. Verifies the existing plan's digest and path against the provided --expected-* arguments.
      2. Atomically moves the existing plan to a backup location in gitnexus-plan-backups/ (within the Git-admin directory).
      3. Publishes the new plan using the atomic no-replace primitive.
    • Backups: If a write fails or a plan is displaced, it is moved to a path like git-path:gitnexus-plan-backups/<random-name>. Use git rev-parse --git-path <path> to resolve these, as they are Git-admin paths, not standard working-tree paths.
  6. How manifest extraction and symbol resolution work

    main

    The ManifestExtractor resolves links defined in group.yaml to create Contract objects and CrossLink edges.

    Symbol Resolution Logic:

    • Existing Symbols: Uses resolveSymbol (label-scoped Cypher) to find the real symbolUid and reference.
    • Missing Symbols: If a symbol is not found, it generates a synthetic UID using the format manifest::repo::cid.

    Label-scoped Querying: To prevent accidental cross-matches, resolveSymbol uses an allowlist form for labels rather than disjunctions. This avoids issues with LadybugDB's parser regarding reserved keywords.

    Supported Label Mappings:

    • topic $\rightarrow$ labels(n) IN ['Function','Method','Class','Interface']
    • grpc/thrift method $\rightarrow$ labels(n) IN ['Function','Method']
    • grpc/thrift service $\rightarrow$ labels(n) IN ['Class','Interface']
    • lib $\rightarrow$ labels(n) IN ['Module']
  7. Understand the gitnexus-work contract with gitnexus-plan

    main

    The interaction between gitnexus-work and gitnexus-plan follows a strict contract:

    • Input: A 13-section plan document. The machine-readable interface is found in §11's implementation_context fields.
    • Evidence Provenance: evidence_provenance is mandatory. The executor loads the plan via a read-plan command that consumes base64 bytes from a receipt to ensure byte-identical integrity. It recomputes the global dirty digest and sorted cited-path manifest.
    • Path Validation: For Schema-2, generated_plan_path must be a normalized repo-relative path (e.g., docs/plans/<date>-gitnexus-plan-<slug>.md). It must match the read receipt's canonical target-repo-relative path byte-for-byte.
    • Drift Handling: If drift invalidates scope, requirements, a key technical decision, or the planned seam, the Deepen process is reserved for resolution.
  8. Understand the `pdg_query` MCP tool and PDG layers

    main

    The pdg_query tool provides access to the Program Dependence Graph (PDG) layers of a repository. These layers are opt-in and must be enabled during indexing using the --pdg flag. If the repository was not indexed with --pdg, the tool will return an empty result set with a note: "no PDG layer …".

    PDG Layers (Build Order)

    All layers are stored as BasicBlock → BasicBlock edges in the CodeRelation table, keyed by the type property:

    1. L1 CFG: Per-function basic blocks and control-flow edges.
    2. L2 REACHING_DEF: Data dependence (GEN/KILL def→use) via a pure solver.
    3. L5 CDG: Control dependence (Ferrante control dependence/post-dominators).

    Note: There is no Function → BasicBlock edge. All edges exist between BasicBlock nodes.

  9. Manage refactoring risks

    main

    When performing large-scale refactors, use these rules to mitigate risk:

    Risk FactorMitigation
    Many callers (>5)Use rename for automated updates instead of manual changes.
    Cross-area refsUse detect_changes after the refactor to verify the actual scope.
    String/dynamic refsUse query to find non-structural references that rename might miss.
    External/public APIVersion and deprecate the old symbol properly rather than just renaming it.
  10. How field and property type resolution works

    main

    GitNexus supports deep chain resolution (up to 3 levels, e.g., user.address.city.getName()) across 10 languages. Key technical components include:

    • SymbolTable fieldByOwner index: Provides $O(1)$ field lookup using the key format ownerNodeId\0fieldName.
    • Edge Types:
      • HAS_PROPERTY: Used on Property symbols with a declaredType.
      • ACCESSES: Tracks read/write field access across 12 languages.
    • Mixed Chains: Supports unified MixedChainStep[] for chains combining fields and methods (e.g., svc.getUser().address.save()).
    • Language Specifics:
      • C++: Captures field_declaration and supports field_expression receivers.
      • Rust: Supports unit struct instantiation.
      • Ruby: Uses YARD @return for attr_accessor.
  11. Prohibitions and constraints in gitnexus-work

    main

    When using the gitnexus-work skill, the following actions are strictly prohibited:

    • Skipping Gates: Never perform a symbol edit without an impact query, and never commit without running detect_changes.
    • Scope Creep: Do not expand the scope beyond the provided plan; follow the deferred follow-ups defined in §12.
    • Plan Mutation: Do not mutate the body of the plan file itself (committing the file verbatim during Phase 2 is allowed, but changing its logic is not).
    • Weakening Tests: Never weaken failing tests to force a pass.
    • Unverified Work: Never present unverified work as verified.
  12. Map Git Status to Evidence States and Renames

    main

    GitNexus maps raw Git porcelain v2 facts into specific state values and handles renames by creating two endpoint facts.

    State Mapping

    • renamed: The standard state for a rename. A rename contributes two endpoints:
      • Old endpoint: path=<old>, rename_from=absent, rename_to=<new>
      • New endpoint: path=<new>, rename_from=<old>, rename_to=absent
    • mixed: Occurs if a worktree-dirty rename destination is used, or if a path has multiple distinct facts (e.g., a staged deletion plus a recreated file).
    • deleted: For a deletion.
    • staged: For index-only changes.
    • unstaged: For worktree-only changes.
    • untracked: For ? status (files existing only outside Git layers).
    • clean: For a path cited outside the dirty set that exists in all layers.
    • absent: For a path where no layer exists.

    Special Path Handling

    • Directory Markers: Git's ? child/ marker has the trailing slash removed during normalization; child is treated as a bounded directory object.
    • Renames: Sorting is determined by the record's position in the sorted path list, not by whether it is the 'old' or 'new' endpoint.