Why KiroGraph

KiroGraph is a semantic code knowledge graph built specifically for Kiro. It gives Kiro a pre-indexed understanding of your codebase: symbol relationships, call graphs, type hierarchies, impact radius, so it can answer complex questions in a single MCP tool call instead of cascading through file reads, greps, and globs.

The problem

When an AI coding agent works on a complex task, it explores your codebase one tool call at a time: read a file, grep for a symbol, glob for related files, read another file. Each of those burns context window and adds latency. On large codebases this becomes the bottleneck: not the reasoning, but the exploration.

The approach

KiroGraph parses your entire codebase with tree-sitter, extracts symbols and their relationships into a local SQLite graph database, and optionally generates vector embeddings for natural-language search. The result is a structured knowledge graph that can answer "who calls this function?", "what breaks if I change this?", or "find code related to authentication" in milliseconds, without reading a single file.

Why Kiro

KiroGraph is designed around Kiro's architecture:

This tight integration is why Kiro is the primary and fully supported target. The hooks, steering, and agent config are all Kiro-native concepts that make the experience seamless.

Scope and other tools

The core of KiroGraph (the graph database, tree-sitter parsing, MCP server, and CLI) is tool-agnostic. Any MCP-capable client can query the same graph. Experimental integrations for 33 other tools are available via kirograph install --target <name>, but they lack the automatic sync hooks and steering that make the Kiro experience seamless. See Other Tools for the full list.

When run without --target, kirograph install auto-detects which AI coding tools are installed on your system and offers to configure them all in one pass.

Issues and PRs for non-Kiro targets are welcome, but there is no guarantee they will be supported or merged without active help from the contributor. The project's development focus remains on the Kiro integration.

Installation

From npm

npm install -g kirograph

From source

git clone https://github.com/davide-desio-eleva/kirograph.git
cd kirograph
npm install
npm run build
sudo npm install -g .

After building, both kirograph and the short alias kg are available globally.

Verify

kirograph --version

Uninstalling

# Remove from a project
kirograph uninit [path]      # prompts to remove integration files and .kirograph/ data
kirograph uninit --force     # remove everything without confirmation

# Remove the CLI globally (npm)
npm uninstall -g kirograph

# Remove the CLI globally (from source)
cd kirograph && npm uninstall -g .

Quick Start

Run this inside any project you want to index:

kirograph install              # auto-detects platforms, interactive setup
kirograph install --all        # auto-detect + install all without prompting
kirograph install --target kiro   # install for a specific platform only

Without --target, the installer auto-detects which AI coding tools are installed (Kiro, Cursor, Claude Code, Windsurf, etc.) and offers to configure them all. Then it prompts you for:

Then restart Kiro IDE (or run kiro-cli --agent kirograph). Kiro will now use KiroGraph tools automatically whenever you ask it to work on your code.

Tip: You can also use the short alias kg install.

Feature Comparison

KiroGraph combines features from 9 separate open-source projects (160k+ combined ⭐) into a single integrated MCP server.

Code Graph & Analysis

FeatureKiroGraphCodeGraphCRGjMunchtokensave
Tree-sitter AST parsing
Symbol search (FTS)
Call graph (callers/callees)
Impact/blast radius
Type hierarchy traversal
Circular dependency detection
Dead code detection
Hotspot/hub detection
Execution flow tracing
Community/cluster detection
Edge confidence scoring
Framework-aware routes✅ (14+)✅ (14)
Trace (path between symbols)
Mixed iOS/RN bridging

Architecture & Refactoring

FeatureKiroGraphCodeGraphCRGtokensave
Package graph
Layer detection
Coupling metrics (Ca/Ce/instability)
Refactoring suggestions
Rename preview

🔒 Security (opt-in: enableSecurity: true)

None of the compared MCP tools include dependency vulnerability scanning. The relevant comparison for this module is against dedicated SCA tools — see the security section for configuration and CLI reference, or the table below for a direct SCA comparison.

FeatureKiroGraphCodeGraphCRGjMunchcavememrtktokensave
Dependency vulnerability scanning
OSV vulnerability database
Batch OSV queries (1000 deps/request)
Call-graph reachability analysis
Combined risk score (CVSS + EPSS + reachability + staleness)
Architecture-layer impact (affected layers)
CycloneDX 1.5 SBOM export
CycloneDX 1.5 VEX export
Fix suggestions per ecosystem
EPSS exploitation probability
License compliance (SPDX + policy)
Dependency staleness score
Dashboard security overlay
CVE suppression list
Manual CVE registration
Queryable via MCP by AI agents
Call-graph attack surface mapping
Secrets detection with blast radius
SAST-lite (SQL injection, eval, path traversal)
AST-based SAST (ast-grep patterns)✅ opt-in
Live structural code search (kirograph_live_search)✅ opt-in
Supply chain health (OpenSSF Scorecard)
Dependency confusion detection
Remediation SLA tracking
CI/CD SARIF export (GitHub Security tab)
OWASP Top 10 mapping

KiroGraph-Sec vs dedicated SCA tools

ToolReachabilitySBOM/VEXEPSSLicenseStalenessMCPFreeEcosystems
KiroGraph-Sec✅ call-graph✅ CycloneDX 1.514
Trivy✅ CycloneDX10+ (+ OS)
Grype✅ via Syft10+
OWASP Dep-Check✅ CycloneDX8+
npm auditnpm only
Snyk✅ (paid)✅ (paid)10+
Dependabot10+

KiroGraph-Sec uses the call graph already built from code indexing to determine whether vulnerable code is actually reachable from entry points — not just present as a transitive dependency. It is the only free SCA tool with EPSS scoring, license policy enforcement, and staleness tracking across 14 ecosystems.

Semantic Search & Memory

FeatureKiroGraphCodeGraphCRGcavememlean-ctxEngramtokensave
Vector embeddings
9 pluggable semantic engines
Custom HuggingFace models
Embedding compression 20–30× (TurboQuant)✅ (v0.21.0)
SIMD-accelerated ANN (TurboVec/Rust)✅ (v0.23.0)
Persistent cross-session memory
Observations linked to symbols
Conflict detection (relations)✅ (v0.24.0)
Stale observation review✅ (v0.24.0)
Passive learning capture✅ (v0.24.0)
Stable topic key✅ (v0.24.0)
Session synthesis / workspace briefs✅ (v0.20.0)
Compressed storage
Zero LLM tokens on write
FTS search
Cloud / git sync
Knowledge graph (temporal facts)
Property graph (code edges)

Documentation & Data

FeatureKiroGraphCodeGraphCRGjMunchtokensave
Documentation indexing✅ (9 formats)✅ (8+)
Section-level retrieval
Code ↔ docs cross-references
Tabular data querying
CSV/JSON/Excel/Parquet
PDF indexing (page-level)✅ (v0.22.0)
Server-side aggregations

Token Optimization

FeatureKiroGraphCodeGraphCRGcavemanrtklean-ctxheadroomtokensave
Shell output compression✅ (kirograph_exec)✅ (20+)✅ (56 modules)
Agent prose compression✅ (lite/full/ultra)
On-demand compression (any text)✅ (kirograph_compress)✅ (CCR core)
File read caching✅ (kirograph_read)✅ (~13 tokens)
CCR (retrieve cached content)✅ (kirograph_retrieve)
KV cache prefix stability✅ (stable markers)
Multiple read modes (map/sig/diff)✅ (kirograph_read)✅ (10 modes)
Token analytics/tracking✅ (dashboard)
Context budget/governance✅ (kirograph_budget)
Estimated context savings
Reproducible benchmarks✅ (per-call metrics)

Integration & Platform Support

FeatureKiroGraphCodeGraphCRGjMunchcavememrtklean-ctxtokensave
MCP server (stdio)✅ (62 tools)
Multi-platform targets✅ (34)✅ (7)✅ (13)✅ (any)✅ (28+)
Auto-detection
Auto-sync hooks
Interactive visualization✅ (dashboard)
Graph export (GraphML/Cypher/Obsidian)
100% local (no API keys)

Language & Framework Support

FeatureKiroGraphCodeGraphCRGjMunchtokensave
Languages supported33+2230+20+50+
Framework detection✅ (26)✅ (14)
Route extraction✅ (14+)✅ (14)

How Indexing Works

Indexing has six layers: structural (always on), semantic (opt-in), architecture (opt-in), documentation (opt-in), data (opt-in), and security (opt-in).

Structural layer

tree-sitter parses every source file into an AST. Nodes and edges are extracted and written to .kirograph/kirograph.db. This powers all graph traversal tools and exact/FTS symbol search. No extra dependencies. Runs on every kirograph index or kirograph sync.

Extracts 26 node kinds: function, method, class, interface, struct, trait, protocol, enum, type_alias, property, field, variable, constant, enum_member, parameter, import, export, route, component, file, module, namespace, dependency, vulnerability, and more.

13 edge types: calls, imports, exports, extends, implements, contains, references, instantiates, overrides, decorates, type_of, returns, uses.

Semantic layer (opt-in)

When enableEmbeddings: true, KiroGraph generates 768-dimensional vector embeddings for every embeddable symbol using nomic-ai/nomic-embed-text-v1.5 (~130 MB, downloaded once to ~/.kirograph/models/). Powers natural-language search in kirograph_context.

Nine pluggable semantic engines:

EngineStoreSearch typeExtra deps
cosine (default)kirograph.dbExact cosine, linear scannone
turboquant.kirograph/turboquant.binANN, sub-linearturboquant-js (pure JS)
turbovec.kirograph/turbovec.tvim + .tvim.idsANN, sub-linearnapi-rs native addon (Rust build, auto-built by installer)
sqlite-vec.kirograph/vec.dbANN, sub-linearbetter-sqlite3, sqlite-vec
orama.kirograph/orama.jsonHybrid (full-text + vector)@orama/orama
pglite.kirograph/pglite/Hybrid, exact (WASM pgvector)@electric-sql/pglite
lancedb.kirograph/lancedb/ANN, sub-linear@lancedb/lancedb
qdrant.kirograph/qdrant/ANN (HNSW), sub-linearqdrant-local
typesense.kirograph/typesense/ANN (HNSW), sub-lineartypesense

Architecture layer (opt-in)

When enableArchitecture: true, KiroGraph detects packages and architectural layers (api, service, data, ui, shared) and computes coupling metrics (Ca, Ce, instability) between them. Results stored in arch_* tables in kirograph.db.

Documentation layer (opt-in)

When enableDocs: true, KiroGraph indexes project documentation by heading hierarchy and section structure. Instead of reading entire doc files, agents retrieve exactly the section they need via stable section IDs.

Supports 9 formats: Markdown (.md, .mdx, .cheatmd), reStructuredText (.rst), AsciiDoc (.adoc), RDoc (.rdoc), Org-mode (.org), HTML (.html), plain text (.txt), and OpenAPI/Swagger specs (content-detected in .yaml/.json files).

Sections are cross-referenced to code symbols via backtick detection, CamelCase/snake_case pattern matching, and stored as doc_code_refs using stable qualified_name keys.

Data layer (opt-in)

When enableData: true, KiroGraph indexes tabular data files and documents (CSV, TSV, JSONL, JSON, Excel, Parquet, PDF) that live alongside your code. Instead of reading raw data files into context, agents query structured schemas and filtered rows — saving 95–99% of tokens.

Supports 7 formats: CSV/TSV (built-in, streaming), JSONL/NDJSON (built-in), JSON arrays (built-in), Excel .xlsx/.xls (optional dep: xlsx), Parquet (optional dep: parquetjs-lite), PDF (optional dep: @firecrawl/pdf-inspector, prebuilt Rust binary). PDFs are page-indexed: each page becomes a row with content (markdown), needs_ocr, has_tables, and has_columns columns. Scanned pages are flagged rather than skipped.

Each dataset is profiled with column types, cardinality, null rates, min/max, sample values, and auto-generated NL summaries. Data files are cross-referenced to code symbols via path detection (readFileSync, pd.read_csv, SQL COPY FROM, pdfplumber.open, etc.) and stored as data_code_refs.

Context token budget per module

Every enabled tool is registered in the model context on each MCP call. The full tool list costs ~5,290 tokens with all flags enabled; enabling only the modules you need cuts this proportionally.

FlagTools~Tokens
core (always-on)3~170
enableNavigation3~120
enableMemory16~746
enableSecurity15~675
enableData10~519
enableWiki10~319
enableCodeHealth25~935
enableDocs5~241
enableAgentUtils4~278
enableArchitecture5~205
enableWatchmen3~140
enablePatterns3~93
trackCallSites2~84
enableGitContext7~410
enableComplexity5~660
enableEditPrimitives5~280
enableBranch3~300
enableShellExec1~71
enableGeneralCompression1~68
Total (all flags)126~6,240

Supported Languages

General-purpose

LanguageExtensions
TypeScript.ts
JavaScript.js
TSX.tsx
JSX.jsx
Python.py
Go.go
Rust.rs
Java.java
C.c, .h
C++.cpp, .cc, .cxx, .hpp
C#.cs
PHP.php
Ruby.rb
Swift.swift
Kotlin.kt
Dart.dart
Scala.scala, .sc, .sbt
Lua.lua
Zig.zig, .zon
Bash.sh, .bash, .zsh
OCaml.ml, .mli
Elm.elm
Objective-C.m
Julia.jl
R.r
Perl.pl, .pm
PowerShell.ps1, .psm1, .psd1
SQL.sql
GDScript.gd
Nix.nix
Verilog / SystemVerilog.v, .sv, .svh
Jupyter Notebook.ipynb (Python cells via tree-sitter)

Frontend & UI

LanguageExtensions
React / React Native.tsx, .jsx (via TypeScript/JSX grammars)
Next.js.tsx, .jsx (via TypeScript/JSX grammars)
Angular.ts, .html (via TypeScript/HTML grammars)
Svelte.svelte
Vue.vue
Astro.astro
ReScript.res, .resi
HTML.html, .htm
CSS.css
SCSS / Sass.scss, .sass

Domain-specific

LanguageDomainExtensions
SolidityBlockchain / Web3.sol
ElixirDistributed systems / Real-time.ex, .exs

Configuration & Infrastructure

LanguageExtensions
YAML.yaml, .yml
HCL (Terraform).tf, .tfvars

Framework Detection

KiroGraph auto-detects frameworks and enriches the graph with framework-specific semantics (routes, components, lifecycle methods).

Web Frameworks

LanguageFrameworks
JavaScript / TypeScriptReact, Next.js, React Native, Angular, Svelte, SvelteKit, Express, Fastify, Koa
VueVue, Nuxt
PythonDjango, Flask, FastAPI
RubyRails
JavaSpring, Spring Boot, Spring MVC
ScalaPlay, Akka HTTP, http4s
GoGeneric Go resolver
RustGeneric Rust resolver
C#ASP.NET Core
SwiftSwiftUI, UIKit, Vapor
DartFlutter (layer detection, widget classification as component, route extraction from MaterialApp / GoRouter / AutoRoute, Method Channel bridge)
PHPLaravel
ElixirPhoenix
SolidityHardhat, Foundry, Truffle (OpenZeppelin patterns)

Infrastructure as Code

ToolDetection
AWS CDKcdk.json or aws-cdk-lib in deps
SSTsst.config.ts or sst in deps
Serverless Frameworkserverless.yml or serverless.ts
AWS SAMtemplate.yaml with AWS::Serverless
Terraform / OpenTofu.terraform/ or .tf files
PulumiPulumi.yaml or @pulumi/* deps
CloudFormationAWSTemplateFormatVersion in template
AWS Amplify Gen 2amplify/backend.ts or @aws-amplify/backend in deps

Containers & Orchestration

ToolDetection
Kubernetes / HelmChart.yaml or K8s manifest directories
Docker Composedocker-compose.yml or compose.yaml

Configuration Management

ToolDetection
Ansibleansible.cfg or standard role directory structure

Detected frameworks are stored in config and used to improve symbol extraction and resolution. Routes, components, and lifecycle methods are extracted as first-class nodes in the graph.

Using with Kiro

kirograph install sets up four things in your Kiro workspace. All coexist, so you can switch between IDE and CLI freely. Kiro is the primary and fully supported target.

MCP Server (.kiro/settings/mcp.json)

Registers the KiroGraph MCP server with all 20 tools auto-approved. Used by both the IDE and the CLI agent.

{
  "mcpServers": {
    "kirograph": {
      "command": "kirograph",
      "args": ["serve", "--mcp"],
      "autoApprove": [
        "kirograph_search", "kirograph_context", "kirograph_callers",
        "kirograph_callees", "kirograph_impact", "kirograph_node",
        "kirograph_status", "kirograph_files", "kirograph_dead_code",
        "kirograph_circular_deps", "kirograph_path", "kirograph_type_hierarchy",
        "kirograph_architecture", "kirograph_coupling", "kirograph_package",
        "kirograph_hotspots", "kirograph_surprising", "kirograph_diff",
        "kirograph_exec", "kirograph_gain"
      ]
    }
  }
}

IDE Hooks (.kiro/hooks/)

Up to three hooks are installed (.kiro.hook extension):

Hook fileEventTypeBehavior
kirograph-sync-if-dirty.kiro.hookagentStoprunCommandRuns kirograph sync --quiet when the agent stops. Skips unchanged files via content hashing, so it's fast even when nothing changed.
kirograph-compress-hint.kiro.hookpreToolUse (shell)askAgentReminds the agent to use kirograph_exec for commands that benefit from token compression. Only installed when shell compression is enabled.
kirograph-mem-capture.kiro.hookagentStopaskAgentPrompts the agent to store important observations (decisions, errors, patterns) in memory at the end of each session. Only installed when memory is enabled.

The sync hook replaces the previous per-file approach (mark-dirty-on-save, mark-dirty-on-create, sync-on-delete). A single agentStop hook handles all file changes in one pass with zero overhead during active editing.

Global Hook Library (~/.kirograph/hooks/)

Personal Kiro hooks can be saved outside any project and reused across workspaces:

CommandAction
kirograph hook save [path]Copy hooks from .kiro/hooks/ to ~/.kirograph/hooks/ (overwrites same filename)
kirograph hook import [path]Copy global hooks into .kiro/hooks/
kirograph hook listList saved global hooks (display name and description)

During interactive kirograph install --target kiro (no --yes), if the global store is non-empty, the installer adds a Hooks step (after Agent Behavior, before Memory) to import global hooks (None, All, or Select specific hooks). Selected hooks are copied after bundled KiroGraph hooks are written. Use kirograph hook import for a standalone import outside install.

CLI Agent Config (.kiro/agents/kirograph.json)

A custom agent for Kiro CLI that wires up the MCP server and references the steering file as a resource. Sync is handled at session boundaries:

EventAction
agentSpawnkirograph sync-if-dirty --quiet (catches edits made between sessions)
userPromptSubmitkirograph sync-if-dirty --quiet (keeps graph fresh within a session)
stopkirograph sync-if-dirty --quiet (deferred flush, mirrors IDE agentStop)

The CLI agent format only supports command hooks (shell commands), not askAgent prompts. Memory capture and compression hints are handled via the steering file instructions instead — the agent reads them from .kiro/steering/kirograph.md which is referenced as a resource.

kiro-cli --agent kirograph
# or, inside an active session:
/agent swap kirograph

Steering File (.kiro/steering/kirograph.md)

Always-active (inclusion: always). Teaches the Kiro IDE to prefer graph tools over file scanning. Includes a quick decision guide and — when enabled — dedicated sections for memory, documentation, data, and security tools. The CLI agent has the same instructions inlined in its prompt field.

Workflow Steering Files (inclusion: manual)

KiroGraph installs 5–6 task-specific steering files alongside the main one. These use inclusion: manual — they are not always active. Kiro loads them on demand when you mention the workflow in your prompt, or when you explicitly invoke them.

How to activate

Available workflow files

FileInvoke withWhen to use
kirograph-review.md/kirograph-reviewStructured code review — blast radius, test coverage, coupling analysis
kirograph-debug.md/kirograph-debugSystematic debugging — trace calls, check recent changes, find root cause
kirograph-architecture.md/kirograph-architectureArchitecture exploration — packages, layers, coupling metrics, cycles
kirograph-onboard.md/kirograph-onboardOnboarding a new codebase — structure, entry points, key symbols
kirograph-refactor.md/kirograph-refactorSafe refactoring — blast radius, rename preview, verify changes
kirograph-security.md/kirograph-securitySecurity audit — CVE triage, EPSS prioritization, reachability deep-dive, license compliance, staleness check, SBOM/VEX export (written only when enableSecurity: true)

All workflow files follow the same structure: numbered steps with exact tool calls and parameters, an interpretation reference table, and tips. They are self-contained — no additional context needed.

Other Tools (Experimental)

⚠️ Community-contributed, vibecoded, unverified. These integrations are provided as-is. PRs welcome for fixes and corrections.

KiroGraph can be installed for any MCP-capable coding agent. All targets share the same .kirograph/ data — installing another target only writes that tool's integration files and reuses the existing graph.

How It Works

Every target does two things:

  1. Registers the MCP server — writes a config file that tells the tool to launch kirograph serve --mcp as a stdio MCP server.
  2. Injects agent instructions — writes a rules/instructions file that teaches the agent to prefer graph tools over grep/glob when .kirograph/ exists.

Supported Targets (33)

ToolTargetMCP ConfigInstructionsHooksPattern
🎯 Kiro (primary)kiro.kiro/settings/mcp.jsonSteering + CLI agent✅ sync + hint + memoryFull
Cursorcursor.cursor/mcp.json.cursor/rules/kirograph.mdc✅ sync on stopA
GitHub Copilotcopilot.github/copilot-mcp.json.github/copilot-instructions.md✅ sync on session-endA
Roo Coderoo.roo/mcp.json.roo/rules/kirograph.mdA
JetBrains Juniejunie.junie/mcp/mcp.json.junie/AGENTS.mdA
Continuecontinue.continue/mcpServers/kirograph.json.continue/rules/kirograph.mdA
Warpwarp.warp/.mcp.jsonAGENTS.mdA
Traetrae.trae/mcp.json.trae/rules/kirograph.mdA
Augment Codeaugment.augment/mcp.jsonaugment-guidelines.mdA
Sourcegraph Ampamp.amp/config.json.amp/instructions.mdA
Tabninetabnine.tabnine/mcp.json.tabnine/instructions.mdA
Claude Codeclaude.mcp.jsonCLAUDE.md✅ sync on StopB
Codex CLIcodex.codex/hooks.jsonAGENTS.md✅ sync on StopB
Gemini CLIgemini-cli.gemini/settings.jsonGEMINI.md✅ SessionEndC
OpenCodeopencode.opencode.json.opencode.json (instructions)✅ pluginC
Kilo Codekilokilo.json.kilo/rules/kirograph.mdC
Devindevin.devin/config.jsonAGENTS.md✅ .devin/hooks.v1.jsonC
OpenHandsopenhands.openhands/config.jsonAGENTS.mdC
WindsurfwindsurfPrint command.windsurf/rules/kirograph.md✅ sync on responseD
ClineclinePrint command.clinerules/kirograph.md✅ sync scriptD
AntigravityantigravityPrint commandGEMINI.md✅ .agents/hooks.jsonD
AideraiderPrint CLI flagCONVENTIONS.mdD
Replit AgentreplitPrint commandAGENTS.mdD
Block GoosegoosePrint commandAGENTS.mdD
Mistral Vibemistral-vibePrint command.kirograph/mistral-vibe.mdD
IBM Bobibm-bobPrint command.kirograph/ibm-bob.mdD
CrushcrushPrint command.kirograph/crush.mdD
Droid Factorydroid-factoryPrint command.kirograph/droid-factory.mdD
ForgeCodeforgecodePrint command.kirograph/forgecode.mdD
iFlow CLIiflowPrint command.kirograph/iflow.mdD
Qwen CodeqwenPrint command.kirograph/qwen.mdD
Atlassian Rovo DevrovoPrint command.kirograph/rovo.mdD
QoderqoderPrint command.kirograph/qoder.mdD

Integration Patterns

Pattern A — Project-level MCP config + rules file: The installer writes a JSON config file the tool reads on startup, plus a rules/instructions file the agent loads into context. Restart the tool after installing.

Pattern B — Standard mcpServers + project memory file: Writes a standard mcpServers config plus a generated block in the tool's project memory file (CLAUDE.md, GEMINI.md). The block is idempotent.

Pattern C — Custom config format: The tool has its own config schema. The installer merges the kirograph entry without overwriting other settings.

Pattern D — Print-only: The tool's MCP config is user-scoped or cloud-hosted. The installer writes instructions locally and prints the exact command to register the MCP server.

Auto-Sync Hooks

For tools that support lifecycle hooks, the installer writes auto-sync hooks that run kirograph sync when the agent finishes — no manual intervention needed.

ToolHook fileEventBehavior
Kiro.kiro/hooks/*.kiro.hookagentStop + preToolUseSync + compression hint + memory capture
Cursor.cursor/hooks.jsonstopSync on task completion
Windsurf.windsurf/hooks.jsonpost_cascade_responseSync after each response
Claude Code.claude/settings.jsonStopSync on session stop
GitHub Copilot.github/hooks.jsonsession-endSync on session end
Cline.clinerules/hooks/task_completedtask_completedExecutable script that syncs
Codex CLI.codex/hooks.jsonStopSync on session stop
Antigravity.agents/hooks.jsonStopSync on execution stop
Gemini CLI.gemini/settings.jsonSessionEndSync on session end
OpenCode.opencode/plugins/kirograph-sync.jssession.idleJS plugin that syncs
Devin.devin/hooks.v1.jsonStopSync on session stop

For tools without a hook system (22 targets), the generated instructions include a "Session Hygiene" section that tells the agent to manually run kirograph sync at the start and end of each session.

Multiple Targets

You can install multiple targets in the same project. They all share the same .kirograph/ graph data. Multiple targets can write to AGENTS.md simultaneously using unique block IDs.

kirograph install                      # Auto-detect all platforms
kirograph install --all                # Same, skip confirmation prompt
kirograph install --target cursor      # Install for a specific platform only

Configuration

All configuration is in .kirograph/config.json. The interactive kirograph install writes this for you.

FieldTypeDefaultDescription
Indexing
languagesstring[][]Limit indexing to specific languages (empty = all)
includestring[][]Glob patterns to include (empty = include everything not excluded)
excludestring[]see belowGlob patterns to exclude from indexing
maxFileSizenumber1048576Skip files larger than this (bytes, default 1MB)
extractDocstringsbooleantrueExtract JSDoc, docstrings, and comments
trackCallSitesbooleantrueRecord line/column for call edges
frameworkHintsstring[]autoOverride framework detection (e.g. ["react", "express"])
fuzzyResolutionThresholdnumber0.5Name matching threshold for cross-file resolution (0.0–1.0)
syncWarningThresholdnumber10Warn in kirograph_status when pending files exceed this count (0 = disable)
Semantic Search
enableEmbeddingsbooleanfalseEnable semantic (vector) search
embeddingModelstring"nomic-ai/nomic-embed-text-v1.5"HuggingFace model ID
embeddingDimnumber768Embedding dimension
semanticEnginestring"cosine"Engine: cosine, turboquant, turbovec, sqlite-vec, orama, pglite, lancedb, qdrant, typesense
turboquantBitsnumber3TurboQuant bits per coordinate (1–8). Controls compression/quality tradeoff. Changing requires kirograph index --force.
turboquantMemDocsbooleanfalseUse TurboQuant ANN index for memory and doc search (requires turboquant-js).
turbovecBitsnumber4TurboVec bits per coordinate (2, 3, or 4). Controls compression/quality tradeoff. Changing requires kirograph index --force.
turbovecMemDocsbooleanfalseUse TurboVec ANN index for memory and doc search (requires built addon).
useVecIndexbooleanfalseDeprecated alias for semanticEngine: "sqlite-vec"
typesenseDashboardbooleanfalseOpen Typesense dashboard after indexing
qdrantDashboardbooleanfalseOpen Qdrant dashboard after indexing
Architecture
enableArchitecturebooleanfalseEnable architecture analysis (package graph + layer detection)
architectureLayersobject-Custom layer definitions: { "layerName": ["glob/**"] }
Memory
enableMemorybooleanfalseEnable persistent cross-session memory
memorySearchAlphanumber0.5FTS/vector blend (0 = FTS only, 1 = vector only)
memoryKeepRawbooleantrueStore original text alongside compressed version
memoryMaxObservationsnumber10000Max observations before auto-pruning oldest
memorySessionTimeoutnumber3600000Session timeout in ms (default 1 hour)
memoryContextLimitnumber3Max observations surfaced in kirograph_context
memoryContextThresholdnumber0.3Min relevance score to surface in context
memoryExcludePatternsstring[][]Glob patterns for files to exclude from symbol linking
Documentation
enableDocsbooleanfalseEnable documentation indexing (section-level retrieval)
docsIncludestring[]["**/*.md", ...]Glob patterns for doc files to include
docsExcludestring[]["node_modules/**", ...]Glob patterns for doc files to exclude
docsLinkCodebooleantrueAuto-link doc sections to code symbols
docsContextLimitnumber0Max doc sections in kirograph_context (0 = disabled)
docsContextThresholdnumber0.5Min confidence for doc refs in context
docsMaxFileSizenumber1048576Max doc file size in bytes
docsSummarizationstring"first-sentence"Summary strategy: embedding, first-sentence, off
Data
enableDatabooleanfalseEnable tabular data indexing and querying
dataIncludestring[]["**/*.csv", ...]Glob patterns for data files to include
dataExcludestring[]["node_modules/**", ...]Glob patterns for data files to exclude
dataLinkCodebooleantrueAuto-link data files to code symbols via path detection
dataContextLimitnumber0Max datasets in kirograph_context (0 = disabled)
dataMaxFileSizenumber52428800Max data file size in bytes (50MB)
dataMaxRowsnumber1000000Max rows to index per file
dataQueryLimitnumber500Max rows returned per query (hard cap)
dataMaxResponseTokensnumber8000Max token budget per data tool response
Agent Behavior
cavemanModestring"off"Communication compression: off, lite, full, ultra
shellCompressionLevelstring"normal"Shell command compression: off, normal, aggressive, ultra
minLogLevelstring"warn"Log level: debug, info, warn, error

Caveman Mode

Caveman mode

Caveman mode compresses the agent's communication style, cutting token usage on responses without affecting tool calls or code output. Inspired by caveman by JuliusBrussee.

The rules are injected at session start via the steering file (IDE) and the inline agent prompt (kiro-cli), so they're always in context with no extra tool calls.

ModeStyle
offNormal responses (default)
liteCompact, no filler, full sentences
fullFragments, no articles, short synonyms
ultraMaximum compression, abbreviations, → for causality

Caveman mode never touches code blocks, file paths, URLs, or technical terms, only prose.

Auto-clarity exceptions: the agent temporarily reverts to normal prose for security warnings, confirmations of irreversible actions (delete, overwrite, force-push), and multi-step sequences where fragment order could cause misunderstanding. Compressed style resumes immediately after.

kirograph caveman lite    # set mode
kirograph caveman         # show current mode
Takes effect on the next agent session. The steering file and CLI agent config are regenerated immediately when you run the command.

Shell Compression

shell compression mode

KiroGraph includes a built-in shell compression engine inspired by rtk. The kirograph_exec MCP tool runs shell commands and returns token-optimized output, saving 60-90% of tokens on verbose commands.

Supported command families: git (status, log, diff, push, pull, commit, add, fetch, branch), GitHub CLI (gh pr list/view, gh issue list, gh run list), test runners (jest, vitest, pytest, cargo test, go test, rspec, minitest, playwright), linters/build (eslint, tsc, ruff, clippy, cargo build, prettier, biome, golangci-lint, rubocop, next build), file listings (ls, find, tree), search (grep, rg, grouped by file), diff (condensed context), docker/k8s (docker ps, images, logs, compose ps, kubectl pods, logs, services), package managers (npm, pip, bundle, prisma generate), AWS (sts, ec2, lambda, logs, cloudformation, dynamodb, iam, s3, ecs, sqs, sns), network (curl, wget, strips progress).

LevelStyle
normalBalanced: removes noise, keeps structure (default)
aggressiveMore compact: groups by category, limits output
ultraMaximum compression: counts and summaries only
kirograph compression normal     # balanced (default)
kirograph compression aggressive # more compact
kirograph compression ultra      # maximum compression
kirograph compression off        # disable hook (tool still available)
kirograph compression            # show current level
kirograph gain                   # show token savings stats
kirograph gain --graph           # ASCII graph (last 30 days)

Set during kirograph install (interactive arrow-key menu) or any time after. The configured level is used as the default when the agent calls kirograph_exec without specifying one explicitly.

Error preservation: Failed commands always show full diagnostic output regardless of compression level.

Configure in .kirograph/config.json: "shellCompressionLevel": "normal" (default). Set to "off" to disable the hook and steering section. The kirograph_exec tool remains available regardless.

Coexistence with Caveman Mode

Compression and caveman mode are complementary, they compress different things:

They stack: with both enabled, shell commands return 60-90% fewer tokens and the agent's explanations around those results are also shorter. Pick both independently during kirograph install. The "ultra + ultra" combo gives maximum token savings on both fronts.

General-purpose Compression (opt-in)

When enableGeneralCompression: true is set, the kirograph_compress MCP tool is available for on-demand compression of arbitrary text before it reaches the model. Inspired by headroom by Tejas Chopra.

Unlike kirograph_exec (which compresses automatically in the background when a shell command runs) or caveman mode (which compresses the agent's own prose via steering), kirograph_compress is an explicit, agent-initiated action — the agent decides when to compress, what to compress, and at what intensity.

Two engines, one interface

Pass command to activate the rtk-style structural engine. Omit it to use the caveman grammar engine:

EngineActivated byBest forTechnique
rtk shellcommand presentgit, npm, test logs, docker, AWSPattern-matched per command family — removes noise lines, deduplicates, groups
caveman grammarno commandprose, observations, LLM explanationsStrips filler words, articles, hedging — preserves code blocks, paths, URLs

Compression levels

LevelStyle
lite / normalLight pass — minimal removals, safe for any content
full / aggressiveMedium — default, removes most noise without losing meaning
ultraMaximum — also abbreviates common phrases; some signal loss possible

Every call returns inline savings: [42% tokens saved | 1800→1044 | rtk:git:aggressive].

When to use

  • The agent received a long shell output outside of kirograph_exec (e.g. via a tool that runs a command directly)
  • A block of text needs to be summarised before being stored as a memory observation
  • You want to compare compressed vs original before deciding what to pass to a follow-up tool call

When not to use

  • Commands run via kirograph_exec — already compressed automatically
  • Agent prose — enable caveman mode instead (automatic, zero tool-call overhead)
  • Source code — compression may break identifiers or whitespace-sensitive content
Enable via kirograph install (General-purpose compression question) or set "enableGeneralCompression": true in .kirograph/config.json. Independent from cavemanMode and shellCompressionLevel.

Memory (opt-in)

KiroGraph Memory

When enableMemory: true is set in .kirograph/config.json, KiroGraph stores persistent observations across sessions. Decisions, errors, patterns, and architecture notes are captured with zero LLM tokens on write (compression is deterministic, symbol linking is programmatic, embedding uses the local model) and minimal tokens on read. Inspired by cavemem by Julius Brussee and Engram by Gentleman-Programming.

How it works

The write path runs entirely without LLM involvement:

  1. An observation is received (via hook or manual kirograph_mem_store call)
  2. If caveman mode is enabled, the text is compressed deterministically using the configured level
  3. A content hash deduplicates against existing observations
  4. Symbol names in the text are detected and linked to graph nodes via qualified_name
  5. The observation is embedded using the same local model and semantic engine as code symbols

On read, kirograph_mem_search performs hybrid FTS + vector search. Linked observations also surface automatically in kirograph_context and kirograph_impact results. Search results include inline relation annotations (⚡ conflict, ✓ compatible) so the agent sees contradictions without a separate query.

Conflict detection and knowledge hygiene

As the memory base grows, observations can contradict each other across sessions. KiroGraph provides a typed relation system to keep knowledge consistent:

  • Scan: kirograph_mem_conflicts_scan uses FTS similarity to find candidate contradiction pairs, skipping already-reviewed ones.
  • Compare: kirograph_mem_compare places two observations side by side and creates a typed relation (supersedes, conflicts_with, compatible, scoped, related, not_conflict).
  • Judge: kirograph_mem_judge finalizes a pending relation with a confidence score and reason — resolving the conflict or confirming compatibility.

Stable addressing and stale scheduling

topicKey is a stable semantic identifier (e.g. "architecture/auth-model") that lets multiple sessions address the same concept without knowing its UUID. Pass it to kirograph_mem_store for any decision that may be revisited or superseded.

reviewAfter is an epoch-ms timestamp that schedules an observation for re-evaluation — useful after a planned migration, a library upgrade, or a time-boxed experiment. kirograph_mem_review lists all overdue observations; kirograph_mem_mark_reviewed clears them once validated.

Passive capture

kirograph_mem_capture extracts and stores observations from structured markdown text without LLM involvement. Bullets under headings like ## Key Learnings, ## Decisions, and ## Observations are parsed and stored as individual observations. This lets agents dump their reasoning in a structured block at session end and have KiroGraph index it automatically.

MCP Tools

ToolDescription
kirograph_mem_searchHybrid search over observations (FTS + vector, configurable alpha blend). Results include inline relation annotations.
kirograph_mem_storeStore an observation with auto-compression, symbol linking, and embedding. Accepts topicKey and reviewAfter.
kirograph_mem_timelineList recent sessions and their observations chronologically
kirograph_mem_statusMemory subsystem health: sessions, observations, embedding coverage, relations count, pending conflicts
kirograph_mem_reviewList observations past their review_after date — stale facts for re-evaluation
kirograph_mem_mark_reviewedClear an observation's review_after date, removing it from the review queue
kirograph_mem_compareEstablish a typed relation between two observations (IDs or topic_keys). Types: supersedes, conflicts_with, compatible, scoped, related, not_conflict
kirograph_mem_judgeFinalize a pending conflict relation — confirm, revise, or dismiss
kirograph_mem_captureExtract and store structured learnings from text with ## Key Learnings, ## Observations, ## Decisions sections
kirograph_mem_save_promptSave the current user prompt to session memory for context reconstruction
kirograph_mem_suggest_topic_keyGenerate a deterministic topic_key slug (e.g. "architecture/auth-model") from kind + title
kirograph_mem_conflicts_scanScan recent observations for potential conflicts using FTS similarity — returns candidate pairs

CLI Commands

# Search (mirrors kirograph_mem_search)
kirograph mem search <query>
kirograph mem search <query> --kind error --limit 5

# Store (mirrors kirograph_mem_store)
kirograph mem store "decided to use idempotency keys for payments"
kirograph mem store "auth bug: token refresh missing" --kind error

# Timeline & status
kirograph mem timeline
kirograph mem status

# Maintenance (CLI-only)
kirograph mem prune --older-than 90d
kirograph mem reembed
kirograph mem lint
kirograph mem export --format jsonl

Session management

Sessions are managed automatically. On the first kirograph_mem_store call, KiroGraph checks for an active session (same IDE, started within the configured timeout). If none exists, a new session is created. The agentStop hook closes the session automatically.

The inactivity timeout defaults to 2 hours and is configurable via memorySessionTimeout (in seconds).

Configuration

FieldTypeDefaultDescription
enableMemorybooleanfalseEnable persistent memory
memorySearchAlphanumber0.5FTS/vector blend (0 = pure FTS, 1 = pure vector)
memoryKeepRawbooleanfalseStore uncompressed originals when caveman is on
memoryMaxObservationsnumber10000Auto-prune threshold
memorySessionTimeoutnumber7200Seconds of inactivity before auto-closing a session
memoryContextLimitnumber3Max observations shown in kirograph_context
memoryContextThresholdnumber0.3Min relevance score to include in context
memoryExcludePatternsstring[][]Glob patterns for paths to never capture

Privacy

Wrap sensitive content in <private>...</private> blocks — they are stripped before storage. All data stays in the local .kirograph/kirograph.db file, same as the rest of the graph.

Watchmen (opt-in) experimental

KiroGraph Watchmen
⚠ Experimental feature. Output quality in local synthesis mode varies significantly depending on the model chosen and the hardware it runs on. Smaller or heavily quantized models may produce incomplete briefs or lower-quality skill files. Inference time also depends on your machine — expect 8–15 s on Apple Silicon M1+ and 30–60 s on Intel CPU with the default model. Use watchmenSynthesisMode: 'agent' on Kiro for best results, or choose a larger model if local quality matters.

When enableWatchmen: true is set (requires enableMemory: true), KiroGraph automatically synthesizes accumulated memory observations into workspace brief files. When the observation count since the last synthesis reaches watchmenThreshold (default: 5), kirograph_mem_store returns a watchmenReady signal. Inspired by watchmen by firstbatch.

Synthesis is performed by a local HuggingFace model (watchmenSynthesisMode: 'local', default) or delegated to the active AI agent ('agent', Kiro only, consumes tokens).

Local model

The default mode uses onnx-community/gemma-4-E4B-it-ONNX via @huggingface/transformers (ONNX Runtime). The model is downloaded once to ~/.kirograph/models/ alongside the embedding model — the same cache directory, no extra setup.

Download~3–4 GB one-time
RAM during inference~3–5 GB
Speed on Apple Silicon (M1+)8–15 seconds (CoreML acceleration via ONNX Runtime)
Speed on Intel CPU30–60 seconds
When it runsOnly at agentStop when threshold is reached — not a persistent process
API key requiredNo
Data leaves machineNo

Output per tool

ToolFile written
Kiro.kiro/steering/kirograph-watchmen.md (inclusion: always) + individual watchmen-<slug>.md skill files (inclusion: manual)
Claude CodeCLAUDE.md (upserts ## KiroGraph Watchmen block)
Codex, Copilot CLI, Devin, Goose, Warp, Roo, OpenHands, Replit, JunieAGENTS.md
Gemini CLI / AntiGravityGEMINI.md
AiderCONVENTIONS.md
Augmentaugment-guidelines.md
Rules-based tools (Cursor, Cline, Windsurf…)AGENTS.md fallback

Configuration

FieldTypeDefaultDescription
enableWatchmenbooleanfalseEnable Watchmen. Requires enableMemory: true.
watchmenThresholdnumber5Minimum new observations before watchmenReady fires.
watchmenSynthesisModestring'local''local' — runs a local HuggingFace model on-device (no API key, no external calls); 'agent' — delegates to the active AI agent via askAgent hook (Kiro only, consumes tokens).
watchmenLocalModelstring'onnx-community/gemma-4-E4B-it-ONNX'HuggingFace model ID for local synthesis. Downloaded once to ~/.kirograph/models/. ~3–4 GB, ~3–5 GB RAM at inference, 8–15 s on Apple Silicon. Only used when watchmenSynthesisMode: 'local'.

Wiki (opt-in)

KiroGraph Wiki

When enableWiki: true is set in .kirograph/config.json, KiroGraph maintains a project-level knowledge wiki — a set of structured markdown pages that compound knowledge across sessions. Unlike memory observations (ephemeral, session-scoped), wiki pages are curated, durable facts: architecture decisions, API contracts, domain concepts, and process steps. The LLM reads, writes, and searches pages via MCP tools; a two-step ingest flow (ingest → apply-diff) gives the agent explicit control over what enters the wiki. Inspired by Andrej Karpathy's LLM Wiki gist: the three-op pattern (ingest → apply → lint), the WIKI_DIFF block format, the two-tool ingest flow, and the principle of knowledge compounding rather than accumulating.

How it works

  1. Agent calls kirograph_wiki_ingest with a source text (meeting notes, code review, design doc).
  2. The tool returns a structured prompt containing the wiki schema, the current manifest, and the source text.
  3. In agent mode (default): the agent generates a WIKI_DIFF block and calls kirograph_wiki_apply_diff to commit it. The agentStop hook prompts this automatically.
  4. In local model mode: the source is queued in wiki_queue. At agentStop, a runCommand hook invokes kirograph wiki synthesize which runs a local HuggingFace model to generate and apply diffs — zero API cost, no data leaves your machine.
  5. Pages are written to .kirograph/wiki/ as markdown files and indexed in SQLite with FTS5 full-text search.

kirograph_wiki_context surfaces relevant pages automatically inside kirograph_context results when the query matches wiki content above the configured threshold.

MCP Tools

ToolDescription
kirograph_wiki_ingestReturns a structured prompt for the agent to generate a WIKI_DIFF. In local mode, queues the source instead.
kirograph_wiki_apply_diffApplies a WIKI_DIFF string to the wiki: creates, upserts, or appends pages; surfaces conflicts.
kirograph_wiki_searchFTS5 full-text search over wiki pages. Returns ranked results with content snippets.
kirograph_wiki_pageRetrieve a single wiki page by slug.
kirograph_wiki_listList all wiki pages with title, slug, source count, and last-updated date.
kirograph_wiki_statusWiki health summary: page count, total sources, oldest/newest page, wiki directory.

WIKI_DIFF format

The LLM produces structured diff blocks that the tool applies atomically:

WIKI_DIFF_START
{"page": "auth-service", "title": "Auth Service", "action": "create"}

# Auth Service

Handles JWT token generation and validation with RS256 signing.
Tokens expire after 15 minutes.

## Related
- [[payment-flow]]
WIKI_DIFF_END

Supported actions: create (new page), upsert (overwrite), append (add section). Conflicts (incoming content contradicts an existing page) are surfaced as WIKI_DIFF_CONFLICTS blocks for the agent to resolve, or auto-resolved when wikiAutoResolveConflicts: true.

CLI Commands

# Initialise the wiki (creates SCHEMA.md and MANIFEST.md)
kirograph wiki init

# List all pages
kirograph wiki list
kirograph wiki list --format json

# Full-text search
kirograph wiki search "JWT authentication"

# Read a page
kirograph wiki page auth-service

# Ingest a source (agent mode: returns prompt; local mode: queues source)
kirograph wiki ingest --source "design docs" --file ./docs/auth-design.md

# Run local-model synthesis over the queue (local mode only)
kirograph wiki synthesize
kirograph wiki synthesize --quiet

# Rebuild the DB index from wiki markdown files on disk
kirograph wiki reindex

# Lint the wiki: detect broken links, orphan pages
kirograph wiki lint

# Wiki status
kirograph wiki status

Local model synthesis

When wikiSynthesisMode: 'local', KiroGraph queues source texts and runs a local HuggingFace model (wikiLocalModel) at agentStop via a runCommand hook. Same infrastructure as Watchmen — model downloaded once to ~/.kirograph/models/, runs on-device, no API key required.

Download~3–4 GB one-time (Gemma 4 default)
RAM during inference~3–5 GB
Speed on Apple Silicon (M1+)8–20 seconds per source
Hook typerunCommandkirograph wiki synthesize --quiet
API key requiredNo
Data leaves machineNo

Configuration

FieldTypeDefaultDescription
enableWikibooleanfalseEnable the wiki module
wikiSynthesisModestring'agent''agent' — agent generates WIKI_DIFF via askAgent hook; 'local' — local HuggingFace model via runCommand hook
wikiLocalModelstring'onnx-community/gemma-4-E4B-it-ONNX'HuggingFace model ID for local synthesis. Only used when wikiSynthesisMode: 'local'.
wikiAutoResolveConflictsbooleanfalseAutomatically apply incoming content when a conflict is detected, discarding the existing version
wikiContextLimitnumber3Max wiki pages included in kirograph_context results
wikiContextThresholdnumber0.1Minimum FTS relevance score to include a page in context
wikiSourcesstring[]['docs/']Source directories for auto-ingest suggestions

Documentation (opt-in)

KiroGraph Documentation

When enableDocs: true is set in .kirograph/config.json, KiroGraph indexes project documentation by heading hierarchy and section structure. Instead of reading entire doc files, agents retrieve exactly the section they need via stable section IDs — saving 92–97% of tokens compared to reading full files. Inspired by jDocMunch-MCP by J. Gravelle.

How it works

The indexing pipeline:

  1. Scans the project for documentation files matching docsInclude / docsExclude patterns
  2. Detects the format (Markdown, RST, AsciiDoc, etc.) and parses headings into a section hierarchy
  3. Generates stable section IDs: {file_path}::{ancestor-chain/slug}#{level}
  4. Computes SHA-256 content hashes for incremental re-indexing (skips unchanged files)
  5. If docsLinkCode: true, detects code symbol references (backtick patterns, CamelCase, snake_case) and stores cross-references via qualified_name
  6. Stores everything in doc_sections and doc_code_refs tables in the same SQLite DB

On read, agents use kirograph_docs_search (FTS5) to find sections, kirograph_docs_section to retrieve content, and kirograph_docs_refs to navigate code ↔ docs cross-references.

Supported formats

FormatExtensionsParsing strategy
Markdown.md, .mdx, .cheatmdATX (#) + setext headings
reStructuredText.rstAdornment-based heading detection
AsciiDoc.adoc, .asciidoc= heading hierarchy
RDoc.rdoc= heading hierarchy (Ruby)
Org-mode.org* heading hierarchy
HTML.html, .htm<h1><h6> headings
Plain text.txtALL CAPS + underline detection
OpenAPI/Swagger.yaml, .yml, .jsonOperations grouped by tag (content-detected)

MCP Tools

ToolDescription
kirograph_docs_tocTable of contents for a file or the whole project (flat or tree)
kirograph_docs_searchFTS5 search across documentation sections (independent from code search)
kirograph_docs_sectionRetrieve full content of a section by stable ID, with optional context (ancestors + children)
kirograph_docs_outlineHeading hierarchy for a single document
kirograph_docs_refsBidirectional code ↔ doc cross-references

CLI Commands

# Table of contents
kirograph docs toc                          # whole project
kirograph docs toc README.md                # single file
kirograph docs toc README.md --tree         # nested tree

# Search
kirograph docs search "authentication"
kirograph docs search "config" --file docs/guide.md --limit 5

# Retrieve a section
kirograph docs section "README.md::installation#1"
kirograph docs section "README.md::installation#1" --context

# Outline
kirograph docs outline docs/api.md

# Cross-references
kirograph docs refs "docs/auth.md::oauth/token-refresh#2"

# Maintenance
kirograph docs reindex                      # force full re-index
kirograph docs lint                         # health checks
kirograph docs reembed                      # re-embed with current model

Context integration (opt-in)

By default, kirograph_context does not include doc sections — the agent uses kirograph_docs_* tools explicitly. If you want docs to surface automatically in context results, set docsContextLimit to a value greater than 0 during install (or in config).

When enabled, kirograph_context queries doc_code_refs for the symbols it found and includes up to N relevant doc sections (above docsContextThreshold score).

Configuration

FieldTypeDefaultDescription
enableDocsbooleanfalseEnable documentation indexing
docsIncludestring[]["**/*.md", ...]Glob patterns for doc files to include
docsExcludestring[]["node_modules/**", ...]Glob patterns for doc files to exclude
docsLinkCodebooleantrueAuto-link doc sections to code symbols
docsContextLimitnumber0Max doc sections in kirograph_context (0 = disabled)
docsContextThresholdnumber0.3Min relevance score for context inclusion
docsMaxFileSizenumber1048576Max doc file size in bytes (1 MB)
docsSummarizationstring"first-sentence"Summary strategy: embedding, first-sentence, off

Token savings

Documentation tools are tracked in kirograph_gain as a separate "Docs tools" source category. Typical savings per call:

ToolWithout kirographWith kirographSavings
kirograph_docs_toc~10,000 tokens~400–80092–96%
kirograph_docs_search~8,000–13,000~300–60093–97%
kirograph_docs_section~2,500~200–80068–92%
kirograph_docs_outline~2,500~200–40084–92%
kirograph_docs_refs~7,400~300–50093–96%

Data (opt-in)

KiroGraph Data

When enableData: true is set in .kirograph/config.json, KiroGraph indexes tabular data files and documents (CSV, TSV, JSONL, JSON, Excel, Parquet, PDF) that live alongside your code — test fixtures, seed data, configuration tables, sample datasets, reports. Instead of reading raw data files into context, agents query structured schemas and filtered rows — saving 95–99% of tokens. Inspired by jDataMunch-MCP by J. Gravelle.

Key features

  • Streaming parser: never loads full files into memory. Processes line-by-line (CSV/JSONL) or in chunks (Excel/Parquet).
  • Column profiling: type inference (string, integer, float, boolean, date), cardinality, null percentages, min/max, mean, sample values.
  • Server-side computation: filters, aggregations, joins, and correlations run in SQLite. Only results enter the context window.
  • Incremental indexing: content hash (SHA-256) per file. Only re-indexes files that changed.
  • Optional format deps: CSV/TSV/JSONL/JSON are built-in (zero deps). Excel requires xlsx, Parquet requires parquetjs-lite, PDF requires @firecrawl/pdf-inspector (prebuilt Rust binary, linux-x64 and macOS ARM64).
  • Code ↔ data linking: detects file path references in source code and populates data_code_refs. Enables test fixture awareness in kirograph affected.
  • Schema drift detection: tracks profile history across re-indexes. kirograph data drift shows added/removed/changed columns.
  • NL summaries: auto-generated natural-language descriptions for each column based on profile patterns.
  • Validation rules: infers rules from profiles (required, type, range, enum, uniqueness).
  • Anti-loop detection: warns when agent paginates row-by-row instead of using aggregations.
  • Token budget enforcement: responses exceeding dataMaxResponseTokens are truncated.

Supported formats

KiroGraph Firecrawl PDF Inspector
FormatExtensionsDependenciesParsing strategy
CSV.csvNone (built-in)Line-by-line streaming
TSV.tsvNone (built-in)Line-by-line streaming (tab delimiter)
JSONL / NDJSON.jsonl, .ndjsonNone (built-in)Line-by-line streaming
JSON array.json (in data/ dirs)None (built-in)Streaming array parse
Excel.xlsx, .xlsxlsx (optional)Sheet-by-sheet, row iteration
Parquet.parquetparquetjs-lite (optional)Column-chunk streaming
PDF.pdf@firecrawl/pdf-inspector (optional, prebuilt Rust)Per-page markdown extraction; each page = one row with content, needs_ocr, has_tables, has_columns. Mixed/scanned PDFs: text pages indexed normally, scanned pages flagged. linux-x64 and macOS ARM64 only.

MCP tools

ToolDescription
kirograph_data_listList all indexed datasets with row counts, column counts, file sizes
kirograph_data_describeFull schema profile: column names, types, cardinality, null%, samples
kirograph_data_queryFiltered row retrieval with structured operators (eq, gt, contains, in, between)
kirograph_data_aggregateServer-side GROUP BY: count, sum, avg, min, max, count_distinct
kirograph_data_searchSearch column names and sample values by keyword
kirograph_data_joinCross-dataset SQL JOIN (inner, left, right)
kirograph_data_correlationsPairwise Pearson correlations between numeric columns
kirograph_data_qualityData quality triage: rank columns by risk score; surfaces OCR-flagged pages and encoding issues for PDF datasets

Configuration

FieldTypeDefaultDescription
enableDatabooleanfalseEnable tabular data indexing and querying
dataIncludestring[]['**/*.csv', '**/*.tsv', '**/*.jsonl', '**/*.ndjson', 'data/**/*.json', '**/*.pdf']Glob patterns for data files to include
dataExcludestring[]['node_modules/**', ...]Glob patterns for data files to exclude
dataContextLimitnumber0Max datasets in kirograph_context results (0 = disabled). For PDF datasets, keep this at 0–1 — PDF content columns are verbose and inflate context significantly.
dataMaxFileSizenumber52428800Max data file size in bytes (50MB)
dataMaxRowsnumber1000000Max rows to index per file
dataQueryLimitnumber500Max rows returned per query (hard cap)
dataMaxResponseTokensnumber8000Max token budget per response (truncates if exceeded)
dataLinkCodebooleantrueAuto-link data files to code symbols via path detection

Token savings

ToolNaive cost (without)Typical output (with)Savings
kirograph_data_describe~50,000–111M tokens~2,000–4,000 tokens96–99.99%
kirograph_data_query~50,000+ tokens~1,000–3,000 tokens94–99%
kirograph_data_aggregate~50,000+ tokens~500–1,500 tokens97–99%
kirograph_data_search~10,000 tokens~200–500 tokens95–98%
kirograph_data_list~2,000 tokens~200–400 tokens80–90%

Security

KiroGraph Security

When enableSecurity: true, KiroGraph scans dependency manifests for known vulnerabilities and performs reachability analysis to determine if vulnerable code is actually reachable from entry points.

Configuration

FieldTypeDefaultDescription
enableSecuritybooleanfalseEnable dependency scanning and vulnerability detection
securityDatabasesstring[]["OSV"]Vulnerability databases to query
securityAutoEnrichbooleantrueAuto-run vulnerability enrichment after manifest parsing

Pipeline

The security pipeline runs after architecture analysis during indexing:

code extraction → reference resolution → architecture analysis → security analysis

Phases: manifest discovery → dependency parsing → dependency graph integration → vulnerability enrichment (OSV) → reachability analysis → impact analysis.

Supported ecosystems

EcosystemManifestLock FilePurl Prefix
npm / pnpmpackage.jsonpackage-lock.json, pnpm-lock.yaml, yarn.lockpkg:npm/
Mavenpom.xmlpkg:maven/
Gradlebuild.gradle, build.gradle.ktsgradle.lockfilepkg:maven/
Gogo.modgo.sumpkg:golang/
piprequirements.txtpkg:pypi/
Python (modern)pyproject.tomlpoetry.lock, pdm.lock, uv.lockpkg:pypi/
CargoCargo.tomlCargo.lockpkg:cargo/
NuGet*.csproj, packages.configpackages.lock.jsonpkg:nuget/
RubyGemsGemfileGemfile.lockpkg:gem/
Composercomposer.jsoncomposer.lockpkg:composer/
Swift PMPackage.swiftPackage.resolvedpkg:swift/
Dart/Flutterpubspec.yamlpubspec.lockpkg:pub/
Elixir/Hexmix.exsmix.lockpkg:hex/

Reachability verdicts

VerdictMeaning
affectedAt least one path exists from an entry point to the vulnerable dependency through call, import, or reference edges
not_affectedNo path exists from any entry point to the vulnerable dependency, and no unresolved imports were encountered
under_investigationThe traversal encountered unresolved imports — the vulnerability might be reachable through an unresolved path

CLI commands

CommandDescription
kirograph security [path]Overview: dep count, vulnerability count, verdict breakdown, stale warnings (--refresh-staleness)
kirograph vulns [path]List vulnerabilities — --severity, --verdict, --epss <n>, --stale, --refresh, --add
kirograph reachability <target>Check reachability for a CVE ID or package name — verdict, call paths, impact summary
kirograph licenses [path]List dependency licenses, check policy (--policy, --deny, --warn)
kirograph staleness [path]Check dependency freshness against registries (--threshold, --refresh)
kirograph vex [--output file]Export CycloneDX 1.5 VEX document
kirograph sbom [--output file]Export CycloneDX 1.5 SBOM document
kirograph vulns --fail-on <condition>Exit code 1 if condition met: affected, any, critical, high, epss=0.5. Use in CI pipelines.
kirograph vulns --group-by workspaceGroup vulnerabilities by source manifest directory (monorepo support).
kirograph vulns --sort risk|cvss|epss|nameSort order. Default: risk (combined score: reachability × CVSS × EPSS × staleness).
kirograph vuln suppress <cveId> [--reason] [--expires]Mark a CVE as suppressed (false positive or accepted risk). Stored in .kirograph/security-suppressions.json.
kirograph vuln unsuppress <cveId>Remove a suppression.
kirograph vuln suppressionsList all active suppressions.
kirograph security --fail-on affectedExit code 1 if any affected vulnerabilities exist.
kirograph security export [--output file] [--open]Generate self-contained HTML dashboard — Overview, Vulnerabilities, SBOM, VEX, Licenses, Staleness tabs. --open launches in browser immediately.
kirograph attack-surface [path]Map HTTP routes to reachable vulnerable dependencies — exposure level (public/authenticated/internal), hop count, risk score. --public-only, --limit, --format json.
kirograph security secrets [path]Scan for 14 secret types (AWS keys, GitHub tokens, DB URLs, JWT, etc.) with call-graph blast radius. --include-tests, --severity, --format json.
kirograph security flows [path]SAST-lite: SQL injection, eval/exec, unsafe deserialization, path traversal, weak crypto. Each finding tagged with OWASP Top 10 (2021) category. --type sql, --format json.
kirograph pattern [--list] [--library <id>] [--lang] [--format]AST structural search — live pattern, library browser, specific rule runner. Exit 1 on findings for CI.
kirograph security ci-report [path]Generate CI/CD security report in JSON, SARIF 2.1.0 (GitHub Security tab), or compact text. --format sarif --output results.sarif, --fail-on critical.
kirograph supply-chain [path]Supply chain health: OpenSSF Scorecard scores, maintainer count, abandoned package detection (>365 days), new package risk (<30 days). --threshold high, --refresh.
kirograph dep-confusion [path]Detect dependency confusion (internal package names in public registries) and typosquatting (Levenshtein ≤ 2 from popular packages). --format json.
kirograph remediation [path]SLA tracking per CVE — critical=7d, high=30d, medium=90d. Shows days open, days with fix available, SLA status. --overdue-only, --format json.

CycloneDX output

KiroGraph-Sec exports industry-standard CycloneDX 1.5 documents:

  • SBOM — Full software bill of materials with all dependencies as components, package URLs, and dependency relationships
  • VEX — Vulnerability Exploitability eXchange with reachability-derived analysis states and justifications

Feature comparison →

TurboQuant

KiroGraph TurboQuant

TurboQuant is an optional upgrade that compresses your vector embeddings at storage time and replaces the default linear scan with an approximate nearest-neighbour (ANN) index — with zero native dependencies.

Built on turboquant-js by Danilo Dev, a TypeScript implementation of Google's TurboQuant algorithm. Embeddings are compressed immediately on kirograph index:

  1. Walsh-Hadamard rotation with random sign flips in O(d log d). Distributes energy uniformly across all coordinates before quantization.
  2. Lloyd-Max scalar quantization per rotated coordinate. Each value is encoded in turboquantBits bits (default: 3) using optimal codebooks.

Compression at a glance

VectorsRaw Float32 in RAMTurboQuant (3 bit)Reduction
1,000~3 MB~120 KB25×
10,000~30 MB~1.2 MB25×
100,000~300 MB~12 MB25×

When to use TurboQuant

SituationRecommendation
Small project, < 5,000 symbolscosine is fine
Large project, native modules OKsqlite-vec or lancedb
Large project, no native modules (CI, ARM, restricted env)turboquant
Memory or docs search getting slowturboquantMemDocs: true

Setup

npm install turboquant-js
{
  "enableEmbeddings": true,
  "semanticEngine": "turboquant",
  "turboquantBits": 4
}

Or select it interactively during kirograph install — the installer auto-runs npm install turboquant-js for you. Falls back silently to cosine if turboquant-js is not installed.

Configuration

FieldTypeDefaultDescription
turboquantBitsnumber3Bits per coordinate (1–8). Lower = smaller, less accurate. Changing requires kirograph index --force.
turboquantMemDocsbooleanfalseAlso use TurboQuant ANN index for memory observations and doc sections.

The compressed index is serialized to .kirograph/turboquant.bin at the end of indexing and reloaded in milliseconds on startup. Run kirograph status to see live compression stats.

TurboVec

KiroGraph TurboVec

TurboVec is the Rust/SIMD counterpart of TurboQuant. It runs the same Walsh-Hadamard + Lloyd-Max quantization algorithm in Rust and exposes it to Node.js as a napi-rs native addon (native/turbovec-node/). SIMD-accelerated: NEON on ARM64 (Apple Silicon, AWS Graviton), AVX-512BW on x86-64. On macOS it links Apple's Accelerate framework; on Linux it links OpenBLAS; on Windows it uses pure-Rust matrixmultiply.

Built on turbovec by Ryan Codrai.

Why is native/turbovec-node/ outside src/? It is a Rust crate with its own build system (Cargo + napi-rs), not TypeScript compiled by tsc. It has its own Cargo.toml, package.json, and produces a platform-specific .node binary. The TypeScript wrapper that loads it lives at src/vectors/turbovec-index.ts — that is the integration boundary.

Compression at a glance

VectorsRaw Float32 in RAMTurboVec (4 bit)Reduction
1,000~3 MB~160 KB~19×
10,000~30 MB~1.6 MB~19×
100,000~300 MB~16 MB~19×

When to use TurboVec vs TurboQuant

SituationRecommendation
No Rust toolchain, CI/ARM, restricted envturboquant — zero native deps
macOS/Linux, want fastest ANN, Rust build OKturbovec — SIMD acceleration
Windowsturbovec works but installer requires manual rustup first

Setup

The simplest path is kirograph install — it auto-installs Rust (via rustup) if missing on macOS/Linux, then builds the addon. Or manually:

cd native/turbovec-node
npm install
npm run build   # requires Rust toolchain — https://rustup.rs
{
  "enableEmbeddings": true,
  "semanticEngine": "turbovec",
  "turbovecBits": 4
}

Falls back silently to cosine if the addon is not built.

Configuration

FieldTypeDefaultDescription
turbovecBitsnumber4Bits per coordinate (2, 3, or 4 only — validated at Rust level). Lower = smaller, less accurate. Changing requires kirograph index --force.
turbovecMemDocsbooleanfalseAlso use TurboVec ANN index for memory observations and doc sections.

The index is stored as two files: .kirograph/turbovec.tvim (binary) and .kirograph/turbovec.tvim.ids (JSON sidecar mapping internal u64 hashes back to string symbol IDs). Both are written atomically at the end of indexing.

Savings Heuristics

kirograph gain tracks two types of savings: compression (measured exactly) and graph tools (estimated via heuristics). For graph tools, the system estimates what the agent would have spent doing the same work without KiroGraph:

ToolWhat the agent would do manuallyEstimated naive cost
kirograph_contextRead 5-10 files to orient on a task~7,500-15,000 tokens
kirograph_searchRun grep + read top matches~3,300 tokens
kirograph_callersGrep for symbol + read each calling file~8,300 tokens
kirograph_calleesRead function body + grep for each call~3,900 tokens
kirograph_impactRecursive grep + read per depth level~6,900 × depth
kirograph_nodeRead the full file containing the symbol~1,500 tokens
kirograph_filesRun find or ls -R~2,000 tokens
kirograph_pathTrace connections (multiple grep + read)~7,700 tokens
kirograph_type_hierarchyGrep for extends/implements + read each file~5,400 tokens
kirograph_dead_codeNot feasible manually (read every file)5× output, min 15,000
kirograph_hotspotsNot feasible manually (count edges for every symbol)5× output, min 15,000
kirograph_architectureNot feasible manually4× output, min 7,500

Constants: 1,500 tokens per average source file (~200 lines), 800 tokens per grep result set, 2,000 tokens per directory listing. These are conservative estimates; in practice agents often read more files, retry failed searches, and explore dead ends.

Credits

Original idea

KiroGraph is inspired by CodeGraph by Colby McHenry. The original concept of building a semantic code graph for AI coding agents comes from his work.

Inspirations

  • cavemem by Julius Brussee: the memory module's hook-based observation capture, deterministic compression, and SQLite storage pattern.
  • Engram by Gentleman-Programming: conflict detection (typed relations + judgment workflow), topic_key stable addressing, review_after stale observation scheduling, passive capture, and prompt saving patterns.
  • caveman by Julius Brussee: the caveman mode's agent prose compression concept, multi-level steering injection.
  • watchmen by firstbatch: the watchmen module's session-mining concept, workspace brief generation, and AGENTS.md mirroring pattern.
  • LLM Wiki by Andrej Karpathy: the wiki module's three-op pattern (ingest → apply → lint), WIKI_DIFF block format, two-tool ingest flow, and the principle of knowledge compounding rather than accumulating.
  • jDocMunch-MCP by J. Gravelle: the documentation module's section-first retrieval approach, stable section IDs, and byte-offset addressing.
  • jDataMunch-MCP by J. Gravelle: the data module's column profiling, streaming parsers, and server-side aggregation approach.
  • code-review-graph by Tirth Kanani: community detection, execution flow tracing, refactoring tools, and multi-platform auto-detection patterns.
  • rtk by rtk-ai: the shell compression module's command-family approach and token-optimized output patterns.
  • lean-ctx by Yves Gugger: file read caching, multiple read modes, and context budget governance concepts.
  • headroom by Tejas Chopra: the CCR (Cached Content Retrieval) pattern behind kirograph_retrieve, the dual-engine on-demand compression behind kirograph_compress, and the KV cache prefix stability approach (deterministic cache markers).
  • turboquant-js by Danilo Dev: the TurboQuant engine — TypeScript implementation of Google's Walsh-Hadamard + Lloyd-Max quantization algorithm used for embedding compression.
  • turbovec by Ryan Codrai: the TurboVec engine — Rust implementation of TurboQuant with SIMD acceleration, exposed to Node.js via a napi-rs native addon.
  • pdf-inspector by Firecrawl: the PDF parser used in the data module — pure Rust, no OCR, no network, prebuilt binaries for linux-x64 and macOS ARM64. Exposes per-page markdown extraction with OCR and layout flags via a napi-rs native addon.
  • tokensave: gap-close roadmap inspiration — code quality tools (complexity, god class, recursion, doc coverage), git workflow context tools (diff_context, commit_context, test_map), atomic edit primitives, multi-branch indexing, per-call token metrics, and MCP protocol annotations (readOnlyHint, alwaysLoad).

Contributors

  • Alessandro Franceschi: Claude Code and Codex integration, Elixir/Phoenix language and framework support.
  • Mauro Argo: original idea for the architecture layer analysis feature.

Stargazers & Community

Thank you to everyone who contributed and starred the project on GitHub.

stars forks contributors