morpharch 2.2.3

Monorepo architecture drift visualizer with animated TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<p align="center">
  <img src="assets/logo.svg" alt="MorphArch logo" width="600">
</p>

<p align="center">
  <strong>Inspect repository structure, drift, and hotspots from the terminal.</strong>
</p>

<p align="center">
  <a href="https://crates.io/crates/morpharch"><img src="https://img.shields.io/crates/v/morpharch" alt="Crates.io"></a>
  <a href="https://docs.rs/morpharch"><img src="https://img.shields.io/docsrs/morpharch" alt="docs.rs"></a>
  <a href="https://morpharch.dev"><img src="https://img.shields.io/badge/website-morpharch.dev-7aa2f7" alt="Website"></a>
  <a href="https://github.com/onplt/morpharch/actions/workflows/ci.yml"><img src="https://github.com/onplt/morpharch/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://github.com/onplt/morpharch#license"><img src="https://img.shields.io/crates/l/morpharch" alt="License"></a>
</p>

MorphArch scans Git history, extracts dependency edges from source code,
computes architectural health, and helps you inspect large repositories through
a terminal UI designed for repeated analysis.

It supports Rust, TypeScript, JavaScript, Python, and Go out of the box, and
works well with Nx, Turborepo, pnpm workspaces, Cargo workspaces, and other
monorepo layouts.

<p align="center">
  <img src="website/static/img/demo.gif" alt="MorphArch TUI demo" width="900">
</p>

---

## Why MorphArch

- **Grouped by default**: large repositories open on a cluster map instead of
  a full raw dependency graph.
- **Git-native**: scan history, not only `HEAD`, and replay changes in the TUI.
- **Language-aware**: import extraction uses safe fast paths with AST fallback
  instead of plain regex matching.
- **Operational**: the TUI is built for triage, inspection, drift review, and
  focused debugging inside the terminal.
- **Configurable**: ignore presets, scoring rules, boundaries, clustering, and
  presentation can all be tuned in `morpharch.toml`.

---

## Features

- **First-parent history scanning**: walks a deterministic Git history stream
  with `gix` and avoids merge-order ambiguity.
- **Repo-scoped local cache**: stores commit frames, checkpoints, and scan
  state in SQLite for fast replay and incremental updates.
- **Language-aware dependency extraction**: parses Rust, TypeScript,
  JavaScript, Python, and Go with comment/string-safe fast paths and AST
  fallback.
- **Terminal UI built for inspection**: cluster map, cluster details, focused
  inspect lens, timeline, and contextual insights.
- **Scale-aware health scoring**: cycle, layering, hub, coupling, cognitive,
  and instability debt combine into a 0-100 health score.
- **Blast radius analysis**: inspect likely downstream impact for high-risk
  modules without leaving the terminal.
- **Config-driven clustering**: semantic families, rules, constraints, aliases,
  kind hints, and color mode can all be customized per repo.
- **AI architecture assistant**: ask natural language questions about your
  codebase's health, coupling, hotspots, and blast radius — powered by any
  OpenAI-compatible LLM.
- **Incremental performance**: subtree caching, blob caching, delta frames, and
  parallel parsing reduce repeated scan cost substantially.

---

## Installation

### Quick install

```bash
cargo install morpharch
```

Linux / macOS:

```bash
curl -fsSL https://raw.githubusercontent.com/onplt/morpharch/main/install.sh | sh
```

Windows PowerShell:

```powershell
irm https://raw.githubusercontent.com/onplt/morpharch/main/install.ps1 | iex
```

### Other install methods

| Platform | Command |
|----------|---------|
| `cargo-binstall` | `cargo binstall morpharch` |
| Homebrew | `brew install onplt/morpharch` |
| npm | `npm install -g morpharch` |
| Scoop | `scoop bucket add morpharch https://github.com/onplt/scoop-morpharch` then `scoop install morpharch` |
| AUR | `yay -S morpharch-bin` |
| Docker | `docker run --rm -v .:/repo ghcr.io/onplt/morpharch scan . -n 1` |

From source:

```bash
git clone https://github.com/onplt/morpharch.git
cd morpharch
cargo build --release
```

---

## Quick Start

```bash
# Scan a repository and open the TUI
morpharch watch .

# Static report for HEAD
morpharch analyze --path .

# Historical drift table
morpharch list-drift --path .

# Recent cached graph frames
morpharch list-graphs --path .
```

If you are exploring a large repo for the first time, start with a commit
limit:

```bash
morpharch watch . -n 150 -s 200
```

### TUI mental model

1. `Map`: start with a cluster-level view of the repository.
2. `Cluster details`: open one subsystem to inspect members, dependencies, and
   link pressure.
3. `Inspect`: center a single member and use the focused raw graph only
   when you need graph-level detail.

The insights panel then gives you:

- `Overview`: current state, recent trend, risk drivers, and suggested actions
- `Hotspots`: the modules creating the most pressure
- `Blast`: downstream impact for high-risk modules

---

## Commands

### `morpharch scan <path>`

Scan a Git repository, compute per-commit dependency data, and store it in the
local repo-scoped cache.

```bash
morpharch scan .
morpharch scan /path/to/repo -n 100
```

| Flag | Description |
|------|-------------|
| `-n, --max-commits <N>` | Maximum commits to scan. `0` means unlimited. |

Notes:

- history traversal is `first-parent` only
- repeated scans reuse the local cache when the repo and config are unchanged
- increasing `--max-commits` on an already scanned repo can trigger a backfill rebuild

### `morpharch watch <path>`

Scan a repository and launch the TUI.

```bash
morpharch watch .
morpharch watch . -n 150 -s 200
```

| Flag | Description |
|------|-------------|
| `-n, --max-commits <N>` | Maximum commits to scan before launching the TUI. |
| `-s, --max-snapshots <N>` | Maximum snapshots loaded into the TUI timeline. Default: `200`. |

### `morpharch analyze [commit]`

Generate a detailed report for one commit.

```bash
morpharch analyze --path .
morpharch analyze HEAD~5 --path .
```

### `morpharch list-drift`

Show recent health drift and graph deltas for one repository.

```bash
morpharch list-drift --path .
```

### `morpharch list-graphs`

Show recently stored graph frames for one repository.

```bash
morpharch list-graphs --path .
```

---

## TUI Navigation

### Global model

MorphArch uses one interaction model everywhere:

- `Tab` / `Shift+Tab`: move panel focus
- `j/k` or arrow keys: move selection inside the active panel
- `h/l` or `[ ]`: switch local views or insight tabs
- `Enter`: drill in
- `Esc`: drill out

### Key shortcuts

| Key | Action |
|-----|--------|
| `Tab` / `Shift+Tab` | Cycle panel focus |
| `1-4` | Jump to Packages / Graph / Insights / Timeline |
| `j/k` | Move selection in the active panel |
| `h/l` or `[ ]` | Switch local views or insight tabs |
| `Enter` | Open cluster, inspect member, or open selected item |
| `Esc` | Back out one semantic level |
| `Space` / `p` | Play or pause timeline auto-advance |
| `/` | Filter sidebar entries or graph context |
| `c` | Reset the current graph viewport |
| `r` | Reheat the raw graph layout |
| `x` | Toggle blast overlay |
| `a` | Toggle AI assistant panel |
| `b` / `i` | Toggle sidebar or detail panel |
| `q` | Quit |

### Mouse support

- Click sidebar entries to select them and click map clusters to open the
  corresponding cluster.
- Scroll on the raw graph to zoom.
- Drag the raw graph background to pan.
- Drag the timeline to scrub history.
- Click insight tabs or hotspot rows directly.

---

## Configuration

MorphArch works with zero config, but a `morpharch.toml` in the repo root lets
you tune both analysis and presentation.

```toml
[ignore]
use_defaults = true
presets = ["repo_noise"]
paths = ["third_party/tmp/**"]

[ignore.custom_presets]
repo_noise = [".circleci/**", "scripts/dev/**"]

[scan]
package_depth = 2
external_min_importers = 3
test_path_patterns = [
  "/test/",
  "/tests/",
  "/testdata/",
  "/__tests__/",
  "/fixtures/",
  "/e2e/",
]

[scoring.weights]
cycle = 30
layering = 25
hub = 15
coupling = 12
cognitive = 10
instability = 8

[scoring.thresholds]
hub_exemption_ratio = 0.3
entry_point_max_fan_in = 2
brittle_instability_ratio = 0.8
blast_high_impact_threshold = 0.3
blast_max_critical_paths = 5

[[scoring.boundaries]]
from = "packages/**"
deny = ["apps/**", "cmd/**"]

[scoring.exemptions]
hub_exempt = ["deno_core"]
entry_point_stems = ["main", "index", "app", "lib", "mod", "server"]

[clustering]
strategy = "hybrid"

[clustering.semantic]
collapse_external = true
fallback_family = "workspace"
root_token_min_repeats = 2
include_exact_roots_for_known_heads = true

[clustering.structural]
enabled = true
min_cluster_size = 2
split_threshold = 6
max_cluster_share = 0.45
preserve_family_purity = true
post_merge_small_clusters = true
disambiguate_duplicate_names = true

[[clustering.families]]
name = "runtime"
kind = "infra"
include = ["runtime", "runtime/**"]
split = "never"

[[clustering.rules]]
name = "node_compat"
kind = "domain"
match = ["node", "node/**", "node_*"]

[[clustering.constraints]]
type = "must_group"
members = ["core", "core/**"]

[clustering.presentation]
kind_mode = "explicit_only"
color_mode = "minimal"

[clustering.presentation.aliases]
deps = "third-party"
workspace = "platform"

[clustering.presentation.kinds]
platform = "infra"
third-party = "deps"
```

### Configuration highlights

- `ignore.use_defaults`: enables built-in presets for tooling, build artifacts,
  and generated files
- `ignore.presets` / `ignore.custom_presets`: reusable ignore bundles for large repos
- `scan.package_depth`: controls how many meaningful path segments become one
  package label
- `scan.external_min_importers`: hides low-signal third-party dependencies
  unless they are imported by at least `N` internal packages
- `scan.test_path_patterns`: controls which path fragments are treated as
  non-architectural test or fixture code
- `scoring.boundaries`: explicit architectural rules that feed layering debt
- `clustering.families`: stable semantic grouping for important subsystems
- `clustering.rules`: label-based pattern grouping for dynamic naming cases
- `clustering.presentation.kind_mode`: `explicit_then_heuristic` or `explicit_only`
- `clustering.presentation.color_mode`: `minimal` or `semantic`

### Scan heuristics

- Python relative imports such as `from . import config` and
  `from ..shared import util` are resolved as internal dependencies.
- The default test-path filter is intentionally narrow. Directories like
  `examples/`, `bench/`, and `mocks/` are no longer excluded unless you add
  them explicitly through `scan.test_path_patterns` or `ignore` rules.
- Set `scan.external_min_importers = 0` if you want every third-party
  dependency to stay visible in the TUI and dependency views.

---

## AI Architecture Assistant

Press `a` in the TUI to open the AI assistant panel. It answers natural
language questions about your codebase using the full architecture context:
health scores, dependency edges, blast radius, churn hotspots, bus factor
risks, cycle groups, and more.

### Setup

Set your API key as an environment variable:

```bash
export OPENAI_API_KEY="sk-..."
```

That is all you need — the default config uses `gpt-4o-mini` via the OpenAI
API. For local models or other providers, add an `[ai]` section to
`morpharch.toml`:

```toml
[ai]
provider = "ollama"
api_key_env = ""
model = "llama3.1:8b"
endpoint = "http://localhost:11434/v1/chat/completions"
stream = true
max_tokens = 4096
temperature = 0.3
max_context_tokens = 12000
```

### What you can ask

The assistant has access to all computed architecture data, including:

- health scores (6-component breakdown), drift trends, and scoring config
- module instability, fan-in/fan-out, blast scores, and god module flags
- cluster membership, inter-cluster coupling, and layer topology
- cycle groups (strongly connected components) and boundary violations
- churn hotspots (frequently changed + unstable modules)
- bus factor risks (modules with very few contributors)
- commit-to-commit diffs (what changed since the previous snapshot)

When you inspect a specific module, the assistant automatically receives the
full edge list (all inbound/outbound dependencies with weights), cycle
partners, and per-file metrics for that module.

### Slash commands

| Command | Description |
|---------|-------------|
| `/help` | Show available commands |
| `/model` | Display current AI configuration |
| `/diff N` | Compare architecture with N commits ago |
| `/clear` | Clear conversation history |
| `/history` | Show conversation statistics |
| `/export` | Export conversation to file |

### Interaction features

- **Module highlighting**: module names in AI responses are visually
  highlighted so you can immediately see which modules are discussed.
- **Navigation suggestions**: after a response, the panel suggests "Inspect"
  actions for mentioned modules — press Tab and Enter to navigate directly.
- **Context-aware suggestions**: the panel generates relevant questions based on
  what you are currently viewing (overview, cluster, or module inspect).
- **Streaming**: responses stream in real-time with a spinner indicator.

See the [AI Assistant Guide](https://morpharch.dev/docs/guides/ai-assistant)
for more detail.

---

## Architecture Health Scoring

MorphArch assigns a health score from `0` to `100`.

| Range | Meaning |
|-------|---------|
| `90-100` | Clean |
| `70-89` | Healthy |
| `40-69` | Warning |
| `0-39` | Critical |

The score is built from six components:

- **Cycle debt**
- **Layering debt**
- **Hub / god module debt**
- **Coupling debt**
- **Cognitive debt**
- **Instability debt**

See [morpharch.dev/docs/concepts/scoring](https://morpharch.dev/docs/concepts/scoring) for
the full explanation.

---

## Documentation

- Website: [morpharch.dev]https://morpharch.dev/
- Docs home: [morpharch.dev/docs/intro]https://morpharch.dev/docs/intro
- Intro: [morpharch.dev/docs/intro]https://morpharch.dev/docs/intro
- Quick start: [morpharch.dev/docs/quick-start]https://morpharch.dev/docs/quick-start
- CLI reference: [morpharch.dev/docs/cli-reference]https://morpharch.dev/docs/cli-reference
- Configuration guide: [morpharch.dev/docs/guides/configuration]https://morpharch.dev/docs/guides/configuration
- AI assistant guide: [morpharch.dev/docs/guides/ai-assistant]https://morpharch.dev/docs/guides/ai-assistant
- How it works: [morpharch.dev/docs/concepts/how-it-works]https://morpharch.dev/docs/concepts/how-it-works

Docs source lives under [website/docs](website/docs).
The landing page source lives at [website/src/pages/index.tsx](website/src/pages/index.tsx).

---

## Contributing

```bash
cargo fmt
cargo test
cargo clippy -- -D warnings
```

Website:

```bash
cd website
npm install
npm run typecheck
npm run build
```

---

## License

Apache-2.0 OR MIT