ArchGuard
ArchGuard analyzes source code to extract architectural insights and generates Mermaid diagrams at multiple levels of detail. It supports TypeScript (stable), Go (stable), Java (beta), Python (beta), C++ (beta), and Kotlin/Android (beta) through a plugin system, and exposes query and MCP workflows for architecture inspection.
Screenshots
Package-Level Overview
Class-Level Diagram
Method-Level Detail (CLI Module)
Features
- AI-Native MCP Interface: Query architecture in natural language from Claude Code or Codex — analyze projects, trace dependencies, find implementers, detect cycles
- Multi-Language Support: TypeScript, Go, Java, Python, C++, Kotlin/Android via plugin system
- Multi-Level Diagrams: Package (high-level), Class (default), Method (low-level)
- Go Architecture Atlas: 4-layer visualization — package graph, capability graph, goroutine topology, flow graph
- Kotlin/Android Support: Auto-detect Kotlin projects, parse
build.gradle.kts/settings.gradle.kts, and plan multi-module diagrams - Static Test Analysis: Test coverage mapping, assertion density, orphan detection, and quality issues — no test execution required, including Kotlin/Android projects
- Parallel Processing: High-performance parsing with configurable concurrency
- Smart Caching: File-based caching with SHA-256 hashing for fast repeated runs
- Zero External Dependencies: Local Mermaid rendering using isomorphic-mermaid
- Five-Layer Validation: Automatic syntax, structure, render, quality, and auto-repair validation
- Configuration Files: Project-level config with
archguard.config.jsonsupport - Rich CLI: Interactive progress display with real-time feedback
Quick Start
Installation
npm install -g @yalehwang/archguard
Using with Claude Code
Install ArchGuard as a Claude Code plugin from the npm-source marketplace.
Claude Code runs npm install of the plugin package, which depends on an
exact @yalehwang/archguard version — the full runtime dependency closure
(ordinary JS dependencies, web-tree-sitter, bundled grammar WASM assets,
platform-selected optional packages) is resolved on your machine, with no
global archguard binary, vendored node_modules, or NODE_PATH involved:
claude plugin marketplace add yaleh/archguard
claude plugin install archguard@archguard
Restart Claude Code afterwards so the plugin loads. The plugin bundles the
archguard MCP server (launched via plugin/mcp-launcher.mjs, which resolves
the ArchGuard CLI entry from the plugin's own npm dependency tree) plus the
feature-developer and project-semantics-discovery skills.
Alternatively, register the MCP server directly without the plugin (project
scope, requires a global archguard install):
claude mcp add --scope project archguard -- archguard mcp
For a local checkout, scripts/install-claude-user-scope.sh runs the same
npm-source marketplace flow against your checkout: it adds (or updates) the
archguard marketplace registration, installs (or updates) the
archguard@archguard plugin at user scope, and removes any legacy ArchGuard
entry that older installers left in the deprecated ~/.claude/mcp.json. It
never installs a global archguard binary, never writes a registration into
~/.claude/mcp.json, and never installs or builds native Tree-sitter
packages. The script is idempotent — re-run it to upgrade after pulling a
new version:
bash scripts/install-claude-user-scope.sh
# Register the GitHub marketplace source instead of the local checkout:
bash scripts/install-claude-user-scope.sh --marketplace-source yaleh/archguard
Parser runtime selection (auto | native | wasm)
A normal install is the deterministic WASM baseline: web-tree-sitter
plus the bundled grammar WASM assets are always installed, and the native
tree-sitter runtime/grammar packages are never installed or built by
ArchGuard itself. This holds for the Claude plugin installer as well:
scripts/install-claude-user-scope.sh never installs, builds, or globally
mutates native Tree-sitter packages — the plugin closure it registers is the
WASM baseline. Per language, ARCHGUARD_PARSER_RUNTIME selects the
backend:
auto(default) — probe the native(runtime, grammar)tuple with a health check; use native only when the probe passes, otherwise fall back to WASM and record the reason in diagnostics.native— require native; fail loudly with an actionable error if the probe fails (never silently substitutes WASM).wasm— never touch native modules; portable and deterministic.
ARCHGUARD_PARSER_RUNTIME is the canonical setting. The former
ARCHGUARD_PARSER_BACKEND is a deprecated alias: it applies only when the
canonical variable is unset, and ArchGuard then prints a one-time stderr
warning. Every analysis surfaces a one-line effective-runtime summary —
language → backend chosen → source of choice → fallback reason — in
--verbose mode and always when a fallback occurs; MCP protocol output
stays clean (diagnostics route to stderr).
# Default (auto): per-language health-checked native-first selection with WASM fallback
ARCHGUARD_PARSER_RUNTIME=auto archguard analyze -s ./src --lang go
# Force the portable baseline (diagnostics, restricted CI)
ARCHGUARD_PARSER_RUNTIME=wasm archguard analyze -s ./src --lang go
# Require the native accelerator; fail if unavailable or ABI-incompatible
ARCHGUARD_PARSER_RUNTIME=native archguard analyze -s ./src --lang go
Native acceleration is opt-in and discovered only at runtime: install the
optional native packages (tree-sitter + the per-language grammar packages,
declared as optional peers) into ArchGuard's own package scope, or point
ARCHGUARD_NATIVE_MODULE_ROOT=/path/to/root at a trusted module root
containing them. The analyzed project's node_modules is never consulted.
See Parser Runtime Selection for the
full policy.
Then ask Claude to analyze any project:
Analyze the architecture of
/path/to/my-projectusing archguard MCP.
Claude will call archguard_analyze to parse the project and build a query index. Once done, ask follow-up questions in natural language:
Find all classes that implement
ILanguagePlugin.
Show me what depends on
ArchJSON, depth 1.
Detect circular dependencies in this project.
Review this project's code and documentation using the archguard MCP and the
.archguardoutput files.
Based on the archguard analysis, suggest refactoring directions for reducing coupling.
To include test quality analysis alongside architecture inspection:
Analyze the architecture and test coverage of
/path/to/my-projectusing archguard MCP. Check which source entities lack test coverage and flag any test files with no assertions.
Claude will call archguard_analyze(includeTests: true), then sequence through the test analysis tools:
Which test files have no assertions?
Show me the entity coverage ratio and assertion density for this project.
List all orphan test files — tests with no detected link to source entities.
Re-using an existing analysis: If the project was already analyzed in a previous session, query artifacts persist in .archguard/query/. You can skip re-analysis and query the cache directly:
Using the existing archguard cache, show me what depends on
DiagramProcessor.
Using with Codex
Codex does not read Claude plugin manifests, so its MCP configuration must
launch an ArchGuard installation that owns its own runtime dependency closure.
scripts/install-codex-user-scope.sh registers exactly one TOML-safe
[mcp_servers.archguard] table in the Codex user config
(~/.codex/config.toml, or $CODEX_HOME/config.toml) that invokes the
npm-installed @yalehwang/archguard CLI — never Claude's versioned plugin
cache and never the source checkout:
# Registers the global npm install (discovered via `npm root -g`):
bash scripts/install-codex-user-scope.sh
# Or point at a specific npm-installed ArchGuard root explicitly:
bash scripts/install-codex-user-scope.sh --archguard-root "$(npm root -g)"
The installer is idempotent (re-run it to refresh after an upgrade): it updates
the single archguard table in place, preserves all unrelated Codex
configuration, and forwards the parser-runtime policy as
ARCHGUARD_PARSER_RUNTIME (--parser-runtime auto|native|wasm, default
auto). It writes an entry of this shape:
[mcp_servers.archguard]
command = "node"
args = ["<npm-install>/@yalehwang/archguard/dist/cli/index.js", "mcp"]
env = { ARCHGUARD_PARSER_RUNTIME = "auto" }
startup_timeout_sec = 30
tool_timeout_sec = 120
Alternatively, register manually (requires archguard on Codex's PATH):
codex mcp add archguard -- archguard mcp
Then prompt Codex in the same way and verify in the Codex TUI with /mcp (or
codex mcp list). The same MCP tools are available.
Analyzing an External Project
Point archguard at any project path — no configuration file needed:
Analyze the architecture of
/home/user/work/my-projectusing archguard MCP.
Archguard auto-detects the language and project structure, generates diagrams under <project>/.archguard/, and builds the query index for follow-up queries. Kotlin/Android projects are detected from build.gradle.kts, settings.gradle.kts, .kt, and .kts markers and can be analyzed without forcing --lang kotlin.
Standalone CLI
Run directly without an AI assistant:
# Analyze current project (auto-detects language and structure)
archguard analyze
# Analyze an external project
archguard analyze -s /path/to/project/src
# Go project
archguard analyze -s ./cmd --lang go
CLI Commands
analyze
Analyze a project and generate architecture diagrams.
archguard analyze [options]
Source & Selection:
-s, --sources <paths...>- Source directories; triggers auto-detection and multi-diagram generation--diagrams <levels...>- Filter by level:package|class|method(language-dependent)--lang <language>- Language:typescript|go|java|python|cpp|kotlin(auto-detected)--config <path>- Config file path (default:archguard.config.json)
Output:
--work-dir <dir>- ArchGuard work directory (default:./.archguard)--cache-dir <dir>- Cache directory (default:<work-dir>/cache)--output-dir <dir>- Output directory-f, --format <type>- Output format:mermaid|json(default:mermaid)-e, --exclude <patterns...>- Exclude glob patterns
Performance:
--no-cache- Disable cache-c, --concurrency <num>- Parallel parsing workers (default: CPU cores)-v, --verbose- Verbose output
Mermaid:
--mermaid-theme <theme>- Theme:default|forest|dark|neutral--mermaid-renderer <renderer>- Renderer:isomorphic|cli
Go Atlas (enabled by default for Go):
--atlas- Enable Atlas mode--no-atlas- Disable Atlas mode, use standard Go parsing--atlas-layers <layers>- Comma-separated layers:package,capability,goroutine,flow--atlas-strategy <strategy>- Analysis strategy:none|selective|full--atlas-no-tests- Exclude test files from Atlas extraction--atlas-include-tests- Include test packages in Atlas--atlas-protocols <protocols>- Protocols included in flow graph
Examples:
# Basic analysis
archguard analyze
# Filter generated diagrams by level
archguard analyze --diagrams class method
# Generate JSON for tooling integration
archguard analyze -s ./src --output-dir . -f json
# Go project with Architecture Atlas
archguard analyze -s ./cmd --lang go
# Go without Atlas (faster, basic diagram)
archguard analyze -s ./cmd --lang go --no-atlas
# High concurrency
archguard analyze -s ./src -c 8 -v
# Exclude test files
archguard analyze -s ./src -e "**/*.test.ts" "**/*.spec.ts"
# Dark theme
archguard analyze -s ./src --mermaid-theme dark
# Analyze architecture and generate test quality report
archguard analyze --include-tests
# Refresh test report only, skip re-parsing source (faster)
archguard analyze --tests-only
# Kotlin/Android project (explicit language selection is optional)
archguard analyze -s ./app/src/main/java --lang kotlin
query
Query persisted architecture entities and relationships.
archguard query [options]
Common examples:
archguard query --summary
archguard query --entity "DiagramProcessor"
archguard query --entity "DiagramProcessor" --format json
archguard query --entity "DiagramProcessor" --format json --verbose
archguard query --deps-of "DiagramProcessor" --depth 2
archguard query --implementers-of "ILanguagePlugin"
archguard query --list-scopes
Typical architecture checking tasks:
- Dependency impact:
archguard query --deps-of "DiagramProcessor" --depth 2 - Reverse impact:
archguard query --used-by "DiagramProcessor" --depth 2 - Extension points:
archguard query --implementers-of "ILanguagePlugin" - Circular dependencies:
archguard query --cycles - Refactoring hotspots:
archguard query --high-coupling - Orphans:
archguard query --orphans
See Architecture Checking Scenarios for task-oriented workflows.
mcp
Start the ArchGuard MCP server over stdio.
archguard mcp [--arch-dir <dir>] [--scope <key>]
The MCP server exposes the query tools plus archguard_analyze, which refreshes query artifacts for the current MCP session. Query tools default to the persisted global scope and return summary entities unless verbose: true is requested.
Claude Code — add via CLI (project scope):
claude mcp add --scope project archguard -- archguard mcp
Codex — register at user scope via the installer (launches the
npm-installed CLI), or manually via CLI / ~/.codex/config.toml:
bash scripts/install-codex-user-scope.sh # idempotent, TOML-safe
codex mcp add archguard -- archguard mcp # manual alternative
Available MCP tools:
Architecture query:
| Tool | Purpose |
|---|---|
archguard_summary |
Project overview: entity/relation counts, scope list |
archguard_find_entity |
Look up a named class, interface, or function |
archguard_get_dependencies |
Outgoing dependencies of an entity (what it uses) |
archguard_get_dependents |
Incoming dependencies of an entity (who uses it) |
archguard_find_implementers |
All implementations of an interface |
archguard_find_subclasses |
All subclasses of a base class |
archguard_get_file_entities |
All entities defined in a source file |
archguard_detect_cycles |
Circular dependency detection |
archguard_analyze |
Refresh query artifacts; pass includeTests: true to include test analysis |
Test analysis (requires archguard_analyze(includeTests: true) first):
| Tool | Purpose |
|---|---|
archguard_detect_test_patterns |
Detect test frameworks and return suggested pattern config — call this first |
archguard_get_test_metrics |
Summary: file counts, entity coverage ratio, assertion density, issue counts |
archguard_get_test_issues |
Per-file issues: zero_assertion, orphan_test, assertion_poverty, skip_accumulation |
archguard_get_entity_coverage |
Per-entity coverage map with confidence scores |
Git history analysis:
| Tool | Purpose |
|---|---|
archguard_analyze_git |
Index git history for change-based queries |
archguard_get_change_context |
Commits and changed files for an entity |
archguard_get_cochange |
Files that frequently change together |
archguard_get_change_risk |
Change risk score based on churn and coupling |
archguard_get_ownership |
Author ownership breakdown per file or entity |
See MCP Usage Guide for setup, tool reference, and usage patterns.
init
Initialize configuration file:
archguard init
Creates archguard.config.json with defaults. Use -f js for a JavaScript config.
cache
archguard cache stats # View cache statistics
archguard cache clear # Clear all cached data
archguard cache path # Show cache directory
Language Support
| Language | Status | Parser | Features |
|---|---|---|---|
| TypeScript | Stable | ts-morph (AST) | Classes, interfaces, enums, dependencies, path aliases |
| Go | Stable | tree-sitter + gopls | Structs, interfaces, goroutines, Architecture Atlas |
| Java | Beta | tree-sitter | Classes, interfaces, Maven/Gradle deps |
| Python | Beta | tree-sitter | Classes, functions, pip/Poetry deps |
| C++ | Beta | tree-sitter | Structs, classes, inheritance, CMake deps |
| Kotlin/Android | Beta | tree-sitter | Classes, interfaces, top-level functions, build.gradle.kts deps, settings.gradle.kts multi-module planning, static test analysis |
Go Architecture Atlas
For Go projects, ArchGuard generates a multi-layer architecture atlas showing:
- Package Graph — inter-package dependencies and coupling
- Capability Graph — functional capability clusters
- Goroutine Topology — concurrent execution patterns and channel topology
- Flow Graph — data and control flow paths
# Full Atlas (default when --lang go)
archguard analyze -s ./cmd --lang go
# Specific layers only
archguard analyze -s ./cmd --lang go --atlas-layers package,capability
# Standard diagram without Atlas
archguard analyze -s ./cmd --lang go --no-atlas
gopls is optional but improves interface detection accuracy from ~75% to ~95%:
go install golang.org/x/tools/gopls@latest
See Go Plugin Usage Guide for details.
Configuration
archguard.config.json
{
"format": "mermaid",
"exclude": ["**/*.test.ts", "**/*.spec.ts", "**/node_modules/**"],
"concurrency": 4,
"workDir": "./.archguard",
"outputDir": "./docs/architecture",
"cache": { "enabled": true, "dir": "./.archguard/cache" },
"mermaid": {
"renderer": "isomorphic",
"theme": "default",
"transparentBackground": true
},
"cli": {
"command": "claude",
"args": [],
"timeout": 60000
}
}
Multi-Diagram Configuration
Generate multiple diagrams with different sources and levels in one run:
{
"diagrams": [
{
"name": "overview",
"sources": ["./src"],
"level": "package"
},
{
"name": "modules/cli",
"sources": ["./src/cli"],
"level": "class"
},
{
"name": "modules/parser",
"sources": ["./src/parser"],
"level": "method"
}
],
"outputDir": "./docs/architecture"
}
# Generate all diagrams
archguard analyze
# Filter configured diagrams by level
archguard analyze --diagrams class method
Configuration Fields
| Field | Type | Default | Description |
|---|---|---|---|
source |
string | ./src |
Source directory (single-diagram mode) |
diagrams |
array | — | Multi-diagram config (overrides source) |
format |
string | mermaid |
Output format: mermaid or json |
exclude |
string[] | [] |
Glob patterns to exclude |
concurrency |
number | CPU cores | Parallel parsing workers |
workDir |
string | ./.archguard |
Work directory for cache and query artifacts |
outputDir |
string | ./.archguard/output |
Output directory |
cache.enabled |
boolean | true |
Enable file-based caching |
mermaid.theme |
string | default |
Diagram theme |
mermaid.transparentBackground |
boolean | true |
Transparent PNG background |
projectSemantics |
object | — | Skill-authored project knowledge consumed during analysis |
Skill-Authored Project Semantics
ArchGuard does not discover project semantics at runtime. Skills or users write project knowledge, and ArchGuard loads, validates, merges, and consumes it during analysis.
Authoritative locations and priority:
archguard.config.json.projectSemantics.archguard/project-semantics.json- built-in defaults
The sidecar file uses the same shape as archguard.config.json.projectSemantics.
{
"additionalTestPatterns": ["tests/**/*.ts"],
"customAssertionPatterns": ["expect[A-Z]\\w+"],
"architecturalLayers": {
"src/analysis": "analysis",
"src/cli": "cli",
"src/rendering": "rendering"
},
"suggestedDepth": 2
}
If either the config projectSemantics block or .archguard/project-semantics.json is malformed, ArchGuard fails fast during configuration load or analysis startup instead of silently ignoring the knowledge.
Output Formats
Mermaid (default)
Generates .mmd, .svg, and .png files:
archguard/
├── overview/
│ ├── package.mmd
│ ├── package.svg
│ └── package.png
├── modules/
│ ├── cli.mmd
│ └── cli.png
└── index.md
Example .mmd output:
graph TD
UserService[UserService<br/>+ getUser(id): Promise<User><br/>+ createUser(data): Promise<User>]
User[User<br/>+ id: string<br/>+ name: string]
UserService --> User : uses
ArchJSON
Structured JSON for tooling integration:
{
"version": "1.0",
"language": "typescript",
"timestamp": "2024-01-01T00:00:00.000Z",
"entities": [
{
"id": "UserService",
"name": "UserService",
"type": "class",
"members": [...]
}
],
"relations": [
{ "from": "UserService", "to": "User", "type": "dependency" }
]
}
Performance
- Parallel Processing: Automatically uses all CPU cores for parsing
- Smart Caching: SHA-256 file hashing; 80%+ cache hit rate on repeated runs
- Benchmark (ArchGuard self-analysis, 30+ files):
- First run: ~6–10 seconds
- Cached run: < 3 seconds
- Throughput: ~4–5 files/second
- Memory: < 300 MB
Tune concurrency:
archguard analyze -s ./src -c 8 # custom workers
archguard analyze -s ./src -c 1 # sequential (debugging)
Architecture
For current implementation details, see:
Project Structure
archguard/
├── src/
│ ├── cli/ # CLI commands and utilities
│ │ ├── commands/ # analyze, init, cache
│ │ ├── progress/ # Progress reporting
│ │ ├── processors/ # Diagram processing pipeline
│ │ └── utils/ # Config loader, error handler
│ ├── core/ # Plugin registry and interfaces
│ │ └── interfaces/ # ILanguagePlugin, IParser, IDependencyExtractor
│ ├── parser/ # TypeScript AST parsing
│ │ ├── typescript-parser.ts
│ │ ├── parallel-parser.ts
│ │ └── extractors/ # class, interface, enum, relation
│ ├── mermaid/ # Diagram generation
│ │ ├── diagram-generator.ts
│ │ ├── renderer.ts
│ │ ├── validation-pipeline.ts
│ │ └── validators/ # parse, structural, render, quality
│ ├── plugins/ # Language plugins
│ │ ├── typescript/ # Stable
│ │ ├── golang/ # Stable (tree-sitter + gopls + Atlas)
│ │ │ └── atlas/ # package, capability, goroutine, flow builders
│ │ ├── java/ # Beta
│ │ ├── python/ # Beta
│ │ ├── cpp/ # Beta (tree-sitter + CMake)
│ │ └── kotlin/ # Beta (tree-sitter + build.gradle.kts)
│ └── types/ # Core types (config, ArchJSON, extensions)
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ ├── plugins/ # Per-plugin tests
│ └── core/ # Plugin registry tests
└── docs/ # Documentation and screenshots
Data Flow
CLI / MCP entrypoint
│
▼ Shared analysis core (`runAnalysis`)
Config normalization + diagram selection
│
▼ DiagramProcessor
ArchJsonProvider + language plugins
│
▼ ArchJSON (entities + relations + optional extensions)
│
├─► Query artifacts (`.archguard/query/*`)
├─► Mermaid / JSON outputs (`.archguard/output/*`)
└─► Go Atlas extension (package / capability / goroutine / flow)
│
▼ QueryEngine / MCP query tools
Architecture inspection workflows
Development
Prerequisites
- Node.js >= 18.0.0
- npm or yarn
Optional, for enhanced features:
- gopls — Semantic interface detection for Go projects
Setup
git clone https://github.com/yaleh/archguard.git
cd archguard
npm install
npm run build
npm test
Testing
npm test # All tests (vitest)
npm run test:unit # Unit tests
npm run test:integration # Integration tests
npm run test:coverage # With coverage report
npm run test:watch # Watch mode
Code Quality
npm run lint # ESLint check
npm run lint:fix # Auto-fix
npm run format # Prettier
npm run type-check # TypeScript check
npm run build && npm run lint && npm run type-check && npm test
Self-Analysis
npm run build
# Analyze ArchGuard itself
node dist/cli/index.js analyze -v
# Package-level overview only
node dist/cli/index.js analyze --diagrams package
# Method-level detail for a module
node dist/cli/index.js analyze -s ./src/cli --diagrams method
Technology Stack
| Category | Technology | Version | Purpose |
|---|---|---|---|
| Language | TypeScript | ^5.3.0 | Type-safe development |
| Runtime | Node.js | >=18.0.0 | JavaScript runtime |
| TS Parser | ts-morph | ^21.0.0 | TypeScript AST |
| Go Parser | tree-sitter + tree-sitter-go | ^0.25.0 | Go AST |
| Java/Python Parser | tree-sitter | ^0.25.0 | Java/Python AST |
| Go LSP | gopls | latest | Semantic interface detection |
| Diagram Generation | isomorphic-mermaid | ^0.1.1 | Local Mermaid rendering |
| Image Processing | sharp | ^0.34.5 | SVG → PNG conversion |
| Process Management | execa | ^8.0.0 | Subprocess execution |
| Testing | Vitest | ^1.2.0 | Unit/integration tests |
| CLI | commander | ^11.1.0 | Command-line interface |
| Progress | ora, chalk | ^8.x, ^5.x | Interactive CLI |
| Concurrency | p-limit | ^5.0.0 | Parallel processing |
| Configuration | zod | ^3.25.76 | Config validation |
Troubleshooting
See TROUBLESHOOTING.md for common issues.
Quick fixes:
- Go interface detection low — install gopls:
go install golang.org/x/tools/gopls@latest - Slow first run — normal; subsequent runs use cache (80%+ hit rate)
- Render errors — the five-layer validator auto-repairs most issues; run with
-vfor details - Install fails with missing
tree-sitterbinding — use the packaged release tarball that bundles the required prebuilttree-sitterbinary for your platform/runtime; source rebuild fallback is disabled
Documentation
- CLI Usage Guide
- Architecture Checking Scenarios
- MCP Usage Guide
- Configuration Reference
- Go Plugin Usage Guide
- Architecture Overview
- Plugin Development Guide
- Plugin Registry
- Troubleshooting
Contributing
This project follows:
- TDD Methodology: Tests written before implementation
- Plugin System: Add new languages via
ILanguagePlugin - Clean Code: Readable, maintainable code
See CONTRIBUTING.md for documentation management details.
License
MIT
Credits
Built with:
- ts-morph for TypeScript parsing
- tree-sitter for Go/Java/Python parsing
- Mermaid for diagram syntax
- isomorphic-mermaid for rendering