codeknit
A static code structure extractor. codeknit parses source code and extracts structural information (functions, classes, methods, relationships) into a compact intermediate representation suitable for LLM consumption.
Why
LLMs are great at generating code, but struggle with large-scale refactoring. They can't hold an entire codebase in context, so they miss duplication, inconsistent patterns, and architectural drift.
codeknit solves this by converting your codebase into a compact structural graph that focuses just on the code skeleton: function signatures, class hierarchies, call relationships, and module boundaries. No implementation details, no noise. LLMs can parse this representation directly and produce concrete, well-informed refactoring plans across hundreds of files.
Use with AI coding assistants
codeknit ships as a plugin for Claude Code, Codex, and Kiro. It contains a single codeknit skill that teaches the assistant when and how to run parse, graph analyze, and fingerprint, and how to read the .skt output. You don't need to install the binary yourself. The first time the skill runs, it checks for codeknit. If the binary is missing, the skill downloads the latest release for your platform, verifies it against the release checksums.txt, and installs it to ~/.local/bin.
Claude Code (run in your shell, or inside a session as /plugin ...):
claude plugin marketplace add awslabs/codeknit --sparse .claude-plugin skills
claude plugin install codeknit@codeknit
Codex:
codex plugin marketplace add awslabs/codeknit --sparse .agents --sparse .codex-plugin --sparse skills
codex plugin add codeknit@codeknit
Kiro IDE: open the Powers panel, choose Add Custom Power → Import power from GitHub, and enter https://github.com/awslabs/codeknit.
Kiro CLI (installs from a local path):
git clone --depth 1 --filter=blob:none --sparse https://github.com/awslabs/codeknit ~/.codeknit-power
git -C ~/.codeknit-power sparse-checkout set skills
kiro-cli powers install ~/.codeknit-power
--sparse is optional. It keeps the clone down to the plugin manifests and skills/ instead of the whole source tree. To update, run claude plugin marketplace update codeknit, codex plugin marketplace upgrade, Check for updates in the Kiro Powers panel, or git -C ~/.codeknit-power pull followed by the install command again.
The skill can also be copied by hand into any assistant that reads Agent Skills: copy skills/codeknit/ into ~/.claude/skills/, ~/.codex/skills/, or ~/.kiro/skills/. To pin the binary version, set CODEKNIT_VERSION. To change the install location, set CODEKNIT_INSTALL_DIR.
Supported languages
C, C++, C#, Go, Java, JavaScript, PHP, Python, Ruby, Rust, Scala, TypeScript
See the language capability matrix for tested API extraction and known limitations. TypeScript/JavaScript module extensions (.mts, .cts, .mjs, .cjs) are supported. TSX uses the JSX-aware TypeScript grammar.
For ambiguous .h files, all source-processing commands accept --header-language c|cpp (default c). Use --header-language cpp for C++ headers named .h; .hpp and .hxx already use C++.
Installation
From prebuilt binaries
Prebuilt binaries are available on the releases page for Linux, macOS, and Windows (amd64 and arm64).
Download the archive for your platform, extract it, and move the binary onto your PATH:
# macOS (Apple Silicon) — adjust OS/arch and version as needed
VERSION=0.1.0
OS=darwin # darwin, linux, or windows
ARCH=arm64 # arm64 or amd64
curl -sSL -o codeknit.tar.gz \
"https://github.com/awslabs/codeknit/releases/download/v${VERSION}/codeknit_${VERSION}_${OS}_${ARCH}.tar.gz"
tar -xzf codeknit.tar.gz
sudo mv codeknit /usr/local/bin/
On Windows, download the ..._windows_amd64.zip archive from the releases page, extract it, and move codeknit.exe to a directory on your PATH.
Verify the download against the published checksums:
curl -sSL -O "https://github.com/awslabs/codeknit/releases/download/v${VERSION}/checksums.txt"
sha256sum --ignore-missing -c checksums.txt
Then confirm it runs:
codeknit --version
From source
Requires Go 1.26+ and a C compiler (CGo is needed for tree-sitter).
git clone https://github.com/awslabs/codeknit.git
cd codeknit
make build
# Binary is at ./bin/codeknit
Add to your PATH
If you installed the binary to a custom location instead of /usr/local/bin/, add it to your shell:
# bash (~/.bashrc)
export PATH="$PATH:/path/to/codeknit"
# zsh (~/.zshrc)
export PATH="$PATH:/path/to/codeknit"
# fish (~/.config/fish/config.fish)
fish_add_path /path/to/codeknit
Reload your shell or run source ~/.bashrc (or ~/.zshrc) for the change to take effect.
Verify it works:
codeknit --version
Shell completions
codeknit supports auto-completion for bash, zsh, fish, and PowerShell:
# bash
codeknit completion bash >> ~/.bashrc
# zsh
codeknit completion zsh >> ~/.zshrc
# fish
codeknit completion fish > ~/.config/fish/completions/codeknit.fish
# PowerShell
codeknit completion powershell >> $PROFILE
Usage
codeknit has five primary command workflows:
codeknit parse— extract structural information into.sktfilescodeknit fingerprint— detect duplicate and near-duplicate code using fuzzy hashingcodeknit graph show— generate an interactive HTML graph visualizationcodeknit graph analyze— run structural analysis algorithms and emit an LLM-readable reportcodeknit graph hotspots— rank change hotspots using Git history and graph structure
Parse a codebase
# Flat directory output (default, writes to ./skeleton)
codeknit parse ./myproject
# Custom output directory
codeknit parse ./myproject ./output
# Tree-mirroring directory output
codeknit parse ./myproject ./output --output-mode directory-tree
# Inline output to stdout
codeknit parse ./myproject --output-mode inline
Interactive mode
Running codeknit with no arguments launches the interactive terminal UI, which guides you through all available commands and options.
codeknit
Parse flags
Flags:
--output-mode string output mode: inline, directory-flat, directory-tree (default "directory-flat")
--format string output format: skt, json (default "skt")
--max-lines int line target for flat output; hard source-chunk limit >=3 for tree (default 500)
--collect-test include test files in analysis
--minify enable dictionary-based output minification
--edges include the [edges] section in output (off by default to save tokens)
--clean replace previous generated output after successful generation
--verbose print progress information during processing
--workers int max concurrent parsing goroutines (0 = NumCPU)
The output directory defaults to ./skeleton when not specified. You can override it by passing a second positional argument. In inline mode, no output directory is used — results go to stdout.
If the output directory already contains .skt files from a previous run, codeknit will refuse to write to avoid mixing stale and fresh output. Pass --clean to replace them after successful generation. Tree output preserves source extensions (foo.c.skt, foo.h.skt); split names include the extension (foo.c_part1.skt). Failed generation preserves previous results, and interrupted directory publication is recovered on the next run. JSON mode protects codeknit.json in the same way.
With --edges, relationships that cannot be established remain visible as --kind[unresolved]--> or --kind[ambiguous]--> in SKT, with candidate IDs when available. JSON carries the same information in resolution and candidates. C/C++ includes use meta/file and meta/include symbols so their edges have short IDs; this does not imply compiler-level header resolution. See the output format reference for examples. When upgrading to 0.5.0, regenerate all output chunks together because symbol IDs and relationship results can change.
Parse examples
# Include test files and minify output
codeknit parse ./src --collect-test --minify
# Include relationship edges (off by default to save tokens)
codeknit parse ./src --edges
# Emit machine-readable JSON to stdout
codeknit parse ./src --output-mode inline --format json
# Re-run and overwrite previous output
codeknit parse ./src --clean
# Custom output directory with tree layout
codeknit parse ./src ./out --output-mode directory-tree
# Limit output file size and parallelism
codeknit parse ./src --max-lines 500 --workers 4
Detect duplicate code
# Find near-duplicates (65-95% similarity, default)
codeknit fingerprint ./myproject
# Find only exact duplicates
codeknit fingerprint ./myproject --min-similarity 100 --max-similarity 100
# Find moderately similar code (50-80%)
codeknit fingerprint ./myproject --min-similarity 50 --max-similarity 80
# Semantic matching — finds embedding neighbors and filters false positives
# requires: ollama serve && ollama pull qwen3-embedding:0.6b
codeknit fingerprint ./myproject --rerank
# Semantic matching with a different model
codeknit fingerprint ./myproject --rerank --model qwen3-embedding:4b
# Include raw fingerprint listing
codeknit fingerprint ./myproject --show-all
# Custom output file
codeknit fingerprint ./myproject -o duplicates.skt
fingerprint computes fuzzy hashes from a normalized intermediate representation of each function, method, variable, and type — capturing semantic operations (assignments, calls, comparisons, control flow) while ignoring variable names, string literals, and type annotations. This enables duplicate detection across different programming languages.
Flags:
-o, --output string output file path (default: ./skeleton/fingerprints.skt)
--min-similarity int minimum similarity percentage to report (0-100) (default 65)
--max-similarity int maximum similarity percentage to report (0-100) (default 95)
--show-all include the [fingerprints] section with raw token data
--rerank find semantic neighbors and rerank candidates with Ollama embeddings
(requires: ollama serve && ollama pull qwen3-embedding:0.6b)
--model string Ollama embedding model to use with --rerank (default: qwen3-embedding:0.6b)
--collect-test include test files in analysis
--workers int max concurrent parsing goroutines (0 = NumCPU)
--verbose print progress information during processing
Exact normalized-token candidates are complete across the 500-symbol retrieval threshold. Near-duplicate retrieval at 500 or more eligible symbols is approximate (top-50 neighbors per symbol); similarity scores are heuristic rankings. Use --min-similarity 100 --max-similarity 100 for exact structural matches. Optional semantic reranking can filter those candidates.
All five source-processing commands accept --include GLOB and --exclude GLOB (repeatable, relative to the input), --max-file-size BYTES (10 MiB by default; 0 disables the limit), and --strict. Scans skip and report symlinks, oversized sources, and unreadable paths. Partial results retain diagnostics; strict mode fails before output is written. See the maintained analysis reliability reference for ignore semantics, publication guarantees, and calibration limits.
Visualize codebase structure
# Generate an interactive HTML graph (opens in browser)
codeknit graph show ./myproject
# Custom output file
codeknit graph show ./myproject -o graph.html
# Include test files
codeknit graph show ./src --collect-test
graph show parses the codebase and produces a self-contained HTML file with an interactive graph visualization. Symbols (functions, classes, types) appear as nodes and their relationships (calls, contains, implements) as edges. The file opens automatically in your default browser.
The viewer draws resolved relationships and shows a count of uncertain relationships. To inspect individual unresolved or ambiguous edges and their candidates, use codeknit parse ./src --output-mode inline --edges (add --format json for JSON).
Flags:
-o, --output string output HTML file path (default: ./skeleton/codeknit-graph.html)
--collect-test include test files in analysis
--workers int max concurrent parsing goroutines (0 = NumCPU)
--verbose print progress information during processing
Analyze codebase structure
# Run structural analysis with defaults
codeknit graph analyze ./myproject
# Custom output and thresholds
codeknit graph analyze ./myproject -o analysis.skt --fan-threshold 15
# Show more results per section
codeknit graph analyze ./myproject --top-n 50
# Include test files
codeknit graph analyze ./src --collect-test
graph analyze runs structural graph algorithms on the codebase and emits an LLM-readable .skt report. It detects code quality issues such as cyclic dependencies, hub symbols, dead code, god classes, deep inheritance chains, bottleneck functions, and more.
The 22 algorithms include: cyclic dependency detection (Tarjan's SCC), hub detection (fan-in/fan-out coupling), orphan detection, god class/function detection, instability metric, deep inheritance chains, betweenness centrality, articulation points, PageRank, transitive fan-in (blast radius), change propagation simulation, circular package dependencies, layer violation detection, reachability from entry points, weakly connected components, dependency weight, distance from main sequence, shotgun surgery detection, feature envy detection, stable dependency violations, interface segregation violations, and containment depth.
Dependency metrics exclude uncertain relationships and file/include metadata; the report records excluded relationship counts. Fan-in and fan-out count distinct neighbors. Findings are candidates for review: external callers and dynamic dispatch can affect reachability, and change-propagation scores are heuristic weights rather than measured probabilities. See the language support reference for resolution rules and limits.
Flags:
-o, --output string output .skt file path (default: ./skeleton/graph_analysis.skt)
--collect-test include test files in analysis
--workers int max concurrent parsing goroutines (0 = NumCPU)
--verbose print progress information during processing
--fan-threshold int minimum fan-in or fan-out to flag a hub symbol (default 10)
--god-threshold int minimum contains-edge count to flag a god class/function (default 15)
--max-inheritance-depth int flag inheritance chains deeper than this (default 5)
--top-n int cap ranked output sections; 0 = no limit (default 30)
--betweenness-threshold float64 minimum betweenness centrality value to report (default 0.001)
--propagation-cutoff float64 minimum probability to continue change propagation (default 0.05)
Find history-aware hotspots
# Rank files using the last 12 months of Git history
codeknit graph hotspots ./myproject
# Analyze two years and emit JSON
codeknit graph hotspots ./myproject --since 2y --format json -o hotspots.json
# Include larger commits and require stronger temporal coupling
codeknit graph hotspots . --max-files-per-commit 100 --min-cochanges 5
graph hotspots combines commit frequency, line churn, and recency with file-level PageRank, transitive fan-in, and betweenness centrality. It also reports temporal coupling between files that repeatedly change together. Merge commits are excluded by default, and bulk commits are filtered to avoid generated or mechanical changes distorting the results.
Flags:
-o, --output string output file path (default "./skeleton/hotspots.skt")
--format string output format: skt, json (default "skt")
--since string history window: 180d, 12mo, or 2y (default "12mo")
--max-commits int maximum commits to inspect (default 2000)
--max-files-per-commit int exclude larger bulk commits (default 50)
--min-cochanges int minimum shared commits for temporal coupling (default 3)
--top-n int maximum results per section (default 30)
--include-merges include merge commits in history metrics
--collect-test include test files in analysis
--workers int max concurrent parsing goroutines (0 = NumCPU)
--verbose print progress information during processing
Development
# Install dependencies
make deps
# Build
make build
# Run tests
make test
# Lint and format
make lint
# Release (requires a git tag)
git tag v1.0.0
git push --tags
make release
Disclaimer
This project was built almost entirely using Kiro, an AI-powered IDE. The codebase was then iteratively refactored using codeknit itself to identify structural improvements.
It's not meant to be used for production, leverage it to experiment and planning building features and refactoring with LLMs.
License
This project is licensed under the Apache License 2.0. See LICENSE for details.