Skip to content

pageel/para-graph

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

264 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Para-Graph Banner

para-graph 🧠

Structural code analysis tool powered by Tree-sitter AST parsing.

πŸ‡ΊπŸ‡Έ English β€’ πŸ‡»πŸ‡³ TiαΊΏng Việt

License: MIT Version 0.17.6.5 Node >= 18 TypeScript 5.x


Table of Contents

🎯 Overview

para-graph is a deterministic code analysis tool that extracts structural information from multi-language codebases and produces a knowledge graph in JSONL format.

It uses Tree-sitter for fast, accurate AST parsing β€” no compiler pipeline required. The output graph captures:

  • Entities β€” classes, functions, interfaces, arrow functions, methods
  • Relationships β€” imports, function calls, inheritance (future)

Part of the PARA Workspace ecosystem.

πŸ›  Requirements / Tech Stack

  • Node.js >= 18.0.0
  • TypeScript 5.x
  • Tree-sitter (native bindings compiled automatically via node-gyp-build)

✨ Features

  • Multi-Language Support β€” TypeScript, TSX, Python 🐍, Bash 🐚, Go 🐹, PHP 🐘
  • Deep CALLS Capture β€” Extracts member call chains, object+method pairs, and constructors
  • Topological Edge Confidence β€” Edge classification (EXTRACTED, INFERRED, AMBIGUOUS)
  • God Nodes Detection β€” Runtime degree analytics (fanIn/fanOut) with SQLite caching to identify architectural choke points
  • Deterministic parsing β€” Tree-sitter AST & Pure SSEC Queries, no LLM heuristics
  • JSONL & SQLite Dual-Backend β€” Robust storage with FTS5 semantic search and fast cold starts
  • Global Workspace Server β€” Serve multiple project graphs simultaneously via MCP
  • Semantic Enrichment β€” Agent-driven context tagging (summary, complexity, domain concepts)
  • Compact Memory β€” Architectural logs consolidated in .beads/graph/ for context retention
  • Fast In-Memory Query Engine β€” Indexed lookups with LRU cache (Max=3 projects)
  • Impact Analysis β€” BFS traversal to find all affected nodes when changing a code entity
  • Context Bundle β€” Get source code, callers, callees, imports, and tests in one MCP call
  • Agentic Edge Resolution β€” Inject missing relationships (e.g., dynamic Bash imports) directly via MCP
  • MCP Auto-Setup β€” Manifest-declared mcp: block enables automatic IDE configuration via ./para mcp-setup
  • Agent Auto-trigger Hooks β€” BeforeTool hooks that nudge the AI Agent to use Knowledge Graph before file scanning
  • Atomic File Structure Snapshots (v0.17.0+) β€” Captures project directory tree snapshots, hashing files (sha256) into SQLite for version tracking.
  • Protected Files Guard (v0.17.0+) β€” Manages protected files list and alerts if any critical files are missing during snapshot verification.
  • Session Context Compaction (v0.17.1+) β€” Scans and compacts active session rules, skills, and project contract, writing a summary to vibecode_session/artifacts/session.md for context recovery.
  • RRF Hybrid Search Scorer (v0.17.1+) β€” Integrates Reciprocal Rank Fusion (RRF) to merge FTS5 keyword results and LIKE similarity matches.
  • Multi-seed Context Retrieval (v0.17.1+) β€” Gathers comprehensive context from multiple seed node IDs with topological distance capping (20 per seed, 50 globally).
  • Profile-Driven Junk Governance (v0.17.6.1+) β€” Auto-detects and classifies untracked or ignored junk files based on profile markers (Astro, TypeScript, CF Workers, Python, PHP) or explicit configuration, categorizing them into 3 safety tiers.

πŸš€ Quick Start

Prerequisite: Make sure you have Node.js (>= 18.0.0) and npm installed on your system. Notice: better-sqlite3 is dynamically installed during setup only for Node < 22 environments to skip native compilation on modern Node versions.

# Clone
git clone https://github.com/pageel/para-graph.git
cd para-graph

# Install
npm install

# Build
npm run build

# Scan a project by name (auto-detects paths)
npx para-graph build my-project

Or run directly without cloning:

npx para-graph build ./src ./output

πŸ“– Usage

CLI Commands

# Scan by project name (auto-detect workspace)
para-graph build <project-name>

# Scan source code and export graph (manual paths)
para-graph build <target-dir> [output-dir] [--clean]

# Inject Graph Data & Validate Drift in Markdown Docs/Plans
para-graph inject <target-dir>

# Take a snapshot of the project directory structure
para-graph project-snapshot <project-name>

# Compare two project snapshots
para-graph project-diff <project-name> <src-snap-id> <tgt-snap-id>

# Start MCP server for AI Agent integration
para-graph serve [workspace-root]

# Manage BeforeTool hooks
para-graph hooks install
para-graph hooks uninstall
para-graph hooks status

# Show help
para-graph --help

Hooks Command

The hooks command manages BeforeTool hooks that automatically nudge your AI Agent to use the Knowledge Graph instead of scanning files blindly.

# Install hook into ~/.gemini/settings.json
para-graph hooks install

# Check current hook status
para-graph hooks status

# Remove hook and restore original settings
para-graph hooks uninstall

How it works:

  1. para-graph build generates the Knowledge Graph
  2. para-graph hooks install injects a BeforeTool hook into Gemini CLI settings
  3. On the next file access, the Agent receives a context nudge: "Knowledge Graph is available β€” use MCP tools first"
  4. A lock file prevents repeated nudging in the same session
  5. para-graph build automatically resets the lock after graph updates

Build Command

# Basic usage
para-graph build my-project                  # Shorthand (recommended)
para-graph build ./src                       # Output to ./output/
para-graph build ./src ./my-graph            # Custom output directory
para-graph build ./src ./out --clean        # Wipe existing graph, scan from scratch
Argument Required Default Description
project-name βœ… (or target-dir) β€” Name of project in workspace (auto-resolves repo/ and .beads/graph/)
target-dir βœ… (or project-name) β€” Directory containing supported source files
output-dir β€” ./output Where to write the graph output
--clean β€” β€” Do not load existing graph, overwrite and scan from scratch

Serve Command

# Start MCP server (stdio transport)
para-graph serve /path/to/workspace

# Or let it auto-detect the workspace root (if inside one)
para-graph serve

🧠 Graph Enrichment Strategy (The 20% Rule)

para-graph supports AI-driven semantic enrichment, but you should NOT enrich 100% of the graph nodes. We strictly recommend the 20% Rule (Compact Memory Rule):

  1. Focus on God Nodes: Only enrich the top 10-20% of structural nodes that orchestrate logic (high degree/fan-in/fan-out) and core domain entities.
  2. Signal-to-Noise Ratio: Simple getters, setters, utilities, and test fixtures should rely entirely on Tree-sitter AST and their names. Enriching them bloats the context window and wastes tokens.
  3. Semantic Drift Protection: By only enriching core architectural hubs (which change less frequently), you reduce the maintenance burden of keeping semantic summaries synced with the source code.
  4. Graph-based Inference: The AI can naturally infer the purpose of small utility functions by observing the CALLS edges connected to a well-enriched God Node.

πŸ’‘ Best Practice: When using the /para-graph workflow's compact action, the system is hardcoded to find and enrich the top 3 God Nodes incrementally per run. Do not attempt to batch-enrich the entire project.

πŸ€– MCP Server Setup

To connect para-graph to an AI Agent editor (like Claude Desktop, Cursor, or Google Antigravity), you need to configure their respective MCP settings.

Auto-Setup (Recommended)

If you are using PARA Workspace v1.8.2+, you can automatically configure the MCP server in your IDE by running:

./para mcp-setup

This will safely detect your active IDE and inject the para-graph MCP server configuration.

Manual Setup (Fallback)

If you prefer to configure the server manually:

Claude Desktop / Antigravity

Edit your claude_desktop_config.json (or mcp_config.json for Antigravity) and add the following:

{
  "mcpServers": {
    "para-graph": {
      "command": "<ABSOLUTE_WORKSPACE_PATH>/cli/para",
      "args": [
        "graph",
        "serve",
        "<ABSOLUTE_WORKSPACE_PATH>"
      ]
    }
  }
}

Note: Replace <ABSOLUTE_WORKSPACE_PATH> with the absolute path to your PARA Workspace root directory.

Cursor

Go to Cursor Settings > Features > MCP Servers > Add New MCP Server:

  • Name: para-graph
  • Type: command
  • Command: <ABSOLUTE_WORKSPACE_PATH>/cli/para graph serve <ABSOLUTE_WORKSPACE_PATH>

Available MCP Tools

Once connected, your AI Agent gains access to the following tools:

  • graph_query: Search entities by name or semantic type.
  • graph_edges: Find function callers and imports connected to a node.
  • graph_enrich: Save semantic documentation, complexity, and domain concepts to a node.
  • graph_impact_analysis: Discover upstream/downstream affected files and nodes (blast radius) when changing code.
  • graph_context_bundle: Get the entire context of a code snippet (source code, callers, callees, imports, tests) in one call. Supports multi-seed node IDs.
  • graph_add_edges: Batch inject edges (CALLS, IMPORTS_FROM) to resolve relationships for weak AST-linking languages (e.g. Bash).
  • graph_god_nodes: Retrieve the most connected nodes in the graph to prioritize AI enrichment.
  • graph_expand_node: Retrieve only the source code for a specific node with AST bounds checking.
  • graph_link_docs: Link documentation markdown files to graph nodes based on anchor tags.
  • insight_push: Push a project insight (lesson, risk, decision, pattern, gotcha) to the database.
  • insight_search: Search project insights using full-text search with metadata filters.
  • insight_validate: Update the confidence lifecycle of a project insight (hypothesis -> validated -> deprecated).
  • memory_push: Push a session event (conversation, decision, error) to the project MemoryStore.
  • memory_search: Full-text search (FTS5) over stored memory events by keyword.
  • memory_curate: Cluster raw events into semantic slices using session-based curation.
  • graph_audit_csa: Run Convergent Specification Architecture (CSA) compliance audit for a project.
  • graph_fix_csa: Run CSA self-healing fix for dangling spec references (auto-replaces drifted spec anchors in code files).
  • project_snapshot: Take a snapshot of the project directory structure, record metadata to SQLite, and verify protected files. Also detects and classifies physical junk files based on active profiles (auditJunk: true), returning both a backward-compatible flat list and a 3-tier safety report.
  • project_diff: Compare two project snapshots to identify added, removed, and modified files (physical drift detection).
  • project_protected_files: List, add, or remove protected files for a project.
  • project_session_compact: Scan rules, skills, and project contract, and write a compacted context summary for agent recovery.
  • project_state_get: Get cached project metadata and task counts from SQLite. Checks freshness against configuration files via MD5 hashes.
  • project_state_sync: Sync and cache project metadata and task counts from config files (project.md, backlog.md, sprint-current.md) into SQLite database.

Library Usage

// Import as a library
import { CodeGraph } from 'para-graph';

// Import MCP server factory
import { createServer } from 'para-graph/mcp';

πŸ“Š Output Format

Three files are generated in the output directory:

entities.jsonl

One code entity per line, sorted by file path:

{"id":"src/graph/code-graph.ts::CodeGraph","type":"class","name":"CodeGraph","filePath":"src/graph/code-graph.ts","startLine":10,"endLine":81,"exportType":"named","signature":"export class CodeGraph {"}

relations.jsonl

One relationship per line, sorted by source file:

{"sourceId":"src/index.ts","targetId":"./parser/file-walker.js","relation":"IMPORTS_FROM","sourceFile":"src/index.ts","sourceLine":3}

metadata.json

Summary statistics:

{
  "version": "0.1.0",
  "nodeCount": 31,
  "edgeCount": 47,
  "fileCount": 6,
  "createdAt": "2026-04-21T03:35:33.508Z"
}

Entity Types

Type Description
file Source file
class Class declaration
function Function, method, or arrow function
interface Interface declaration
variable Variable declaration (future)

Relation Types

Relation Description
IMPORTS_FROM File imports from another module
CALLS Function/method calls another function
INHERITS Class extends another (future)
IMPLEMENTS Class implements interface (future)

πŸ—οΈ Architecture

src/
β”œβ”€β”€ cli.ts                    # Subcommand router (shebang entrypoint)
β”œβ”€β”€ commands/
β”‚   β”œβ”€β”€ build.ts              # Build command β€” scan, parse, export graph
β”‚   β”œβ”€β”€ serve.ts              # Serve command β€” MCP server lifecycle
β”‚   β”œβ”€β”€ inject.ts             # Inject command β€” Living Docs context
β”‚   └── hooks.ts              # Hooks command β€” BeforeTool hook management
β”œβ”€β”€ graph/
β”‚   β”œβ”€β”€ models.ts             # GraphNode, GraphEdge type definitions
β”‚   β”œβ”€β”€ code-graph.ts         # In-memory graph with dual indexing
β”‚   β”œβ”€β”€ jsonl-exporter.ts     # Serialize graph β†’ JSONL files
β”‚   β”œβ”€β”€ jsonl-importer.ts     # Load graph from JSONL files
β”‚   └── graph-store.ts        # LRU cache manager for multi-project graphs
β”œβ”€β”€ mcp/
β”‚   β”œβ”€β”€ server.ts             # MCP server factory (pure library export)
β”‚   β”œβ”€β”€ tools.ts              # MCP tools: query, edges, enrich, impact_analysis, context_bundle, add_edges
β”‚   └── resources.ts          # MCP resources: JSONL file access
β”œβ”€β”€ parser/
β”‚   β”œβ”€β”€ registry.ts           # Language Registry (lazy-loads parsers by extension)
β”‚   β”œβ”€β”€ tree-sitter-parser.ts # AST parsing and SSEC mapping engine
β”‚   └── file-walker.ts        # Recursive multi-language file scanner
└── queries/
    β”œβ”€β”€ typescript.scm        # SSEC query patterns for TS/TSX
    β”œβ”€β”€ python.scm            # SSEC query patterns for Python
    β”œβ”€β”€ go.scm                # SSEC query patterns for Go
    β”œβ”€β”€ php.scm               # SSEC query patterns for PHP
    └── bash.scm              # SSEC query patterns for Bash

Data Flow

Source files β†’ File Walker β†’ Registry Lookup β†’ Tree-sitter Parser + SSEC Query β†’ CodeGraph (in-memory) β†’ JSONL Export
                                                                                       β”‚
                                                                                 GraphStore (LRU)
                                                                                       β”‚
                                                                                 MCP Server β†’ AI Agent

Installed Directory Structure & Integration

When you run ./para install-tool para-graph, the tool is installed and distributes its components across 4 different areas in the PARA Workspace:

workspace-root/
β”œβ”€β”€ .para/tools/graph/              # [Area A] Tool Engine Core
β”‚   β”œβ”€β”€ dist/                       # Compiled JavaScript files
β”‚   β”‚   β”œβ”€β”€ cli.js                  # Main CLI Router
β”‚   β”‚   └── mcp/server.js           # MCP Server Core
β”‚   β”œβ”€β”€ package.json                # Runtime dependencies and version
β”‚   β”œβ”€β”€ tool.manifest.yml           # Manifest declaring agent assets
β”‚   └── install-hooks.sh            # Post-install hook script
β”‚
β”œβ”€β”€ Resources/references/para-workspace/cli/commands/graph.sh  # [Area B] CLI Shell Wrapper (or Projects/para-workspace/repo/... in dev profile)
β”‚
β”œβ”€β”€ .agents/                        # [Area C] Agent Intelligence
β”‚   β”œβ”€β”€ workflows/para-graph.md     # Graph operation workflow
β”‚   β”œβ”€β”€ skills/para-graph/          # Skill for AI Agent interactions
β”‚   β”œβ”€β”€ skills/csa/                 # Skill for CSA compliance auditing
β”‚   β”œβ”€β”€ rules/graph-first-policy.md # Rule enforcing graph queries
β”‚   └── rules/csa-compliance.md     # Rule enforcing CSA double-binding
β”‚
└── ~/.gemini/antigravity-ide/knowledge/  # [Area D] Knowledge Items (IDE Context Store)
    β”œβ”€β”€ para_graph_architecture/    # Architecture documentation for AI
    β”œβ”€β”€ para_graph_mcp_tools/       # MCP tools usage instructions
    └── para_graph_workflows/       # CLI commands catalog

Area Description

  • A. Engine Core (.para/tools/graph/): The actual executable code of the tool, extracted from the release tarball.
    • No Source Code (src/): TypeScript source files are omitted. Only compiled JavaScript files exist in dist/ for zero-overhead runtime.
    • install-hooks.sh: Auto-runs after extraction to trigger dependency installation, synchronize Knowledge Items, and register the MCP server in the IDE configuration.
  • B. CLI Wrapper (cli/commands/graph.sh): Sourced by the main para script. In production, this wrapper is generated at Resources/references/para-workspace/cli/commands/graph.sh. On developer environments with the dev profile active, it installs into Projects/para-workspace/repo/cli/commands/graph.sh instead. When you run ./para graph build ..., this wrapper maps to node .para/tools/graph/dist/cli.js build ... to execute the engine.
  • C. Agent Intelligence (.agents/): Copied from the tool templates to empower the IDE's AI Agent with commands (/para-graph), skills, and rules.
  • D. Knowledge Items (~/.gemini/.../knowledge/): Markdown-based context files synchronized to the IDE storage. They provide the AI Agent with immediate awareness of the code graph's architecture, tools, and commands.

πŸ› οΈ Development

# Install dependencies
npm install

# Run in development
npm run dev

# Build TypeScript
npm run build

# Run tests
npm run test

Tech Stack

Component Technology
Runtime Node.js β‰₯ 18
Language TypeScript 5.x (strict mode)
AST Parser tree-sitter + tree-sitter-typescript
Test Runner Vitest
Dev Runner tsx

🧠 AI Intelligence (PARA Workspace)

This tool ships AI intelligence artifacts that enhance the PARA Workspace agent experience. When installed via ./para install-tool para-graph, these artifacts are automatically fetched from GitHub and installed into your workspace's .agents/ directory:

Type Name Version Description & Usage
Workflow /para-graph 2.0.1 Type @[/para-graph] to instruct the AI to re-scan and update the graph memory.
Skill para-graph 2.5.0 Centralized Graph Intelligence Router. Loaded on-demand for workflows like /plan, /docs, /brainstorm to provide graph enrichment and architecture validation.
Skill csa 1.1.0 Global Convergent Specification Architecture (CSA) skill for workspace-wide verification and documentation quality gates.
Rule graph-first-policy 1.1.0 Enforces graph-first development practices. The agent will proactively query the MCP server before making architecture decisions.
Knowledge Item para_graph_architecture β€” Describes the core architecture of the hybrid code-knowledge graph, nodes and edges schemas, and directory layout inside the .beads/graph/ folder.
Knowledge Item para_graph_mcp_tools β€” Instruction guide on using MCP tools (graph_query, graph_context_bundle, etc.) to query and interact with the code graph.
Knowledge Item para_graph_workflows β€” Guides on integrating para-graph CLI commands (build, serve, link) with the PARA workspace workflows.

v0.12.0+: AI Intelligence is no longer bundled in the tarball. It is fetched on-demand from GitHub via the post_install() hook. Update independently: ./para install-tool para-graph --sync.

Requires PARA Workspace v1.8.5+ for automatic template sync.

πŸ—ΊοΈ Roadmap

Phase Description Status
P1 Structural Base (Tree-sitter AST) βœ… Done
P2 Semantic Enrichment (Agent-Driven) βœ… Done
P3 Storage & Query Engine βœ… Done
P4 CLI Integration & NPM Package βœ… Done
P5 Multi-language Support & Query Refactor βœ… Done
P6 Impact & Context Queries βœ… Done
P7 Agentic Bash Edge Resolution βœ… Done
P8 Deep CALLS + Pattern Detection βœ… Done
P9 Edge Resolution & Topology Analytics βœ… Done
P10 Agent Auto-trigger (Hook Injection) βœ… Done
P11 Compact Memory βœ… Done
P12 SQLite Storage Engine (Dual Backend) βœ… Done
P13 Freshness-Aware Memory βœ… Done
P14 Schema Evolution + Code Search πŸ“‹ Planned
P-Vis Graph Visualization MVP πŸ“‹ Planned
PX Documentation & Stable Release (v1.0.0) πŸ“‹ Planned

πŸ“„ License

MIT

About

🧠 para-graph is a deterministic code analysis tool that extracts structural information from multi-language codebases and produces a knowledge graph in JSONL format.

Resources

License

Stars

3 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors