Every developer has seen the same lifecycle play out in a growing repository:
- Someone writes a clean Mermaid diagram in
README.mdon day one. - Three months later, half the files have been renamed, two modules silently formed a circular dependency, and a parser started importing directly from the CLI entrypoint.
- Meanwhile, AI coding agents asked to "document the architecture" either hallucinate module boxes that never existed or emit tangled Mermaid graphs where arrows cut straight through labels and break dark-mode contrast.
I wanted something fundamentally different: a deterministic, zero-LLM compiler and CI gate that treats architecture diagrams as verifiable build artifacts instead of disposable drawings.
That is why I built archink — an open-source TypeScript CLI and library that:
- Extracts real module dependency graphs from TypeScript/JavaScript ASTs plus Python and Go imports
- Detects circular dependencies using Tarjan's Strongly Connected Components (SCC)
- Solves Sugiyama layered DAG layouts (plus Sequence and 2×2 Matrix diagrams) deterministically
- Renders zero-shadow vector SVGs across four editorial themes and offline interactive HTML viewers
- Fails CI (
exit 1) with SARIF 2.1.0 or Markdown reports whenever diagrams drift from real code or violate layer rules
The Problem With "Diagram-as-Prompting"
When diagrams are written by hand or generated by an LLM prompt without grounding, three failure modes show up immediately:
| Failure Mode | What Breaks in Practice | What archink Does Instead |
|---|---|---|
| Visual slop | Overlapping edges, blurry CSS/SVG shadows, inconsistent padding, poor contrast | Pure 1px hairline editorial palettes, Sugiyama crossing reduction, port-distributed cubic splines |
| Hallucinated boxes | Diagrams cite legacy_cache.ts or omit newly added modules | Scans real imports via typescript AST + Python/Go resolvers (archink scan) |
| Silent architectural rot | Circular imports and inverted layer dependencies slip into main | Enforces --fail-on-cycles, --fail-on-drift, and --rule "<from> !-> <to>" |
Everything in archink runs 100% locally with zero paid APIs, zero headless browsers, and zero network calls.
Architecture Overview: Four Deterministic Stages
Under the hood, archink is split into nine single-responsibility TypeScript modules under src/:
- Extract & Parse (
src/scanner.ts,src/parsers.ts) — Builds a canonicalDiagramSpeceither by scanning a repository or parsing.mmd/.jsoninputs. - Analyze Topology (
src/scanner.ts) — ComputesfanIn,fanOut, LOC, export counts, orphan files, hub nodes, and circular dependency SCCs. - Solve Coordinates (
src/layout.ts) — Computes collision-free positions for layered DAGs, sequence diagrams, and 2×2 quadrant matrices. - Render or Gate (
src/renderer.ts,src/verifier.ts) — Emits deterministic SVG, self-contained interactive HTML, Mermaid syntax, or CI verification verdicts (pretty,json,markdown,sarif).
Let's walk through how each stage works in detail.
Stage 1: Real Multi-Language Topology Extraction (src/scanner.ts)
Regexes break fast on JavaScript/TypeScript imports (comments, multi-line imports, type-only re-exports, dynamic import()). Instead, archink uses the official typescript compiler parser (ts.createSourceFile) to walk the AST of .ts, .tsx, .mts, .cts, .js, .jsx, .mjs, and .cjs files.
It extracts:
- Static
ImportDeclaration(import ... from '...') - Re-exports (
export { ... } from '...') - Dynamic
import('...')and CommonJSrequire('...') - Top-level exported symbol counts and lines of code (LOC)
Resolving Real-World ESM & Monorepo Paths
Two details trip up naive TypeScript dependency scanners:
- NodeNext ESM imports: In modern ESM TypeScript (
"module": "NodeNext"),src/cli.tswritesimport { runCli } from './cli.js', even though the file on disk is.ts.archinkstrips.js/.jsx/.mjs/.cjssuffixes and probes.ts,.tsx,.mts,.cts, and/index.*variants automatically. -
tsconfig.jsonpathsaliases: Wildcard aliases such as"@/*": ["src/*"]are read fromtsconfig.jsonand resolved back to real source paths.
For polyglot codebases, scanner.ts also parses:
- Python (
.py):import pkg.modand relativefrom ..pkg import x(walking parent directories per leading dot and resolving.py/__init__.py) - Go (
.go): Single and groupedimport ( ... )blocks mapped againstgo.mod'smoduleprefix
Tarjan SCC Cycle Detection
Once the directed adjacency list is built, findCycles() runs Tarjan's Strongly Connected Components algorithm. Any SCC with size > 1 (or a self-loop) is flagged as an architectural cycle, and every edge inside that SCC is tagged with style: 'cycle' so it renders in crimson dashed linework and fails CI when --fail-on-cycles is enabled.
Running archink scan . on archink itself outputs:
archink scan :: archink Architecture Files: 9 | Edges: 22 | Cycles: 0 | Orphans: 0 Languages: typescript=9 Top hubs: src/types.ts(in:8,out:0), src/scanner.ts(in:3,out:1), src/themes.ts(in:3,out:1), src/layout.ts(in:2,out:1), src/parsers.ts(in:2,out:1) Stage 2: Deterministic Sugiyama Layered Layout (src/layout.ts)
Most messy auto-diagrams fail because they place nodes on naive grids and draw straight lines between centers. archink implements a full Sugiyama layered graph pipeline:
- Feedback-Arc Cycle Breaking (
breakCycles): Performs a deterministic DFS over sorted node IDs to temporarily reverse back-edges so cyclic repositories still layer cleanly, while preserving the real arrowhead direction at render time. - Longest-Path Rank Assignment (
assignLayers): Computes topological ranks (0..L) and pulls pure source nodes closer to their nearest consumers so top-level files don't float awkwardly far above deep layers. - Virtual Dummy Waypoints: Whenever an edge spans more than one layer (
|rank(to) - rank(from)| > 1),layout.tsinserts virtual dummy vertices at every intermediate rank. That lets multi-layer connectors curve around intermediate module cards instead of slicing straight through text. - 6-Pass Barycenter Crossing Minimization: Runs 6 alternating downward/upward barycenter sweeps, adding a light
0.15group-median affinity so modules belonging to the same directory swimlane stay contiguous. - Swimlane Intrusion Safeguard: Before drawing a dashed group container around a directory,
layout.tschecksrectsOverlap()against every non-member node. A swimlane box is never allowed to accidentally enclose an unrelated module. - Port-Distributed Cubic Splines: When
src/types.tshasfanIn: 8, connecting all 8 arrows to(x + width/2, y)creates an unreadable ink blob.archinksorts incoming and outgoing edges by peer cross-axis coordinate and distributes ports across[0.2, 0.8]of each node's face, routing smooth cubic Bezier curves through waypoints.
Here is the actual SVG archink generated for its own src/ directory in swiss-paper (TB) and obsidian-ink (LR):
Stage 3: Editorial Themes, Sequence Diagrams, Matrices & Offline HTML
Four Zero-Shadow Editorial Themes (src/themes.ts)
Instead of generic gradients or blurry drop shadows, archink ships four crisp 1px-hairline palettes:
-
swiss-paper— Archival off-white (#FAF9F6) with cobalt/teal/vermilion role accents -
obsidian-ink— Deep carbon studio canvas (#0D1017) for dark-mode docs -
blueprint-mono— Prussian drafting-table blue (#0A2240) with crisp linework -
warm-editorial— Book-print cream (#F5EFE6) with charcoal ink, forest sage, and terracotta
Mermaid Compiler, Sequence Diagrams, and 2×2 Matrices
Already have Mermaid .mmd files? You can compile flowchart / graph (with subgraph, shapes like [(db)], ([pill]), {diamond}, {{hexagon}}, chains A --> B --> C, and A & B --> C) or sequenceDiagram directly into editorial SVGs:
node dist/cli.js render ci-sequence.mmd --theme obsidian-ink --format svg --out sequence.svg node dist/cli.js render tradeoff-matrix.json --theme warm-editorial --format svg --out matrix.svg Offline Interactive HTML Viewer
Passing --format html embeds the vector SVG inside a single self-contained HTML file with zero external scripts or CDNs:
- Mouse-drag pan + scroll-wheel zoom
- Live module search (
/filter) - Click any node to dim unrelated modules and inspect its upstream callers and downstream dependencies in a side drawer
- One-click Download SVG
Stage 4: The Architecture Drift & Boundary Gate (src/verifier.ts)
Pretty diagrams are only half the story. The real superpower is keeping architecture honest on every pull request.
First, snapshot a baseline contract:
node dist/cli.js init --dir . --out .archink.json Then run archink check in CI:
node dist/cli.js check .archink.json \ --repo . \ --rule "parser !-> entry" \ --rule "themes !-> scanner" \ --fail-on-cycles \ --fail-on-drift \ --format sarif \ --out archink.sarif Here is what archink check catches automatically:
| Rule ID | What It Catches |
|---|---|
DRIFT_PHANTOM_NODE | Diagram claims a module exists that was deleted or renamed |
DRIFT_MISSING_NODE | New source file added to the repo isn't reflected in the diagram |
DRIFT_PHANTOM_EDGE | Arrow in diagram has no matching import in AST |
DRIFT_MISSING_EDGE | Real import between mapped modules is undocumented |
ARCH_CYCLE | Circular dependency detected via Tarjan SCC |
ARCH_LAYER_VIOLATION | Import violates forbiddenRules or CLI --rule "<from> !-> <to>" |
Verified failing output on a fixture containing a cycle, layer leak, stale node, and undocumented edge:
archink check :: FAIL (Demo Service) Summary : errors=4, warnings=0, cycles=1, drift(phantom=1+0, missing=0+1), boundary=1 [ERROR] ARCH_CYCLE :: Circular dependency cycle detected: src/cli.ts <-> src/parser.ts at src/cli.ts hint: Extract shared types/interfaces into a lower-layer module to break the cycle. [ERROR] ARCH_LAYER_VIOLATION :: Forbidden dependency: parser !-> entry (src/parser.ts -> src/cli.ts) at src/parser.ts hint: Invert the dependency with an interface or move shared logic out of src/cli.ts. [ERROR] DRIFT_PHANTOM_NODE :: Diagram node "src/legacy_cache.ts" (legacy_cache.ts) does not match any source module. hint: Remove stale module from diagram or update its path/label to match the codebase. [ERROR] DRIFT_MISSING_EDGE :: Actual import "src/parser.ts -> src/cli.ts" is undocumented in diagram "Demo Service". at src/parser.ts hint: Add this dependency edge or refactor the import if unintended. Because verifier.ts emits SARIF 2.1.0, Markdown, JSON, and terminal output, you can drop it straight into GitHub Actions to annotate PR diffs or fail builds on exit code 1.
Using archink With AI Coding Agents (SKILL.md)
archink ships with an Agent Skills standard SKILL.md so coding agents like Claude Code, Antigravity, Cursor, and Codex follow a strict deterministic workflow:
- Run
archink scan .to ground every module name and coupling metric in real AST imports before documenting anything. - Render clean SVG/HTML artifacts via
archink scanorarchink renderinstead of raw ASCII boxes. - Run
archink checkwith--fail-on-cyclesand layer boundary rules before declaring an architectural refactor finished.
Try It Locally
git clone https://github.com/md1qamar/archink.git cd archink npm install npm run typecheck npm test # 12/12 tests passing across scanner, parsers, layout/renderer, and verifier/CLI You can also use it programmatically from TypeScript:
import { scanRepository, renderSvg, verifyArchitecture, parseBoundaryRule } from 'archink'; const scan = scanRepository('.', { ignoreTests: true }); const svg = renderSvg(scan.spec, { theme: 'swiss-paper', direction: 'LR' }); const report = verifyArchitecture({ repoDir: '.', spec: scan.spec, failOnCycles: true, failOnDrift: true, rules: [parseBoundaryRule('parser !-> entry')], }); Wrapping Up
Diagrams should be as trustworthy as your compiler and test suite. By tying visual layout directly to AST import extraction, Tarjan cycle detection, and CI drift gates, archink makes sure your architecture docs stay sharp and honest as your codebase evolves.
Check out the full source code, tests, and SKILL.md on GitHub:
👉 github.com/md1qamar/archink (MIT Licensed)
If you try it on one of your TypeScript, Python, or Go repos, let me know what diagrams or boundary rules you'd like to see next!