Documentation

ripwire-rs is a high-throughput code intelligence engine and context router for AI coding agents and developers. It indexes 36 programming languages via Tree-Sitter to construct directed call graphs, calculate symbol impact via Personalized PageRank, slice intra-procedural dataflow, and enforce pre-commit quality gates.

Lineage & Attribution: ripwire-rs is an idiomatic Rust port and rewrite of the original C++23 ripwire engine authored by David Brewster at Red Hat Emerging Technologies. We gratefully acknowledge their foundational work on token-budgeted streaming call graphs, pre-commit delta heuristics, and deterministic code intelligence for AI agents.
100% Local & Zero Telemetry Guarantee: ripwire-rs is completely offline-by-design. It makes zero network calls, contains zero analytics or telemetry, and performs zero model training. Your proprietary source code never leaves your workstation. It functions purely as an in-process local AST parser that emits structured context to stdout or stdio MCP for the agent harness or LLM you control. Automated secret redaction is active by default.

Installation

Homebrew (macOS & Linux)

brew install casonadams/tap/ripwire-rs

APT (Ubuntu & Debian — amd64 & arm64)

echo "deb [trusted=yes] https://casonadams.github.io/homebrew-tap/apt stable main" | sudo tee /etc/apt/sources.list.d/casonadams.list
sudo apt update && sudo apt install ripwire-rs

DNF / RPM (Fedora, RHEL & CentOS — x86_64 & aarch64)

curl -fsSL https://casonadams.github.io/homebrew-tap/rpm/casonadams.repo | sudo tee /etc/yum.repos.d/casonadams.repo
sudo dnf install ripwire-rs

Cargo & cargo-binstall

cargo binstall ripwire-rs
# or compile from crates.io source:
cargo install ripwire-rs

From Source

git clone https://github.com/casonadams/ripwire-rs.git && cd ripwire-rs && make install

ripwire-rs CLI Reference

The ripwire-rs binary offers both direct flag-based execution and structured workflow subcommands.

ripwire-rs [PATH] [--top-k <N>] [--max-tokens <N>] [--stable] [--legend <MODE>] [--cache <PATH>] [--no-cache] [--scip <FILE>]
Architecture
What It Does

Parses the repository at PATH (defaults to current directory), builds the workspace call graph across 36 languages, executes Personalized PageRank, and streams ranked symbol definitions with incoming callers as canonical XML (bounded by --top-k symbol count or --max-tokens / --pack-budget streaming limits). Automatically caches compiled call graphs in TMPDIR for sub-second repeat queries (use --no-cache for cold parse). --scip=index.scip overlays a compiler-backed SCIP index: the call sites it resolves bind exactly (prov="scip", header precise=K) and bypass the cache.

The same global --scip=PATH overlay works before or after navigate, plain or task-ranked orient, and mcp. MCP retains its indexed graph for the session. Multiline calls match the callee identifier's index line; reports preserve the call expression's start line. Unreadable or malformed indexes fail explicitly without a name-only fallback.

How It Works

Runs Tree-Sitter syntax queries in parallel via Rayon, interns symbols with Lasso, resolves call references through a multi-tier precedence ladder, and executes power iteration over a compressed sparse row (CSR) transpose in-edge matrix. Serializes binary cache payloads keyed by git HEAD SHA and file mtimes to deliver warm map responses in under 50ms on medium repos and ~600ms on 7,000+ file codebases with 60%–85% lower memory footprint than C++.

When To Use It

When first landing in an unfamiliar codebase, retrieving high-level architectural anchors, or packing dense, budget-bounded context into LLM prompts without hallucinated dependencies.

ripwire-rs --quality-delta
Safety Gate
What It Does

Compares uncommitted working tree changes against git HEAD (or a pinned baseline) and reports code quality regressions across complexity, duplication, dead code, and contract breaks. Exits non-zero if gating regressions are detected.

How It Works

Computes multi-vector quality snapshots (Campbell cognitive complexity via cccc, cyclomatic complexity, Type-1/2/3 AST clones, arity changes) on both revisions and diffs the findings, filtering out expected churn and self-registering test macros.

When To Use It

In pre-commit hooks, local developer validation before git push, or automated CI/CD merge-safety pull request checks.

ripwire-rs --lint [--sarif]
Linter & SARIF
What It Does

Scans the repository for AST code smells (complexity spikes, deep nesting, high parameter counts, dead functions) and emits Ripwire XML or standard SARIF 2.1.0 JSON when --sarif is passed.

When To Use It

In GitHub Code Scanning workflows, IDE diagnostics, or automated pull request quality checks.

ripwire-rs --edit-plan <PLAN_JSON> [--dry-run]
Atomic Edits
What It Does

Executes multi-file AST symbol edits transactionally with two-phase preflight validation and --dry-run verification.

When To Use It

When applying coordinated multi-symbol refactorings generated by an AI coding agent without risking partial file corruption.

ripwire-rs --test-gate [FILES]
Safety Gate
What It Does

Pre-PR verification gate: identifies all test suites that reach modified files and detects untested transitive blast radius. Exits with status code 4 if obligations remain.

How It Works

Inspects git working tree diffs, traces reverse call graph reachability to test harnesses, and evaluates untested downstream symbols across 1-hop and transitive edges.

When To Use It

In pre-push and PR verification gates to ensure all modified code is tested before opening pull requests.

ripwire-rs --expand <SYMS>
Detail Ladder
What It Does

Expands full source bodies and callee signatures for comma-separated symbols, wrapped in token-dense CDATA XML blocks.

How It Works

Extracts exact byte spans from the underlying source files, resolving qualified selectors (`Type::method`, `file:name`), and streams the function bodies to stdout.

When To Use It

When drilling down from architectural map summaries to implementation details of specific core functions.

ripwire-rs --dead-code
Architecture
What It Does

Scans the entire workspace call graph and identifies internal functions and methods with zero incoming callers.

How It Works

Computes in-degree matrix offsets across the graph, filtering out public library entry points and self-registering test macros.

When To Use It

During codebase refactoring, dead-weight cleanup, or technical debt audits to find safely removable internal code.

ripwire-rs --edit-check <SYM>
Safety Gate
What It Does

Verifies whether recent modifications to symbol <SYM> altered its parameter count or visibility, identifying all direct callers in the codebase that become incompatible with the new signature.

How It Works

Extracts parameter counts and visibility modifiers from the AST at both revisions. Traverses 1-hop reverse call graph edges to check if existing call sites pass matching argument arity.

When To Use It

Immediately after refactoring or modifying a public function, method, or constructor signature, before executing full workspace test suites.

ripwire-rs --affected <PATH>
Safety Gate
What It Does

Identifies exactly which test files transitively reach the changed file or symbol <PATH>, ranking them by evidence tier (edited tests, partner-named tests, call hop distance).

How It Works

Computes transitive reachability over reverse call graph edges from the target node, keeping nodes in test files (tests/, test_*, *_test.*, *.test.*, *.spec.*). Tests named after a changed file are added as partner="1" rows even with no call edge; a file with several candidate partners gets none.

When To Use It

To run a surgical, high-confidence subset of fast regression tests instead of running the entire multi-minute test suite during tight TDD loops.

ripwire-rs --hotspots
Metrics
What It Does

Ranks repository files by maintenance risk score, combining commit churn with cognitive complexity to highlight fragile, high-risk code hotspots.

How It Works

Mines git commit history with exponential half-life time decay (weighting recent revisions higher) and multiplies file commit frequency by average McCabe and Campbell cognitive complexity.

When To Use It

Prior to architectural refactoring, when scoping technical debt, or when allocating code review attention to the most defect-prone files in a repository.

ripwire-rs --dmm [REV|A..B]
Quality
What It Does

Computes the Delta Maintainability Model (DMM) scalar in [0,1], quantifying the proportion of code volume churn that made the codebase healthier.

When To Use It

In CI gates or wave reviews to track whether refactorings genuinely reduced unit risk or introduced new technical debt.

ripwire-rs --quality-panel [PRESET]
Panel
What It Does

Runs the unified 6-family quality panel (structural, lexical, confusion, historical, colocation, state) in one report ranked by distinct families fired.

When To Use It

Before major code convergence to perform a wide-angle sanity check across all quality evidence families simultaneously.

ripwire-rs --cochange [<FILE>]
Git Analytics
What It Does

Surfaces companion files that historically change together with <FILE>, detecting hidden Fowler's Shotgun Surgery coupling.

How It Works

Scans multi-file commit transactions across git history, filters out repository-wide merge-bombs (>100 files), and calculates co-change support, confidence, and surprise ratios.

When To Use It

Before editing an interface, schema, or configuration file, to guarantee that all implicit partner files (docs, test fixtures, downstream consumers) are updated in the same change.

ripwire-rs --slice <SYM[:VAR]> [--slice-flow <fwd|back|both>]
Slicing
What It Does

Traces intra-procedural def-use variable occurrences inside function <SYM>, mapping how variable <VAR> is initialized, assigned, and consumed.

How It Works

Implements the ARISE slicing algorithm (arXiv:2605.03117) over Tree-sitter AST nodes to build localized def-use chains, control dependencies, and reaching definitions in forward, backward, or bidirectional flow.

When To Use It

When debugging variable corruption, auditing taint propagation or untrusted user input, or tracing complex state mutations without stepping through a live debugger.

ripwire-rs --clones [--min-tokens <N>]
Hygiene
What It Does

Scans the codebase for duplicate logic, grouping candidate functions into exact (Type-1), renamed identifier (Type-2), and near-miss gapped (Type-3) clone groups.

How It Works

Tokenizes function bodies while skipping comments and string literals, computes $k$-gram token window hashes with in-place sort-dedup, evaluates Jaccard similarity, and validates near-misses via Longest Common Subsequence (LCS).

When To Use It

During code audits to consolidate duplicate utility routines into shared helpers, or to prevent boilerplate copy-pasting in team workflows.

ripwire-rs --callers <SYM> / --callees <SYM> / --find-symbol <SYM>
Navigation
What It Does

Emits the 1-hop neighborhood of a symbol: all direct incoming callers, outgoing callees, definitions, and ambiguity metrics formatted as XML. Works seamlessly across code symbols and database tables (e.g. ripwire-rs . --callers=user_accounts lists all functions across Dart, Rust, Python, TypeScript, Go, etc. that query or mutate that table).

How It Works

Interns <SYM> in $O(1)$ to find matching graph node IDs and directly indexes the CSR row offsets and target vectors without iterator allocations.

When To Use It

When tracing call hierarchies, checking who invokes a utility function, or inspecting the dependencies invoked by a given method.

ripwire-rs --impact <SYM> [--impact-depth <N>]
Navigation
What It Does

Computes the full transitive downstream blast radius of modifying <SYM>, ranking all dependent symbols by PageRank influence. Automatically traces blast radius across language boundaries—including from .sql migration files through to application services and test suites that touch altered tables (pairs with --affected, --test-gate, and --situ).

How It Works

Seeds Personalized PageRank with mass focused on <SYM> and runs power iteration across outgoing call edges to measure relative dependency concentration.

Unbound candidate calls appear separately as <dc> rows, not graph edges. dc_shown of declined_calls says how many a capped list holds; raise --token-budget to show more.

When To Use It

Before deprecating, modifying, or removing a core interface, data structure, or shared utility function to determine the full scope of downstream impact.

ripwire-rs --uses <SYM>
Lineage & Uses
What It Does

Emits every statically resolvable use-site of <SYM> across the repository (calls, reads, writes, imports, inheritance)—including cross-language embedded SQL table lineage extracted automatically from application string literals.

Lists every indexed site by default. Use --limit=N --offset=M for a path-and-line ordered window, then continue at next_offset.

How It Works

Zero extra flags required. During standard AST ingestion across all 36 languages, string literals containing SQL DML (SELECT ... FROM, JOIN, INSERT INTO, UPDATE, DELETE FROM) automatically emit RefRole::Read and RefRole::Write references attributed to the enclosing function or method, resolving directly to .sql table definitions in the workspace graph.

Python, JavaScript/TypeScript, and Rust also index bare non-local variable reads, excluding bindings, writes, labels, and lexical shadows. Grep's reads and reads_at use these references rather than text estimates; unsupported binding forms remain evidence floors.

When To Use It

When refactoring database schemas or migrating tables (e.g. ripwire-rs . --uses=user_accounts) to identify every backend service, repository method, query function, or migration touching that table.

ripwire-rs --path-between <A:B>
Architecture
What It Does

Finds the shortest directed call chain connecting symbol A to symbol B, returning the exact hop-by-hop sequence of intermediate functions.

How It Works

Executes bidirectional breadth-first search (BFS) over the resolved directed CSR call graph edges, returning reachability and hop count.

When To Use It

Investigating how an API controller reaches a database query, or checking for unintended architectural layer breaches between disparate modules.

ripwire-rs . --html [<FILE>] [--color-by <MODE>]
Visualization
What It Does

Exports a standalone, interactive HTML visualization of the call graph with pan-zoom canvas, node search, and configurable coloring modes.

How It Works

Embeds graph topology and metadata into an SVG canvas with interactive controls, supporting coloring by language, Louvain community clusters, cognitive complexity, or churn.

When To Use It

Architecture reviews, developer onboarding, and visually communicating system structure to non-technical stakeholders.

ripwire-rs . --grep <PAT> [--grep-in code|any] [--grep-scope line|file] [--and <PAT>] [--not <PAT>] [--in <PATH>]
Search
What It Does

Literal search with span tiering (code by default, --grep-in=any adds comments and strings), boolean filtering (--and, --not, --grep-scope) and path restriction (--in), annotating every hit with its enclosing AST definition and listing matches in off-index text files in a trailing <unindexed> element.

How It Works

Classifies code, comment, and literal spans through language semantics. Comments are withheld when code hits exist; strings ride along with fewer than eight code hits. The innermost AST byte span identifies each hit's enclosing symbol.

When To Use It

Finding symbol references or keywords scoped to a specific directory or parent module while excluding noise.

ripwire-rs . --baseline / --baseline-update / --pin-census
Safety Gate
What It Does

Pins and updates architectural baselines and quality census snapshots stamped with git HEAD, enabling progressive ratcheting of codebase health without false alarms on legacy code.

How It Works

Writes baseline sidecar files recording known violations so --quality-delta enforces zero net-new regressions. --quality-baseline refuses on a dirty tree that already gates against HEAD; --allow-dirty pins anyway and later deltas report baseline_absorbed=. A regression-free delta collapses stale ack rows to stale_by_kind=; --show-stale prints them.

When To Use It

Establishing a quality ratchet in legacy codebases or ratcheting quality improvements across release branches.

ripwire-rs . --report / --legend-dict
Inspection
What It Does

Generates executive Markdown architecture summaries (--report) or emits full schema legend dictionaries (--legend-dict) explaining all AST tags and attribute abbreviations.

How It Works

Synthesizes connectivity, ranking, and quality panel metrics into human-readable Markdown or machine-verifiable schema definitions.

When To Use It

Creating architectural documentation for PR descriptions or configuring coding agent prompt preambles.

ripwire-rs . --help-task <TASK>
Retrieval
What It Does

Analyzes a natural-language engineering task description and recommends the optimal ripwire-rs verb, flags, and syntax to answer it with minimal token cost.

How It Works

Maps intent keywords and structural goals against ripwire-rs's operational ontology, returning recommended command invocations.

When To Use It

Coding agent prompt routing and developer onboarding when deciding which ripwire-rs command fits a complex debugging task.

ripwire-rs . --pack-task <TASK> [--partition <N>]
Orchestration
What It Does

Packages ranked signatures, top implementation bodies, 1-hop callers, and affected tests under a single token budget—or partitions the surface into 1 shared core plus N minimally-overlapping subagent bundles (N=2..16).

How It Works

Carves assignable task symbols along Louvain call-graph communities (falling back to file grouping for edgeless types and median-splitting when K < N), packs bins largest-first, and reports pairwise Jaccard overlap.

When To Use It

Single-call agent task orientation or fanning a multi-symbol feature across parallel subagents without duplicate discovery spend.

ripwire-rs . --plan-lanes [<N>] [--task <GOAL> | --brief <FILE>]
Orchestration
What It Does

Emits a deterministic 1-line JSON worktree plan predicting which parallel agent lanes will collide, touch each other's contracts, and in what order they should land.

How It Works

Keys symbol claims on path-qualified FNV-1a hashes (path\0scope\0name), intersects claims against transitive caller blast radii, and orders lanes by fewest conflicts first.

When To Use It

Before spawning N parallel git worktree agents on a shared repository.

Structured Subcommands

Categorized workflow groups providing focused subcommands for developer and agent workflows:

ripwire-rs orient [PATH] [--for <TASK>] [--scip <FILE>]
Exploration
What It Does

Returns a task-lens ranked inventory of building block symbols, signatures, and callers most relevant to a natural language task description.

How It Works

Combines BM25 lexical token matching with Personalized PageRank proximity to score and rank symbol definitions under a deterministic byte or token ceiling.

When To Use It

The entry point for starting any multi-symbol feature, bug fix, or agent task in an unfamiliar repository.

ripwire-rs navigate [PATH] --symbol <SYM> [--callers | --callees | --impact] [--scip <FILE>]
Navigation
What It Does

Navigates symbol neighborhoods and downstream impact trees with explicit command options.

How It Works

Direct CSR index traversals yielding file paths, line bounds, and call hierarchy rankings.

When To Use It

Scripted agent tools or editor extensions requiring structured subcommands rather than top-level flags.

ripwire-rs gate [PATH] [--edit-check <SYM>] [--affected <PATH>] [--quality-delta]
Safety Gate
What It Does

Runs pre-commit verification checks in a unified batch, outputting structured pass/fail results for CI runners and git hooks.

How It Works

Dispatches contract comparison, test reachability, and quality delta regression evaluation concurrently.

When To Use It

In .pre-commit-config.yaml, GitHub Actions PR workflows, or local git hook scripts before committing.

ripwire-rs metrics [PATH] [--hotspots]
Metrics
What It Does

Analyzes repository codebase health, reporting cognitive complexity, Halstead volume, Posnett readability, and historical commit churn.

How It Works

Parses AST control structures for McCabe and Campbell complexity alongside information-theoretic readability entropy models.

When To Use It

During sprint retrospectives, technical debt triage, and code quality audits.

ripwire-rs slice [PATH] --symbol <SYM:VAR> [--slice-flow <fwd|back|both>]
Slicing
What It Does

Dedicated subcommand interface for intra-procedural def-use variable slicing with step-by-step dataflow tracing.

How It Works

AST dataflow engine traversing intra-procedural expression trees and control statements.

When To Use It

Vulnerability auditing, finding dead variable assignments, and validating functional state immutability.

ripwire-rs mcp [PATH] [--scip <FILE>]
Integration
What It Does

Starts a persistent stdio JSON-RPC server implementing the Model Context Protocol (MCP) for AI coding assistants.

How It Works

Overlapping tools return canonical CLI XML/text in result.content[0].text, with identical facts, defaults, errors, limits, grouping, provenance, and declined evidence. Maps default to 200 symbols / 65536 bytes; rank signals are pagerank, authority, hub, degree, ccx, and stable (unknown signals error). Connect defaults to radius 2. Situational awareness emits ripwire-rs.situ/v1 XML. Slice shares CLI root, flow/depth validation, and errors.

Impact's optional MCP max_depth matches global CLI --impact-depth=N, also with navigate --impact. Reports preserve legends without session mutation. CLI --json preserves XML hierarchy and text/CDATA: root tag/attributes/items, leaf text, mixed text interleaved in items, reserved-name attributes under attributes, and namespaced names as {uri}local; malformed reports error. Batch uses the real root and shared registry, caps both transports at 16, and rejects recursive batches/writes per item.

Batch success entries retain tool/result/kind (xml|text|json); malformed names fail per item, and CLI XML safely escapes text/JSON results. MCP owners accepts integer detail > 0; whereis accepts listing=defs|refs|all and boolean full_text, rejecting invalid listings. Detail 2 includes all requested bodies with accurate shown/total; root/revision and effective connect radius remain canonical.

When To Use It

In any MCP-compatible client or coding agent to equip AI workflows with native code intelligence tools.

ripwire-rs skills [DIR] / ripwire-rs --add-skills
Agents
What It Does

Provisions 17 pre-packaged ripwire-rs agent skills and the active manifest (.ripwire-rs-manifest-v1) directly into ~/.agents/skills (or a custom directory).

How It Works

Embeds all 17 skill definition packages into the binary, resolving cross-platform agent discovery paths and repairing stale or broken symlinks safely.

When To Use It

When onboarding coding agents to immediately activate ripwire-rs skills across any repository.

Pre-Commit Verification Gates

Ripwire integrates directly into pre-commit workflows and CI/CD pipelines to prevent regressions:

Model Context Protocol (MCP) Tools

Ripwire embeds a native JSON-RPC stdio server exposing context routing tools directly to any MCP-compatible coding agent:

Tool Category Description
exploreRetrievalRanked map, bodies, callers, and test targets in a single byte-budgeted response.
forRetrievalTask-lens relevance ranking using BM25 and Personalized PageRank.
batchRetrievalExecute up to 16 heterogeneous sub-queries in a single call.
fetch_bodyRetrievalFetch symbol definition source code by handle or name with optional line bounds.
exemplarRetrievalRetrieve the best-in-class implementation of a given role (fn, class, interface).
legoRetrievalInterface contract view with all implementors across the workspace.
grepSearchTrigram literal search annotated with enclosing symbols and definitions.
find_symbolNavigation1-hop symbol neighborhood: callers, callees, definitions, and ambiguity metrics.
find_referencing_symbolsNavigationDirect (1-hop) callers of a symbol or database table.
callersNavigationCanonical direct caller report with definition grouping.
calleesNavigationCanonical direct callee report with provenance and declined evidence.
impactNavigationTransitive blast radius of a symbol or database table via call and reference hierarchy.
usesNavigationStatically resolvable use-sites (call, read, write, import, extends), including embedded SQL table lineage from application strings.
path_betweenArchitectureShortest directed call path between two symbols.
connectArchitectureMinimal directed connecting subgraph relating 2..16 symbols.
analyzeArchitectureArchitecture map ranked by PageRank or chosen metric.
rank_byArchitectureArchitecture map ranked by pagerank, authority, hub, degree, ccx, or stable; unknown signals error.
situational_awarenessArchitectureDiff context: blast radius, tests to run, and forgotten co-change partners.
from_traceDebuggingMaps stack trace frames and compiler errors onto indexed symbol definitions.
sliceSlicingIntra-procedural def-use variable slicing (forward, backward, or both).
cochangeGit AnalyticsHistorical Shotgun Surgery co-change coupling.
ownersGit AnalyticsRecency-weighted author ownership per file.
edit_checkSafety GatesVerify caller compatibility after editing a function contract.
affectedSafety GatesTransitive test reachability mapping from changed symbols.
quality_baselineSafety GatesSnapshot code quality floor at current commit; refuses on a dirty tree that already gates unless allow_dirty is true.
quality_deltaSafety GatesPre-commit quality regression self-check against baseline or git HEAD.
doc_driftDocumentationDetect out-of-bounds file:line references in markdown documents.
mentionsDocumentationLocate markdown design notes referencing a code symbol in backticks.
memory_recallDocumentationRelevant documentation and design notes matching a task.
flagsInspectionDark feature flags, #ifdef guards, and runtime environment variable reads.
whereisInspectionBranch divergence tracker: finds which branch's tree defines a symbol.
stray_contentInspectionLines authored on a divergent branch not present in HEAD.
replace_symbol_bodyAtomic EditAtomically replace an entire symbol definition with verified byte rollback.
insert_before_symbolAtomic EditAtomically insert source code before a symbol definition.
insert_after_symbolAtomic EditAtomically insert source code after a symbol definition.

Algorithms & Academic Lenses

ripwire-rs implements 11 academic and algorithmic lenses over codebase graphs and behavioral histories:

Rust Library API

Embed ripwire-rs directly into your Rust developer tools, custom CLI utilities, or AI agent runtimes:

// Cargo.toml
[dependencies]
ripwire-rs = "0.6"

// src/main.rs
use ripwire_rs::ingest::{LanguageRegistry, ingest_in_memory_files};
use ripwire_rs::{Graph, Interner, Lang, PageRankConfig};

fn main() {
    let interner = Interner::new();
    let registry = LanguageRegistry::new();
    let files = [("src/main.rs", Lang::Rust, b"fn main() { run(); }\nfn run() {}" as &[u8])];
    let ingest = ingest_in_memory_files(&files, &registry, &interner);

    let graph = Graph::build(&ingest, &interner);
    let pr = graph.page_rank(&PageRankConfig::default());

    println!(
        "Indexed {} symbols and {} edges (iters={})",
        ingest.symbols.len(),
        graph.edge_count(),
        pr.iterations
    );
}