diff --git a/.cartographer.yml b/.cartographer.yml
new file mode 100644
index 0000000..a4608be
--- /dev/null
+++ b/.cartographer.yml
@@ -0,0 +1,17 @@
+# Architecture rules for repo-cartographer itself (dogfooding the check).
+rules:
+  forbidden:
+    - from: "src/lib/**"
+      to:   "src/tools/**"
+      reason: "library code must not depend on tool implementations (dependencies point inward)"
+    - from: "src/lib/**"
+      to:   "src/server.ts"
+      reason: "library code must not depend on the server entry point"
+
+  # Report cycles without failing the build. (The top-level src/lib/tools grouping
+  # produces one benign cycle because shared types live in src/types.ts.)
+  cycles: warn
+
+diagram:
+  level: high
+  outPath: docs/architecture
diff --git a/.github/workflows/architecture.yml b/.github/workflows/architecture.yml
new file mode 100644
index 0000000..53600f4
--- /dev/null
+++ b/.github/workflows/architecture.yml
@@ -0,0 +1,85 @@
+name: Architecture
+
+on:
+  pull_request:
+  workflow_dispatch:
+
+permissions:
+  contents: read
+  pull-requests: write
+
+jobs:
+  architecture:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-node@v4
+        with:
+          # 22+: `node --test` only accepts glob patterns from v22.6, and Node 20 is EOL.
+          node-version: 22
+          cache: npm
+
+      - run: npm ci
+      - run: npm run build
+      - run: npm test
+
+      # Build locally instead of `npx repo-cartographer` so this dogfoods the repo
+      # itself before the package is published. External consumers use action.yml.
+      - name: Enforce architecture rules
+        run: node dist/index.js check . --config .cartographer.yml
+
+      # --format mermaid pinned: the PR comment below embeds a ```mermaid fence.
+      - name: Regenerate architecture diagram
+        if: always()
+        run: node dist/index.js map . -o docs/architecture --level high --format mermaid
+
+      - name: Comment on the PR
+        if: ${{ always() && github.event_name == 'pull_request' }}
+        uses: actions/github-script@v7
+        env:
+          DIAGRAM_OUT: docs/architecture
+        with:
+          script: |
+            const fs = require('fs');
+            const marker = '<!-- repo-cartographer -->';
+            const outBase = process.env.DIAGRAM_OUT || 'docs/architecture';
+            const mermaidPath = `${outBase}.mermaid`;
+            const mermaid = fs.existsSync(mermaidPath) ? fs.readFileSync(mermaidPath, 'utf8').trim() : '';
+            const violations = fs.existsSync('violations.json')
+              ? JSON.parse(fs.readFileSync('violations.json', 'utf8')) : [];
+            const errs = violations.filter(v => v.level === 'error').length;
+            const warns = violations.length - errs;
+            const head = violations.length
+              ? `**${errs} error(s), ${warns} warning(s)**`
+              : '✅ No architecture rule violations.';
+            const list = violations.map(v => {
+              const icon = v.level === 'error' ? '❌' : '⚠️';
+              return v.kind === 'forbidden'
+                ? `${icon} \`${v.from}\` → \`${v.to}\` — ${v.reason}`
+                : `${icon} ${v.reason}`;
+            }).join('\n');
+            const body = [
+              marker,
+              '### 🗺️ Architecture check',
+              '',
+              head,
+              list ? '\n' + list : '',
+              '',
+              '<details><summary>Architecture diagram</summary>',
+              '',
+              '```mermaid',
+              mermaid,
+              '```',
+              '',
+              '</details>',
+            ].join('\n');
+
+            const { owner, repo } = context.repo;
+            const issue_number = context.issue.number;
+            const { data: comments } = await github.rest.issues.listComments({ owner, repo, issue_number });
+            const existing = comments.find(c => c.body && c.body.includes(marker));
+            if (existing) {
+              await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
+            } else {
+              await github.rest.issues.createComment({ owner, repo, issue_number, body });
+            }
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..437d0c0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+dist/
+*.log
+.DS_Store
+
+# Written by `repo-cartographer check` into the working directory on every run.
+violations.json
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..95775b5
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,99 @@
+# CLAUDE.md — repo-cartographer
+
+## What this is
+An MCP (Model Context Protocol) server that helps any LLM understand a codebase
+and produce an **architecture diagram** for it. Tagline: "Understand any
+codebase in 60 seconds."
+
+It is model-agnostic: it works with any MCP client (Claude Code, Claude Desktop,
+ChatGPT/OpenAI Agents SDK, Cursor, Copilot, Cline, etc.). Do NOT add any
+Claude-specific dependency.
+
+## Core design principle (do not violate)
+The **server does deterministic extraction only. The model does the reasoning.**
+The server must never try to semantically "understand" code. It parses hard
+facts (file tree, import edges, manifests, framework detection, entry points)
+and returns structured JSON. The connected LLM turns those facts into the
+diagram and narrative.
+
+This split is intentional: it keeps the server simple, testable, and portable,
+and it is the main selling point when people evaluate the project.
+
+## Tech
+- TypeScript, ESM ("type": "module").
+- @modelcontextprotocol/sdk (stdio transport).
+- zod for input validation.
+- No heavy parsers required. Prefer lightweight regex / line scanning. Optional:
+  es-module-lexer for JS/TS imports. Keep dependencies minimal.
+
+## Scope (MVP — must stay small, ~2 day build)
+- Languages: JavaScript/TypeScript and Python only for v1.
+- Handle large repos by SUMMARIZING (cap files scanned, skip node_modules,
+  .git, dist, build, venv, __pycache__, vendor). Never dump every file.
+- Everything runs locally against a filesystem path. No network calls.
+
+## Tools to implement (build & test one at a time)
+1. `scan_repo(path)` -> JSON:
+   - detected languages, frameworks (from package.json / pyproject.toml /
+     requirements.txt / common config files),
+   - top-level modules/directories with short role guesses,
+   - entry points (main, index, __main__, bin, scripts),
+   - manifest summary (name, deps).
+2. `build_import_graph(path)` -> JSON:
+   - nodes = files/modules, edges = import/require relationships (JS/TS + Py).
+   - collapse to module/directory level when the file count is large.
+3. `generate_diagram(path, level)` -> string:
+   - combine scan + import graph into a DRAFT Mermaid flowchart.
+   - `level` = "high" (dirs/services) | "detail" (files). Default "high".
+   - This is a draft the model is expected to refine.
+4. `render_diagram(mermaid, outPath)`:
+   - write a self-contained .html that renders the Mermaid via CDN, plus the
+     raw .mermaid file. This HTML is the shareable artifact — make it look good.
+
+## Resource
+- `about://author` -> returns author/contact info as a Markdown string
+  (mimeType: "text/markdown").
+- Store all author details in ONE exported constant (e.g. AUTHOR) at the top
+  of the resource module, so they're easy to update in one place.
+- Content should be tasteful and brief: who I am, a one-line note that I'm
+  available for freelance/contract work on AI/agent/MCP tooling, and links.
+- Do NOT make it salesy or long. It's a business card, not a pitch.
+- Use the exact content below.
+
+Author content to return:
+
+  # builditwithgk
+
+  Hi — I'm Gopi K devm (builditwithgk). I build practical AI tooling,
+  autonomous agents, and MCP servers.
+
+  **repo-cartographer** is one of my open-source projects. If it saved you
+  time and you'd like help building LLM or agent tooling for your team, I'm
+  available for freelance and contract work.
+
+  - GitHub: https://github.com/builditwithgk
+  - HuggingFace: https://huggingface.co/builditwithgk
+  - Portfolio: https://scaleup-solutions.in/
+  - Email: builditwithgk@gmail.com
+
+  _Available for work._
+
+## Robustness
+- Validate all tool inputs with zod. Never throw raw on a missing path — return
+  a clear error object.
+- Ignore binary files and the excluded dirs above.
+- Deterministic output ordering (sort) so diagrams are stable across runs.
+
+## Deliverables
+- src/ with clean, commented code.
+- README.md focused on the OUTCOME, with:
+  - install via `npx`,
+  - a `claude mcp add` snippet,
+  - a short "use it with the OpenAI Agents SDK" snippet (prove cross-model),
+  - one example diagram (run it against this repo itself).
+- An example rendered diagram committed to the repo.
+
+## Build order
+Plan first. Then: project skeleton + stdio server that lists tools -> tool 1 ->
+test -> tool 2 -> test -> tool 3 -> test -> tool 4 -> test -> resource ->
+README + example. Test each tool with the MCP Inspector before moving on.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..a068a3b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Gopi K devm (builditwithgk)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a4f33ba
--- /dev/null
+++ b/README.md
@@ -0,0 +1,211 @@
+# repo-cartographer
+
+> **Understand any codebase in 60 seconds.** An [MCP](https://modelcontextprotocol.io) server that turns any repository into an architecture diagram.
+
+![TypeScript](https://img.shields.io/badge/TypeScript-ESM-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Version](https://img.shields.io/badge/version-1.0.0-blue) ![MCP](https://img.shields.io/badge/MCP-model--agnostic-brightgreen) [![Architecture](https://github.com/builditwithgk/repo-cartographer/actions/workflows/architecture.yml/badge.svg)](https://github.com/builditwithgk/repo-cartographer/actions/workflows/architecture.yml)
+
+Point your LLM at a folder and get back an architecture map: languages, frameworks, entry points, modules, and an import graph — rendered as a [Mermaid](https://mermaid.js.org/) diagram you can drop into a PR, a doc, or an onboarding guide.
+
+It is **model-agnostic**. It speaks the Model Context Protocol over stdio, so it works with Claude Code, Claude Desktop, Cursor, Cline, Copilot, or the OpenAI Agents SDK — no Claude-specific dependency.
+
+## Why it's different
+
+**The server extracts hard facts. The model does the reasoning.**
+
+`repo-cartographer` never tries to "understand" your code semantically. It parses deterministic facts — file tree, import edges, manifests, framework detection, entry points — and hands your LLM structured JSON plus a **draft** diagram. Your model turns those facts into the final narrative and a refined diagram.
+
+That split keeps the server small, fast, testable, and portable — and it means the diagram is grounded in what's actually in the repo, not hallucinated.
+
+## Example output
+
+Running `generate_diagram` against **this repo** produces (a draft the model then refines):
+
+```mermaid
+flowchart TD
+    n0["src · 2 files"]
+    n1["src/lib · library code · 9 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 4 files"]
+    n0 --> n1
+    n0 --> n2
+    n0 --> n3
+    n1 --> n0
+    n3 --> n0
+    n3 --> n1
+```
+
+A self-contained, shareable HTML render is committed under [`examples/`](examples/) (both a high-level and a file-level [`detail`](examples/repo-cartographer-detail.html) view).
+
+## Install & run
+
+Requires Node.js 18+.
+
+```bash
+# Run directly (no install)
+npx -y repo-cartographer
+
+# …or from source
+git clone https://github.com/builditwithgk/repo-cartographer
+cd repo-cartographer
+npm install
+npm run build
+node dist/index.js
+```
+
+The server communicates over stdio; AI clients launch it that way. You can also use it directly from a terminal — see below.
+
+## Command line (no AI needed)
+
+The same binary is dual-mode: with no arguments it's the MCP server; with a subcommand it's a plain CLI for humans and CI.
+
+```bash
+# Draw a diagram — path in, architecture.html out
+npx -y repo-cartographer map ./my-project
+npx -y repo-cartographer map ./my-project --level detail -o docs/architecture
+npx -y repo-cartographer map ./my-project --format dot   # Graphviz DOT instead of Mermaid
+
+# Enforce architecture rules (exits 1 on an error-level violation — use it in CI)
+npx -y repo-cartographer check ./my-project --config .cartographer.yml
+```
+
+Zip-friendly: if you point it at an extracted "Download ZIP" folder (`repo-main/` wrapper and all), it detects the wrapper and maps the real repo root — noted in the output, never silent.
+
+Two output notations, one strategy: **Mermaid because that's where people read it** (GitHub renders it natively in PR comments and READMEs), **DOT because that's what their tools eat** (pipe it into Graphviz, Backstage, or anything else: `dot -Tsvg architecture.dot`). Both come with the same shareable HTML page and role-colored modules. When the repo has a `.cartographer.yml`, its `diagram:` section supplies the defaults for `--level`, `--format` and `-o`; explicit flags always win.
+
+`check` reads a rules file and flags **forbidden cross-boundary imports** and **dependency cycles** — deterministically, no LLM involved, so it's safe to gate a merge:
+
+```yaml
+# .cartographer.yml
+rules:
+  forbidden:
+    - from: "src/ui/**"
+      to:   "src/db/**"
+      reason: "UI must go through the service layer, not the DB directly."
+  cycles: error        # error | warn | off
+```
+
+**Adopting on an existing codebase?** Record today's violations as an accepted baseline, so only *new* ones fail the build:
+
+```bash
+npx -y repo-cartographer check . --update-baseline   # writes .cartographer-baseline.json
+```
+
+Commit that file; later runs auto-detect it and pass unless a PR introduces a *new* violation.
+
+## Architecture governance in CI (GitHub Action)
+
+A composite action ([`action.yml`](action.yml)) runs `check` on every PR — failing the
+build on an error-level violation and posting a sticky comment with the diagram and
+any violations:
+
+```yaml
+# .github/workflows/architecture.yml
+on: pull_request
+permissions: { contents: read, pull-requests: write }
+jobs:
+  architecture:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: builditwithgk/repo-cartographer@v1
+        with: { path: ., config: .cartographer.yml }
+```
+
+This repo dogfoods it in [`.github/workflows/architecture.yml`](.github/workflows/architecture.yml).
+Full design + phases: [docs/github-action.md](docs/github-action.md).
+
+## Use it with Claude Code
+
+```bash
+claude mcp add repo-cartographer -- npx -y repo-cartographer
+```
+
+Then ask: *"Use repo-cartographer to map ./my-project and draw me an architecture diagram."*
+
+### Claude Desktop
+
+Add to `claude_desktop_config.json`:
+
+```json
+{
+  "mcpServers": {
+    "repo-cartographer": {
+      "command": "npx",
+      "args": ["-y", "repo-cartographer"]
+    }
+  }
+}
+```
+
+## Use it with the OpenAI Agents SDK
+
+Same server, a different model — the whole point of MCP:
+
+```python
+import asyncio
+from agents import Agent, Runner
+from agents.mcp import MCPServerStdio
+
+async def main():
+    async with MCPServerStdio(
+        params={"command": "npx", "args": ["-y", "repo-cartographer"]},
+    ) as cartographer:
+        agent = Agent(
+            name="Cartographer",
+            instructions=(
+                "Use the repo tools to gather facts, then refine the draft "
+                "Mermaid diagram into a clean architecture map."
+            ),
+            mcp_servers=[cartographer],
+        )
+        result = await Runner.run(agent, "Map ./my-project and explain its architecture.")
+        print(result.final_output)
+
+asyncio.run(main())
+```
+
+## Tools & resources
+
+| Tool | What it returns |
+| --- | --- |
+| **`map_repo(path, level?, format?, outPath?)`** | **The one-shot flow.** Point it at a folder and get a downloadable architecture diagram (`architecture.html` + `.mermaid`/`.dot`) plus a facts summary and the draft source inline — in a single call. |
+| `scan_repo(path)` | Languages, frameworks, entry points, top-level modules (with role guesses), and a manifest summary — as JSON facts. |
+| `build_import_graph(path)` | Intra-repo import/require edges for JS/TS + Python. Nodes are files, auto-collapsed to module level for large repos. |
+| `generate_diagram(path, level?, format?)` | A **draft** diagram. `level` = `"high"` (modules, default) or `"detail"` (files grouped by module); `format` = `"mermaid"` (default) or `"dot"` (Graphviz). |
+| `render_diagram(source, outPath, format?)` | Writes a self-contained, styled `.html` (renders via CDN: Mermaid, or Viz for DOT) plus the raw `.mermaid`/`.dot` file. |
+
+| Resource | |
+| --- | --- |
+| `about://author` | Who built this and how to reach them (Markdown). |
+
+**Most of the time you just want `map_repo`** — "path in, diagram out." Reach for the four granular tools only when you want to compose the steps yourself (e.g. let the model refine the diagram source between `generate_diagram` and `render_diagram`).
+
+## How it stays fast on big repos
+
+- **Languages:** JavaScript/TypeScript and Python (v1).
+- **Skips** `node_modules`, `.git`, `dist`, `build`, `venv`, `__pycache__`, `vendor`, and other build/dependency/cache directories (plus all hidden dirs).
+- **Caps** the number of files scanned and bytes read per file; **collapses** the import graph to directory level past a threshold. Anything capped is reported in the output — never dropped silently.
+- **No network calls** at scan time. (The rendered HTML pulls Mermaid from a CDN only when *you* open it in a browser.)
+- **Deterministic:** output is sorted and stable, so diagrams don't churn between runs.
+
+## Development
+
+```bash
+npm run dev        # run from source with tsx
+npm run build      # type-check + emit to dist/
+npm test           # unit tests (node:test, no build step needed)
+npm run typecheck  # type-check src/ and test/ together, no emit
+```
+
+Tests cover the deterministic core — import resolution (JS/TS + Python), module
+collapsing, cycle detection, rule globs, baseline diffing, Mermaid rendering and
+the `check` end-to-end path. They run against `src/` via `tsx`, so there is no
+build step and no test framework dependency.
+
+## Author
+
+Built by **Gopi K devm** ([builditwithgk](https://github.com/builditwithgk)) — see `about://author`, or [scaleup-solutions.in](https://scaleup-solutions.in/). Available for freelance and contract work on AI, agent, and MCP tooling.
+
+## License
+
+MIT
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 0000000..f6a7e59
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,30 @@
+# TODO / Tech debt — repo-cartographer
+
+## Deferred (intentionally, for now)
+- [ ] **Initial git commit.** Repo has zero commits. Hold off until manual testing passes. `.gitignore` already excludes `node_modules/` + `dist/`.
+- [ ] **Publish to npm** so `npx -y repo-cartographer` works. Until then, README's npx commands only work from source (`npm run build` + `node dist/index.js`).
+
+## Roadmap — the "enterprising" direction
+- [x] **One-shot `map_repo(path)`** — path in, downloadable diagram out (shipped).
+- [x] **CLI (`map` + `check`)** — dual-mode binary; `check` enforces forbidden imports + cycles from a `.cartographer.yml`, writes `violations.json`, exits 1 on error. (shipped)
+- [x] **GitHub Action (Phase 2)** — composite [`action.yml`](action.yml) + dogfood workflow that runs `check` on every PR and posts diagram + violations as a sticky comment. (shipped)
+- [x] **"New violations only" (Phase 3)** — `check --update-baseline` writes `.cartographer-baseline.json`; later runs fail only on newly-introduced violations. (shipped)
+- [ ] **Publish to npm** — required before the `uses: builditwithgk/repo-cartographer@v1` action works for external consumers (it runs `npx repo-cartographer`).
+- [x] **Unit tests** — 169 tests under [`test/`](test/) via `node:test` + `tsx` (`npm test`), no new dependencies and no build step. Cover import resolution (JS/TS + Python), module collapsing, Tarjan cycles, rule globs, config loading, baseline diffing, walking, manifest/entry-point detection, Mermaid + DOT rendering and `runCheck` end-to-end. `npm run typecheck` type-checks `src/` + `test/` together via [`tsconfig.test.json`](tsconfig.test.json). (shipped)
+- [x] **Zip-wrapper auto-descent** — a directory containing no files and exactly one visible subfolder (GitHub "Download ZIP" shape) is stepped past (bounded, noted in tool output) by every tool via `resolveRepoRoot`. Guard: a lone source container (`src/`, `lib/`, `packages/`…) is never treated as a wrapper — that would rewrite every repo-relative glob. Found by testing the fresh-clone flow against extracted sample zips: pre-fix, a 219-file repo mapped as "1 module · 0 edges". Also added: `LICENSE` (MIT — README/package.json already claimed it). (shipped)
+- [x] **Diagram formats + role styling** — `format: mermaid | dot` on `map_repo`/`generate_diagram`/`render_diagram`, `--format` on the CLI, `diagram.format` in `.cartographer.yml`, and a `format` input on the Action (comment pins mermaid — the PR fence can't render DOT). High-level diagrams color modules by role family (shared palette across both emitters); DOT HTML renders via the Viz CDN. `map` now reads its defaults from the config's `diagram:` section (flags win) — that section used to be dead config. Strategy: Mermaid because that's where people read it, DOT because that's what their tools eat. (shipped)
+
+## Found by the tests (fixed)
+- [x] **Raw NUL bytes in source.** `src/lib/baseline.ts` and `src/lib/imports.ts` used a literal NUL as a composite-key separator, stored as an actual byte. Git would have marked both files binary (no diffs, no reviewable PRs), and any text-normalizing tool could silently delete the separator and change key semantics. Replaced with escape sequences — identical at runtime, ASCII in source.
+- [x] **A hidden architecture violation, caused by the above.** `readTextCapped` skips any file with a NUL in the first 4 KB as binary, so `src/lib/baseline.ts` was never scanned for imports — hiding its `import type { Violation } from "../tools/checkRepo.js"`, a real breach of this repo's own `src/lib/** -> src/tools/**` rule. `Violation`/`CheckResult` now live in `src/types.ts` (re-exported from `checkRepo.ts` for compatibility) so dependencies point inward.
+- [x] **HTML injection in the rendered diagram.** `render_diagram` inlined the Mermaid source into a `<script>` block via `JSON.stringify` without escaping `<`, so a `</script>` in the diagram text closed the block early and turned the rest into live HTML in the shareable `architecture.html`. Not reachable through `map_repo` (labels are escaped), but `render_diagram` accepts arbitrary text. Now escaped via `jsonForScript()`.
+
+## Possible enhancements (v2+)
+- [ ] More formats behind the same enum, only on demand: D2 (prettiest, but audience overlaps DOT) and C4/Structurizr (needs module filtering/levels first — revisit after Phase 4 metrics exist).
+- [ ] `diagram.direction` (TD/LR) option — LR reads better for layered repos; kept out of v1 to avoid auto-detection flakiness in diffs.
+- [ ] Swap regex import parsing for `es-module-lexer` (JS/TS) for higher-fidelity edges. Currently pure regex to keep deps minimal.
+- [ ] Distinguish `import type` from a value import so type-only edges can be reported separately (the regex parser treats them alike).
+- [ ] Support more languages (Go, Rust, Java) beyond JS/TS + Python.
+- [ ] Option to vendor Mermaid into the rendered HTML so it works fully offline (today it loads Mermaid from a CDN at view time).
+- [ ] Parse the `requirements/*.txt` directory layout, not just files *named* `requirements*.txt`. Current behaviour is pinned by a test in `test/detect.test.ts`.
+- [ ] Consider declaring `engines` in `package.json` before publishing (`npm test` needs Node >= 22 for `node --test` glob patterns).
diff --git a/action.yml b/action.yml
new file mode 100644
index 0000000..b2a8cb1
--- /dev/null
+++ b/action.yml
@@ -0,0 +1,101 @@
+name: "repo-cartographer"
+description: "Enforce architecture rules and post an architecture diagram on pull requests."
+branding:
+  icon: "map"
+  color: "blue"
+
+inputs:
+  path:
+    description: "Path to the repository root to analyze."
+    default: "."
+  config:
+    description: "Path to the rules file (default: auto-detect .cartographer.yml in path)."
+    default: ""
+  baseline:
+    description: "Path to a baseline of accepted pre-existing violations (default: auto-detect .cartographer-baseline.json in path). Only NEW violations then fail the build."
+    default: ""
+  level:
+    description: "Diagram granularity: 'high' or 'detail'."
+    default: "high"
+  format:
+    description: "Diagram notation: 'mermaid' or 'dot'. The PR comment can only embed 'mermaid'; with 'dot' the comment omits the diagram and only the files are written."
+    default: "mermaid"
+  out:
+    description: "Diagram output base path (writes <out>.html and <out>.mermaid)."
+    default: "docs/architecture"
+  version:
+    description: "repo-cartographer npm version to run."
+    default: "latest"
+  comment:
+    description: "Post/update a PR comment with the diagram and any violations."
+    default: "true"
+
+runs:
+  using: "composite"
+  steps:
+    - name: Enforce architecture rules
+      shell: bash
+      run: |
+        CONFIG_ARG=""
+        if [ -n "${{ inputs.config }}" ]; then CONFIG_ARG="--config ${{ inputs.config }}"; fi
+        BASELINE_ARG=""
+        if [ -n "${{ inputs.baseline }}" ]; then BASELINE_ARG="--baseline ${{ inputs.baseline }}"; fi
+        npx -y "repo-cartographer@${{ inputs.version }}" check "${{ inputs.path }}" $CONFIG_ARG $BASELINE_ARG
+
+    - name: Regenerate architecture diagram
+      if: always()
+      shell: bash
+      run: |
+        npx -y "repo-cartographer@${{ inputs.version }}" map "${{ inputs.path }}" \
+          -o "${{ inputs.out }}" --level "${{ inputs.level }}" --format "${{ inputs.format }}"
+
+    - name: Comment on the PR
+      if: ${{ always() && inputs.comment == 'true' && github.event_name == 'pull_request' }}
+      uses: actions/github-script@v7
+      env:
+        DIAGRAM_OUT: ${{ inputs.out }}
+      with:
+        script: |
+          const fs = require('fs');
+          const marker = '<!-- repo-cartographer -->';
+          const outBase = process.env.DIAGRAM_OUT || 'docs/architecture';
+          const mermaidPath = `${outBase}.mermaid`;
+          const mermaid = fs.existsSync(mermaidPath) ? fs.readFileSync(mermaidPath, 'utf8').trim() : '';
+          const violations = fs.existsSync('violations.json')
+            ? JSON.parse(fs.readFileSync('violations.json', 'utf8')) : [];
+          const errs = violations.filter(v => v.level === 'error').length;
+          const warns = violations.length - errs;
+          const head = violations.length
+            ? `**${errs} error(s), ${warns} warning(s)**`
+            : '✅ No architecture rule violations.';
+          const list = violations.map(v => {
+            const icon = v.level === 'error' ? '❌' : '⚠️';
+            return v.kind === 'forbidden'
+              ? `${icon} \`${v.from}\` → \`${v.to}\` — ${v.reason}`
+              : `${icon} ${v.reason}`;
+          }).join('\n');
+          const body = [
+            marker,
+            '### 🗺️ Architecture check',
+            '',
+            head,
+            list ? '\n' + list : '',
+            '',
+            '<details><summary>Architecture diagram</summary>',
+            '',
+            '```mermaid',
+            mermaid,
+            '```',
+            '',
+            '</details>',
+          ].join('\n');
+
+          const { owner, repo } = context.repo;
+          const issue_number = context.issue.number;
+          const { data: comments } = await github.rest.issues.listComments({ owner, repo, issue_number });
+          const existing = comments.find(c => c.body && c.body.includes(marker));
+          if (existing) {
+            await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
+          } else {
+            await github.rest.issues.createComment({ owner, repo, issue_number, body });
+          }
diff --git a/docs/architecture.html b/docs/architecture.html
new file mode 100644
index 0000000..3873ec6
--- /dev/null
+++ b/docs/architecture.html
@@ -0,0 +1,108 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>architecture — architecture</title>
+<style>
+  :root { color-scheme: light dark; --bg:#ffffff; --fg:#1a1a1a; --muted:#666; --card:#f6f8fa; --border:#e2e5e9; --accent:#3b6fd4; }
+  @media (prefers-color-scheme: dark) {
+    :root { --bg:#0f1115; --fg:#e6e6e6; --muted:#9aa0a6; --card:#171a21; --border:#2a2f3a; --accent:#6f9dff; }
+  }
+  * { box-sizing: border-box; }
+  body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background:var(--bg); color:var(--fg); }
+  header { padding:20px 24px; border-bottom:1px solid var(--border); display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
+  header h1 { font-size:18px; margin:0; font-weight:650; }
+  header .tag { font-size:12px; color:var(--muted); }
+  main { padding:24px; }
+  .diagram { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:20px; overflow-x:auto; }
+  .diagram .mermaid, .diagram #graph { display:flex; justify-content:center; }
+  .diagram #graph svg { max-width:100%; height:auto; }
+  .bar { display:flex; gap:8px; margin:16px 0 0; }
+  button { font:inherit; font-size:13px; padding:7px 13px; border-radius:8px; border:1px solid var(--border); background:var(--card); color:var(--fg); cursor:pointer; }
+  button:hover { border-color:var(--accent); }
+  details { margin-top:16px; }
+  summary { cursor:pointer; color:var(--muted); font-size:13px; }
+  pre.src { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px; overflow:auto; font-size:12.5px; line-height:1.5; }
+  footer { padding:16px 24px; color:var(--muted); font-size:12px; border-top:1px solid var(--border); }
+  a { color:var(--accent); }
+</style>
+</head>
+<body>
+<header>
+  <h1>architecture</h1>
+  <span class="tag">architecture diagram · draft · mermaid</span>
+</header>
+<main>
+  <div class="diagram">
+    <pre class="mermaid">flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --&gt; n1
+    n0 --&gt; n2
+    n0 --&gt; n3
+    n1 --&gt; n0
+    n3 --&gt; n0
+    n3 --&gt; n1
+    n4 --&gt; n0
+    n4 --&gt; n1
+    n4 --&gt; n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975</pre>
+  </div>
+  <div class="bar">
+    <button id="copy">Copy Mermaid source</button>
+    <button id="download">Download .mermaid</button>
+  </div>
+  <details>
+    <summary>View Mermaid source</summary>
+    <pre class="src">flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --&gt; n1
+    n0 --&gt; n2
+    n0 --&gt; n3
+    n1 --&gt; n0
+    n3 --&gt; n0
+    n3 --&gt; n1
+    n4 --&gt; n0
+    n4 --&gt; n1
+    n4 --&gt; n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975</pre>
+  </details>
+</main>
+<footer>Generated by <a href="https://github.com/builditwithgk/repo-cartographer">repo-cartographer</a>. This is a draft — refine it with your model.</footer>
+<script>
+  const SRC = "flowchart TD\n    %% repo-cartographer — high-level architecture (DRAFT, refine me)\n    n0[\"src · 4 files\"]\n    n1[\"src/lib · library code · 14 files\"]\n    n2[\"src/resources · resource handlers · 1 file\"]\n    n3[\"src/tools · tool implementations · 6 files\"]\n    n4[\"test · tests · 14 files\"]\n    n0 --> n1\n    n0 --> n2\n    n0 --> n3\n    n1 --> n0\n    n3 --> n0\n    n3 --> n1\n    n4 --> n0\n    n4 --> n1\n    n4 --> n3\n    class n1,n2,n3 shared\n    class n4 test\n    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654\n    classDef test fill:#499894,color:#ffffff,stroke:#397975";
+  document.getElementById("copy").addEventListener("click", async () => {
+    try { await navigator.clipboard.writeText(SRC); } catch (e) {}
+  });
+  document.getElementById("download").addEventListener("click", () => {
+    const blob = new Blob([SRC], { type: "text/plain" });
+    const a = document.createElement("a");
+    a.href = URL.createObjectURL(blob);
+    a.download = "architecture" + ".mermaid";
+    a.click();
+    URL.revokeObjectURL(a.href);
+  });
+</script>
+<script type="module">
+  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
+  const dark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
+  mermaid.initialize({ startOnLoad: true, theme: dark ? "dark" : "default", securityLevel: "strict" });
+</script>
+</body>
+</html>
diff --git a/docs/architecture.mermaid b/docs/architecture.mermaid
new file mode 100644
index 0000000..8c63393
--- /dev/null
+++ b/docs/architecture.mermaid
@@ -0,0 +1,20 @@
+flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --> n1
+    n0 --> n2
+    n0 --> n3
+    n1 --> n0
+    n3 --> n0
+    n3 --> n1
+    n4 --> n0
+    n4 --> n1
+    n4 --> n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975
\ No newline at end of file
diff --git a/docs/github-action.md b/docs/github-action.md
new file mode 100644
index 0000000..0a659c3
--- /dev/null
+++ b/docs/github-action.md
@@ -0,0 +1,181 @@
+# GitHub Action — architecture governance on every PR
+
+> Status: **implemented.** The composite action lives in [`action.yml`](../action.yml);
+> this repo dogfoods it in [`.github/workflows/architecture.yml`](../.github/workflows/architecture.yml).
+> This is the next step up from a diagram generator: enforcing architecture rules in CI.
+
+## Usage (for consumers)
+
+Once published to npm, another repo enforces its architecture in one step:
+
+```yaml
+# .github/workflows/architecture.yml
+name: Architecture
+on: pull_request
+permissions:
+  contents: read
+  pull-requests: write
+jobs:
+  architecture:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: builditwithgk/repo-cartographer@v1
+        with:
+          path: .
+          config: .cartographer.yml   # optional; auto-detected if omitted
+          level: high                 # optional
+```
+
+The step fails the PR when an error-level rule is violated and posts (or updates) a
+single sticky PR comment with the diagram and any violations.
+
+## The one job it does
+
+On every pull request:
+
+1. **Enforce architecture rules** — fail the check if the PR introduces a
+   forbidden cross-boundary import (e.g. `ui/` importing `db/`) or a new
+   dependency cycle.
+2. **Regenerate the architecture diagram** and post it (plus any violations) as a
+   PR comment.
+
+The enforcement step is **100% deterministic — no LLM in the CI path.** It runs on
+the exact import edges `build_import_graph` already produces, so it's fast,
+reproducible, and can safely gate a merge. The diagram is the human-friendly
+artifact layered on top.
+
+## Why it's credible with what we already have
+
+`build_import_graph(path)` returns `{ nodes, edges }` — directed intra-repo import
+edges for JS/TS + Python. Everything below is a pure function over that graph:
+
+- **Forbidden import** = an edge whose `from` matches a boundary glob and whose
+  `to` matches a forbidden target glob.
+- **Cycle** = a strongly-connected component of size > 1 (Tarjan/DFS over `edges`).
+
+No new analysis engine required — just rules on top of existing facts.
+
+## Config: `.cartographer.yml` (committed to the repo)
+
+```yaml
+rules:
+  # Fail the PR if any of these import edges exist.
+  forbidden:
+    - from: "src/ui/**"
+      to:   "src/db/**"
+      reason: "UI must go through the service layer, not the DB directly."
+    - from: "**"
+      to:   "src/internal/**"
+      reason: "internal/ is private to its package."
+
+  # New import cycles between modules.
+  cycles: error        # error | warn | off
+
+diagram:
+  level: high          # high | detail
+  format: mermaid      # mermaid | dot (Graphviz)
+  outPath: docs/architecture   # regenerated each run (architecture.html + raw source)
+```
+
+## CLI the Action calls (small delta from today's code)
+
+The published `bin` becomes dual-mode — MCP server by default, CLI when given a
+subcommand:
+
+```bash
+repo-cartographer                       # (default) MCP stdio server — unchanged
+repo-cartographer map   <path> [-o out] [--level high|detail] [--format mermaid|dot]
+repo-cartographer check <path> [--config .cartographer.yml]   # exit 1 on error-level violations
+```
+
+- `map`  → thin wrapper over the existing `runMapRepo`.
+- `check` → `runBuildImportGraph` → load rules → evaluate forbidden edges + cycles
+  → print a report + write `violations.json` → `process.exit(hasError ? 1 : 0)`.
+
+New dependencies are confined to this CLI/Action layer (the MCP server stays at
+its two deps): a glob matcher (`minimatch`, or a ~30-line subset) and a YAML
+parser (`yaml`, or restrict the config to JSON). Cycle detection is hand-rolled.
+
+## The workflow: `.github/workflows/architecture.yml`
+
+```yaml
+name: Architecture
+on: pull_request
+
+permissions:
+  contents: read
+  pull-requests: write
+
+jobs:
+  architecture:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-node@v4
+        with:
+          node-version: 20
+
+      - name: Enforce architecture rules
+        id: check
+        run: npx -y repo-cartographer check . --config .cartographer.yml
+        # exits 1 (fails the job) if any error-level rule is violated
+
+      - name: Regenerate architecture diagram
+        if: always()
+        run: npx -y repo-cartographer map . -o docs/architecture --level high
+
+      - name: Comment on the PR
+        if: always()
+        uses: actions/github-script@v7
+        with:
+          script: |
+            const fs = require('fs');
+            const mermaid = fs.readFileSync('docs/architecture.mermaid', 'utf8');
+            const violations = fs.existsSync('violations.json')
+              ? JSON.parse(fs.readFileSync('violations.json', 'utf8')) : [];
+            const lines = violations.length
+              ? violations.map(v => `${v.level === 'error' ? '❌' : '⚠️'} \`${v.from}\` → \`${v.to}\` — ${v.reason}`)
+              : ['✅ No architecture rule violations.'];
+            const body = [
+              '### 🗺️ Architecture check',
+              '', ...lines, '',
+              '<details><summary>Updated architecture diagram</summary>',
+              '', '```mermaid', mermaid, '```', '', '</details>',
+            ].join('\n');
+            // upsert a single sticky comment (find-by-marker, then update or create)
+            // ...github.rest.issues.{listComments,updateComment,createComment}
+```
+
+(Package the three steps as a composite action — `builditwithgk/repo-cartographer-action@v1`
+— so consumers add just one `uses:` line.)
+
+## Sample PR comment
+
+> ### 🗺️ Architecture check
+>
+> **2 violations** (1 error, 1 warning)
+>
+> ❌ `src/ui/Login.tsx` → `src/db/client.ts` — UI must go through the service layer, not the DB directly.
+> ⚠️ new cycle: `orders → risk → orders`
+>
+> <details><summary>Updated architecture diagram</summary>
+>
+> *(rendered Mermaid flowchart)*
+>
+> </details>
+
+## Build checklist (phased)
+
+- [x] **Phase 0** — deterministic import graph (`build_import_graph`).
+- [x] **Phase 1 — CLI.** `map` + `check` subcommands; rules loader; glob match; Tarjan cycle detection; `violations.json`; correct exit code.
+- [x] **Phase 2 — Action.** Composite `action.yml` + dogfood workflow + sticky PR comment (upsert by marker).
+- [x] **Phase 3 — "new" vs "existing".** `check --update-baseline` records accepted violations to `.cartographer-baseline.json`; later runs (auto-detecting that file, or via `--baseline`) fail only on *newly introduced* violations, so adopting on a messy repo doesn't block every PR on day one.
+- [ ] **Phase 4** — coupling/fan-in metrics, drift trend, hosted GitHub App + dashboard.
+
+## Design guardrails
+
+- **CI path stays LLM-free and deterministic** — a merge gate must be reproducible.
+- **Local-first** — the Action runs in the customer's own CI; source never leaves.
+- **Adopt-gradually** — the baseline (`--update-baseline`) is what makes it usable on
+  an existing large codebase instead of a wall of red on first install.
diff --git a/examples/repo-cartographer-detail.html b/examples/repo-cartographer-detail.html
new file mode 100644
index 0000000..ae758ff
--- /dev/null
+++ b/examples/repo-cartographer-detail.html
@@ -0,0 +1,358 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>repo-cartographer-detail — architecture</title>
+<style>
+  :root { color-scheme: light dark; --bg:#ffffff; --fg:#1a1a1a; --muted:#666; --card:#f6f8fa; --border:#e2e5e9; --accent:#3b6fd4; }
+  @media (prefers-color-scheme: dark) {
+    :root { --bg:#0f1115; --fg:#e6e6e6; --muted:#9aa0a6; --card:#171a21; --border:#2a2f3a; --accent:#6f9dff; }
+  }
+  * { box-sizing: border-box; }
+  body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background:var(--bg); color:var(--fg); }
+  header { padding:20px 24px; border-bottom:1px solid var(--border); display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
+  header h1 { font-size:18px; margin:0; font-weight:650; }
+  header .tag { font-size:12px; color:var(--muted); }
+  main { padding:24px; }
+  .diagram { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:20px; overflow-x:auto; }
+  .diagram .mermaid, .diagram #graph { display:flex; justify-content:center; }
+  .diagram #graph svg { max-width:100%; height:auto; }
+  .bar { display:flex; gap:8px; margin:16px 0 0; }
+  button { font:inherit; font-size:13px; padding:7px 13px; border-radius:8px; border:1px solid var(--border); background:var(--card); color:var(--fg); cursor:pointer; }
+  button:hover { border-color:var(--accent); }
+  details { margin-top:16px; }
+  summary { cursor:pointer; color:var(--muted); font-size:13px; }
+  pre.src { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px; overflow:auto; font-size:12.5px; line-height:1.5; }
+  footer { padding:16px 24px; color:var(--muted); font-size:12px; border-top:1px solid var(--border); }
+  a { color:var(--accent); }
+</style>
+</head>
+<body>
+<header>
+  <h1>repo-cartographer-detail</h1>
+  <span class="tag">architecture diagram · draft · mermaid</span>
+</header>
+<main>
+  <div class="diagram">
+    <pre class="mermaid">flowchart TD
+    %% repo-cartographer — detail-level architecture (DRAFT, refine me)
+    subgraph g0["src"]
+        n0["cli.ts"]
+        n1["index.ts"]
+        n17["server.ts"]
+        n24["types.ts"]
+    end
+    subgraph g1["src/lib"]
+        n2["baseline.ts"]
+        n3["cycles.ts"]
+        n4["detect.ts"]
+        n5["dot.ts"]
+        n6["fsutil.ts"]
+        n7["glob.ts"]
+        n8["ignore.ts"]
+        n9["imports.ts"]
+        n10["mermaid.ts"]
+        n11["paths.ts"]
+        n12["result.ts"]
+        n13["roles.ts"]
+        n14["rules.ts"]
+        n15["walk.ts"]
+    end
+    subgraph g2["src/resources"]
+        n16["author.ts"]
+    end
+    subgraph g3["src/tools"]
+        n18["buildImportGraph.ts"]
+        n19["checkRepo.ts"]
+        n20["generateDiagram.ts"]
+        n21["mapRepo.ts"]
+        n22["renderDiagram.ts"]
+        n23["scanRepo.ts"]
+    end
+    subgraph g4["test"]
+        n25["baseline.test.ts"]
+        n26["check.test.ts"]
+        n27["cycles.test.ts"]
+        n28["detect.test.ts"]
+        n29["dot.test.ts"]
+        n30["glob.test.ts"]
+        n31["fixture.ts"]
+        n32["imports.test.ts"]
+        n33["mermaid.test.ts"]
+        n34["paths.test.ts"]
+        n35["renderDiagram.test.ts"]
+        n36["roles.test.ts"]
+        n37["rules.test.ts"]
+        n38["walk.test.ts"]
+    end
+    n0 --&gt; n2
+    n0 --&gt; n14
+    n0 --&gt; n19
+    n0 --&gt; n21
+    n0 --&gt; n24
+    n1 --&gt; n0
+    n1 --&gt; n17
+    n2 --&gt; n24
+    n3 --&gt; n24
+    n4 --&gt; n6
+    n4 --&gt; n8
+    n4 --&gt; n11
+    n4 --&gt; n24
+    n5 --&gt; n9
+    n5 --&gt; n11
+    n5 --&gt; n13
+    n5 --&gt; n24
+    n9 --&gt; n6
+    n9 --&gt; n8
+    n9 --&gt; n11
+    n9 --&gt; n24
+    n10 --&gt; n9
+    n10 --&gt; n11
+    n10 --&gt; n13
+    n10 --&gt; n24
+    n14 --&gt; n24
+    n15 --&gt; n6
+    n15 --&gt; n8
+    n15 --&gt; n11
+    n17 --&gt; n12
+    n17 --&gt; n16
+    n17 --&gt; n18
+    n17 --&gt; n20
+    n17 --&gt; n21
+    n17 --&gt; n22
+    n17 --&gt; n23
+    n18 --&gt; n8
+    n18 --&gt; n9
+    n18 --&gt; n11
+    n18 --&gt; n15
+    n18 --&gt; n24
+    n19 --&gt; n3
+    n19 --&gt; n7
+    n19 --&gt; n9
+    n19 --&gt; n11
+    n19 --&gt; n14
+    n19 --&gt; n15
+    n19 --&gt; n24
+    n20 --&gt; n4
+    n20 --&gt; n5
+    n20 --&gt; n9
+    n20 --&gt; n10
+    n20 --&gt; n11
+    n20 --&gt; n15
+    n20 --&gt; n24
+    n21 --&gt; n15
+    n21 --&gt; n20
+    n21 --&gt; n22
+    n21 --&gt; n23
+    n22 --&gt; n24
+    n23 --&gt; n4
+    n23 --&gt; n11
+    n23 --&gt; n13
+    n23 --&gt; n15
+    n23 --&gt; n24
+    n25 --&gt; n2
+    n25 --&gt; n24
+    n25 --&gt; n31
+    n26 --&gt; n14
+    n26 --&gt; n19
+    n26 --&gt; n31
+    n27 --&gt; n3
+    n27 --&gt; n24
+    n28 --&gt; n4
+    n28 --&gt; n31
+    n29 --&gt; n5
+    n29 --&gt; n20
+    n29 --&gt; n24
+    n29 --&gt; n31
+    n30 --&gt; n7
+    n31 --&gt; n11
+    n32 --&gt; n9
+    n32 --&gt; n24
+    n32 --&gt; n31
+    n33 --&gt; n10
+    n33 --&gt; n24
+    n34 --&gt; n11
+    n35 --&gt; n22
+    n35 --&gt; n31
+    n36 --&gt; n13
+    n37 --&gt; n14
+    n37 --&gt; n31
+    n38 --&gt; n15
+    n38 --&gt; n31</pre>
+  </div>
+  <div class="bar">
+    <button id="copy">Copy Mermaid source</button>
+    <button id="download">Download .mermaid</button>
+  </div>
+  <details>
+    <summary>View Mermaid source</summary>
+    <pre class="src">flowchart TD
+    %% repo-cartographer — detail-level architecture (DRAFT, refine me)
+    subgraph g0["src"]
+        n0["cli.ts"]
+        n1["index.ts"]
+        n17["server.ts"]
+        n24["types.ts"]
+    end
+    subgraph g1["src/lib"]
+        n2["baseline.ts"]
+        n3["cycles.ts"]
+        n4["detect.ts"]
+        n5["dot.ts"]
+        n6["fsutil.ts"]
+        n7["glob.ts"]
+        n8["ignore.ts"]
+        n9["imports.ts"]
+        n10["mermaid.ts"]
+        n11["paths.ts"]
+        n12["result.ts"]
+        n13["roles.ts"]
+        n14["rules.ts"]
+        n15["walk.ts"]
+    end
+    subgraph g2["src/resources"]
+        n16["author.ts"]
+    end
+    subgraph g3["src/tools"]
+        n18["buildImportGraph.ts"]
+        n19["checkRepo.ts"]
+        n20["generateDiagram.ts"]
+        n21["mapRepo.ts"]
+        n22["renderDiagram.ts"]
+        n23["scanRepo.ts"]
+    end
+    subgraph g4["test"]
+        n25["baseline.test.ts"]
+        n26["check.test.ts"]
+        n27["cycles.test.ts"]
+        n28["detect.test.ts"]
+        n29["dot.test.ts"]
+        n30["glob.test.ts"]
+        n31["fixture.ts"]
+        n32["imports.test.ts"]
+        n33["mermaid.test.ts"]
+        n34["paths.test.ts"]
+        n35["renderDiagram.test.ts"]
+        n36["roles.test.ts"]
+        n37["rules.test.ts"]
+        n38["walk.test.ts"]
+    end
+    n0 --&gt; n2
+    n0 --&gt; n14
+    n0 --&gt; n19
+    n0 --&gt; n21
+    n0 --&gt; n24
+    n1 --&gt; n0
+    n1 --&gt; n17
+    n2 --&gt; n24
+    n3 --&gt; n24
+    n4 --&gt; n6
+    n4 --&gt; n8
+    n4 --&gt; n11
+    n4 --&gt; n24
+    n5 --&gt; n9
+    n5 --&gt; n11
+    n5 --&gt; n13
+    n5 --&gt; n24
+    n9 --&gt; n6
+    n9 --&gt; n8
+    n9 --&gt; n11
+    n9 --&gt; n24
+    n10 --&gt; n9
+    n10 --&gt; n11
+    n10 --&gt; n13
+    n10 --&gt; n24
+    n14 --&gt; n24
+    n15 --&gt; n6
+    n15 --&gt; n8
+    n15 --&gt; n11
+    n17 --&gt; n12
+    n17 --&gt; n16
+    n17 --&gt; n18
+    n17 --&gt; n20
+    n17 --&gt; n21
+    n17 --&gt; n22
+    n17 --&gt; n23
+    n18 --&gt; n8
+    n18 --&gt; n9
+    n18 --&gt; n11
+    n18 --&gt; n15
+    n18 --&gt; n24
+    n19 --&gt; n3
+    n19 --&gt; n7
+    n19 --&gt; n9
+    n19 --&gt; n11
+    n19 --&gt; n14
+    n19 --&gt; n15
+    n19 --&gt; n24
+    n20 --&gt; n4
+    n20 --&gt; n5
+    n20 --&gt; n9
+    n20 --&gt; n10
+    n20 --&gt; n11
+    n20 --&gt; n15
+    n20 --&gt; n24
+    n21 --&gt; n15
+    n21 --&gt; n20
+    n21 --&gt; n22
+    n21 --&gt; n23
+    n22 --&gt; n24
+    n23 --&gt; n4
+    n23 --&gt; n11
+    n23 --&gt; n13
+    n23 --&gt; n15
+    n23 --&gt; n24
+    n25 --&gt; n2
+    n25 --&gt; n24
+    n25 --&gt; n31
+    n26 --&gt; n14
+    n26 --&gt; n19
+    n26 --&gt; n31
+    n27 --&gt; n3
+    n27 --&gt; n24
+    n28 --&gt; n4
+    n28 --&gt; n31
+    n29 --&gt; n5
+    n29 --&gt; n20
+    n29 --&gt; n24
+    n29 --&gt; n31
+    n30 --&gt; n7
+    n31 --&gt; n11
+    n32 --&gt; n9
+    n32 --&gt; n24
+    n32 --&gt; n31
+    n33 --&gt; n10
+    n33 --&gt; n24
+    n34 --&gt; n11
+    n35 --&gt; n22
+    n35 --&gt; n31
+    n36 --&gt; n13
+    n37 --&gt; n14
+    n37 --&gt; n31
+    n38 --&gt; n15
+    n38 --&gt; n31</pre>
+  </details>
+</main>
+<footer>Generated by <a href="https://github.com/builditwithgk/repo-cartographer">repo-cartographer</a>. This is a draft — refine it with your model.</footer>
+<script>
+  const SRC = "flowchart TD\n    %% repo-cartographer — detail-level architecture (DRAFT, refine me)\n    subgraph g0[\"src\"]\n        n0[\"cli.ts\"]\n        n1[\"index.ts\"]\n        n17[\"server.ts\"]\n        n24[\"types.ts\"]\n    end\n    subgraph g1[\"src/lib\"]\n        n2[\"baseline.ts\"]\n        n3[\"cycles.ts\"]\n        n4[\"detect.ts\"]\n        n5[\"dot.ts\"]\n        n6[\"fsutil.ts\"]\n        n7[\"glob.ts\"]\n        n8[\"ignore.ts\"]\n        n9[\"imports.ts\"]\n        n10[\"mermaid.ts\"]\n        n11[\"paths.ts\"]\n        n12[\"result.ts\"]\n        n13[\"roles.ts\"]\n        n14[\"rules.ts\"]\n        n15[\"walk.ts\"]\n    end\n    subgraph g2[\"src/resources\"]\n        n16[\"author.ts\"]\n    end\n    subgraph g3[\"src/tools\"]\n        n18[\"buildImportGraph.ts\"]\n        n19[\"checkRepo.ts\"]\n        n20[\"generateDiagram.ts\"]\n        n21[\"mapRepo.ts\"]\n        n22[\"renderDiagram.ts\"]\n        n23[\"scanRepo.ts\"]\n    end\n    subgraph g4[\"test\"]\n        n25[\"baseline.test.ts\"]\n        n26[\"check.test.ts\"]\n        n27[\"cycles.test.ts\"]\n        n28[\"detect.test.ts\"]\n        n29[\"dot.test.ts\"]\n        n30[\"glob.test.ts\"]\n        n31[\"fixture.ts\"]\n        n32[\"imports.test.ts\"]\n        n33[\"mermaid.test.ts\"]\n        n34[\"paths.test.ts\"]\n        n35[\"renderDiagram.test.ts\"]\n        n36[\"roles.test.ts\"]\n        n37[\"rules.test.ts\"]\n        n38[\"walk.test.ts\"]\n    end\n    n0 --> n2\n    n0 --> n14\n    n0 --> n19\n    n0 --> n21\n    n0 --> n24\n    n1 --> n0\n    n1 --> n17\n    n2 --> n24\n    n3 --> n24\n    n4 --> n6\n    n4 --> n8\n    n4 --> n11\n    n4 --> n24\n    n5 --> n9\n    n5 --> n11\n    n5 --> n13\n    n5 --> n24\n    n9 --> n6\n    n9 --> n8\n    n9 --> n11\n    n9 --> n24\n    n10 --> n9\n    n10 --> n11\n    n10 --> n13\n    n10 --> n24\n    n14 --> n24\n    n15 --> n6\n    n15 --> n8\n    n15 --> n11\n    n17 --> n12\n    n17 --> n16\n    n17 --> n18\n    n17 --> n20\n    n17 --> n21\n    n17 --> n22\n    n17 --> n23\n    n18 --> n8\n    n18 --> n9\n    n18 --> n11\n    n18 --> n15\n    n18 --> n24\n    n19 --> n3\n    n19 --> n7\n    n19 --> n9\n    n19 --> n11\n    n19 --> n14\n    n19 --> n15\n    n19 --> n24\n    n20 --> n4\n    n20 --> n5\n    n20 --> n9\n    n20 --> n10\n    n20 --> n11\n    n20 --> n15\n    n20 --> n24\n    n21 --> n15\n    n21 --> n20\n    n21 --> n22\n    n21 --> n23\n    n22 --> n24\n    n23 --> n4\n    n23 --> n11\n    n23 --> n13\n    n23 --> n15\n    n23 --> n24\n    n25 --> n2\n    n25 --> n24\n    n25 --> n31\n    n26 --> n14\n    n26 --> n19\n    n26 --> n31\n    n27 --> n3\n    n27 --> n24\n    n28 --> n4\n    n28 --> n31\n    n29 --> n5\n    n29 --> n20\n    n29 --> n24\n    n29 --> n31\n    n30 --> n7\n    n31 --> n11\n    n32 --> n9\n    n32 --> n24\n    n32 --> n31\n    n33 --> n10\n    n33 --> n24\n    n34 --> n11\n    n35 --> n22\n    n35 --> n31\n    n36 --> n13\n    n37 --> n14\n    n37 --> n31\n    n38 --> n15\n    n38 --> n31";
+  document.getElementById("copy").addEventListener("click", async () => {
+    try { await navigator.clipboard.writeText(SRC); } catch (e) {}
+  });
+  document.getElementById("download").addEventListener("click", () => {
+    const blob = new Blob([SRC], { type: "text/plain" });
+    const a = document.createElement("a");
+    a.href = URL.createObjectURL(blob);
+    a.download = "repo-cartographer-detail" + ".mermaid";
+    a.click();
+    URL.revokeObjectURL(a.href);
+  });
+</script>
+<script type="module">
+  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
+  const dark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
+  mermaid.initialize({ startOnLoad: true, theme: dark ? "dark" : "default", securityLevel: "strict" });
+</script>
+</body>
+</html>
diff --git a/examples/repo-cartographer-detail.mermaid b/examples/repo-cartographer-detail.mermaid
new file mode 100644
index 0000000..5172bf2
--- /dev/null
+++ b/examples/repo-cartographer-detail.mermaid
@@ -0,0 +1,145 @@
+flowchart TD
+    %% repo-cartographer — detail-level architecture (DRAFT, refine me)
+    subgraph g0["src"]
+        n0["cli.ts"]
+        n1["index.ts"]
+        n17["server.ts"]
+        n24["types.ts"]
+    end
+    subgraph g1["src/lib"]
+        n2["baseline.ts"]
+        n3["cycles.ts"]
+        n4["detect.ts"]
+        n5["dot.ts"]
+        n6["fsutil.ts"]
+        n7["glob.ts"]
+        n8["ignore.ts"]
+        n9["imports.ts"]
+        n10["mermaid.ts"]
+        n11["paths.ts"]
+        n12["result.ts"]
+        n13["roles.ts"]
+        n14["rules.ts"]
+        n15["walk.ts"]
+    end
+    subgraph g2["src/resources"]
+        n16["author.ts"]
+    end
+    subgraph g3["src/tools"]
+        n18["buildImportGraph.ts"]
+        n19["checkRepo.ts"]
+        n20["generateDiagram.ts"]
+        n21["mapRepo.ts"]
+        n22["renderDiagram.ts"]
+        n23["scanRepo.ts"]
+    end
+    subgraph g4["test"]
+        n25["baseline.test.ts"]
+        n26["check.test.ts"]
+        n27["cycles.test.ts"]
+        n28["detect.test.ts"]
+        n29["dot.test.ts"]
+        n30["glob.test.ts"]
+        n31["fixture.ts"]
+        n32["imports.test.ts"]
+        n33["mermaid.test.ts"]
+        n34["paths.test.ts"]
+        n35["renderDiagram.test.ts"]
+        n36["roles.test.ts"]
+        n37["rules.test.ts"]
+        n38["walk.test.ts"]
+    end
+    n0 --> n2
+    n0 --> n14
+    n0 --> n19
+    n0 --> n21
+    n0 --> n24
+    n1 --> n0
+    n1 --> n17
+    n2 --> n24
+    n3 --> n24
+    n4 --> n6
+    n4 --> n8
+    n4 --> n11
+    n4 --> n24
+    n5 --> n9
+    n5 --> n11
+    n5 --> n13
+    n5 --> n24
+    n9 --> n6
+    n9 --> n8
+    n9 --> n11
+    n9 --> n24
+    n10 --> n9
+    n10 --> n11
+    n10 --> n13
+    n10 --> n24
+    n14 --> n24
+    n15 --> n6
+    n15 --> n8
+    n15 --> n11
+    n17 --> n12
+    n17 --> n16
+    n17 --> n18
+    n17 --> n20
+    n17 --> n21
+    n17 --> n22
+    n17 --> n23
+    n18 --> n8
+    n18 --> n9
+    n18 --> n11
+    n18 --> n15
+    n18 --> n24
+    n19 --> n3
+    n19 --> n7
+    n19 --> n9
+    n19 --> n11
+    n19 --> n14
+    n19 --> n15
+    n19 --> n24
+    n20 --> n4
+    n20 --> n5
+    n20 --> n9
+    n20 --> n10
+    n20 --> n11
+    n20 --> n15
+    n20 --> n24
+    n21 --> n15
+    n21 --> n20
+    n21 --> n22
+    n21 --> n23
+    n22 --> n24
+    n23 --> n4
+    n23 --> n11
+    n23 --> n13
+    n23 --> n15
+    n23 --> n24
+    n25 --> n2
+    n25 --> n24
+    n25 --> n31
+    n26 --> n14
+    n26 --> n19
+    n26 --> n31
+    n27 --> n3
+    n27 --> n24
+    n28 --> n4
+    n28 --> n31
+    n29 --> n5
+    n29 --> n20
+    n29 --> n24
+    n29 --> n31
+    n30 --> n7
+    n31 --> n11
+    n32 --> n9
+    n32 --> n24
+    n32 --> n31
+    n33 --> n10
+    n33 --> n24
+    n34 --> n11
+    n35 --> n22
+    n35 --> n31
+    n36 --> n13
+    n37 --> n14
+    n37 --> n31
+    n38 --> n15
+    n38 --> n31
\ No newline at end of file
diff --git a/examples/repo-cartographer-dot.dot b/examples/repo-cartographer-dot.dot
new file mode 100644
index 0000000..8e3fcef
--- /dev/null
+++ b/examples/repo-cartographer-dot.dot
@@ -0,0 +1,20 @@
+digraph "repo-cartographer" {
+    // repo-cartographer — high-level architecture (DRAFT, refine me)
+    rankdir=TB;
+    node [shape=box, style="rounded,filled", fontname="Helvetica,Arial,sans-serif", fillcolor="#eef1f4", color="#8b949e", fontcolor="#1f2328"];
+    edge [color="#57606a"];
+    "src" [label="src\n4 files"];
+    "src/lib" [label="src/lib\nlibrary code\n14 files", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "src/resources" [label="src/resources\nresource handlers\n1 file", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "src/tools" [label="src/tools\ntool implementations\n6 files", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "test" [label="test\ntests\n14 files", fillcolor="#499894", fontcolor="#ffffff", color="#397975"];
+    "src" -> "src/lib";
+    "src" -> "src/resources";
+    "src" -> "src/tools";
+    "src/lib" -> "src";
+    "src/tools" -> "src";
+    "src/tools" -> "src/lib";
+    "test" -> "src";
+    "test" -> "src/lib";
+    "test" -> "src/tools";
+}
\ No newline at end of file
diff --git a/examples/repo-cartographer-dot.html b/examples/repo-cartographer-dot.html
new file mode 100644
index 0000000..a4abbb2
--- /dev/null
+++ b/examples/repo-cartographer-dot.html
@@ -0,0 +1,90 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>repo-cartographer-dot — architecture</title>
+<style>
+  :root { color-scheme: light dark; --bg:#ffffff; --fg:#1a1a1a; --muted:#666; --card:#f6f8fa; --border:#e2e5e9; --accent:#3b6fd4; }
+  @media (prefers-color-scheme: dark) {
+    :root { --bg:#0f1115; --fg:#e6e6e6; --muted:#9aa0a6; --card:#171a21; --border:#2a2f3a; --accent:#6f9dff; }
+  }
+  * { box-sizing: border-box; }
+  body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background:var(--bg); color:var(--fg); }
+  header { padding:20px 24px; border-bottom:1px solid var(--border); display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
+  header h1 { font-size:18px; margin:0; font-weight:650; }
+  header .tag { font-size:12px; color:var(--muted); }
+  main { padding:24px; }
+  .diagram { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:20px; overflow-x:auto; }
+  .diagram .mermaid, .diagram #graph { display:flex; justify-content:center; }
+  .diagram #graph svg { max-width:100%; height:auto; }
+  .bar { display:flex; gap:8px; margin:16px 0 0; }
+  button { font:inherit; font-size:13px; padding:7px 13px; border-radius:8px; border:1px solid var(--border); background:var(--card); color:var(--fg); cursor:pointer; }
+  button:hover { border-color:var(--accent); }
+  details { margin-top:16px; }
+  summary { cursor:pointer; color:var(--muted); font-size:13px; }
+  pre.src { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px; overflow:auto; font-size:12.5px; line-height:1.5; }
+  footer { padding:16px 24px; color:var(--muted); font-size:12px; border-top:1px solid var(--border); }
+  a { color:var(--accent); }
+</style>
+</head>
+<body>
+<header>
+  <h1>repo-cartographer-dot</h1>
+  <span class="tag">architecture diagram · draft · dot</span>
+</header>
+<main>
+  <div class="diagram">
+    <div id="graph"></div>
+  </div>
+  <div class="bar">
+    <button id="copy">Copy DOT source</button>
+    <button id="download">Download .dot</button>
+  </div>
+  <details>
+    <summary>View DOT source</summary>
+    <pre class="src">digraph "repo-cartographer" {
+    // repo-cartographer — high-level architecture (DRAFT, refine me)
+    rankdir=TB;
+    node [shape=box, style="rounded,filled", fontname="Helvetica,Arial,sans-serif", fillcolor="#eef1f4", color="#8b949e", fontcolor="#1f2328"];
+    edge [color="#57606a"];
+    "src" [label="src\n4 files"];
+    "src/lib" [label="src/lib\nlibrary code\n14 files", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "src/resources" [label="src/resources\nresource handlers\n1 file", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "src/tools" [label="src/tools\ntool implementations\n6 files", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];
+    "test" [label="test\ntests\n14 files", fillcolor="#499894", fontcolor="#ffffff", color="#397975"];
+    "src" -&gt; "src/lib";
+    "src" -&gt; "src/resources";
+    "src" -&gt; "src/tools";
+    "src/lib" -&gt; "src";
+    "src/tools" -&gt; "src";
+    "src/tools" -&gt; "src/lib";
+    "test" -&gt; "src";
+    "test" -&gt; "src/lib";
+    "test" -&gt; "src/tools";
+}</pre>
+  </details>
+</main>
+<footer>Generated by <a href="https://github.com/builditwithgk/repo-cartographer">repo-cartographer</a>. This is a draft — refine it with your model.</footer>
+<script>
+  const SRC = "digraph \"repo-cartographer\" {\n    // repo-cartographer — high-level architecture (DRAFT, refine me)\n    rankdir=TB;\n    node [shape=box, style=\"rounded,filled\", fontname=\"Helvetica,Arial,sans-serif\", fillcolor=\"#eef1f4\", color=\"#8b949e\", fontcolor=\"#1f2328\"];\n    edge [color=\"#57606a\"];\n    \"src\" [label=\"src\\n4 files\"];\n    \"src/lib\" [label=\"src/lib\\nlibrary code\\n14 files\", fillcolor=\"#79706e\", fontcolor=\"#ffffff\", color=\"#5d5654\"];\n    \"src/resources\" [label=\"src/resources\\nresource handlers\\n1 file\", fillcolor=\"#79706e\", fontcolor=\"#ffffff\", color=\"#5d5654\"];\n    \"src/tools\" [label=\"src/tools\\ntool implementations\\n6 files\", fillcolor=\"#79706e\", fontcolor=\"#ffffff\", color=\"#5d5654\"];\n    \"test\" [label=\"test\\ntests\\n14 files\", fillcolor=\"#499894\", fontcolor=\"#ffffff\", color=\"#397975\"];\n    \"src\" -> \"src/lib\";\n    \"src\" -> \"src/resources\";\n    \"src\" -> \"src/tools\";\n    \"src/lib\" -> \"src\";\n    \"src/tools\" -> \"src\";\n    \"src/tools\" -> \"src/lib\";\n    \"test\" -> \"src\";\n    \"test\" -> \"src/lib\";\n    \"test\" -> \"src/tools\";\n}";
+  document.getElementById("copy").addEventListener("click", async () => {
+    try { await navigator.clipboard.writeText(SRC); } catch (e) {}
+  });
+  document.getElementById("download").addEventListener("click", () => {
+    const blob = new Blob([SRC], { type: "text/plain" });
+    const a = document.createElement("a");
+    a.href = URL.createObjectURL(blob);
+    a.download = "repo-cartographer-dot" + ".dot";
+    a.click();
+    URL.revokeObjectURL(a.href);
+  });
+</script>
+<script src="https://cdn.jsdelivr.net/npm/@viz-js/viz@3/lib/viz-standalone.js"></script>
+<script>
+  Viz.instance()
+    .then((viz) => document.getElementById("graph").replaceChildren(viz.renderSVGElement(SRC)))
+    .catch((e) => { document.getElementById("graph").textContent = "Could not render diagram: " + e; });
+</script>
+</body>
+</html>
diff --git a/examples/repo-cartographer.html b/examples/repo-cartographer.html
new file mode 100644
index 0000000..b3ca57a
--- /dev/null
+++ b/examples/repo-cartographer.html
@@ -0,0 +1,108 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>repo-cartographer — architecture</title>
+<style>
+  :root { color-scheme: light dark; --bg:#ffffff; --fg:#1a1a1a; --muted:#666; --card:#f6f8fa; --border:#e2e5e9; --accent:#3b6fd4; }
+  @media (prefers-color-scheme: dark) {
+    :root { --bg:#0f1115; --fg:#e6e6e6; --muted:#9aa0a6; --card:#171a21; --border:#2a2f3a; --accent:#6f9dff; }
+  }
+  * { box-sizing: border-box; }
+  body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background:var(--bg); color:var(--fg); }
+  header { padding:20px 24px; border-bottom:1px solid var(--border); display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
+  header h1 { font-size:18px; margin:0; font-weight:650; }
+  header .tag { font-size:12px; color:var(--muted); }
+  main { padding:24px; }
+  .diagram { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:20px; overflow-x:auto; }
+  .diagram .mermaid, .diagram #graph { display:flex; justify-content:center; }
+  .diagram #graph svg { max-width:100%; height:auto; }
+  .bar { display:flex; gap:8px; margin:16px 0 0; }
+  button { font:inherit; font-size:13px; padding:7px 13px; border-radius:8px; border:1px solid var(--border); background:var(--card); color:var(--fg); cursor:pointer; }
+  button:hover { border-color:var(--accent); }
+  details { margin-top:16px; }
+  summary { cursor:pointer; color:var(--muted); font-size:13px; }
+  pre.src { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px; overflow:auto; font-size:12.5px; line-height:1.5; }
+  footer { padding:16px 24px; color:var(--muted); font-size:12px; border-top:1px solid var(--border); }
+  a { color:var(--accent); }
+</style>
+</head>
+<body>
+<header>
+  <h1>repo-cartographer</h1>
+  <span class="tag">architecture diagram · draft · mermaid</span>
+</header>
+<main>
+  <div class="diagram">
+    <pre class="mermaid">flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --&gt; n1
+    n0 --&gt; n2
+    n0 --&gt; n3
+    n1 --&gt; n0
+    n3 --&gt; n0
+    n3 --&gt; n1
+    n4 --&gt; n0
+    n4 --&gt; n1
+    n4 --&gt; n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975</pre>
+  </div>
+  <div class="bar">
+    <button id="copy">Copy Mermaid source</button>
+    <button id="download">Download .mermaid</button>
+  </div>
+  <details>
+    <summary>View Mermaid source</summary>
+    <pre class="src">flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --&gt; n1
+    n0 --&gt; n2
+    n0 --&gt; n3
+    n1 --&gt; n0
+    n3 --&gt; n0
+    n3 --&gt; n1
+    n4 --&gt; n0
+    n4 --&gt; n1
+    n4 --&gt; n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975</pre>
+  </details>
+</main>
+<footer>Generated by <a href="https://github.com/builditwithgk/repo-cartographer">repo-cartographer</a>. This is a draft — refine it with your model.</footer>
+<script>
+  const SRC = "flowchart TD\n    %% repo-cartographer — high-level architecture (DRAFT, refine me)\n    n0[\"src · 4 files\"]\n    n1[\"src/lib · library code · 14 files\"]\n    n2[\"src/resources · resource handlers · 1 file\"]\n    n3[\"src/tools · tool implementations · 6 files\"]\n    n4[\"test · tests · 14 files\"]\n    n0 --> n1\n    n0 --> n2\n    n0 --> n3\n    n1 --> n0\n    n3 --> n0\n    n3 --> n1\n    n4 --> n0\n    n4 --> n1\n    n4 --> n3\n    class n1,n2,n3 shared\n    class n4 test\n    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654\n    classDef test fill:#499894,color:#ffffff,stroke:#397975";
+  document.getElementById("copy").addEventListener("click", async () => {
+    try { await navigator.clipboard.writeText(SRC); } catch (e) {}
+  });
+  document.getElementById("download").addEventListener("click", () => {
+    const blob = new Blob([SRC], { type: "text/plain" });
+    const a = document.createElement("a");
+    a.href = URL.createObjectURL(blob);
+    a.download = "repo-cartographer" + ".mermaid";
+    a.click();
+    URL.revokeObjectURL(a.href);
+  });
+</script>
+<script type="module">
+  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
+  const dark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
+  mermaid.initialize({ startOnLoad: true, theme: dark ? "dark" : "default", securityLevel: "strict" });
+</script>
+</body>
+</html>
diff --git a/examples/repo-cartographer.mermaid b/examples/repo-cartographer.mermaid
new file mode 100644
index 0000000..8c63393
--- /dev/null
+++ b/examples/repo-cartographer.mermaid
@@ -0,0 +1,20 @@
+flowchart TD
+    %% repo-cartographer — high-level architecture (DRAFT, refine me)
+    n0["src · 4 files"]
+    n1["src/lib · library code · 14 files"]
+    n2["src/resources · resource handlers · 1 file"]
+    n3["src/tools · tool implementations · 6 files"]
+    n4["test · tests · 14 files"]
+    n0 --> n1
+    n0 --> n2
+    n0 --> n3
+    n1 --> n0
+    n3 --> n0
+    n3 --> n1
+    n4 --> n0
+    n4 --> n1
+    n4 --> n3
+    class n1,n2,n3 shared
+    class n4 test
+    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654
+    classDef test fill:#499894,color:#ffffff,stroke:#397975
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..445f80e
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,2110 @@
+{
+  "name": "repo-cartographer",
+  "version": "1.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "repo-cartographer",
+      "version": "1.0.0",
+      "license": "MIT",
+      "dependencies": {
+        "@modelcontextprotocol/sdk": "^1.29.0",
+        "yaml": "^2.9.0",
+        "zod": "^4.4.3"
+      },
+      "bin": {
+        "repo-cartographer": "dist/index.js"
+      },
+      "devDependencies": {
+        "@types/node": "^26.1.1",
+        "tsx": "^4.23.1",
+        "typescript": "^7.0.2"
+      }
+    },
+    "node_modules/@esbuild/aix-ppc64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
+      "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/android-arm": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
+      "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/android-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
+      "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/android-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
+      "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/darwin-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
+      "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/darwin-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
+      "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/freebsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
+      "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-arm": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
+      "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
+      "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-ia32": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
+      "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-loong64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
+      "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-mips64el": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
+      "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-ppc64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
+      "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-riscv64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
+      "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-s390x": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
+      "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/linux-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
+      "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/netbsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/netbsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
+      "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/openbsd-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
+      "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/openbsd-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
+      "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/openharmony-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
+      "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/sunos-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
+      "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/win32-arm64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
+      "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/win32-ia32": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
+      "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/win32-x64": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
+      "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@hono/node-server": {
+      "version": "2.0.11",
+      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.11.tgz",
+      "integrity": "sha512-bjD221KPLoJTWUwso1J6fGKiTXEUFedG/s0visavY4zakFPkeGURMRNly+FhBHs7T8Dz4qHaZIMX9ZoJHSJtKA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=20"
+      },
+      "peerDependencies": {
+        "hono": "^4"
+      }
+    },
+    "node_modules/@modelcontextprotocol/sdk": {
+      "version": "1.29.0",
+      "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
+      "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@hono/node-server": "^1.19.9",
+        "ajv": "^8.17.1",
+        "ajv-formats": "^3.0.1",
+        "content-type": "^1.0.5",
+        "cors": "^2.8.5",
+        "cross-spawn": "^7.0.5",
+        "eventsource": "^3.0.2",
+        "eventsource-parser": "^3.0.0",
+        "express": "^5.2.1",
+        "express-rate-limit": "^8.2.1",
+        "hono": "^4.11.4",
+        "jose": "^6.1.3",
+        "json-schema-typed": "^8.0.2",
+        "pkce-challenge": "^5.0.0",
+        "raw-body": "^3.0.0",
+        "zod": "^3.25 || ^4.0",
+        "zod-to-json-schema": "^3.25.1"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "peerDependencies": {
+        "@cfworker/json-schema": "^4.1.1",
+        "zod": "^3.25 || ^4.0"
+      },
+      "peerDependenciesMeta": {
+        "@cfworker/json-schema": {
+          "optional": true
+        },
+        "zod": {
+          "optional": false
+        }
+      }
+    },
+    "node_modules/@types/node": {
+      "version": "26.1.1",
+      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
+      "integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "undici-types": "~8.3.0"
+      }
+    },
+    "node_modules/@typescript/typescript-aix-ppc64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+      "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-darwin-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+      "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-darwin-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+      "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-freebsd-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+      "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-freebsd-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+      "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-arm": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+      "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+      "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-loong64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+      "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-mips64el": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+      "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-ppc64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+      "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-riscv64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+      "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-s390x": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+      "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-linux-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+      "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-netbsd-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+      "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-netbsd-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+      "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-openbsd-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+      "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-openbsd-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+      "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-sunos-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+      "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-win32-arm64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+      "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/@typescript/typescript-win32-x64": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+      "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "Apache-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/accepts": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+      "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-types": "^3.0.0",
+        "negotiator": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/ajv": {
+      "version": "8.20.0",
+      "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
+      "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+      "license": "MIT",
+      "dependencies": {
+        "fast-deep-equal": "^3.1.3",
+        "fast-uri": "^3.0.1",
+        "json-schema-traverse": "^1.0.0",
+        "require-from-string": "^2.0.2"
+      },
+      "funding": {
+        "type": "github",
+        "url": "https://github.com/sponsors/epoberezkin"
+      }
+    },
+    "node_modules/ajv-formats": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+      "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+      "license": "MIT",
+      "dependencies": {
+        "ajv": "^8.0.0"
+      },
+      "peerDependencies": {
+        "ajv": "^8.0.0"
+      },
+      "peerDependenciesMeta": {
+        "ajv": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/body-parser": {
+      "version": "2.3.0",
+      "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
+      "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "^3.1.2",
+        "content-type": "^2.0.0",
+        "debug": "^4.4.3",
+        "http-errors": "^2.0.1",
+        "iconv-lite": "^0.7.2",
+        "on-finished": "^2.4.1",
+        "qs": "^6.15.2",
+        "raw-body": "^3.0.2",
+        "type-is": "^2.1.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/body-parser/node_modules/content-type": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
+      "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/bytes": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+      "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/call-bind-apply-helpers": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+      "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/call-bound": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+      "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "get-intrinsic": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/content-disposition": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
+      "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/content-type": {
+      "version": "1.0.5",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+      "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie": {
+      "version": "0.7.2",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+      "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie-signature": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+      "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.6.0"
+      }
+    },
+    "node_modules/cors": {
+      "version": "2.8.6",
+      "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
+      "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
+      "license": "MIT",
+      "dependencies": {
+        "object-assign": "^4",
+        "vary": "^1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/cross-spawn": {
+      "version": "7.0.6",
+      "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+      "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+      "license": "MIT",
+      "dependencies": {
+        "path-key": "^3.1.0",
+        "shebang-command": "^2.0.0",
+        "which": "^2.0.1"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
+    "node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/depd": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+      "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/dunder-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+      "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "gopd": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/ee-first": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+      "license": "MIT"
+    },
+    "node_modules/encodeurl": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+      "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/es-define-property": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+      "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-errors": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+      "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-object-atoms": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+      "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/esbuild": {
+      "version": "0.28.1",
+      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
+      "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.28.1",
+        "@esbuild/android-arm": "0.28.1",
+        "@esbuild/android-arm64": "0.28.1",
+        "@esbuild/android-x64": "0.28.1",
+        "@esbuild/darwin-arm64": "0.28.1",
+        "@esbuild/darwin-x64": "0.28.1",
+        "@esbuild/freebsd-arm64": "0.28.1",
+        "@esbuild/freebsd-x64": "0.28.1",
+        "@esbuild/linux-arm": "0.28.1",
+        "@esbuild/linux-arm64": "0.28.1",
+        "@esbuild/linux-ia32": "0.28.1",
+        "@esbuild/linux-loong64": "0.28.1",
+        "@esbuild/linux-mips64el": "0.28.1",
+        "@esbuild/linux-ppc64": "0.28.1",
+        "@esbuild/linux-riscv64": "0.28.1",
+        "@esbuild/linux-s390x": "0.28.1",
+        "@esbuild/linux-x64": "0.28.1",
+        "@esbuild/netbsd-arm64": "0.28.1",
+        "@esbuild/netbsd-x64": "0.28.1",
+        "@esbuild/openbsd-arm64": "0.28.1",
+        "@esbuild/openbsd-x64": "0.28.1",
+        "@esbuild/openharmony-arm64": "0.28.1",
+        "@esbuild/sunos-x64": "0.28.1",
+        "@esbuild/win32-arm64": "0.28.1",
+        "@esbuild/win32-ia32": "0.28.1",
+        "@esbuild/win32-x64": "0.28.1"
+      }
+    },
+    "node_modules/escape-html": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+      "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+      "license": "MIT"
+    },
+    "node_modules/etag": {
+      "version": "1.8.1",
+      "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+      "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/eventsource": {
+      "version": "3.0.7",
+      "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+      "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+      "license": "MIT",
+      "dependencies": {
+        "eventsource-parser": "^3.0.1"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/eventsource-parser": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",
+      "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/express": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+      "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+      "license": "MIT",
+      "dependencies": {
+        "accepts": "^2.0.0",
+        "body-parser": "^2.2.1",
+        "content-disposition": "^1.0.0",
+        "content-type": "^1.0.5",
+        "cookie": "^0.7.1",
+        "cookie-signature": "^1.2.1",
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "finalhandler": "^2.1.0",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.0",
+        "merge-descriptors": "^2.0.0",
+        "mime-types": "^3.0.0",
+        "on-finished": "^2.4.1",
+        "once": "^1.4.0",
+        "parseurl": "^1.3.3",
+        "proxy-addr": "^2.0.7",
+        "qs": "^6.14.0",
+        "range-parser": "^1.2.1",
+        "router": "^2.2.0",
+        "send": "^1.1.0",
+        "serve-static": "^2.2.0",
+        "statuses": "^2.0.1",
+        "type-is": "^2.0.1",
+        "vary": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/express-rate-limit": {
+      "version": "8.6.0",
+      "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.0.tgz",
+      "integrity": "sha512-XKJXDsASUOo0LLtFwW5hCcQGH0N4WQc/Rn8/Pvoia+TJFOkkFPvrtW9lZOeeNcxQJspvOIERMwiRLsVFlhHEkA==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.3",
+        "ip-address": "^10.2.0"
+      },
+      "engines": {
+        "node": ">= 16"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/express-rate-limit"
+      },
+      "peerDependencies": {
+        "express": ">= 4.11"
+      }
+    },
+    "node_modules/fast-deep-equal": {
+      "version": "3.1.3",
+      "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+      "license": "MIT"
+    },
+    "node_modules/fast-uri": {
+      "version": "3.1.4",
+      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz",
+      "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/fastify"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fastify"
+        }
+      ],
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/finalhandler": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+      "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "on-finished": "^2.4.1",
+        "parseurl": "^1.3.3",
+        "statuses": "^2.0.1"
+      },
+      "engines": {
+        "node": ">= 18.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/forwarded": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+      "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/fresh": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+      "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.3",
+      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+      "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/function-bind": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+      "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-intrinsic": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+      "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "es-define-property": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "es-object-atoms": "^1.1.1",
+        "function-bind": "^1.1.2",
+        "get-proto": "^1.0.1",
+        "gopd": "^1.2.0",
+        "has-symbols": "^1.1.0",
+        "hasown": "^2.0.2",
+        "math-intrinsics": "^1.1.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+      "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+      "license": "MIT",
+      "dependencies": {
+        "dunder-proto": "^1.0.1",
+        "es-object-atoms": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/gopd": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+      "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-symbols": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+      "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/hasown": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+      "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+      "license": "MIT",
+      "dependencies": {
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/hono": {
+      "version": "4.12.31",
+      "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.31.tgz",
+      "integrity": "sha512-zJIHFrl6bq3RDd2YusFNCDlM8qUprxKswyi/OPzPyzKDdyBXDqWx8bZlZ7R+saTdSTatUmb3O7K4SspGPaEOQg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=16.9.0"
+      }
+    },
+    "node_modules/http-errors": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+      "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+      "license": "MIT",
+      "dependencies": {
+        "depd": "~2.0.0",
+        "inherits": "~2.0.4",
+        "setprototypeof": "~1.2.0",
+        "statuses": "~2.0.2",
+        "toidentifier": "~1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/iconv-lite": {
+      "version": "0.7.3",
+      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+      "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+      "license": "MIT",
+      "dependencies": {
+        "safer-buffer": ">= 2.1.2 < 3.0.0"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/inherits": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+      "license": "ISC"
+    },
+    "node_modules/ip-address": {
+      "version": "10.2.0",
+      "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
+      "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 12"
+      }
+    },
+    "node_modules/ipaddr.js": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+      "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/is-promise": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+      "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+      "license": "MIT"
+    },
+    "node_modules/isexe": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+      "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+      "license": "ISC"
+    },
+    "node_modules/jose": {
+      "version": "6.2.4",
+      "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.4.tgz",
+      "integrity": "sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/panva"
+      }
+    },
+    "node_modules/json-schema-traverse": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+      "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+      "license": "MIT"
+    },
+    "node_modules/json-schema-typed": {
+      "version": "8.0.2",
+      "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
+      "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
+      "license": "BSD-2-Clause"
+    },
+    "node_modules/math-intrinsics": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+      "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/media-typer": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+      "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/merge-descriptors": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+      "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/mime-db": {
+      "version": "1.54.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+      "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime-types": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+      "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "^1.54.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/ms": {
+      "version": "2.1.3",
+      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+      "license": "MIT"
+    },
+    "node_modules/negotiator": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+      "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/object-assign": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+      "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/object-inspect": {
+      "version": "1.13.4",
+      "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+      "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/on-finished": {
+      "version": "2.4.1",
+      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+      "license": "MIT",
+      "dependencies": {
+        "ee-first": "1.1.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/once": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+      "license": "ISC",
+      "dependencies": {
+        "wrappy": "1"
+      }
+    },
+    "node_modules/parseurl": {
+      "version": "1.3.3",
+      "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+      "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/path-key": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+      "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/path-to-regexp": {
+      "version": "8.4.2",
+      "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
+      "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
+      "license": "MIT",
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/pkce-challenge": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+      "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=16.20.0"
+      }
+    },
+    "node_modules/proxy-addr": {
+      "version": "2.0.7",
+      "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+      "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+      "license": "MIT",
+      "dependencies": {
+        "forwarded": "0.2.0",
+        "ipaddr.js": "1.9.1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/qs": {
+      "version": "6.15.3",
+      "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
+      "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "es-define-property": "^1.0.1",
+        "side-channel": "^1.1.1"
+      },
+      "engines": {
+        "node": ">=0.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/range-parser": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
+      "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/raw-body": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+      "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "~3.1.2",
+        "http-errors": "~2.0.1",
+        "iconv-lite": "~0.7.0",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/require-from-string": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+      "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/router": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+      "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "is-promise": "^4.0.0",
+        "parseurl": "^1.3.3",
+        "path-to-regexp": "^8.0.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      }
+    },
+    "node_modules/safer-buffer": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+      "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+      "license": "MIT"
+    },
+    "node_modules/send": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+      "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.3",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.1",
+        "mime-types": "^3.0.2",
+        "ms": "^2.1.3",
+        "on-finished": "^2.4.1",
+        "range-parser": "^1.2.1",
+        "statuses": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/serve-static": {
+      "version": "2.2.1",
+      "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+      "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+      "license": "MIT",
+      "dependencies": {
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "parseurl": "^1.3.3",
+        "send": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/setprototypeof": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+      "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+      "license": "ISC"
+    },
+    "node_modules/shebang-command": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+      "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+      "license": "MIT",
+      "dependencies": {
+        "shebang-regex": "^3.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/shebang-regex": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+      "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/side-channel": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
+      "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.4",
+        "side-channel-list": "^1.0.1",
+        "side-channel-map": "^1.0.1",
+        "side-channel-weakmap": "^1.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-list": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
+      "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.4"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-map": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+      "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-weakmap": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+      "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3",
+        "side-channel-map": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/statuses": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+      "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/toidentifier": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+      "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.6"
+      }
+    },
+    "node_modules/tsx": {
+      "version": "4.23.1",
+      "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz",
+      "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "esbuild": "~0.28.0"
+      },
+      "bin": {
+        "tsx": "dist/cli.mjs"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      }
+    },
+    "node_modules/type-is": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
+      "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
+      "license": "MIT",
+      "dependencies": {
+        "content-type": "^2.0.0",
+        "media-typer": "^1.1.0",
+        "mime-types": "^3.0.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/type-is/node_modules/content-type": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
+      "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/typescript": {
+      "version": "7.0.2",
+      "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+      "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "tsc": "bin/tsc"
+      },
+      "engines": {
+        "node": ">=16.20.0"
+      },
+      "optionalDependencies": {
+        "@typescript/typescript-aix-ppc64": "7.0.2",
+        "@typescript/typescript-darwin-arm64": "7.0.2",
+        "@typescript/typescript-darwin-x64": "7.0.2",
+        "@typescript/typescript-freebsd-arm64": "7.0.2",
+        "@typescript/typescript-freebsd-x64": "7.0.2",
+        "@typescript/typescript-linux-arm": "7.0.2",
+        "@typescript/typescript-linux-arm64": "7.0.2",
+        "@typescript/typescript-linux-loong64": "7.0.2",
+        "@typescript/typescript-linux-mips64el": "7.0.2",
+        "@typescript/typescript-linux-ppc64": "7.0.2",
+        "@typescript/typescript-linux-riscv64": "7.0.2",
+        "@typescript/typescript-linux-s390x": "7.0.2",
+        "@typescript/typescript-linux-x64": "7.0.2",
+        "@typescript/typescript-netbsd-arm64": "7.0.2",
+        "@typescript/typescript-netbsd-x64": "7.0.2",
+        "@typescript/typescript-openbsd-arm64": "7.0.2",
+        "@typescript/typescript-openbsd-x64": "7.0.2",
+        "@typescript/typescript-sunos-x64": "7.0.2",
+        "@typescript/typescript-win32-arm64": "7.0.2",
+        "@typescript/typescript-win32-x64": "7.0.2"
+      }
+    },
+    "node_modules/undici-types": {
+      "version": "8.3.0",
+      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
+      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/unpipe": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+      "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/vary": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+      "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/which": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+      "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+      "license": "ISC",
+      "dependencies": {
+        "isexe": "^2.0.0"
+      },
+      "bin": {
+        "node-which": "bin/node-which"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
+    "node_modules/wrappy": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+      "license": "ISC"
+    },
+    "node_modules/yaml": {
+      "version": "2.9.0",
+      "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
+      "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
+      "license": "ISC",
+      "bin": {
+        "yaml": "bin.mjs"
+      },
+      "engines": {
+        "node": ">= 14.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/eemeli"
+      }
+    },
+    "node_modules/zod": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
+      "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/colinhacks"
+      }
+    },
+    "node_modules/zod-to-json-schema": {
+      "version": "3.25.2",
+      "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
+      "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
+      "license": "ISC",
+      "peerDependencies": {
+        "zod": "^3.25.28 || ^4"
+      }
+    }
+  }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..81633da
--- /dev/null
+++ b/package.json
@@ -0,0 +1,55 @@
+{
+  "name": "repo-cartographer",
+  "version": "1.0.0",
+  "description": "Understand any codebase in 60 seconds — an MCP server that turns any repo into an architecture diagram.",
+  "type": "module",
+  "main": "dist/index.js",
+  "bin": {
+    "repo-cartographer": "dist/index.js"
+  },
+  "files": [
+    "dist"
+  ],
+  "scripts": {
+    "build": "tsc",
+    "dev": "tsx src/index.ts",
+    "start": "node dist/index.js",
+    "test": "node --import tsx --test \"test/**/*.test.ts\"",
+    "typecheck": "tsc -p tsconfig.test.json"
+  },
+  "keywords": [
+    "mcp",
+    "model-context-protocol",
+    "architecture",
+    "diagram",
+    "mermaid",
+    "codebase"
+  ],
+  "author": {
+    "name": "Gopi K devm (builditwithgk)",
+    "email": "builditwithgk@gmail.com",
+    "url": "https://github.com/builditwithgk"
+  },
+  "homepage": "https://github.com/builditwithgk/repo-cartographer#readme",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/builditwithgk/repo-cartographer.git"
+  },
+  "bugs": {
+    "url": "https://github.com/builditwithgk/repo-cartographer/issues"
+  },
+  "license": "MIT",
+  "dependencies": {
+    "@modelcontextprotocol/sdk": "^1.29.0",
+    "yaml": "^2.9.0",
+    "zod": "^4.4.3"
+  },
+  "overrides": {
+    "@hono/node-server": "^2.0.5"
+  },
+  "devDependencies": {
+    "@types/node": "^26.1.1",
+    "tsx": "^4.23.1",
+    "typescript": "^7.0.2"
+  }
+}
diff --git a/src/cli.ts b/src/cli.ts
new file mode 100644
index 0000000..d26c5f6
--- /dev/null
+++ b/src/cli.ts
@@ -0,0 +1,187 @@
+import { existsSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { runMapRepo } from "./tools/mapRepo.js";
+import { runCheck } from "./tools/checkRepo.js";
+import type { DiagramFormat, DiagramLevel, Violation } from "./types.js";
+import { DEFAULT_RULES, findConfig, loadRules } from "./lib/rules.js";
+import { BASELINE_NAME, findBaseline, loadBaseline, partitionByBaseline, writeBaseline } from "./lib/baseline.js";
+
+interface ParsedArgs {
+  positional: string[];
+  out?: string;
+  level?: string;
+  format?: string;
+  config?: string;
+  baseline?: string;
+  updateBaseline?: boolean;
+}
+
+function parseArgs(argv: string[]): ParsedArgs {
+  const parsed: ParsedArgs = { positional: [] };
+  for (let i = 0; i < argv.length; i++) {
+    const a = argv[i];
+    if (a === "-o" || a === "--out") parsed.out = argv[++i];
+    else if (a === "--level") parsed.level = argv[++i];
+    else if (a === "--format") parsed.format = argv[++i];
+    else if (a === "-c" || a === "--config") parsed.config = argv[++i];
+    else if (a === "--baseline") parsed.baseline = argv[++i];
+    else if (a === "--update-baseline") parsed.updateBaseline = true;
+    else if (a.startsWith("-")) throw new Error(`Unknown option: ${a}`);
+    else parsed.positional.push(a);
+  }
+  return parsed;
+}
+
+function requirePath(args: ParsedArgs): string {
+  const p = args.positional[0];
+  if (!p) throw new Error("Missing <path>. Usage shown with: repo-cartographer help");
+  return p;
+}
+
+function asLevel(value: string | undefined, fallback: DiagramLevel): DiagramLevel {
+  if (value === undefined) return fallback;
+  if (value !== "high" && value !== "detail") throw new Error(`--level must be 'high' or 'detail', got '${value}'`);
+  return value;
+}
+
+function asFormat(value: string | undefined, fallback: DiagramFormat): DiagramFormat {
+  if (value === undefined) return fallback;
+  if (value !== "mermaid" && value !== "dot") {
+    throw new Error(`--format must be 'mermaid' or 'dot', got '${value}'`);
+  }
+  return value;
+}
+
+const HELP = `repo-cartographer — architecture diagrams & governance
+
+Usage:
+  repo-cartographer                         Run as an MCP server (stdio; how AI clients launch it)
+  repo-cartographer map <path> [options]    Write a downloadable architecture diagram
+  repo-cartographer check <path> [options]  Enforce architecture rules (exits 1 on error-level violations)
+  repo-cartographer help                    Show this help
+
+map options:
+  -o, --out <path>     Output base path (default: <repo>/architecture)
+      --level <lvl>    'high' (default) or 'detail'
+      --format <fmt>   'mermaid' (default; renders on GitHub) or 'dot' (Graphviz)
+  Defaults for these come from the 'diagram:' section of .cartographer.yml when
+  the repo has one; explicit flags always win.
+
+check options:
+  -c, --config <file>    Rules file (default: .cartographer.yml/.yaml/.json in <path>)
+      --baseline <file>  Accepted pre-existing violations (default: .cartographer-baseline.json
+                         in <path>); only NEW violations then fail the build
+      --update-baseline  Record the current violations as the baseline and exit 0
+
+Docs: https://github.com/builditwithgk/repo-cartographer
+`;
+
+function cliMap(args: ParsedArgs): void {
+  const path = requirePath(args);
+
+  // Flags win; otherwise the repo's .cartographer.yml `diagram:` section, if
+  // any, supplies the defaults (its outPath is repo-relative by convention).
+  const configPath = findConfig(path);
+  const defaults = configPath ? loadRules(configPath).diagram : DEFAULT_RULES.diagram;
+  const out = args.out ?? (configPath ? join(path, defaults.outPath) : undefined);
+
+  const result = runMapRepo(path, asLevel(args.level, defaults.level), out, asFormat(args.format, defaults.format));
+  const s = result.summary;
+  process.stdout.write(
+    `Mapped ${result.htmlPath}\n` +
+      `  languages: ${s.languages.join(", ") || "—"}\n` +
+      `  frameworks: ${s.frameworks.join(", ") || "—"}\n` +
+      `  ${s.codeFiles} code files · ${s.modules} modules · ${s.edgesShown} edges shown\n` +
+      `\nOpen the .html file in a browser to view the diagram.\n`,
+  );
+}
+
+function formatViolation(v: Violation): string {
+  const badge = v.level === "error" ? "❌ ERROR" : "⚠️  WARN ";
+  const head =
+    v.kind === "forbidden" ? `${badge} forbidden  ${v.from} → ${v.to}` : `${badge} cycle      ${v.reason}`;
+  return v.kind === "forbidden" ? `${head}\n           ${v.reason}` : head;
+}
+
+function cliCheck(args: ParsedArgs): void {
+  const path = requirePath(args);
+
+  const configPath = args.config ?? findConfig(path);
+  if (!configPath) {
+    process.stdout.write(
+      `No .cartographer.yml found in ${path} — nothing to enforce.\n` +
+        `Add rules (see docs/github-action.md) to gate PRs on architecture.\n`,
+    );
+    // Still emit an empty report so CI steps downstream don't choke.
+    writeViolations([]);
+    return;
+  }
+
+  const result = runCheck(path, loadRules(configPath));
+
+  // --update-baseline: accept the current violations and exit 0.
+  if (args.updateBaseline) {
+    const target = args.baseline ?? join(path, BASELINE_NAME);
+    writeBaseline(target, result.violations);
+    process.stdout.write(`Wrote baseline with ${result.violations.length} accepted violation(s) → ${target}\n`);
+    return;
+  }
+
+  // Apply a baseline if one exists: only NEW violations count. A path that
+  // doesn't exist yet (common on the first CI run) is treated as "no baseline".
+  const baselinePath = args.baseline ?? findBaseline(path);
+  const baselineSet = baselinePath && existsSync(baselinePath) ? loadBaseline(baselinePath) : null;
+  const { fresh, baselined } = baselineSet
+    ? partitionByBaseline(result.violations, baselineSet)
+    : { fresh: result.violations, baselined: [] as Violation[] };
+
+  const freshErrors = fresh.filter((v) => v.level === "error").length;
+  const freshWarns = fresh.length - freshErrors;
+
+  process.stdout.write(
+    `Architecture check — ${result.path}\n` +
+      `  ${result.stats.codeFiles} code files · ${result.stats.edges} edges · ${result.stats.modules} modules\n` +
+      `  rules: ${configPath}\n` +
+      (baselineSet ? `  baseline: ${baselinePath} (${baselined.length} pre-existing ignored)\n` : "") +
+      "\n",
+  );
+
+  if (fresh.length === 0) {
+    process.stdout.write("✅ No new violations.\n");
+  } else {
+    for (const v of fresh) process.stdout.write(`${formatViolation(v)}\n`);
+    process.stdout.write(`\n${freshErrors} new error(s), ${freshWarns} new warning(s)\n`);
+  }
+
+  // violations.json holds the actionable (new) violations for the PR comment.
+  writeViolations(fresh);
+
+  if (freshErrors > 0) process.exitCode = 1;
+}
+
+function writeViolations(violations: Violation[]): void {
+  try {
+    writeFileSync(join(process.cwd(), "violations.json"), JSON.stringify(violations, null, 2), "utf8");
+  } catch {
+    /* non-fatal: the report was already printed to stdout */
+  }
+}
+
+/** Entry for the `map` / `check` / `help` subcommands. */
+export async function runCli(argv: string[]): Promise<void> {
+  const [cmd, ...rest] = argv;
+  try {
+    if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
+      process.stdout.write(HELP);
+      return;
+    }
+    const args = parseArgs(rest);
+    if (cmd === "map") return cliMap(args);
+    if (cmd === "check") return cliCheck(args);
+    process.stderr.write(`Unknown command: ${cmd}\n\n${HELP}`);
+    process.exitCode = 2;
+  } catch (e) {
+    process.stderr.write(`Error: ${e instanceof Error ? e.message : String(e)}\n`);
+    process.exitCode = 1;
+  }
+}
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 0000000..c3bbfdc
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+/**
+ * Entry point — dual mode:
+ *   • no subcommand  -> run the MCP stdio server (how AI clients launch it)
+ *   • map / check    -> run the CLI (how humans and CI use it)
+ *
+ * The CLI and server modules are imported lazily so neither pays for the other's
+ * dependencies at startup.
+ */
+const CLI_COMMANDS = new Set(["map", "check", "help", "--help", "-h"]);
+
+async function run(): Promise<void> {
+  const cmd = process.argv[2];
+  if (cmd && CLI_COMMANDS.has(cmd)) {
+    const { runCli } = await import("./cli.js");
+    await runCli(process.argv.slice(2));
+  } else {
+    const { startServer } = await import("./server.js");
+    await startServer();
+  }
+}
+
+run().catch((e) => {
+  process.stderr.write(`Fatal: ${e instanceof Error ? e.message : String(e)}\n`);
+  process.exit(1);
+});
diff --git a/src/lib/baseline.ts b/src/lib/baseline.ts
new file mode 100644
index 0000000..e41fbe4
--- /dev/null
+++ b/src/lib/baseline.ts
@@ -0,0 +1,56 @@
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { Violation } from "../types.js";
+
+/** Default baseline filename, sits next to the config in the repo. */
+export const BASELINE_NAME = ".cartographer-baseline.json";
+
+/**
+ * Stable identity for a violation, independent of severity. Two runs produce the
+ * same fingerprint for "the same" violation, so a baseline can recognize it.
+ *
+ * Fields are joined with a NUL byte because a NUL can never appear in a path, so
+ * no pair of distinct violations can collide on the same key. Fingerprints are
+ * in-memory Set keys only — never serialized — so this separator is free to change.
+ */
+export function fingerprintViolation(v: Violation): string {
+  return v.kind === "forbidden"
+    ? `forbidden\u0000${v.from}\u0000${v.to}`
+    : `cycle\u0000${v.reason}`;
+}
+
+/** Find an auto-detected baseline file in `dir`, or null. */
+export function findBaseline(dir: string): string | null {
+  const p = join(dir, BASELINE_NAME);
+  return existsSync(p) ? p : null;
+}
+
+/** Load a baseline file into a set of fingerprints. Throws on malformed JSON. */
+export function loadBaseline(file: string): Set<string> {
+  const raw = JSON.parse(readFileSync(file, "utf8"));
+  const entries: Violation[] = Array.isArray(raw) ? raw : Array.isArray(raw?.violations) ? raw.violations : [];
+  return new Set(entries.map(fingerprintViolation));
+}
+
+/** Write the current violations as the accepted baseline (human-readable). */
+export function writeBaseline(file: string, violations: Violation[]): void {
+  const payload = {
+    generatedBy: "repo-cartographer",
+    note: "Accepted pre-existing violations. Delete an entry to start failing on it again.",
+    violations,
+  };
+  writeFileSync(file, JSON.stringify(payload, null, 2), "utf8");
+}
+
+/** Split violations into those not in the baseline ("new") and those that are. */
+export function partitionByBaseline(
+  violations: Violation[],
+  baseline: Set<string>,
+): { fresh: Violation[]; baselined: Violation[] } {
+  const fresh: Violation[] = [];
+  const baselined: Violation[] = [];
+  for (const v of violations) {
+    (baseline.has(fingerprintViolation(v)) ? baselined : fresh).push(v);
+  }
+  return { fresh, baselined };
+}
diff --git a/src/lib/cycles.ts b/src/lib/cycles.ts
new file mode 100644
index 0000000..873af66
--- /dev/null
+++ b/src/lib/cycles.ts
@@ -0,0 +1,76 @@
+import type { ImportEdge } from "../types.js";
+
+/**
+ * Find dependency cycles via Tarjan's strongly-connected-components algorithm.
+ * Any SCC with more than one node is a cycle; self-loops are reported too.
+ * Returns each cycle as a sorted list of node ids (deterministic order).
+ */
+export function findCycles(nodes: string[], edges: ImportEdge[]): string[][] {
+  const adj = new Map<string, string[]>();
+  for (const n of nodes) adj.set(n, []);
+  const selfLoops: string[] = [];
+  for (const e of edges) {
+    if (e.from === e.to) {
+      selfLoops.push(e.from);
+      continue;
+    }
+    if (!adj.has(e.from)) adj.set(e.from, []);
+    if (!adj.has(e.to)) adj.set(e.to, []);
+    adj.get(e.from)!.push(e.to);
+  }
+
+  let index = 0;
+  const indices = new Map<string, number>();
+  const low = new Map<string, number>();
+  const onStack = new Set<string>();
+  const stack: string[] = [];
+  const cycles: string[][] = [];
+
+  // iterative Tarjan (avoids deep recursion on large graphs)
+  const allNodes = [...adj.keys()].sort();
+  for (const start of allNodes) {
+    if (indices.has(start)) continue;
+    const work: Array<{ node: string; i: number }> = [{ node: start, i: 0 }];
+    while (work.length) {
+      const frame = work[work.length - 1];
+      const { node } = frame;
+      if (frame.i === 0) {
+        indices.set(node, index);
+        low.set(node, index);
+        index++;
+        stack.push(node);
+        onStack.add(node);
+      }
+      const neighbors = adj.get(node) ?? [];
+      if (frame.i < neighbors.length) {
+        const next = neighbors[frame.i];
+        frame.i++;
+        if (!indices.has(next)) {
+          work.push({ node: next, i: 0 });
+        } else if (onStack.has(next)) {
+          low.set(node, Math.min(low.get(node)!, indices.get(next)!));
+        }
+      } else {
+        if (low.get(node) === indices.get(node)) {
+          const comp: string[] = [];
+          let w: string;
+          do {
+            w = stack.pop()!;
+            onStack.delete(w);
+            comp.push(w);
+          } while (w !== node);
+          if (comp.length > 1) cycles.push(comp.sort());
+        }
+        work.pop();
+        if (work.length) {
+          const parent = work[work.length - 1].node;
+          low.set(parent, Math.min(low.get(parent)!, low.get(node)!));
+        }
+      }
+    }
+  }
+
+  for (const n of [...new Set(selfLoops)].sort()) cycles.push([n]);
+  cycles.sort((a, b) => (a.join() < b.join() ? -1 : a.join() > b.join() ? 1 : 0));
+  return cycles;
+}
diff --git a/src/lib/detect.ts b/src/lib/detect.ts
new file mode 100644
index 0000000..1f99bba
--- /dev/null
+++ b/src/lib/detect.ts
@@ -0,0 +1,307 @@
+import { join } from "node:path";
+import type { ManifestSummary } from "../types.js";
+import { MAX_FILE_BYTES, MAX_GUARD_SCAN } from "./ignore.js";
+import { readTextCapped } from "./fsutil.js";
+import { basename, extname } from "./paths.js";
+
+/* ----------------------------- languages ----------------------------- */
+
+const LANG_BY_EXT: Record<string, string> = {
+  ".ts": "TypeScript",
+  ".tsx": "TypeScript",
+  ".mts": "TypeScript",
+  ".cts": "TypeScript",
+  ".js": "JavaScript",
+  ".jsx": "JavaScript",
+  ".mjs": "JavaScript",
+  ".cjs": "JavaScript",
+  ".py": "Python",
+  ".pyi": "Python",
+  ".go": "Go",
+  ".rs": "Rust",
+  ".java": "Java",
+  ".kt": "Kotlin",
+  ".rb": "Ruby",
+  ".php": "PHP",
+  ".cs": "C#",
+  ".c": "C",
+  ".h": "C",
+  ".cpp": "C++",
+  ".cc": "C++",
+  ".hpp": "C++",
+  ".swift": "Swift",
+  ".scala": "Scala",
+  ".sh": "Shell",
+  ".sql": "SQL",
+};
+
+/** Programming languages present, most prevalent first (ties broken by name). */
+export function detectLanguages(files: string[]): string[] {
+  const counts = new Map<string, number>();
+  for (const f of files) {
+    const lang = LANG_BY_EXT[extname(f)];
+    if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
+  }
+  return [...counts.entries()]
+    .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : 1))
+    .map(([lang]) => lang);
+}
+
+/* ----------------------------- frameworks ---------------------------- */
+
+/** Dependency name -> friendly framework/library label. */
+const FRAMEWORK_MAP: Record<string, string> = {
+  // JS / TS
+  react: "React",
+  "react-dom": "React",
+  next: "Next.js",
+  vue: "Vue",
+  svelte: "Svelte",
+  express: "Express",
+  fastify: "Fastify",
+  koa: "Koa",
+  vite: "Vite",
+  webpack: "Webpack",
+  rollup: "Rollup",
+  esbuild: "esbuild",
+  jest: "Jest",
+  vitest: "Vitest",
+  mocha: "Mocha",
+  electron: "Electron",
+  "@modelcontextprotocol/sdk": "MCP SDK",
+  zod: "Zod",
+  tailwindcss: "Tailwind CSS",
+  redux: "Redux",
+  "@reduxjs/toolkit": "Redux Toolkit",
+  "socket.io": "Socket.IO",
+  axios: "Axios",
+  prisma: "Prisma",
+  mongoose: "Mongoose",
+  sequelize: "Sequelize",
+  // Python
+  flask: "Flask",
+  django: "Django",
+  fastapi: "FastAPI",
+  streamlit: "Streamlit",
+  pandas: "pandas",
+  numpy: "NumPy",
+  "scikit-learn": "scikit-learn",
+  tensorflow: "TensorFlow",
+  torch: "PyTorch",
+  langchain: "LangChain",
+  langgraph: "LangGraph",
+  openai: "OpenAI SDK",
+  anthropic: "Anthropic SDK",
+  pydantic: "Pydantic",
+  sqlalchemy: "SQLAlchemy",
+  celery: "Celery",
+  requests: "Requests",
+  aiohttp: "aiohttp",
+  dhanhq: "DhanHQ",
+  kiteconnect: "Zerodha Kite Connect",
+  "python-telegram-bot": "python-telegram-bot",
+  backtrader: "Backtrader",
+  ccxt: "CCXT",
+  matplotlib: "Matplotlib",
+  plotly: "Plotly",
+  yfinance: "yfinance",
+  "ta-lib": "TA-Lib",
+  ta: "TA (technical-analysis)",
+};
+
+function mapFrameworks(deps: ReadonlySet<string>): string[] {
+  const out = new Set<string>();
+  for (const [dep, label] of Object.entries(FRAMEWORK_MAP)) {
+    if (deps.has(dep)) out.add(label);
+  }
+  for (const d of deps) {
+    if (d.startsWith("@nestjs/")) out.add("NestJS");
+    if (d.startsWith("@angular/")) out.add("Angular");
+  }
+  return [...out].sort();
+}
+
+/* ------------------------- manifest parsing -------------------------- */
+
+/** Normalize a dependency name for matching (lowercase; Python "_" -> "-"). */
+function normDep(name: string): string {
+  return name.toLowerCase().replace(/_/g, "-");
+}
+
+function parseRequirements(text: string, deps: Set<string>): void {
+  for (const raw of text.split(/\r?\n/)) {
+    const line = raw.split("#")[0].trim();
+    if (!line || line.startsWith("-")) continue; // skip options like -r, -e
+    const m = /^([A-Za-z0-9_.-]+)/.exec(line);
+    if (m) deps.add(normDep(m[1]));
+  }
+}
+
+function parseSetupPy(text: string, deps: Set<string>): void {
+  const block = /install_requires\s*=\s*\[([\s\S]*?)\]/.exec(text);
+  if (!block) return;
+  for (const m of block[1].matchAll(/['"]([A-Za-z0-9_.-]+)/g)) deps.add(normDep(m[1]));
+}
+
+/** Extract name + dependencies from pyproject.toml (regex, no TOML parser). */
+function parsePyproject(text: string, deps: Set<string>): string | null {
+  let name: string | null = null;
+  const nameM = /(?:^|\n)\s*name\s*=\s*["']([^"']+)["']/.exec(text);
+  if (nameM) name = nameM[1];
+
+  // PEP 621: dependencies = ["flask>=2", ...] (possibly multi-line)
+  for (const block of text.matchAll(/dependencies\s*=\s*\[([\s\S]*?)\]/g)) {
+    for (const m of block[1].matchAll(/['"]([A-Za-z0-9_.-]+)/g)) deps.add(normDep(m[1]));
+  }
+  // Poetry: [tool.poetry.dependencies] table of `pkg = "..."`
+  const poetry = /\[tool\.poetry\.dependencies\]([\s\S]*?)(?:\n\[|$)/.exec(text);
+  if (poetry) {
+    for (const m of poetry[1].matchAll(/(?:^|\n)\s*([A-Za-z0-9_.-]+)\s*=/g)) {
+      const dep = normDep(m[1]);
+      if (dep !== "python") deps.add(dep);
+    }
+  }
+  return name;
+}
+
+/**
+ * Build a manifest summary and framework list from the repo's manifests
+ * (package.json, pyproject.toml, requirements*.txt, setup.py).
+ */
+export function detectManifestAndFrameworks(
+  root: string,
+  files: string[],
+): { manifest: ManifestSummary; frameworks: string[]; notes: string[] } {
+  const deps = new Set<string>();
+  const notes: string[] = [];
+  let name: string | null = null;
+  let version: string | null = null;
+  let description: string | null = null;
+
+  if (files.includes("package.json")) {
+    const txt = readTextCapped(join(root, "package.json"), MAX_FILE_BYTES);
+    if (txt) {
+      try {
+        const j = JSON.parse(txt) as Record<string, unknown>;
+        name = typeof j.name === "string" ? j.name : null;
+        version = typeof j.version === "string" ? j.version : null;
+        description = typeof j.description === "string" ? j.description : null;
+        for (const key of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
+          const table = j[key];
+          if (table && typeof table === "object") {
+            for (const d of Object.keys(table)) deps.add(normDep(d));
+          }
+        }
+      } catch {
+        notes.push("package.json present but could not be parsed");
+      }
+    }
+  }
+
+  if (files.includes("pyproject.toml")) {
+    const txt = readTextCapped(join(root, "pyproject.toml"), MAX_FILE_BYTES);
+    if (txt) {
+      const pyName = parsePyproject(txt, deps);
+      if (!name && pyName) name = pyName;
+    }
+  }
+
+  for (const f of files) {
+    if (/(^|\/)requirements[\w.-]*\.txt$/i.test(f)) {
+      const txt = readTextCapped(join(root, f), MAX_FILE_BYTES);
+      if (txt) parseRequirements(txt, deps);
+    }
+  }
+
+  if (files.includes("setup.py")) {
+    const txt = readTextCapped(join(root, "setup.py"), MAX_FILE_BYTES);
+    if (txt) parseSetupPy(txt, deps);
+  }
+
+  const manifest: ManifestSummary = { name, version, description, dependencies: [...deps].sort() };
+  return { manifest, frameworks: mapFrameworks(deps), notes };
+}
+
+/* ---------------------------- entry points --------------------------- */
+
+const ENTRY_BASENAMES: ReadonlySet<string> = new Set([
+  "index.ts",
+  "index.js",
+  "index.mjs",
+  "main.ts",
+  "main.js",
+  "main.py",
+  "__main__.py",
+  "app.py",
+  "app.ts",
+  "app.js",
+  "server.ts",
+  "server.js",
+  "cli.ts",
+  "cli.js",
+  "start.py",
+  "run.py",
+  "manage.py",
+  "wsgi.py",
+  "asgi.py",
+]);
+
+const PY_MAIN_GUARD = /^\s*if\s+__name__\s*==\s*['"]__main__['"]\s*:/m;
+
+/**
+ * Heuristic entry points: package.json `main`/`bin` targets, well-known entry
+ * filenames, and Python files containing a `__main__` guard (capped scan).
+ */
+export function detectEntryPoints(
+  root: string,
+  files: string[],
+): { entryPoints: string[]; notes: string[] } {
+  const set = new Set<string>();
+  const notes: string[] = [];
+  const fileSet = new Set(files);
+
+  // package.json main / bin
+  if (files.includes("package.json")) {
+    const txt = readTextCapped(join(root, "package.json"), MAX_FILE_BYTES);
+    if (txt) {
+      try {
+        const j = JSON.parse(txt) as Record<string, unknown>;
+        const candidates: string[] = [];
+        if (typeof j.main === "string") candidates.push(j.main);
+        if (typeof j.module === "string") candidates.push(j.module);
+        if (typeof j.bin === "string") candidates.push(j.bin);
+        else if (j.bin && typeof j.bin === "object") {
+          for (const v of Object.values(j.bin as Record<string, unknown>)) {
+            if (typeof v === "string") candidates.push(v);
+          }
+        }
+        for (const c of candidates) {
+          const norm = c.replace(/^\.\//, "");
+          if (fileSet.has(norm)) set.add(norm);
+        }
+      } catch {
+        /* already noted in manifest parsing */
+      }
+    }
+  }
+
+  // well-known entry filenames
+  for (const f of files) {
+    if (ENTRY_BASENAMES.has(basename(f))) set.add(f);
+  }
+
+  // python __main__ guard (bounded)
+  let scanned = 0;
+  for (const f of files) {
+    if (extname(f) !== ".py") continue;
+    if (scanned >= MAX_GUARD_SCAN) {
+      notes.push(`Python __main__ scan capped at ${MAX_GUARD_SCAN} files`);
+      break;
+    }
+    scanned++;
+    const txt = readTextCapped(join(root, f), MAX_FILE_BYTES);
+    if (txt && PY_MAIN_GUARD.test(txt)) set.add(f);
+  }
+
+  return { entryPoints: [...set].sort(), notes };
+}
diff --git a/src/lib/dot.ts b/src/lib/dot.ts
new file mode 100644
index 0000000..d52fc66
--- /dev/null
+++ b/src/lib/dot.ts
@@ -0,0 +1,109 @@
+/**
+ * Graphviz DOT emitter — the interop output. Same deterministic facts as the
+ * Mermaid emitter, rendered as `digraph` so users can pipe the result into
+ * Graphviz (`dot -Tsvg`), Backstage, or any other tool that eats DOT. Node ids
+ * are the module keys / file paths themselves (quoted), so diffs stay readable.
+ */
+import type { RenderOptions } from "../types.js";
+import { basename, moduleKey } from "./paths.js";
+import { collapseToModules } from "./imports.js";
+import { CATEGORY_STYLE, roleCategory, roleGuess } from "./roles.js";
+
+/** Escape one line of text for use inside a DOT double-quoted string. */
+function escLine(s: string): string {
+  return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, " ");
+}
+
+/** A DOT double-quoted string (single line). */
+function q(s: string): string {
+  return `"${escLine(s)}"`;
+}
+
+/**
+ * A multi-line DOT label. Parts are escaped individually and then joined with
+ * a literal `\n` sequence — joining first would get the separator re-escaped
+ * and Graphviz would print "\n" as text instead of breaking the line.
+ */
+function qLabel(parts: string[]): string {
+  return `"${parts.map(escLine).join("\\n")}"`;
+}
+
+/** Shared preamble: comment header + defaults that match the Mermaid look. */
+function header(repoName: string, level: string): string[] {
+  return [
+    `digraph ${q(repoName)} {`,
+    `    // ${repoName.replace(/[\r\n]+/g, " ")} — ${level}-level architecture (DRAFT, refine me)`,
+    "    rankdir=TB;",
+    '    node [shape=box, style="rounded,filled", fontname="Helvetica,Arial,sans-serif", fillcolor="#eef1f4", color="#8b949e", fontcolor="#1f2328"];',
+    '    edge [color="#57606a"];',
+  ];
+}
+
+/** High-level: one node per module, collapsed module edges, colored by role. */
+function renderHigh(opts: RenderOptions): string {
+  const counts = new Map<string, number>();
+  for (const f of opts.codeFiles) counts.set(moduleKey(f), (counts.get(moduleKey(f)) ?? 0) + 1);
+
+  const { nodes, edges } = collapseToModules(opts.codeFiles, opts.edges);
+
+  const lines = header(opts.repoName, "high");
+  for (const node of nodes) {
+    const count = counts.get(node) ?? 0;
+    const role = roleGuess(node);
+    const label = [node];
+    if (!role.startsWith("(role")) label.push(role);
+    label.push(`${count} ${count === 1 ? "file" : "files"}`);
+
+    const cat = roleCategory(node);
+    const style = cat
+      ? `, fillcolor="${CATEGORY_STYLE[cat].fill}", fontcolor="#ffffff", color="${CATEGORY_STYLE[cat].stroke}"`
+      : "";
+    lines.push(`    ${q(node)} [label=${qLabel(label)}${style}];`);
+  }
+  const known = new Set(nodes);
+  for (const e of edges) {
+    if (known.has(e.from) && known.has(e.to)) lines.push(`    ${q(e.from)} -> ${q(e.to)};`);
+  }
+  lines.push("}");
+  return lines.join("\n");
+}
+
+/** Detail: file nodes inside per-module clusters (borders colored by role). */
+function renderDetail(opts: RenderOptions): string {
+  const byModule = new Map<string, string[]>();
+  for (const f of opts.codeFiles) {
+    const key = moduleKey(f);
+    let bucket = byModule.get(key);
+    if (!bucket) {
+      bucket = [];
+      byModule.set(key, bucket);
+    }
+    bucket.push(f);
+  }
+
+  const lines = header(opts.repoName, "detail");
+  const modules = [...byModule.keys()].sort();
+  modules.forEach((mod, i) => {
+    const cat = roleCategory(mod);
+    lines.push(`    subgraph cluster_${i} {`);
+    lines.push(`        label=${q(mod)};`);
+    lines.push(`        color="${cat ? CATEGORY_STYLE[cat].stroke : "#8b949e"}";`);
+    for (const f of byModule.get(mod)!.sort()) {
+      lines.push(`        ${q(f)} [label=${q(basename(f))}];`);
+    }
+    lines.push("    }");
+  });
+  // DOT auto-creates nodes named in edges, so guard against dangling endpoints
+  // (Mermaid's renderer gets the same protection from its id lookup).
+  const known = new Set(opts.codeFiles);
+  for (const e of opts.edges) {
+    if (known.has(e.from) && known.has(e.to)) lines.push(`    ${q(e.from)} -> ${q(e.to)};`);
+  }
+  lines.push("}");
+  return lines.join("\n");
+}
+
+/** Build a draft Graphviz DOT digraph from scan + import facts. */
+export function renderDot(opts: RenderOptions): string {
+  return opts.level === "detail" ? renderDetail(opts) : renderHigh(opts);
+}
diff --git a/src/lib/fsutil.ts b/src/lib/fsutil.ts
new file mode 100644
index 0000000..7610c29
--- /dev/null
+++ b/src/lib/fsutil.ts
@@ -0,0 +1,38 @@
+import { readFileSync, statSync } from "node:fs";
+import { resolve } from "node:path";
+
+/**
+ * Resolve `p` to an absolute path and assert it is an existing directory.
+ * Throws a clear Error (caught at the tool boundary) rather than a raw fs error.
+ */
+export function resolveDir(p: string): string {
+  const abs = resolve(p);
+  let st;
+  try {
+    st = statSync(abs);
+  } catch {
+    throw new Error(`Path does not exist: ${abs}`);
+  }
+  if (!st.isDirectory()) {
+    throw new Error(`Path is not a directory: ${abs}`);
+  }
+  return abs;
+}
+
+/**
+ * Read a text file, capped at `maxBytes`. Returns null for missing/unreadable
+ * files and for likely-binary files (a NUL byte in the first 4 KB).
+ */
+export function readTextCapped(abs: string, maxBytes: number): string | null {
+  try {
+    const st = statSync(abs);
+    if (!st.isFile()) return null;
+    const buf = readFileSync(abs);
+    const slice = buf.length > maxBytes ? buf.subarray(0, maxBytes) : buf;
+    const probe = slice.subarray(0, Math.min(4096, slice.length));
+    if (probe.includes(0)) return null; // binary
+    return slice.toString("utf8");
+  } catch {
+    return null;
+  }
+}
diff --git a/src/lib/glob.ts b/src/lib/glob.ts
new file mode 100644
index 0000000..120850d
--- /dev/null
+++ b/src/lib/glob.ts
@@ -0,0 +1,47 @@
+/**
+ * Minimal path-glob matcher for architecture rules. Supported wildcards:
+ *   - a double-star matches any run of characters, including "/" (e.g. `src/ui/**`)
+ *   - a double-star then slash matches any number of leading segments
+ *   - a single star matches any run of characters except "/"
+ *   - a question mark matches a single character except "/"
+ * Paths are repo-relative posix strings.
+ */
+export function globToRegExp(glob: string): RegExp {
+  let re = "";
+  let i = 0;
+  while (i < glob.length) {
+    const c = glob[i];
+    if (c === "*") {
+      if (glob[i + 1] === "*") {
+        if (glob[i + 2] === "/") {
+          re += "(?:.*/)?"; // **/ -> optional leading segments
+          i += 3;
+          continue;
+        }
+        re += ".*"; // ** -> anything, including "/"
+        i += 2;
+        continue;
+      }
+      re += "[^/]*"; // * -> anything except "/"
+      i += 1;
+      continue;
+    }
+    if (c === "?") {
+      re += "[^/]";
+      i += 1;
+      continue;
+    }
+    if ("\\^$.|+()[]{}".includes(c)) {
+      re += `\\${c}`; // escape regex metacharacters
+      i += 1;
+      continue;
+    }
+    re += c;
+    i += 1;
+  }
+  return new RegExp(`^${re}$`);
+}
+
+export function matchGlob(glob: string, path: string): boolean {
+  return globToRegExp(glob).test(path);
+}
diff --git a/src/lib/ignore.ts b/src/lib/ignore.ts
new file mode 100644
index 0000000..17d6a29
--- /dev/null
+++ b/src/lib/ignore.ts
@@ -0,0 +1,41 @@
+/**
+ * Directories to skip and hard caps that keep the server fast and bounded on
+ * large repos. Any cap that fires is reported in tool output — never silently.
+ */
+
+/**
+ * Non-hidden directories that are build output, dependencies, or caches and
+ * should never be walked. (Hidden directories — names starting with "." such as
+ * .git, .venv, .cache — are skipped separately in the walker.)
+ */
+export const EXCLUDED_DIRS: ReadonlySet<string> = new Set([
+  "node_modules",
+  "bower_components",
+  "jspm_packages",
+  "vendor",
+  "dist",
+  "build",
+  "out",
+  "coverage",
+  "venv",
+  "__pycache__",
+  "target", // rust / maven / gradle output
+]);
+
+/** Hard cap on the number of files collected during a walk. */
+export const MAX_FILES = 4000;
+
+/** Maximum bytes read from any single file (for import scanning / manifests). */
+export const MAX_FILE_BYTES = 512 * 1024;
+
+/** Maximum directory recursion depth. */
+export const MAX_DEPTH = 24;
+
+/**
+ * When a repo has more code files than this, `build_import_graph` collapses to
+ * module (directory) level so the graph stays legible.
+ */
+export const MODULE_COLLAPSE_THRESHOLD = 60;
+
+/** Cap on how many Python files are read when probing for a `__main__` guard. */
+export const MAX_GUARD_SCAN = 600;
diff --git a/src/lib/imports.ts b/src/lib/imports.ts
new file mode 100644
index 0000000..391e916
--- /dev/null
+++ b/src/lib/imports.ts
@@ -0,0 +1,212 @@
+import { join } from "node:path";
+import type { ImportEdge } from "../types.js";
+import { MAX_FILE_BYTES } from "./ignore.js";
+import { readTextCapped } from "./fsutil.js";
+import {
+  extname,
+  JS_EXTS,
+  joinPosix,
+  moduleKey,
+  posixDirname,
+  posixNormalize,
+  stripCodeExt,
+} from "./paths.js";
+
+export interface ExtractResult {
+  /** Sorted, de-duplicated intra-repo directed edges. */
+  edges: ImportEdge[];
+  /** Best-effort count of imports that pointed outside the repo. */
+  externalImports: number;
+  /** Number of code files actually read. */
+  filesScanned: number;
+}
+
+/* ------------------------------------------------------------------ *
+ * Specifier extraction (regex — good enough for a draft diagram).    *
+ * ------------------------------------------------------------------ */
+
+const JS_PATTERNS: RegExp[] = [
+  // import X from 'x'   |   import 'x'   |   import type {A} from 'x'
+  /\bimport\s+(?:[^;'"]*?\bfrom\s*)?['"]([^'"]+)['"]/g,
+  // export ... from 'x'
+  /\bexport\s+[^;'"]*?\bfrom\s*['"]([^'"]+)['"]/g,
+  // require('x')
+  /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
+  // dynamic import('x')
+  /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
+];
+
+function extractJsSpecifiers(text: string): string[] {
+  const out: string[] = [];
+  for (const re of JS_PATTERNS) {
+    re.lastIndex = 0;
+    let m: RegExpExecArray | null;
+    while ((m = re.exec(text)) !== null) out.push(m[1]);
+  }
+  return out;
+}
+
+interface PyImport {
+  dots: number;
+  module: string; // dotted module ("" for `from . import x`)
+  names: string[]; // imported names (used only when module === "")
+}
+
+const PY_FROM = /^[ \t]*from[ \t]+(\.*)([A-Za-z0-9_.]*)[ \t]+import[ \t]+(.+?)[ \t]*$/;
+const PY_IMPORT = /^[ \t]*import[ \t]+(.+?)[ \t]*$/;
+
+function parseNameList(raw: string): string[] {
+  // "a, b as c, (d, e)" -> ["a","b","d","e"]
+  return raw
+    .replace(/[()]/g, "")
+    .split(",")
+    .map((s) => s.trim().split(/\s+as\s+/)[0].trim())
+    .filter((s) => s.length > 0 && s !== "*");
+}
+
+function extractPyImports(text: string): PyImport[] {
+  const out: PyImport[] = [];
+  for (const rawLine of text.split(/\r?\n/)) {
+    const line = rawLine;
+    if (/^[ \t]*#/.test(line)) continue;
+    const from = PY_FROM.exec(line);
+    if (from) {
+      out.push({ dots: from[1].length, module: from[2], names: parseNameList(from[3]) });
+      continue;
+    }
+    const imp = PY_IMPORT.exec(line);
+    if (imp) {
+      for (const item of imp[1].split(",")) {
+        const dotted = item.trim().split(/\s+as\s+/)[0].trim();
+        if (dotted) out.push({ dots: 0, module: dotted, names: [] });
+      }
+    }
+  }
+  return out;
+}
+
+/* ------------------------------------------------------------------ *
+ * Resolution of specifiers to intra-repo files.                      *
+ * ------------------------------------------------------------------ */
+
+function resolveJs(fromFile: string, spec: string, fileSet: ReadonlySet<string>): string | null {
+  if (!spec.startsWith(".") && !spec.startsWith("/")) return null; // bare = external
+  const target = posixNormalize(joinPosix(posixDirname(fromFile), spec));
+  if (target === "" || target.startsWith("..")) return null; // escaped repo root
+  const base = stripCodeExt(target);
+  const candidates = [
+    target,
+    base,
+    ...JS_EXTS.map((e) => base + e),
+    ...JS_EXTS.map((e) => joinPosix(base, "index" + e)),
+  ];
+  for (const c of candidates) if (fileSet.has(c)) return c;
+  return null;
+}
+
+function pyCandidates(base: string): string[] {
+  return [base + ".py", base + ".pyi", joinPosix(base, "__init__.py")];
+}
+
+function resolvePyAbsolute(dotted: string, fileSet: ReadonlySet<string>): string | null {
+  const base = dotted.split(".").join("/");
+  for (const c of pyCandidates(base)) if (fileSet.has(c)) return c;
+  return null;
+}
+
+function resolvePyRelative(
+  fromFile: string,
+  dots: number,
+  dotted: string,
+  fileSet: ReadonlySet<string>,
+): string | null {
+  let dir = posixDirname(fromFile);
+  for (let i = 1; i < dots; i++) dir = posixDirname(dir);
+  const sub = dotted ? dotted.split(".").join("/") : "";
+  const base = sub ? joinPosix(dir, sub) : dir;
+  for (const c of pyCandidates(base)) if (fileSet.has(c)) return c;
+  return null;
+}
+
+/* ------------------------------------------------------------------ *
+ * Public API.                                                        *
+ * ------------------------------------------------------------------ */
+
+/**
+ * Read each code file (capped), extract import specifiers, and resolve them to
+ * intra-repo edges. External (npm / PyPI / stdlib) imports are counted, not
+ * turned into nodes.
+ */
+export function extractImports(root: string, codeFiles: string[]): ExtractResult {
+  const fileSet = new Set(codeFiles);
+  const edgeKeys = new Set<string>();
+  const edges: ImportEdge[] = [];
+  let externalImports = 0;
+  let filesScanned = 0;
+
+  const addEdge = (from: string, to: string | null) => {
+    if (to === null) {
+      externalImports++;
+      return;
+    }
+    if (to === from) return; // ignore self-imports
+    // Keys join fields with a NUL byte: it can never occur in a path, so two
+    // distinct (from, to) pairs can never collide on the same key.
+    const key = `${from}\u0000${to}`;
+    if (edgeKeys.has(key)) return;
+    edgeKeys.add(key);
+    edges.push({ from, to });
+  };
+
+  for (const file of codeFiles) {
+    const text = readTextCapped(join(root, file), MAX_FILE_BYTES);
+    if (text === null) continue;
+    filesScanned++;
+    const ext = extname(file);
+
+    if (ext === ".py" || ext === ".pyi") {
+      for (const imp of extractPyImports(text)) {
+        if (imp.dots > 0 && imp.module === "") {
+          // `from . import a, b` -> each name is a sibling submodule
+          for (const name of imp.names) {
+            addEdge(file, resolvePyRelative(file, imp.dots, name, fileSet));
+          }
+        } else if (imp.dots > 0) {
+          addEdge(file, resolvePyRelative(file, imp.dots, imp.module, fileSet));
+        } else {
+          addEdge(file, resolvePyAbsolute(imp.module, fileSet));
+        }
+      }
+    } else {
+      for (const spec of extractJsSpecifiers(text)) {
+        addEdge(file, resolveJs(file, spec, fileSet));
+      }
+    }
+  }
+
+  edges.sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : 0));
+  return { edges, externalImports, filesScanned };
+}
+
+/** Collapse file-level nodes/edges to module (directory) level. */
+export function collapseToModules(
+  codeFiles: string[],
+  edges: ImportEdge[],
+): { nodes: string[]; edges: ImportEdge[] } {
+  const nodeSet = new Set<string>();
+  for (const f of codeFiles) nodeSet.add(moduleKey(f));
+
+  const edgeKeys = new Set<string>();
+  const out: ImportEdge[] = [];
+  for (const e of edges) {
+    const from = moduleKey(e.from);
+    const to = moduleKey(e.to);
+    if (from === to) continue;
+    const key = `${from}\u0000${to}`;
+    if (edgeKeys.has(key)) continue;
+    edgeKeys.add(key);
+    out.push({ from, to });
+  }
+  out.sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : 0));
+  return { nodes: [...nodeSet].sort(), edges: out };
+}
diff --git a/src/lib/mermaid.ts b/src/lib/mermaid.ts
new file mode 100644
index 0000000..084f608
--- /dev/null
+++ b/src/lib/mermaid.ts
@@ -0,0 +1,124 @@
+import type { RenderOptions } from "../types.js";
+import { basename, moduleKey } from "./paths.js";
+import { collapseToModules } from "./imports.js";
+import { CATEGORY_STYLE, roleCategory, roleGuess, type RoleCategory } from "./roles.js";
+
+export type { RenderOptions };
+
+/** Sanitize text for use inside a Mermaid `["..."]` label. */
+function escapeLabel(s: string): string {
+  return s
+    .replace(/[\r\n]+/g, " ")
+    .replace(/["`]/g, "'")
+    .replace(/[[\]{}|<>]/g, "")
+    .trim();
+}
+
+/** Assigns stable ids (prefix + index) to a sorted list of keys. */
+class IdMap {
+  private map = new Map<string, string>();
+  constructor(private prefix: string) {}
+  add(keys: string[]): void {
+    for (const k of [...keys].sort()) {
+      if (!this.map.has(k)) this.map.set(k, `${this.prefix}${this.map.size}`);
+    }
+  }
+  get(key: string): string | undefined {
+    return this.map.get(key);
+  }
+}
+
+function header(repoName: string, level: string): string[] {
+  return [
+    "flowchart TD",
+    `    %% ${escapeLabel(repoName)} — ${level}-level architecture (DRAFT, refine me)`,
+  ];
+}
+
+/** High-level diagram: one node per module, collapsed module edges. */
+function renderHigh(opts: RenderOptions): string {
+  const counts = new Map<string, number>();
+  for (const f of opts.codeFiles) counts.set(moduleKey(f), (counts.get(moduleKey(f)) ?? 0) + 1);
+
+  const { nodes, edges } = collapseToModules(opts.codeFiles, opts.edges);
+  const ids = new IdMap("n");
+  ids.add(nodes);
+
+  const lines = header(opts.repoName, "high");
+  for (const node of nodes) {
+    const count = counts.get(node) ?? 0;
+    const role = roleGuess(node);
+    const parts = [node];
+    if (!role.startsWith("(role")) parts.push(role); // omit the "model to infer" placeholder
+    parts.push(`${count} ${count === 1 ? "file" : "files"}`);
+    lines.push(`    ${ids.get(node)}["${escapeLabel(parts.join(" · "))}"]`);
+  }
+  for (const e of edges) {
+    const a = ids.get(e.from);
+    const b = ids.get(e.to);
+    if (a && b) lines.push(`    ${a} --> ${b}`);
+  }
+
+  // Color modules by role family. Only the categories actually present get a
+  // classDef, so small repos stay small. (Detail level stays neutral — dozens
+  // of colored file boxes read as noise, not architecture.)
+  const byCategory = new Map<RoleCategory, string[]>();
+  for (const node of nodes) {
+    const cat = roleCategory(node);
+    if (!cat) continue;
+    const id = ids.get(node);
+    if (!id) continue;
+    const bucket = byCategory.get(cat);
+    if (bucket) bucket.push(id);
+    else byCategory.set(cat, [id]);
+  }
+  const usedCategories = [...byCategory.keys()].sort();
+  for (const cat of usedCategories) {
+    lines.push(`    class ${byCategory.get(cat)!.join(",")} ${cat}`);
+  }
+  for (const cat of usedCategories) {
+    const { fill, stroke } = CATEGORY_STYLE[cat];
+    lines.push(`    classDef ${cat} fill:${fill},color:#ffffff,stroke:${stroke}`);
+  }
+  return lines.join("\n");
+}
+
+/** Detail diagram: file nodes grouped into per-module subgraphs. */
+function renderDetail(opts: RenderOptions): string {
+  const byModule = new Map<string, string[]>();
+  for (const f of opts.codeFiles) {
+    const key = moduleKey(f);
+    let bucket = byModule.get(key);
+    if (!bucket) {
+      bucket = [];
+      byModule.set(key, bucket);
+    }
+    bucket.push(f);
+  }
+
+  const nodeIds = new IdMap("n");
+  nodeIds.add(opts.codeFiles);
+  const groupIds = new IdMap("g");
+  groupIds.add([...byModule.keys()]);
+
+  const lines = header(opts.repoName, "detail");
+  for (const mod of [...byModule.keys()].sort()) {
+    const files = byModule.get(mod)!.sort();
+    lines.push(`    subgraph ${groupIds.get(mod)}["${escapeLabel(mod)}"]`);
+    for (const f of files) {
+      lines.push(`        ${nodeIds.get(f)}["${escapeLabel(basename(f))}"]`);
+    }
+    lines.push("    end");
+  }
+  for (const e of opts.edges) {
+    const a = nodeIds.get(e.from);
+    const b = nodeIds.get(e.to);
+    if (a && b) lines.push(`    ${a} --> ${b}`);
+  }
+  return lines.join("\n");
+}
+
+/** Build a draft Mermaid flowchart from scan + import facts. */
+export function renderFlowchart(opts: RenderOptions): string {
+  return opts.level === "detail" ? renderDetail(opts) : renderHigh(opts);
+}
diff --git a/src/lib/paths.ts b/src/lib/paths.ts
new file mode 100644
index 0000000..d1042fa
--- /dev/null
+++ b/src/lib/paths.ts
@@ -0,0 +1,114 @@
+/**
+ * Repo-relative path helpers. All paths inside the server use posix separators
+ * ("/") regardless of OS, so output is stable across platforms.
+ */
+
+/** Source extensions we parse for imports (JS/TS + Python — v1 scope). */
+export const CODE_EXT: ReadonlySet<string> = new Set([
+  ".ts",
+  ".tsx",
+  ".mts",
+  ".cts",
+  ".js",
+  ".jsx",
+  ".mjs",
+  ".cjs",
+  ".py",
+  ".pyi",
+]);
+
+/** JS/TS extensions used when resolving extensionless / ".js" import specifiers. */
+export const JS_EXTS: readonly string[] = [
+  ".ts",
+  ".tsx",
+  ".mts",
+  ".cts",
+  ".js",
+  ".jsx",
+  ".mjs",
+  ".cjs",
+];
+
+/**
+ * Common "container" directories that hold the real modules. When a repo nests
+ * everything under one of these, we key modules one level deeper so the diagram
+ * stays informative (e.g. `src/tools` instead of a single `src` blob).
+ */
+const CONTAINERS: ReadonlySet<string> = new Set([
+  "src",
+  "lib",
+  "app",
+  "source",
+  "packages",
+  "internal",
+  "pkg",
+  "cmd",
+]);
+
+/**
+ * Is this a conventional source-container directory name? Used by moduleKey
+ * (key one level deeper) and by the zip-wrapper heuristic (a lone `src/` at
+ * the root is structure, not a wrapper to descend past).
+ */
+export function isContainerDir(name: string): boolean {
+  return CONTAINERS.has(name.toLowerCase());
+}
+
+export function extname(file: string): string {
+  const slash = file.lastIndexOf("/");
+  const dot = file.lastIndexOf(".");
+  if (dot <= slash) return "";
+  return file.slice(dot).toLowerCase();
+}
+
+export function basename(file: string): string {
+  const i = file.lastIndexOf("/");
+  return i < 0 ? file : file.slice(i + 1);
+}
+
+export function isCodeFile(file: string): boolean {
+  return CODE_EXT.has(extname(file));
+}
+
+export function posixDirname(p: string): string {
+  const i = p.lastIndexOf("/");
+  return i < 0 ? "" : p.slice(0, i);
+}
+
+export function joinPosix(a: string, b: string): string {
+  if (a === "") return b;
+  if (b === "") return a;
+  return `${a}/${b}`;
+}
+
+/** Normalize "." and ".." segments in a posix path. */
+export function posixNormalize(p: string): string {
+  const out: string[] = [];
+  for (const part of p.split("/")) {
+    if (part === "" || part === ".") continue;
+    if (part === "..") {
+      if (out.length && out[out.length - 1] !== "..") out.pop();
+      else out.push("..");
+    } else {
+      out.push(part);
+    }
+  }
+  return out.join("/");
+}
+
+/** Strip a trailing JS/TS extension, if present (used for ".js" -> ".ts" resolution). */
+export function stripCodeExt(p: string): string {
+  const ext = extname(p);
+  return JS_EXTS.includes(ext) ? p.slice(0, p.length - ext.length) : p;
+}
+
+/**
+ * Group key for a file: its top-level directory, or "container/second" when the
+ * top level is a known container dir. Root files map to "(root)".
+ */
+export function moduleKey(file: string): string {
+  const parts = file.split("/");
+  if (parts.length === 1) return "(root)";
+  if (CONTAINERS.has(parts[0]) && parts.length >= 3) return `${parts[0]}/${parts[1]}`;
+  return parts[0];
+}
diff --git a/src/lib/result.ts b/src/lib/result.ts
new file mode 100644
index 0000000..333e540
--- /dev/null
+++ b/src/lib/result.ts
@@ -0,0 +1,16 @@
+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
+
+/** Wrap a JS value as a pretty-printed JSON tool result. */
+export function jsonResult(data: unknown): CallToolResult {
+  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
+}
+
+/** Return a plain-text tool result (used for the Mermaid diagram string). */
+export function textResult(text: string): CallToolResult {
+  return { content: [{ type: "text", text }] };
+}
+
+/** Return a structured error result (isError) instead of throwing. */
+export function errResult(message: string): CallToolResult {
+  return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
+}
diff --git a/src/lib/roles.ts b/src/lib/roles.ts
new file mode 100644
index 0000000..c9cbd01
--- /dev/null
+++ b/src/lib/roles.ts
@@ -0,0 +1,121 @@
+/**
+ * Directory-name -> role hint table. These are deliberately shallow heuristics:
+ * a hint the connected LLM refines, never an authoritative classification.
+ */
+const ROLE_HINTS: Record<string, string> = {
+  broker: "external broker/API gateways",
+  brokers: "external broker/API gateways",
+  gateway: "external API gateways",
+  gateways: "external API gateways",
+  strategy: "strategy implementations",
+  strategies: "strategy implementations",
+  engine: "core execution engine",
+  engines: "core execution engine",
+  execution: "order execution",
+  orders: "order management",
+  order: "order management",
+  risk: "risk management",
+  portfolio: "portfolio tracking",
+  data: "data ingestion / feeds",
+  feeds: "market data feeds",
+  monitoring: "monitoring / alerting",
+  alerts: "alerting",
+  dashboard: "UI dashboard",
+  ui: "UI layer",
+  frontend: "frontend",
+  backend: "backend",
+  agents: "AI/LLM agents",
+  agent: "AI/LLM agents",
+  core: "core utilities",
+  common: "shared code",
+  shared: "shared code",
+  utils: "utility helpers",
+  util: "utility helpers",
+  helpers: "helper functions",
+  lib: "library code",
+  libs: "library code",
+  tools: "tool implementations",
+  resources: "resource handlers",
+  handlers: "request handlers",
+  tests: "tests",
+  test: "tests",
+  __tests__: "tests",
+  spec: "tests",
+  config: "configuration",
+  configs: "configuration",
+  settings: "configuration",
+  db: "database layer",
+  database: "database layer",
+  models: "data models",
+  schemas: "schemas",
+  api: "API layer",
+  routes: "route handlers",
+  router: "routing",
+  controllers: "controllers",
+  services: "services",
+  service: "services",
+  components: "UI components",
+  pages: "pages / routes",
+  views: "views",
+  hooks: "hooks",
+  middleware: "middleware",
+  scripts: "scripts",
+  bin: "executables",
+  docs: "documentation",
+  examples: "examples",
+  migrations: "database migrations",
+};
+
+/** Guess a role from a module key's last path segment. */
+export function roleGuess(moduleKeyValue: string): string {
+  const seg = (moduleKeyValue.split("/").pop() ?? moduleKeyValue).toLowerCase();
+  return ROLE_HINTS[seg] ?? "(role: model to infer)";
+}
+
+/* ------------------------------------------------------------------ *
+ * Visual categories. The diagram emitters (Mermaid, DOT) color modules *
+ * by coarse role family so the draft reads as an architecture diagram, *
+ * not a uniform blob. Same shallow-heuristic caveat as ROLE_HINTS.     *
+ * ------------------------------------------------------------------ */
+
+export type RoleCategory = "api" | "core" | "data" | "docs" | "infra" | "shared" | "test" | "ui";
+
+/** Directory names grouped into visual families (must cover every ROLE_HINTS key). */
+const CATEGORY_KEYS: Record<RoleCategory, string[]> = {
+  ui: ["dashboard", "ui", "frontend", "components", "pages", "views", "hooks"],
+  api: ["api", "routes", "router", "controllers", "services", "service", "handlers", "middleware", "gateway", "gateways", "broker", "brokers", "backend"],
+  core: ["engine", "engines", "execution", "orders", "order", "risk", "portfolio", "strategy", "strategies", "agent", "agents", "core"],
+  data: ["data", "feeds", "db", "database", "models", "schemas", "migrations"],
+  shared: ["common", "shared", "utils", "util", "helpers", "lib", "libs", "tools", "resources"],
+  test: ["tests", "test", "__tests__", "spec"],
+  docs: ["docs", "examples"],
+  infra: ["config", "configs", "settings", "scripts", "bin", "monitoring", "alerts"],
+};
+
+const CATEGORY_BY_SEGMENT: ReadonlyMap<string, RoleCategory> = new Map(
+  (Object.entries(CATEGORY_KEYS) as [RoleCategory, string[]][]).flatMap(([cat, keys]) =>
+    keys.map((k) => [k, cat] as const),
+  ),
+);
+
+/** Visual family for a module key, or null when we have no hint (theme default). */
+export function roleCategory(moduleKeyValue: string): RoleCategory | null {
+  const seg = (moduleKeyValue.split("/").pop() ?? moduleKeyValue).toLowerCase();
+  return CATEGORY_BY_SEGMENT.get(seg) ?? null;
+}
+
+/**
+ * Fill/stroke per category, shared by both emitters so Mermaid and DOT output
+ * look like the same tool drew them. Medium-value fills with white labels stay
+ * readable on both light and dark backgrounds (GitHub renders either).
+ */
+export const CATEGORY_STYLE: Record<RoleCategory, { fill: string; stroke: string }> = {
+  api: { fill: "#af7aa1", stroke: "#8a5f7f" },
+  core: { fill: "#e15759", stroke: "#b04547" },
+  data: { fill: "#59a14f", stroke: "#46803e" },
+  docs: { fill: "#9d7660", stroke: "#7c5d4c" },
+  infra: { fill: "#b35c00", stroke: "#8f4a00" },
+  shared: { fill: "#79706e", stroke: "#5d5654" },
+  test: { fill: "#499894", stroke: "#397975" },
+  ui: { fill: "#4e79a7", stroke: "#3a5b80" },
+};
diff --git a/src/lib/rules.ts b/src/lib/rules.ts
new file mode 100644
index 0000000..e0dc931
--- /dev/null
+++ b/src/lib/rules.ts
@@ -0,0 +1,80 @@
+import { existsSync, readFileSync } from "node:fs";
+import { extname, join } from "node:path";
+import { parse as parseYaml } from "yaml";
+import type { DiagramFormat, DiagramLevel } from "../types.js";
+
+export type Severity = "error" | "warn" | "off";
+
+export interface ForbiddenRule {
+  from: string;
+  to: string;
+  reason: string;
+  level: "error" | "warn";
+}
+
+export interface Rules {
+  forbidden: ForbiddenRule[];
+  cycles: Severity;
+  diagram: { level: DiagramLevel; outPath: string; format: DiagramFormat };
+}
+
+export const DEFAULT_RULES: Rules = {
+  forbidden: [],
+  cycles: "off",
+  diagram: { level: "high", outPath: "architecture", format: "mermaid" },
+};
+
+/** Candidate config filenames, in priority order. */
+const CONFIG_NAMES = [".cartographer.yml", ".cartographer.yaml", ".cartographer.json"];
+
+/** Find a config file in `dir`, or return null. */
+export function findConfig(dir: string): string | null {
+  for (const name of CONFIG_NAMES) {
+    const p = join(dir, name);
+    if (existsSync(p)) return p;
+  }
+  return null;
+}
+
+/** Parse + normalize a config file into fully-populated Rules. Throws on bad input. */
+export function loadRules(configPath: string): Rules {
+  const text = readFileSync(configPath, "utf8");
+  const raw = extname(configPath).toLowerCase() === ".json" ? JSON.parse(text) : parseYaml(text);
+  if (raw === null || typeof raw !== "object") {
+    throw new Error(`Config ${configPath} is empty or not a mapping.`);
+  }
+
+  const rulesNode = (raw as Record<string, unknown>).rules;
+  const rules = (rulesNode && typeof rulesNode === "object" ? rulesNode : {}) as Record<string, unknown>;
+
+  const forbidden: ForbiddenRule[] = [];
+  if (Array.isArray(rules.forbidden)) {
+    rules.forbidden.forEach((entry, i) => {
+      const r = entry as Record<string, unknown>;
+      if (typeof r.from !== "string" || typeof r.to !== "string") {
+        throw new Error(`rules.forbidden[${i}] must have string 'from' and 'to'.`);
+      }
+      const level = r.level === "warn" ? "warn" : "error";
+      forbidden.push({
+        from: r.from,
+        to: r.to,
+        reason: typeof r.reason === "string" ? r.reason : "forbidden dependency",
+        level,
+      });
+    });
+  }
+
+  const cycles: Severity =
+    rules.cycles === "warn" || rules.cycles === "off" || rules.cycles === "error"
+      ? rules.cycles
+      : DEFAULT_RULES.cycles;
+
+  const diagramNode = ((raw as Record<string, unknown>).diagram ?? {}) as Record<string, unknown>;
+  const diagram = {
+    level: diagramNode.level === "detail" ? ("detail" as const) : ("high" as const),
+    outPath: typeof diagramNode.outPath === "string" ? diagramNode.outPath : DEFAULT_RULES.diagram.outPath,
+    format: diagramNode.format === "dot" ? ("dot" as const) : ("mermaid" as const),
+  };
+
+  return { forbidden, cycles, diagram };
+}
diff --git a/src/lib/walk.ts b/src/lib/walk.ts
new file mode 100644
index 0000000..27fa527
--- /dev/null
+++ b/src/lib/walk.ts
@@ -0,0 +1,108 @@
+import { readdirSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+import { EXCLUDED_DIRS, MAX_DEPTH, MAX_FILES } from "./ignore.js";
+import { resolveDir } from "./fsutil.js";
+import { isContainerDir } from "./paths.js";
+
+export interface WalkResult {
+  /** Repo-relative posix file paths, sorted. */
+  files: string[];
+  /** Repo-relative posix directory paths (excluding root), sorted. */
+  dirs: string[];
+  /** True if MAX_FILES was hit and the file list is incomplete. */
+  truncated: boolean;
+}
+
+function toPosix(p: string): string {
+  return p.split(sep).join("/");
+}
+
+/**
+ * Step past zip-extraction wrapper folders: GitHub's "Download ZIP" (and most
+ * archive tools) wrap the repo in `<repo>-main/`, so a scan of the extraction
+ * directory would see one giant module and no resolvable imports. A directory
+ * that contains NO files and exactly one visible subdirectory is such a
+ * wrapper; descend (bounded) until the shape changes. Deterministic — shape
+ * only, no name matching.
+ */
+export function descendPastWrapper(root: string): { root: string; descended: string[] } {
+  let current = root;
+  const descended: string[] = [];
+  for (let i = 0; i < 3; i++) {
+    let entries;
+    try {
+      entries = readdirSync(current, { withFileTypes: true });
+    } catch {
+      break;
+    }
+    const files = entries.filter((e) => e.isFile());
+    const dirs = entries.filter(
+      (e) => e.isDirectory() && !e.name.startsWith(".") && !EXCLUDED_DIRS.has(e.name),
+    );
+    // A lone source container (src/, lib/, packages/ …) is repo structure, not
+    // a wrapper — descending would rewrite every repo-relative path and glob.
+    if (files.length !== 0 || dirs.length !== 1 || isContainerDir(dirs[0].name)) break;
+    current = join(current, dirs[0].name);
+    descended.push(dirs[0].name);
+  }
+  return { root: current, descended };
+}
+
+/**
+ * Resolve a tool's input path to the repo root every tool should agree on:
+ * assert it is a directory, then step past any zip wrapper folders. The note
+ * (when a descent happened) is surfaced in tool output so it is never silent.
+ */
+export function resolveRepoRoot(inputPath: string): { root: string; notes: string[] } {
+  const { root, descended } = descendPastWrapper(resolveDir(inputPath));
+  const notes = descended.length
+    ? [`Descended past wrapper folder(s) "${descended.join("/")}" — the given directory contained only a single folder.`]
+    : [];
+  return { root, notes };
+}
+
+/**
+ * Recursively list files under `root`, skipping hidden directories, known build/
+ * dependency directories, and symlinked directories (avoids cycles). Traversal
+ * visits directory entries in sorted order so truncation at MAX_FILES is
+ * deterministic across runs.
+ */
+export function walk(root: string): WalkResult {
+  const files: string[] = [];
+  const dirs: string[] = [];
+  let truncated = false;
+
+  const recur = (abs: string, depth: number): void => {
+    if (depth > MAX_DEPTH) return;
+    let entries;
+    try {
+      entries = readdirSync(abs, { withFileTypes: true });
+    } catch {
+      return; // unreadable directory — skip
+    }
+    entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+
+    const subdirs: string[] = [];
+    for (const e of entries) {
+      const full = join(abs, e.name);
+      if (e.isDirectory()) {
+        if (e.name.startsWith(".") || EXCLUDED_DIRS.has(e.name)) continue;
+        dirs.push(toPosix(relative(root, full)));
+        subdirs.push(full);
+      } else if (e.isFile()) {
+        if (files.length >= MAX_FILES) {
+          truncated = true;
+          continue;
+        }
+        files.push(toPosix(relative(root, full)));
+      }
+      // symlinks and other entry types are intentionally ignored
+    }
+    for (const d of subdirs) recur(d, depth + 1);
+  };
+
+  recur(root, 0);
+  files.sort();
+  dirs.sort();
+  return { files, dirs, truncated };
+}
diff --git a/src/resources/author.ts b/src/resources/author.ts
new file mode 100644
index 0000000..381a3e1
--- /dev/null
+++ b/src/resources/author.ts
@@ -0,0 +1,38 @@
+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+
+/**
+ * All author/contact details live in this single constant so they are easy to
+ * update in one place. Returned verbatim by the `about://author` resource.
+ */
+export const AUTHOR = `# builditwithgk
+
+Hi — I'm Gopi K devm (builditwithgk). I build practical AI tooling,
+autonomous agents, and MCP servers.
+
+**repo-cartographer** is one of my open-source projects. If it saved you
+time and you'd like help building LLM or agent tooling for your team, I'm
+available for freelance and contract work.
+
+- GitHub: https://github.com/builditwithgk
+- HuggingFace: https://huggingface.co/builditwithgk
+- Portfolio: https://scaleup-solutions.in/
+- Email: builditwithgk@gmail.com
+
+_Available for work._
+`;
+
+/** Register the `about://author` resource (Markdown business card). */
+export function registerAuthorResource(server: McpServer): void {
+  server.registerResource(
+    "author",
+    "about://author",
+    {
+      title: "About the author",
+      description: "Who built repo-cartographer and how to get in touch.",
+      mimeType: "text/markdown",
+    },
+    async (uri) => ({
+      contents: [{ uri: uri.href, mimeType: "text/markdown", text: AUTHOR }],
+    }),
+  );
+}
diff --git a/src/server.ts b/src/server.ts
new file mode 100644
index 0000000..2477911
--- /dev/null
+++ b/src/server.ts
@@ -0,0 +1,164 @@
+/**
+ * repo-cartographer MCP server — deterministic extraction only; the connected
+ * model does the reasoning. Every tool returns structured facts (or a draft
+ * diagram), never an interpretation.
+ *
+ * This module builds and starts the stdio server. The CLI entry (index.ts)
+ * launches it when no subcommand is given.
+ */
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import { z } from "zod";
+
+import { errResult, jsonResult, textResult } from "./lib/result.js";
+import { runMapRepo } from "./tools/mapRepo.js";
+import { runScanRepo } from "./tools/scanRepo.js";
+import { runBuildImportGraph } from "./tools/buildImportGraph.js";
+import { runGenerateDiagram } from "./tools/generateDiagram.js";
+import { runRenderDiagram } from "./tools/renderDiagram.js";
+import { registerAuthorResource } from "./resources/author.js";
+
+function message(e: unknown): string {
+  return e instanceof Error ? e.message : String(e);
+}
+
+/** Construct the server with all tools + resources registered. */
+export function buildServer(): McpServer {
+  const server = new McpServer({ name: "repo-cartographer", version: "1.0.0" });
+
+  server.registerTool(
+    "map_repo",
+    {
+      title: "Map repository (one-shot)",
+      description:
+        "Point at a folder and get a downloadable architecture diagram in one call: runs " +
+        "scan + import-graph + render internally and returns the HTML path, a facts summary, and " +
+        "the draft diagram source inline. By default writes architecture.html plus the raw source " +
+        "(.mermaid or .dot) into the repo; pass outPath to write elsewhere. Use the granular tools " +
+        "(scan_repo, build_import_graph, generate_diagram, render_diagram) only when you need to " +
+        "compose the steps yourself.",
+      inputSchema: {
+        path: z.string().describe("Absolute or relative path to the repository root"),
+        level: z.enum(["high", "detail"]).optional().describe("Diagram granularity (default 'high')"),
+        format: z
+          .enum(["mermaid", "dot"])
+          .optional()
+          .describe("Diagram notation: 'mermaid' (default; renders on GitHub) or 'dot' (Graphviz interop)"),
+        outPath: z
+          .string()
+          .optional()
+          .describe("Output base path (default: <repo>/architecture); .html and the raw source are written"),
+      },
+    },
+    async ({ path, level, outPath, format }) => {
+      try {
+        return jsonResult(runMapRepo(path, level ?? "high", outPath, format ?? "mermaid"));
+      } catch (e) {
+        return errResult(message(e));
+      }
+    },
+  );
+
+  server.registerTool(
+    "scan_repo",
+    {
+      title: "Scan repository",
+      description:
+        "Deterministically extract facts from a local repo: programming languages, " +
+        "frameworks/libraries, entry points, top-level modules (with role guesses), and a " +
+        "manifest summary. Returns JSON facts only — no interpretation.",
+      inputSchema: { path: z.string().describe("Absolute or relative path to the repository root") },
+    },
+    async ({ path }) => {
+      try {
+        return jsonResult(runScanRepo(path));
+      } catch (e) {
+        return errResult(message(e));
+      }
+    },
+  );
+
+  server.registerTool(
+    "build_import_graph",
+    {
+      title: "Build import graph",
+      description:
+        "Extract intra-repo import/require relationships for JavaScript/TypeScript and Python. " +
+        "Nodes are files (auto-collapsed to module/directory level for large repos); edges are " +
+        "directed import relationships. Returns JSON.",
+      inputSchema: { path: z.string().describe("Absolute or relative path to the repository root") },
+    },
+    async ({ path }) => {
+      try {
+        return jsonResult(runBuildImportGraph(path));
+      } catch (e) {
+        return errResult(message(e));
+      }
+    },
+  );
+
+  server.registerTool(
+    "generate_diagram",
+    {
+      title: "Generate diagram",
+      description:
+        "Combine scan + import facts into a DRAFT diagram string — Mermaid flowchart (default) " +
+        "or Graphviz DOT. level 'high' (default) shows modules/directories; 'detail' shows files " +
+        "grouped by module. This is a draft the calling model is expected to refine.",
+      inputSchema: {
+        path: z.string().describe("Absolute or relative path to the repository root"),
+        level: z.enum(["high", "detail"]).optional().describe("Diagram granularity (default 'high')"),
+        format: z
+          .enum(["mermaid", "dot"])
+          .optional()
+          .describe("Diagram notation: 'mermaid' (default; renders on GitHub) or 'dot' (Graphviz interop)"),
+      },
+    },
+    async ({ path, level, format }) => {
+      try {
+        return textResult(runGenerateDiagram(path, level ?? "high", format ?? "mermaid"));
+      } catch (e) {
+        return errResult(message(e));
+      }
+    },
+  );
+
+  server.registerTool(
+    "render_diagram",
+    {
+      title: "Render diagram",
+      description:
+        "Write a self-contained, shareable HTML page (renders via CDN: Mermaid, or Viz for " +
+        "Graphviz DOT) plus the raw source file (.mermaid or .dot). Returns the absolute paths written.",
+      inputSchema: {
+        source: z.string().describe("Diagram source to render (Mermaid, or DOT when format is 'dot')"),
+        format: z
+          .enum(["mermaid", "dot"])
+          .optional()
+          .describe("Notation of `source` (default 'mermaid')"),
+        outPath: z
+          .string()
+          .describe("Output path (with or without extension); .html and the raw source siblings are written"),
+      },
+    },
+    async ({ source, outPath, format }) => {
+      try {
+        return jsonResult(runRenderDiagram(source, outPath, format ?? "mermaid"));
+      } catch (e) {
+        return errResult(message(e));
+      }
+    },
+  );
+
+  registerAuthorResource(server);
+  return server;
+}
+
+/** Start the MCP server on stdio. */
+export async function startServer(): Promise<void> {
+  const server = buildServer();
+  const transport = new StdioServerTransport();
+  await server.connect(transport);
+  // stderr is safe for logs; stdout is reserved for the JSON-RPC stream.
+  process.stderr.write("repo-cartographer MCP server running on stdio\n");
+}
diff --git a/src/tools/buildImportGraph.ts b/src/tools/buildImportGraph.ts
new file mode 100644
index 0000000..585c26d
--- /dev/null
+++ b/src/tools/buildImportGraph.ts
@@ -0,0 +1,49 @@
+import type { ImportGraph } from "../types.js";
+import { resolveRepoRoot, walk } from "../lib/walk.js";
+import { isCodeFile } from "../lib/paths.js";
+import { collapseToModules, extractImports } from "../lib/imports.js";
+import { MODULE_COLLAPSE_THRESHOLD } from "../lib/ignore.js";
+
+/**
+ * `build_import_graph` — intra-repo import/require edges for JS/TS + Python.
+ * Collapses to module (directory) level when the file count is large.
+ */
+export function runBuildImportGraph(inputPath: string): ImportGraph {
+  const { root, notes: rootNotes } = resolveRepoRoot(inputPath);
+  const { files, truncated } = walk(root);
+  const codeFiles = files.filter(isCodeFile);
+
+  const { edges, externalImports, filesScanned } = extractImports(root, codeFiles);
+
+  let level: "file" | "module" = "file";
+  let nodes = codeFiles;
+  let outEdges = edges;
+  let collapsed = false;
+
+  if (codeFiles.length > MODULE_COLLAPSE_THRESHOLD) {
+    const m = collapseToModules(codeFiles, edges);
+    nodes = m.nodes;
+    outEdges = m.edges;
+    level = "module";
+    collapsed = true;
+  }
+
+  const notes: string[] = [...rootNotes];
+  if (collapsed) {
+    notes.push(
+      `Graph collapsed to module level (${codeFiles.length} code files > ${MODULE_COLLAPSE_THRESHOLD}). ` +
+        `Call generate_diagram with level "detail" for a file-level view.`,
+    );
+  }
+  if (truncated) notes.push("File scan capped — some files were not included.");
+
+  return {
+    path: root,
+    level,
+    nodes,
+    edges: outEdges,
+    collapsed,
+    stats: { filesScanned, edges: outEdges.length, externalImports, truncated },
+    notes,
+  };
+}
diff --git a/src/tools/checkRepo.ts b/src/tools/checkRepo.ts
new file mode 100644
index 0000000..aa5346d
--- /dev/null
+++ b/src/tools/checkRepo.ts
@@ -0,0 +1,62 @@
+import { resolveRepoRoot, walk } from "../lib/walk.js";
+import { isCodeFile } from "../lib/paths.js";
+import { collapseToModules, extractImports } from "../lib/imports.js";
+import { matchGlob } from "../lib/glob.js";
+import { findCycles } from "../lib/cycles.js";
+import type { Rules } from "../lib/rules.js";
+import type { CheckResult, Violation } from "../types.js";
+
+// Violation / CheckResult live in ../types.js so src/lib can use them without
+// importing a tool implementation (dependencies point inward).
+export type { CheckResult, Violation };
+
+/**
+ * Evaluate architecture rules against a repo's *file-level* import edges
+ * (uncollapsed, so path globs work even on large repos). Deterministic — no LLM.
+ */
+export function runCheck(inputPath: string, rules: Rules): CheckResult {
+  const { root } = resolveRepoRoot(inputPath);
+  const { files } = walk(root);
+  const codeFiles = files.filter(isCodeFile);
+  const { edges } = extractImports(root, codeFiles);
+
+  const violations: Violation[] = [];
+
+  // 1) forbidden cross-boundary imports (file-level)
+  for (const rule of rules.forbidden) {
+    for (const e of edges) {
+      if (matchGlob(rule.from, e.from) && matchGlob(rule.to, e.to)) {
+        violations.push({ level: rule.level, kind: "forbidden", from: e.from, to: e.to, reason: rule.reason });
+      }
+    }
+  }
+
+  // 2) dependency cycles (module-level)
+  const modules = collapseToModules(codeFiles, edges);
+  if (rules.cycles !== "off") {
+    const level = rules.cycles; // "error" | "warn"
+    for (const cycle of findCycles(modules.nodes, modules.edges)) {
+      const label = cycle.length === 1 ? `${cycle[0]} (self-import)` : cycle.join(" → ");
+      violations.push({ level, kind: "cycle", reason: `dependency cycle: ${label}` });
+    }
+  }
+
+  // stable ordering: errors first, then by kind/reason
+  violations.sort(
+    (a, b) =>
+      (a.level === b.level ? 0 : a.level === "error" ? -1 : 1) ||
+      (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) ||
+      ((a.from ?? "") + (a.to ?? "") + a.reason).localeCompare((b.from ?? "") + (b.to ?? "") + b.reason),
+  );
+
+  const errorCount = violations.filter((v) => v.level === "error").length;
+  const warnCount = violations.length - errorCount;
+
+  return {
+    path: root,
+    violations,
+    errorCount,
+    warnCount,
+    stats: { codeFiles: codeFiles.length, edges: edges.length, modules: modules.nodes.length },
+  };
+}
diff --git a/src/tools/generateDiagram.ts b/src/tools/generateDiagram.ts
new file mode 100644
index 0000000..405ba5f
--- /dev/null
+++ b/src/tools/generateDiagram.ts
@@ -0,0 +1,31 @@
+import { basename as pathBasename } from "node:path";
+import { resolveRepoRoot, walk } from "../lib/walk.js";
+import { isCodeFile } from "../lib/paths.js";
+import { extractImports } from "../lib/imports.js";
+import { detectManifestAndFrameworks } from "../lib/detect.js";
+import { renderFlowchart } from "../lib/mermaid.js";
+import { renderDot } from "../lib/dot.js";
+import type { DiagramFormat, DiagramLevel } from "../types.js";
+
+export type { DiagramFormat, DiagramLevel };
+
+/**
+ * `generate_diagram` — combine scan + import facts into a DRAFT diagram string:
+ * Mermaid (default; renders on GitHub) or Graphviz DOT (interop). The connected
+ * model is expected to refine it.
+ */
+export function runGenerateDiagram(
+  inputPath: string,
+  level: DiagramLevel = "high",
+  format: DiagramFormat = "mermaid",
+): string {
+  const { root } = resolveRepoRoot(inputPath);
+  const { files } = walk(root);
+  const codeFiles = files.filter(isCodeFile);
+  const { edges } = extractImports(root, codeFiles);
+  const { manifest } = detectManifestAndFrameworks(root, files);
+  const repoName = manifest.name ?? pathBasename(root);
+
+  const opts = { repoName, level, codeFiles, edges };
+  return format === "dot" ? renderDot(opts) : renderFlowchart(opts);
+}
diff --git a/src/tools/mapRepo.ts b/src/tools/mapRepo.ts
new file mode 100644
index 0000000..9743fc6
--- /dev/null
+++ b/src/tools/mapRepo.ts
@@ -0,0 +1,68 @@
+import { join } from "node:path";
+import { resolveRepoRoot } from "../lib/walk.js";
+import { runScanRepo } from "./scanRepo.js";
+import { runGenerateDiagram, type DiagramFormat, type DiagramLevel } from "./generateDiagram.js";
+import { runRenderDiagram } from "./renderDiagram.js";
+
+export interface MapResult {
+  /** Ready-to-open HTML diagram. */
+  htmlPath: string;
+  /** Raw diagram source written alongside the HTML (.mermaid or .dot). */
+  sourcePath: string;
+  format: DiagramFormat;
+  level: DiagramLevel;
+  /** At-a-glance facts so the caller doesn't need a second tool call. */
+  summary: {
+    languages: string[];
+    frameworks: string[];
+    entryPoints: string[];
+    files: number;
+    codeFiles: number;
+    modules: number;
+    edgesShown: number;
+  };
+  /** The draft diagram source, inline, so the model can refine it without re-fetching. */
+  diagram: string;
+}
+
+/**
+ * `map_repo` — the one-shot flow: point it at a folder and get a downloadable
+ * architecture diagram plus a summary, in a single call. Internally it runs
+ * scan -> generate -> render (composing the granular tools). By default the
+ * diagram is written into the scanned repo as `architecture.html` plus the raw
+ * source (`.mermaid` or `.dot`); pass `outPath` to write elsewhere.
+ */
+export function runMapRepo(
+  inputPath: string,
+  level: DiagramLevel = "high",
+  outPath?: string,
+  format: DiagramFormat = "mermaid",
+): MapResult {
+  // Descend past zip wrappers here too, so the default outPath lands inside
+  // the real repo root (scan/generate would each descend on their own anyway).
+  const { root } = resolveRepoRoot(inputPath);
+
+  const scan = runScanRepo(root);
+  const diagram = runGenerateDiagram(root, level, format);
+  const target = outPath ?? join(root, "architecture");
+  const { htmlPath, sourcePath } = runRenderDiagram(diagram, target, format);
+
+  const edgesShown = (diagram.match(format === "dot" ? /->/g : /-->/g) ?? []).length;
+
+  return {
+    htmlPath,
+    sourcePath,
+    format,
+    level,
+    summary: {
+      languages: scan.languages,
+      frameworks: scan.frameworks,
+      entryPoints: scan.entryPoints,
+      files: scan.stats.files,
+      codeFiles: scan.stats.codeFiles,
+      modules: scan.modules.length,
+      edgesShown,
+    },
+    diagram,
+  };
+}
diff --git a/src/tools/renderDiagram.ts b/src/tools/renderDiagram.ts
new file mode 100644
index 0000000..be6fc8e
--- /dev/null
+++ b/src/tools/renderDiagram.ts
@@ -0,0 +1,151 @@
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import type { DiagramFormat } from "../types.js";
+
+export interface RenderResult {
+  htmlPath: string;
+  /** The raw diagram source written next to the HTML (.mermaid or .dot). */
+  sourcePath: string;
+  format: DiagramFormat;
+}
+
+/** File extension for the raw diagram source, per format. */
+const SOURCE_EXT: Record<DiagramFormat, string> = { mermaid: ".mermaid", dot: ".dot" };
+
+function escapeHtml(s: string): string {
+  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
+
+/**
+ * JSON literal safe to inline in a `<script>` block. `render_diagram` accepts
+ * arbitrary diagram text, and a raw `</script>` in it would close the block
+ * early and turn the remainder into live HTML. Escaping "<" removes that entirely.
+ */
+function jsonForScript(value: string): string {
+  return JSON.stringify(value).replace(/</g, "\\u003c");
+}
+
+/** The format-specific diagram container + renderer script. */
+function renderer(source: string, format: DiagramFormat): { body: string; script: string } {
+  if (format === "dot") {
+    return {
+      body: '<div id="graph"></div>',
+      script: `<script src="https://cdn.jsdelivr.net/npm/@viz-js/viz@3/lib/viz-standalone.js"></script>
+<script>
+  Viz.instance()
+    .then((viz) => document.getElementById("graph").replaceChildren(viz.renderSVGElement(SRC)))
+    .catch((e) => { document.getElementById("graph").textContent = "Could not render diagram: " + e; });
+</script>`,
+    };
+  }
+  return {
+    body: `<pre class="mermaid">${escapeHtml(source)}</pre>`,
+    script: `<script type="module">
+  import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
+  const dark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
+  mermaid.initialize({ startOnLoad: true, theme: dark ? "dark" : "default", securityLevel: "strict" });
+</script>`,
+  };
+}
+
+/** Self-contained HTML page that renders the diagram via CDN (Mermaid or Viz). */
+function buildHtml(source: string, title: string, format: DiagramFormat): string {
+  const safeTitle = escapeHtml(title);
+  const preContent = escapeHtml(source);
+  const { body, script } = renderer(source, format);
+  return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>${safeTitle} — architecture</title>
+<style>
+  :root { color-scheme: light dark; --bg:#ffffff; --fg:#1a1a1a; --muted:#666; --card:#f6f8fa; --border:#e2e5e9; --accent:#3b6fd4; }
+  @media (prefers-color-scheme: dark) {
+    :root { --bg:#0f1115; --fg:#e6e6e6; --muted:#9aa0a6; --card:#171a21; --border:#2a2f3a; --accent:#6f9dff; }
+  }
+  * { box-sizing: border-box; }
+  body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background:var(--bg); color:var(--fg); }
+  header { padding:20px 24px; border-bottom:1px solid var(--border); display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
+  header h1 { font-size:18px; margin:0; font-weight:650; }
+  header .tag { font-size:12px; color:var(--muted); }
+  main { padding:24px; }
+  .diagram { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:20px; overflow-x:auto; }
+  .diagram .mermaid, .diagram #graph { display:flex; justify-content:center; }
+  .diagram #graph svg { max-width:100%; height:auto; }
+  .bar { display:flex; gap:8px; margin:16px 0 0; }
+  button { font:inherit; font-size:13px; padding:7px 13px; border-radius:8px; border:1px solid var(--border); background:var(--card); color:var(--fg); cursor:pointer; }
+  button:hover { border-color:var(--accent); }
+  details { margin-top:16px; }
+  summary { cursor:pointer; color:var(--muted); font-size:13px; }
+  pre.src { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:14px; overflow:auto; font-size:12.5px; line-height:1.5; }
+  footer { padding:16px 24px; color:var(--muted); font-size:12px; border-top:1px solid var(--border); }
+  a { color:var(--accent); }
+</style>
+</head>
+<body>
+<header>
+  <h1>${safeTitle}</h1>
+  <span class="tag">architecture diagram · draft · ${format}</span>
+</header>
+<main>
+  <div class="diagram">
+    ${body}
+  </div>
+  <div class="bar">
+    <button id="copy">Copy ${format === "dot" ? "DOT" : "Mermaid"} source</button>
+    <button id="download">Download ${SOURCE_EXT[format]}</button>
+  </div>
+  <details>
+    <summary>View ${format === "dot" ? "DOT" : "Mermaid"} source</summary>
+    <pre class="src">${preContent}</pre>
+  </details>
+</main>
+<footer>Generated by <a href="https://github.com/builditwithgk/repo-cartographer">repo-cartographer</a>. This is a draft — refine it with your model.</footer>
+<script>
+  const SRC = ${jsonForScript(source)};
+  document.getElementById("copy").addEventListener("click", async () => {
+    try { await navigator.clipboard.writeText(SRC); } catch (e) {}
+  });
+  document.getElementById("download").addEventListener("click", () => {
+    const blob = new Blob([SRC], { type: "text/plain" });
+    const a = document.createElement("a");
+    a.href = URL.createObjectURL(blob);
+    a.download = ${jsonForScript(title)} + ${JSON.stringify(SOURCE_EXT[format])};
+    a.click();
+    URL.revokeObjectURL(a.href);
+  });
+</script>
+${script}
+</body>
+</html>
+`;
+}
+
+/**
+ * `render_diagram` — write a self-contained `.html` (renders via CDN: Mermaid
+ * for mermaid source, Viz/Graphviz for DOT) plus the raw source file. `outPath`
+ * may include an extension or not; both siblings are written from the same base.
+ */
+export function runRenderDiagram(
+  source: string,
+  outPath: string,
+  format: DiagramFormat = "mermaid",
+): RenderResult {
+  if (!source.trim()) throw new Error("Refusing to render an empty diagram.");
+
+  const base = outPath.replace(/\.(html|mermaid|dot)$/i, "");
+  const htmlPath = resolve(`${base}.html`);
+  const sourcePath = resolve(`${base}${SOURCE_EXT[format]}`);
+  const title = base.split(/[\\/]/).pop() || "diagram";
+
+  try {
+    mkdirSync(dirname(htmlPath), { recursive: true });
+    writeFileSync(sourcePath, source, "utf8");
+    writeFileSync(htmlPath, buildHtml(source, title, format), "utf8");
+  } catch (e) {
+    throw new Error(`Could not write diagram files: ${e instanceof Error ? e.message : String(e)}`);
+  }
+
+  return { htmlPath, sourcePath, format };
+}
diff --git a/src/tools/scanRepo.ts b/src/tools/scanRepo.ts
new file mode 100644
index 0000000..d484ee5
--- /dev/null
+++ b/src/tools/scanRepo.ts
@@ -0,0 +1,47 @@
+import type { ModuleInfo, ScanResult } from "../types.js";
+import { resolveRepoRoot, walk } from "../lib/walk.js";
+import { isCodeFile, moduleKey } from "../lib/paths.js";
+import { detectLanguages, detectManifestAndFrameworks, detectEntryPoints } from "../lib/detect.js";
+import { roleGuess } from "../lib/roles.js";
+
+/** Group the file list into top-level modules with role guesses. */
+function buildModules(files: string[]): ModuleInfo[] {
+  const counts = new Map<string, number>();
+  for (const f of files) {
+    const key = moduleKey(f);
+    counts.set(key, (counts.get(key) ?? 0) + 1);
+  }
+  return [...counts.entries()]
+    .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
+    .map(([dir, fileCount]) => ({ dir, roleGuess: roleGuess(dir), fileCount }));
+}
+
+/**
+ * `scan_repo` — deterministic facts about a repo: languages, frameworks, entry
+ * points, top-level modules, and a manifest summary. No reasoning.
+ */
+export function runScanRepo(inputPath: string): ScanResult {
+  const { root, notes: rootNotes } = resolveRepoRoot(inputPath);
+  const { files, dirs, truncated } = walk(root);
+  const codeFiles = files.filter(isCodeFile);
+
+  const languages = detectLanguages(files);
+  const { manifest, frameworks, notes: manifestNotes } = detectManifestAndFrameworks(root, files);
+  const { entryPoints, notes: entryNotes } = detectEntryPoints(root, files);
+  const modules = buildModules(files);
+
+  const notes = [...rootNotes, ...manifestNotes, ...entryNotes];
+  if (truncated) notes.push(`File scan capped — repository has more than the scan limit; results are partial.`);
+
+  return {
+    path: root,
+    languages,
+    frameworks,
+    entryPoints,
+    modules,
+    manifest,
+    stats: { files: files.length, dirs: dirs.length, codeFiles: codeFiles.length },
+    truncated,
+    notes,
+  };
+}
diff --git a/src/types.ts b/src/types.ts
new file mode 100644
index 0000000..3ce84cb
--- /dev/null
+++ b/src/types.ts
@@ -0,0 +1,115 @@
+/**
+ * Shared type definitions for repo-cartographer.
+ *
+ * These describe the DETERMINISTIC facts the server extracts. The server never
+ * reasons about them — the connected LLM turns these facts into a narrative and
+ * a refined architecture diagram.
+ */
+
+/** A top-level (or second-level) module/directory in the repo. */
+export interface ModuleInfo {
+  /** Repo-relative posix directory key, e.g. "src/tools" or "(root)". */
+  dir: string;
+  /** Heuristic role guess from the directory name — a hint the model refines. */
+  roleGuess: string;
+  /** Number of files grouped under this module. */
+  fileCount: number;
+}
+
+/** Summary of a project manifest (package.json / pyproject.toml / etc.). */
+export interface ManifestSummary {
+  name: string | null;
+  version: string | null;
+  description: string | null;
+  /** Sorted, de-duplicated dependency names (no versions). */
+  dependencies: string[];
+}
+
+/** Result of `scan_repo`. */
+export interface ScanResult {
+  /** Absolute, resolved repo path that was scanned. */
+  path: string;
+  /** Detected programming languages, most prevalent first. */
+  languages: string[];
+  /** Frameworks/libraries inferred from manifests, sorted. */
+  frameworks: string[];
+  /** Heuristic entry points (repo-relative posix paths), sorted. */
+  entryPoints: string[];
+  /** Top-level modules with role guesses. */
+  modules: ModuleInfo[];
+  /** Manifest summary. */
+  manifest: ManifestSummary;
+  /** Coarse counts. */
+  stats: {
+    files: number;
+    dirs: number;
+    codeFiles: number;
+  };
+  /** True if a scan cap was hit (file list is incomplete). */
+  truncated: boolean;
+  /** Human-readable notes about anything capped or unparseable. */
+  notes: string[];
+}
+
+/** A directed import edge (from imports to). */
+export interface ImportEdge {
+  from: string;
+  to: string;
+}
+
+/** Diagram granularity: modules/directories vs individual files. */
+export type DiagramLevel = "high" | "detail";
+
+/**
+ * Diagram output notation. "mermaid" renders natively on GitHub (PR comments,
+ * READMEs) and in the shareable HTML; "dot" is the interop escape hatch — pipe
+ * it into Graphviz, Backstage, or anything else that eats DOT.
+ */
+export type DiagramFormat = "mermaid" | "dot";
+
+/** The deterministic facts a diagram emitter turns into notation. */
+export interface RenderOptions {
+  repoName: string;
+  level: DiagramLevel;
+  codeFiles: string[];
+  /** File-level import edges. */
+  edges: ImportEdge[];
+}
+
+/** A single architecture-rule breach found by `check`. */
+export interface Violation {
+  level: "error" | "warn";
+  kind: "forbidden" | "cycle";
+  from?: string;
+  to?: string;
+  reason: string;
+}
+
+/** Result of `check`. */
+export interface CheckResult {
+  path: string;
+  violations: Violation[];
+  errorCount: number;
+  warnCount: number;
+  stats: { codeFiles: number; edges: number; modules: number };
+}
+
+/** Result of `build_import_graph`. */
+export interface ImportGraph {
+  path: string;
+  /** "file" = node per file; "module" = collapsed to directory level. */
+  level: "file" | "module";
+  /** Node ids (repo-relative posix file paths, or module keys when collapsed). */
+  nodes: string[];
+  /** Intra-repo directed edges. */
+  edges: ImportEdge[];
+  /** True when the graph was collapsed to module level for size. */
+  collapsed: boolean;
+  stats: {
+    filesScanned: number;
+    edges: number;
+    externalImports: number;
+    truncated: boolean;
+  };
+  notes: string[];
+}
diff --git a/test/baseline.test.ts b/test/baseline.test.ts
new file mode 100644
index 0000000..262ae24
--- /dev/null
+++ b/test/baseline.test.ts
@@ -0,0 +1,158 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import {
+  BASELINE_NAME,
+  findBaseline,
+  fingerprintViolation,
+  loadBaseline,
+  partitionByBaseline,
+  writeBaseline,
+} from "../src/lib/baseline.js";
+import type { Violation } from "../src/types.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+/** Fingerprints join their fields with a NUL byte (see fingerprintViolation). */
+const SEP = String.fromCharCode(0);
+
+const forbidden: Violation = {
+  level: "error",
+  kind: "forbidden",
+  from: "src/ui/page.ts",
+  to: "src/db/query.ts",
+  reason: "no direct db access from the UI",
+};
+
+const cycle: Violation = {
+  level: "warn",
+  kind: "cycle",
+  reason: "dependency cycle: src/db → src/ui",
+};
+
+describe("fingerprintViolation", () => {
+  test("identifies a forbidden import by its endpoints", () => {
+    assert.equal(fingerprintViolation(forbidden), ["forbidden", "src/ui/page.ts", "src/db/query.ts"].join(SEP));
+  });
+
+  test("identifies a cycle by its reason", () => {
+    assert.equal(fingerprintViolation(cycle), ["cycle", "dependency cycle: src/db → src/ui"].join(SEP));
+  });
+
+  test("a path can never contain the separator, so kinds cannot be confused", () => {
+    // A forbidden fingerprint has 3 fields, a cycle fingerprint 2 — no overlap.
+    assert.equal(fingerprintViolation(forbidden).split(SEP).length, 3);
+    assert.equal(fingerprintViolation(cycle).split(SEP).length, 2);
+  });
+
+  test("is independent of severity, so re-classifying a rule keeps the baseline valid", () => {
+    assert.equal(fingerprintViolation({ ...forbidden, level: "warn" }), fingerprintViolation(forbidden));
+  });
+
+  test("is independent of the reason text for forbidden imports", () => {
+    // Editing the 'reason' in .cartographer.yml must not resurrect a baselined violation.
+    assert.equal(fingerprintViolation({ ...forbidden, reason: "reworded" }), fingerprintViolation(forbidden));
+  });
+
+  test("distinguishes different endpoints", () => {
+    assert.notEqual(fingerprintViolation({ ...forbidden, to: "src/db/other.ts" }), fingerprintViolation(forbidden));
+  });
+});
+
+describe("findBaseline", () => {
+  test("finds the conventional filename, or returns null", () => {
+    const withFile = makeRepo({ [BASELINE_NAME]: "[]" });
+    assert.equal(findBaseline(withFile), join(withFile, BASELINE_NAME));
+    assert.equal(findBaseline(makeRepo({ "README.md": "" })), null);
+  });
+});
+
+describe("loadBaseline", () => {
+  test("accepts the { violations: [...] } wrapper written by writeBaseline", () => {
+    const root = makeRepo({ [BASELINE_NAME]: JSON.stringify({ violations: [forbidden, cycle] }) });
+    const set = loadBaseline(join(root, BASELINE_NAME));
+    assert.equal(set.size, 2);
+    assert.ok(set.has(fingerprintViolation(forbidden)));
+  });
+
+  test("also accepts a bare array (e.g. a copied violations.json)", () => {
+    const root = makeRepo({ [BASELINE_NAME]: JSON.stringify([forbidden]) });
+    assert.deepEqual([...loadBaseline(join(root, BASELINE_NAME))], [fingerprintViolation(forbidden)]);
+  });
+
+  test("treats an unrecognized shape as an empty baseline", () => {
+    const root = makeRepo({ [BASELINE_NAME]: "{}" });
+    assert.equal(loadBaseline(join(root, BASELINE_NAME)).size, 0);
+  });
+
+  test("throws on malformed JSON rather than silently accepting nothing", () => {
+    const root = makeRepo({ [BASELINE_NAME]: "{ not json" });
+    assert.throws(() => loadBaseline(join(root, BASELINE_NAME)));
+  });
+});
+
+describe("writeBaseline", () => {
+  test("writes readable JSON that loadBaseline round-trips", () => {
+    const root = makeRepo({});
+    const file = join(root, BASELINE_NAME);
+    writeBaseline(file, [forbidden, cycle]);
+
+    const text = readFileSync(file, "utf8");
+    assert.match(text, /"generatedBy": "repo-cartographer"/);
+    assert.ok(text.includes("\n  "), "expected pretty-printed JSON");
+
+    const set = loadBaseline(file);
+    assert.deepEqual(partitionByBaseline([forbidden, cycle], set), {
+      fresh: [],
+      baselined: [forbidden, cycle],
+    });
+  });
+});
+
+describe("partitionByBaseline", () => {
+  test("splits new violations from accepted ones", () => {
+    const baseline = new Set([fingerprintViolation(forbidden)]);
+    assert.deepEqual(partitionByBaseline([forbidden, cycle], baseline), {
+      fresh: [cycle],
+      baselined: [forbidden],
+    });
+  });
+
+  test("an empty baseline leaves every violation fresh", () => {
+    assert.deepEqual(partitionByBaseline([forbidden, cycle], new Set()), {
+      fresh: [forbidden, cycle],
+      baselined: [],
+    });
+  });
+
+  test("a violation introduced after the baseline was written is fresh", () => {
+    const root = makeRepo({});
+    const file = join(root, BASELINE_NAME);
+    writeBaseline(file, [forbidden]);
+
+    const regression: Violation = { ...forbidden, from: "src/ui/other.ts" };
+    const { fresh, baselined } = partitionByBaseline([forbidden, regression], loadBaseline(file));
+
+    assert.deepEqual(fresh, [regression]);
+    assert.deepEqual(baselined, [forbidden]);
+  });
+
+  test("preserves input order within each bucket", () => {
+    const a: Violation = { ...forbidden, from: "src/ui/a.ts" };
+    const b: Violation = { ...forbidden, from: "src/ui/b.ts" };
+    const c: Violation = { ...forbidden, from: "src/ui/c.ts" };
+    const baseline = new Set([fingerprintViolation(b)]);
+    const { fresh } = partitionByBaseline([c, b, a], baseline);
+    assert.deepEqual(fresh, [c, a]);
+  });
+});
+
+describe("BASELINE_NAME", () => {
+  test("is the documented filename", () => {
+    assert.equal(BASELINE_NAME, ".cartographer-baseline.json");
+    // Guard against the constant drifting away from what the CLI help advertises.
+    const root = makeRepo({});
+    writeFileSync(join(root, BASELINE_NAME), "[]", "utf8");
+    assert.equal(findBaseline(root), join(root, ".cartographer-baseline.json"));
+  });
+});
diff --git a/test/check.test.ts b/test/check.test.ts
new file mode 100644
index 0000000..b15b0c9
--- /dev/null
+++ b/test/check.test.ts
@@ -0,0 +1,166 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { join } from "node:path";
+import { runCheck } from "../src/tools/checkRepo.js";
+import { DEFAULT_RULES, type Rules } from "../src/lib/rules.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+/**
+ * A repo with one forbidden import (ui -> db) that also forms a module-level
+ * cycle (src/ui -> src/db -> src/ui), so both rule kinds share one fixture.
+ */
+function repoWithViolations(): string {
+  return makeRepo({
+    "src/ui/page.ts": `import { q } from "../db/query.js";\n`,
+    "src/db/query.ts": `import { helper } from "../ui/helper.js";\n`,
+    "src/ui/helper.ts": "export const helper = 1;\n",
+    "README.md": "not code\n",
+  });
+}
+
+const rules = (overrides: Partial<Rules> = {}): Rules => ({ ...DEFAULT_RULES, ...overrides });
+
+const uiToDb = { from: "src/ui/**", to: "src/db/**", reason: "no direct db access from the UI" };
+
+describe("runCheck — forbidden imports", () => {
+  test("reports an edge matching a forbidden rule", () => {
+    const result = runCheck(repoWithViolations(), rules({ forbidden: [{ ...uiToDb, level: "error" }] }));
+
+    assert.deepEqual(result.violations, [
+      {
+        level: "error",
+        kind: "forbidden",
+        from: "src/ui/page.ts",
+        to: "src/db/query.ts",
+        reason: "no direct db access from the UI",
+      },
+    ]);
+    assert.equal(result.errorCount, 1);
+    assert.equal(result.warnCount, 0);
+  });
+
+  test("honours a warn-level rule", () => {
+    const result = runCheck(repoWithViolations(), rules({ forbidden: [{ ...uiToDb, level: "warn" }] }));
+    assert.equal(result.errorCount, 0);
+    assert.equal(result.warnCount, 1);
+    assert.equal(result.violations[0].level, "warn");
+  });
+
+  test("does not fire when the globs do not match", () => {
+    const rule = { from: "src/api/**", to: "src/db/**", reason: "n/a", level: "error" as const };
+    assert.deepEqual(runCheck(repoWithViolations(), rules({ forbidden: [rule] })).violations, []);
+  });
+
+  test("matches on file paths, so rules work on large repos without collapsing", () => {
+    const rule = { from: "src/ui/page.ts", to: "src/db/query.ts", reason: "exact", level: "error" as const };
+    const result = runCheck(repoWithViolations(), rules({ forbidden: [rule] }));
+    assert.equal(result.violations.length, 1);
+  });
+
+  test("rule globs stay repo-relative when the repo sits inside a zip wrapper", () => {
+    const root = makeRepo({
+      "repo-main/src/ui/page.ts": `import { q } from "../db/query.js";\n`,
+      "repo-main/src/db/query.ts": "export const q = 1;\n",
+    });
+    const result = runCheck(root, rules({ forbidden: [{ ...uiToDb, level: "error" }] }));
+    // Globs like src/ui/** must match — not repo-main/src/ui/**.
+    assert.equal(result.errorCount, 1);
+    assert.equal(result.violations[0].from, "src/ui/page.ts");
+  });
+
+  test("reports each matching edge separately", () => {
+    const root = makeRepo({
+      "src/ui/a.ts": `import "../db/x.js";\n`,
+      "src/ui/b.ts": `import "../db/x.js";\n`,
+      "src/db/x.ts": "export const x = 1;\n",
+    });
+    const result = runCheck(root, rules({ forbidden: [{ ...uiToDb, level: "error" }] }));
+    assert.deepEqual(
+      result.violations.map((v) => v.from),
+      ["src/ui/a.ts", "src/ui/b.ts"],
+    );
+  });
+});
+
+describe("runCheck — cycles", () => {
+  test("reports a module-level cycle when enabled", () => {
+    const result = runCheck(repoWithViolations(), rules({ cycles: "error" }));
+    assert.deepEqual(result.violations, [
+      { level: "error", kind: "cycle", reason: "dependency cycle: src/db → src/ui" },
+    ]);
+  });
+
+  test("respects the warn severity", () => {
+    const result = runCheck(repoWithViolations(), rules({ cycles: "warn" }));
+    assert.equal(result.violations[0].level, "warn");
+    assert.equal(result.errorCount, 0);
+    assert.equal(result.warnCount, 1);
+  });
+
+  test("reports nothing when cycles are off", () => {
+    assert.deepEqual(runCheck(repoWithViolations(), rules({ cycles: "off" })).violations, []);
+  });
+
+  test("an acyclic repo produces no cycle violations", () => {
+    const root = makeRepo({
+      "src/ui/page.ts": `import "../db/query.js";\n`,
+      "src/db/query.ts": "export const q = 1;\n",
+    });
+    assert.deepEqual(runCheck(root, rules({ cycles: "error" })).violations, []);
+  });
+});
+
+describe("runCheck — output shape", () => {
+  test("a clean repo with no rules produces no violations", () => {
+    const result = runCheck(repoWithViolations(), DEFAULT_RULES);
+    assert.deepEqual(result.violations, []);
+    assert.equal(result.errorCount, 0);
+    assert.equal(result.warnCount, 0);
+  });
+
+  test("counts only code files", () => {
+    const result = runCheck(repoWithViolations(), DEFAULT_RULES);
+    assert.deepEqual(result.stats, { codeFiles: 3, edges: 2, modules: 2 }); // README.md excluded
+  });
+
+  test("errors sort ahead of warnings", () => {
+    const result = runCheck(
+      repoWithViolations(),
+      rules({ forbidden: [{ ...uiToDb, level: "error" }], cycles: "warn" }),
+    );
+    assert.deepEqual(
+      result.violations.map((v) => [v.level, v.kind]),
+      [
+        ["error", "forbidden"],
+        ["warn", "cycle"],
+      ],
+    );
+  });
+
+  test("returns the resolved absolute path", () => {
+    const root = repoWithViolations();
+    assert.equal(runCheck(root, DEFAULT_RULES).path, root);
+  });
+
+  test("is deterministic across runs", () => {
+    const root = repoWithViolations();
+    const config = rules({ forbidden: [{ ...uiToDb, level: "error" }], cycles: "warn" });
+    assert.deepEqual(runCheck(root, config), runCheck(root, config));
+  });
+
+  test("an empty repo is handled without error", () => {
+    const result = runCheck(makeRepo({}), rules({ cycles: "error" }));
+    assert.deepEqual(result.violations, []);
+    assert.deepEqual(result.stats, { codeFiles: 0, edges: 0, modules: 0 });
+  });
+
+  test("throws a clear error for a missing path", () => {
+    const missing = join(makeRepo({}), "does-not-exist");
+    assert.throws(() => runCheck(missing, DEFAULT_RULES), /Path does not exist/);
+  });
+
+  test("throws a clear error when the path is a file", () => {
+    const root = makeRepo({ "a.ts": "" });
+    assert.throws(() => runCheck(join(root, "a.ts"), DEFAULT_RULES), /Path is not a directory/);
+  });
+});
diff --git a/test/cycles.test.ts b/test/cycles.test.ts
new file mode 100644
index 0000000..b4532d5
--- /dev/null
+++ b/test/cycles.test.ts
@@ -0,0 +1,78 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { findCycles } from "../src/lib/cycles.js";
+import type { ImportEdge } from "../src/types.js";
+
+const e = (from: string, to: string): ImportEdge => ({ from, to });
+
+describe("findCycles", () => {
+  test("a DAG has no cycles", () => {
+    assert.deepEqual(findCycles(["a", "b", "c"], [e("a", "b"), e("b", "c"), e("a", "c")]), []);
+  });
+
+  test("an isolated node set has no cycles", () => {
+    assert.deepEqual(findCycles(["a", "b"], []), []);
+  });
+
+  test("finds a two-node cycle", () => {
+    assert.deepEqual(findCycles(["a", "b"], [e("a", "b"), e("b", "a")]), [["a", "b"]]);
+  });
+
+  test("finds a longer cycle and excludes nodes hanging off it", () => {
+    const edges = [e("a", "b"), e("b", "c"), e("c", "a"), e("c", "d")];
+    assert.deepEqual(findCycles(["a", "b", "c", "d"], edges), [["a", "b", "c"]]);
+  });
+
+  test("reports a self-import as a single-node cycle", () => {
+    assert.deepEqual(findCycles(["a"], [e("a", "a")]), [["a"]]);
+  });
+
+  test("reports a self-import once even if the edge is repeated", () => {
+    assert.deepEqual(findCycles(["a", "b"], [e("a", "a"), e("a", "a"), e("a", "b")]), [["a"]]);
+  });
+
+  test("finds multiple disjoint cycles, sorted", () => {
+    const edges = [e("c", "d"), e("d", "c"), e("a", "b"), e("b", "a")];
+    assert.deepEqual(findCycles(["a", "b", "c", "d"], edges), [
+      ["a", "b"],
+      ["c", "d"],
+    ]);
+  });
+
+  test("merges overlapping cycles into one strongly-connected component", () => {
+    // a<->b and b<->c share b, so all three are mutually reachable.
+    const edges = [e("a", "b"), e("b", "a"), e("b", "c"), e("c", "b")];
+    assert.deepEqual(findCycles(["a", "b", "c"], edges), [["a", "b", "c"]]);
+  });
+
+  test("handles nodes that appear only in edges", () => {
+    assert.deepEqual(findCycles(["a"], [e("a", "b"), e("b", "a")]), [["a", "b"]]);
+  });
+
+  test("output is independent of node and edge input order", () => {
+    const nodes = ["a", "b", "c", "d", "e", "f"];
+    const edges = [e("a", "b"), e("b", "c"), e("c", "a"), e("d", "e"), e("e", "d"), e("f", "a")];
+    const expected = [
+      ["a", "b", "c"],
+      ["d", "e"],
+    ];
+    assert.deepEqual(findCycles(nodes, edges), expected);
+    assert.deepEqual(findCycles([...nodes].reverse(), [...edges].reverse()), expected);
+  });
+
+  test("is iterative — a 20k-node chain does not overflow the stack", () => {
+    const n = 20_000;
+    const nodes = Array.from({ length: n }, (_, i) => `n${i}`);
+    const edges = Array.from({ length: n - 1 }, (_, i) => e(`n${i}`, `n${i + 1}`));
+    assert.deepEqual(findCycles(nodes, edges), []);
+  });
+
+  test("is iterative — a 20k-node ring is found as one component", () => {
+    const n = 20_000;
+    const nodes = Array.from({ length: n }, (_, i) => `n${i}`);
+    const edges = Array.from({ length: n }, (_, i) => e(`n${i}`, `n${(i + 1) % n}`));
+    const cycles = findCycles(nodes, edges);
+    assert.equal(cycles.length, 1);
+    assert.equal(cycles[0].length, n);
+  });
+});
diff --git a/test/detect.test.ts b/test/detect.test.ts
new file mode 100644
index 0000000..766cedc
--- /dev/null
+++ b/test/detect.test.ts
@@ -0,0 +1,177 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import {
+  detectEntryPoints,
+  detectLanguages,
+  detectManifestAndFrameworks,
+} from "../src/lib/detect.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+describe("detectLanguages", () => {
+  test("orders languages by prevalence, then alphabetically", () => {
+    assert.deepEqual(detectLanguages(["a.ts", "b.tsx", "c.py", "d.go"]), ["TypeScript", "Go", "Python"]);
+  });
+
+  test("breaks ties alphabetically so output is stable", () => {
+    assert.deepEqual(detectLanguages(["a.ts", "b.py"]), ["Python", "TypeScript"]);
+    assert.deepEqual(detectLanguages(["b.py", "a.ts"]), ["Python", "TypeScript"]);
+  });
+
+  test("ignores files with no known language", () => {
+    assert.deepEqual(detectLanguages(["README.md", "logo.png", "Makefile"]), []);
+  });
+});
+
+describe("detectManifestAndFrameworks — package.json", () => {
+  test("reads name, version, description and every dependency table", () => {
+    const root = makeRepo({
+      "package.json": JSON.stringify({
+        name: "my-app",
+        version: "2.1.0",
+        description: "does things",
+        dependencies: { react: "^18", express: "^4" },
+        devDependencies: { vitest: "^1" },
+        peerDependencies: { "react-dom": "^18" },
+      }),
+    });
+
+    const { manifest, frameworks } = detectManifestAndFrameworks(root, ["package.json"]);
+
+    assert.equal(manifest.name, "my-app");
+    assert.equal(manifest.version, "2.1.0");
+    assert.equal(manifest.description, "does things");
+    assert.deepEqual(manifest.dependencies, ["express", "react", "react-dom", "vitest"]);
+    assert.deepEqual(frameworks, ["Express", "React", "Vitest"]);
+  });
+
+  test("recognizes scoped framework families by prefix", () => {
+    const root = makeRepo({
+      "package.json": JSON.stringify({ dependencies: { "@nestjs/core": "^10", "@angular/common": "^17" } }),
+    });
+    assert.deepEqual(detectManifestAndFrameworks(root, ["package.json"]).frameworks, ["Angular", "NestJS"]);
+  });
+
+  test("notes an unparseable package.json instead of throwing", () => {
+    const root = makeRepo({ "package.json": "{ not json" });
+    const { manifest, notes } = detectManifestAndFrameworks(root, ["package.json"]);
+    assert.deepEqual(manifest.dependencies, []);
+    assert.deepEqual(notes, ["package.json present but could not be parsed"]);
+  });
+
+  test("returns empty values when there is no manifest at all", () => {
+    const { manifest, frameworks } = detectManifestAndFrameworks(makeRepo({}), []);
+    assert.deepEqual(manifest, { name: null, version: null, description: null, dependencies: [] });
+    assert.deepEqual(frameworks, []);
+  });
+});
+
+describe("detectManifestAndFrameworks — Python", () => {
+  test("parses requirements.txt, skipping comments and pip options", () => {
+    const root = makeRepo({
+      "requirements.txt": ["flask==2.0", "# a comment", "-r other.txt", "", "scikit_learn>=1.0  # inline"].join("\n"),
+    });
+    const { manifest, frameworks } = detectManifestAndFrameworks(root, ["requirements.txt"]);
+    assert.deepEqual(manifest.dependencies, ["flask", "scikit-learn"]);
+    assert.deepEqual(frameworks, ["Flask", "scikit-learn"]);
+  });
+
+  test("parses a PEP 621 pyproject.toml", () => {
+    const root = makeRepo({
+      "pyproject.toml": ['[project]', 'name = "my-service"', 'dependencies = [', '  "fastapi>=0.1",', '  "pydantic",', ']'].join("\n"),
+    });
+    const { manifest, frameworks } = detectManifestAndFrameworks(root, ["pyproject.toml"]);
+    assert.equal(manifest.name, "my-service");
+    assert.deepEqual(manifest.dependencies, ["fastapi", "pydantic"]);
+    assert.deepEqual(frameworks, ["FastAPI", "Pydantic"]);
+  });
+
+  test("parses a Poetry dependency table and drops the python pin", () => {
+    const root = makeRepo({
+      "pyproject.toml": [
+        "[tool.poetry]",
+        'name = "poetry-app"',
+        "[tool.poetry.dependencies]",
+        'python = "^3.11"',
+        'django = "^5.0"',
+        "[tool.poetry.group.dev.dependencies]",
+      ].join("\n"),
+    });
+    const { manifest, frameworks } = detectManifestAndFrameworks(root, ["pyproject.toml"]);
+    assert.ok(!manifest.dependencies.includes("python"));
+    assert.ok(manifest.dependencies.includes("django"));
+    assert.deepEqual(frameworks, ["Django"]);
+  });
+
+  test("parses install_requires from setup.py", () => {
+    const root = makeRepo({
+      "setup.py": 'from setuptools import setup\nsetup(install_requires=["requests", "numpy>=1.20"])\n',
+    });
+    const { manifest } = detectManifestAndFrameworks(root, ["setup.py"]);
+    assert.deepEqual(manifest.dependencies, ["numpy", "requests"]);
+  });
+
+  test("picks up requirements files in subdirectories", () => {
+    const root = makeRepo({ "backend/requirements-dev.txt": "celery\n" });
+    const { manifest } = detectManifestAndFrameworks(root, ["backend/requirements-dev.txt"]);
+    assert.deepEqual(manifest.dependencies, ["celery"]);
+  });
+
+  test("does not read a requirements/ directory layout (known gap)", () => {
+    // Only files *named* requirements*.txt are parsed, not requirements/*.txt.
+    // Pinned so a future change to the pattern is a deliberate one. See TODO.md.
+    const root = makeRepo({ "requirements/base.txt": "celery\n" });
+    assert.deepEqual(detectManifestAndFrameworks(root, ["requirements/base.txt"]).manifest.dependencies, []);
+  });
+
+  test("package.json wins the name when both manifests exist", () => {
+    const root = makeRepo({
+      "package.json": JSON.stringify({ name: "js-name" }),
+      "pyproject.toml": '[project]\nname = "py-name"\n',
+    });
+    const { manifest } = detectManifestAndFrameworks(root, ["package.json", "pyproject.toml"]);
+    assert.equal(manifest.name, "js-name");
+  });
+});
+
+describe("detectEntryPoints", () => {
+  test("resolves package.json main / module / bin targets", () => {
+    const root = makeRepo({
+      "package.json": JSON.stringify({
+        main: "./bin/tool.js",
+        bin: { tool: "bin/other.js" },
+      }),
+      "bin/tool.js": "",
+      "bin/other.js": "",
+    });
+    const { entryPoints } = detectEntryPoints(root, ["package.json", "bin/other.js", "bin/tool.js"]);
+    assert.deepEqual(entryPoints, ["bin/other.js", "bin/tool.js"]);
+  });
+
+  test("ignores manifest targets that do not exist (e.g. unbuilt dist/)", () => {
+    const root = makeRepo({ "package.json": JSON.stringify({ main: "dist/index.js" }) });
+    assert.deepEqual(detectEntryPoints(root, ["package.json"]).entryPoints, []);
+  });
+
+  test("recognizes well-known entry filenames anywhere in the tree", () => {
+    const root = makeRepo({ "src/index.ts": "", "app/server.js": "", "lib/helper.ts": "" });
+    const { entryPoints } = detectEntryPoints(root, ["app/server.js", "lib/helper.ts", "src/index.ts"]);
+    assert.deepEqual(entryPoints, ["app/server.js", "src/index.ts"]);
+  });
+
+  test("detects a Python __main__ guard", () => {
+    const root = makeRepo({
+      "job.py": 'def go():\n    pass\n\nif __name__ == "__main__":\n    go()\n',
+      "helpers.py": "def helper():\n    pass\n",
+    });
+    assert.deepEqual(detectEntryPoints(root, ["helpers.py", "job.py"]).entryPoints, ["job.py"]);
+  });
+
+  test("returns a sorted, de-duplicated list", () => {
+    const root = makeRepo({
+      "package.json": JSON.stringify({ main: "main.py" }),
+      "main.py": 'if __name__ == "__main__":\n    pass\n',
+    });
+    // main.py qualifies three ways (manifest main, known basename, __main__ guard).
+    assert.deepEqual(detectEntryPoints(root, ["main.py", "package.json"]).entryPoints, ["main.py"]);
+  });
+});
diff --git a/test/dot.test.ts b/test/dot.test.ts
new file mode 100644
index 0000000..5d73153
--- /dev/null
+++ b/test/dot.test.ts
@@ -0,0 +1,158 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { renderDot } from "../src/lib/dot.js";
+import { runGenerateDiagram } from "../src/tools/generateDiagram.js";
+import type { ImportEdge, RenderOptions } from "../src/types.js";
+import { makeCodeRepo } from "./helpers/fixture.js";
+
+const e = (from: string, to: string): ImportEdge => ({ from, to });
+
+const opts = (overrides: Partial<RenderOptions> = {}): RenderOptions => ({
+  repoName: "demo",
+  level: "high",
+  codeFiles: ["src/lib/a.ts", "src/lib/b.ts", "src/tools/t.ts"],
+  edges: [e("src/tools/t.ts", "src/lib/a.ts")],
+  ...overrides,
+});
+
+describe("renderDot — high level", () => {
+  test("emits a styled digraph with one node per module", () => {
+    assert.equal(
+      renderDot(opts()),
+      [
+        'digraph "demo" {',
+        "    // demo — high-level architecture (DRAFT, refine me)",
+        "    rankdir=TB;",
+        '    node [shape=box, style="rounded,filled", fontname="Helvetica,Arial,sans-serif", fillcolor="#eef1f4", color="#8b949e", fontcolor="#1f2328"];',
+        '    edge [color="#57606a"];',
+        '    "src/lib" [label="src/lib\\nlibrary code\\n2 files", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];',
+        '    "src/tools" [label="src/tools\\ntool implementations\\n1 file", fillcolor="#79706e", fontcolor="#ffffff", color="#5d5654"];',
+        '    "src/tools" -> "src/lib";',
+        "}",
+      ].join("\n"),
+    );
+  });
+
+  test("uncategorized modules keep the neutral default style", () => {
+    const dot = renderDot(opts({ codeFiles: ["widgets/a.ts"], edges: [] }));
+    assert.ok(dot.includes('"widgets" [label="widgets\\n1 file"];'), dot);
+    assert.ok(!dot.includes('"widgets" [label="widgets\\n1 file", fillcolor'), dot);
+  });
+
+  test("drops edges to modules that are not nodes (DOT would auto-create them)", () => {
+    const dot = renderDot(opts({ edges: [e("src/tools/t.ts", "ghost/x.ts")] }));
+    assert.ok(!dot.includes("ghost"), dot);
+  });
+
+  test("escapes quotes and backslashes in the repo name", () => {
+    const dot = renderDot(opts({ repoName: 'my"repo\\v1', codeFiles: [], edges: [] }));
+    assert.ok(dot.startsWith('digraph "my\\"repo\\\\v1" {'), dot);
+  });
+
+  test("label line breaks are a single \\n escape, never double-escaped", () => {
+    // Regression: escaping after joining turned '\n' into '\\n', which Graphviz
+    // renders as literal text instead of a line break.
+    const dot = renderDot(opts());
+    assert.ok(dot.includes("src/lib\\nlibrary code"), dot);
+    assert.ok(!dot.includes("\\\\n"), dot);
+  });
+
+  test("is stable when the input ordering changes", () => {
+    const base = opts({
+      codeFiles: ["src/a/x.ts", "src/b/y.ts", "src/c/z.ts"],
+      edges: [e("src/c/z.ts", "src/a/x.ts"), e("src/a/x.ts", "src/b/y.ts")],
+    });
+    const shuffled: RenderOptions = {
+      ...base,
+      codeFiles: [...base.codeFiles].reverse(),
+      edges: [...base.edges].reverse(),
+    };
+    assert.equal(renderDot(shuffled), renderDot(base));
+  });
+
+  test("an empty repo still produces a well-formed digraph", () => {
+    const dot = renderDot(opts({ codeFiles: [], edges: [] }));
+    assert.ok(dot.startsWith('digraph "demo" {'));
+    assert.ok(dot.endsWith("}"));
+  });
+});
+
+describe("renderDot — detail level", () => {
+  test("groups file nodes into per-module clusters with role-colored borders", () => {
+    const dot = renderDot(opts({ level: "detail" }));
+    assert.equal(
+      dot,
+      [
+        'digraph "demo" {',
+        "    // demo — detail-level architecture (DRAFT, refine me)",
+        "    rankdir=TB;",
+        '    node [shape=box, style="rounded,filled", fontname="Helvetica,Arial,sans-serif", fillcolor="#eef1f4", color="#8b949e", fontcolor="#1f2328"];',
+        '    edge [color="#57606a"];',
+        "    subgraph cluster_0 {",
+        '        label="src/lib";',
+        '        color="#5d5654";',
+        '        "src/lib/a.ts" [label="a.ts"];',
+        '        "src/lib/b.ts" [label="b.ts"];',
+        "    }",
+        "    subgraph cluster_1 {",
+        '        label="src/tools";',
+        '        color="#5d5654";',
+        '        "src/tools/t.ts" [label="t.ts"];',
+        "    }",
+        '    "src/tools/t.ts" -> "src/lib/a.ts";',
+        "}",
+      ].join("\n"),
+    );
+  });
+
+  test("braces stay balanced", () => {
+    const dot = renderDot(opts({ level: "detail" }));
+    assert.equal((dot.match(/{/g) ?? []).length, (dot.match(/}/g) ?? []).length);
+  });
+
+  test("keeps file-level edges and drops dangling ones", () => {
+    const dot = renderDot(
+      opts({
+        level: "detail",
+        edges: [e("src/lib/a.ts", "src/lib/b.ts"), e("src/lib/a.ts", "missing.ts")],
+      }),
+    );
+    assert.ok(dot.includes('"src/lib/a.ts" -> "src/lib/b.ts";'), dot);
+    assert.ok(!dot.includes("missing.ts"), dot);
+  });
+});
+
+describe("runGenerateDiagram — format plumbing", () => {
+  test("emits Mermaid by default and DOT on request, from the same facts", () => {
+    const { root } = makeCodeRepo({
+      "src/ui/page.ts": `import "../db/query.js";\n`,
+      "src/db/query.ts": "export const q = 1;\n",
+    });
+
+    const mermaid = runGenerateDiagram(root, "high");
+    const dot = runGenerateDiagram(root, "high", "dot");
+
+    assert.ok(mermaid.startsWith("flowchart TD"), mermaid);
+    assert.ok(dot.startsWith("digraph "), dot);
+    // Same module edge in both notations.
+    assert.ok(mermaid.includes("n1 --> n0"), mermaid);
+    assert.ok(dot.includes('"src/ui" -> "src/db";'), dot);
+  });
+
+  test("descends past a zip wrapper folder, so modules do not collapse into one", () => {
+    // GitHub's "Download ZIP" wraps the repo in <name>-main/. Without the
+    // descent this repo maps as a single module with zero high-level edges.
+    const { root } = makeCodeRepo({
+      "repo-main/src/ui/page.ts": `import "../db/query.js";\n`,
+      "repo-main/src/db/query.ts": "export const q = 1;\n",
+    });
+
+    const mermaid = runGenerateDiagram(root, "high");
+
+    assert.ok(mermaid.includes("n1 --> n0"), mermaid); // src/ui -> src/db survived
+    // The title may carry the wrapper's name (it IS the repo name in a GitHub
+    // zip), but module keys must be relative to the descended root.
+    assert.ok(!mermaid.includes("repo-main/"), mermaid);
+    assert.ok(mermaid.includes('"src/ui · UI layer · 1 file"'), mermaid);
+  });
+});
diff --git a/test/glob.test.ts b/test/glob.test.ts
new file mode 100644
index 0000000..ba011c8
--- /dev/null
+++ b/test/glob.test.ts
@@ -0,0 +1,60 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { matchGlob } from "../src/lib/glob.js";
+
+describe("matchGlob", () => {
+  test("'**' crosses directory separators", () => {
+    assert.equal(matchGlob("src/ui/**", "src/ui/a.ts"), true);
+    assert.equal(matchGlob("src/ui/**", "src/ui/deep/nested/b.ts"), true);
+    assert.equal(matchGlob("**", "anything/at/all.ts"), true);
+  });
+
+  test("'dir/**' matches things inside dir, not dir itself", () => {
+    assert.equal(matchGlob("src/ui/**", "src/ui"), false);
+  });
+
+  test("'**' does not match a sibling with a longer name", () => {
+    assert.equal(matchGlob("src/ui/**", "src/uix/a.ts"), false);
+  });
+
+  test("'**/' matches zero or more leading segments", () => {
+    assert.equal(matchGlob("**/config.ts", "config.ts"), true);
+    assert.equal(matchGlob("**/config.ts", "src/config.ts"), true);
+    assert.equal(matchGlob("**/config.ts", "src/deep/config.ts"), true);
+    assert.equal(matchGlob("**/config.ts", "myconfig.ts"), false);
+  });
+
+  test("'*' stops at a directory separator", () => {
+    assert.equal(matchGlob("src/*.ts", "src/a.ts"), true);
+    assert.equal(matchGlob("src/*.ts", "src/deep/a.ts"), false);
+    assert.equal(matchGlob("src/*/index.ts", "src/lib/index.ts"), true);
+    assert.equal(matchGlob("src/*/index.ts", "src/lib/deep/index.ts"), false);
+  });
+
+  test("'?' matches exactly one non-separator character", () => {
+    assert.equal(matchGlob("src/?.ts", "src/a.ts"), true);
+    assert.equal(matchGlob("src/?.ts", "src/ab.ts"), false);
+    assert.equal(matchGlob("src/?.ts", "src//.ts"), false);
+  });
+
+  test("the whole path must match, not just a prefix", () => {
+    assert.equal(matchGlob("src/a.ts", "src/a.ts"), true);
+    assert.equal(matchGlob("src/a.ts", "src/a.ts.map"), false);
+    assert.equal(matchGlob("src/a.ts", "vendor/src/a.ts"), false);
+  });
+
+  test("regex metacharacters are treated literally", () => {
+    // A '.' must not behave as "any character".
+    assert.equal(matchGlob("src/a.b.ts", "src/aXbYts"), false);
+    assert.equal(matchGlob("src/a.b.ts", "src/a.b.ts"), true);
+
+    for (const ch of ["+", "(", ")", "[", "]", "{", "}", "^", "$", "|"]) {
+      const path = `src/a${ch}b.ts`;
+      assert.equal(matchGlob(path, path), true, `literal ${ch}`);
+    }
+  });
+
+  test("matching is case-sensitive", () => {
+    assert.equal(matchGlob("src/**", "SRC/a.ts"), false);
+  });
+});
diff --git a/test/helpers/fixture.ts b/test/helpers/fixture.ts
new file mode 100644
index 0000000..92bd71b
--- /dev/null
+++ b/test/helpers/fixture.ts
@@ -0,0 +1,50 @@
+/**
+ * Throwaway on-disk repos for tests.
+ *
+ * Several units (import extraction, walking, manifest detection, `runCheck`)
+ * read real files, so they need a real directory. Each fixture gets its own
+ * `mkdtemp` directory and everything is removed when the process exits.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { isCodeFile } from "../../src/lib/paths.js";
+
+const created: string[] = [];
+
+process.on("exit", () => {
+  for (const dir of created) {
+    try {
+      rmSync(dir, { recursive: true, force: true });
+    } catch {
+      /* best effort — the OS temp dir gets cleaned eventually */
+    }
+  }
+});
+
+/**
+ * Materialize a repo from a `{ "rel/path": contents }` map and return its
+ * absolute root. Parent directories are created automatically; pass `{}` for an
+ * empty directory.
+ */
+export function makeRepo(files: Record<string, string>): string {
+  const root = mkdtempSync(join(tmpdir(), "repo-carto-"));
+  created.push(root);
+  for (const [rel, contents] of Object.entries(files)) {
+    const abs = join(root, rel);
+    mkdirSync(dirname(abs), { recursive: true });
+    writeFileSync(abs, contents, "utf8");
+  }
+  return root;
+}
+
+/**
+ * Like {@link makeRepo}, but also returns the sorted repo-relative code files —
+ * the exact shape `extractImports` expects from a walk.
+ */
+export function makeCodeRepo(files: Record<string, string>): { root: string; codeFiles: string[] } {
+  return {
+    root: makeRepo(files),
+    codeFiles: Object.keys(files).filter(isCodeFile).sort(),
+  };
+}
diff --git a/test/imports.test.ts b/test/imports.test.ts
new file mode 100644
index 0000000..9089be7
--- /dev/null
+++ b/test/imports.test.ts
@@ -0,0 +1,197 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { collapseToModules, extractImports } from "../src/lib/imports.js";
+import type { ImportEdge } from "../src/types.js";
+import { makeCodeRepo } from "./helpers/fixture.js";
+
+const e = (from: string, to: string): ImportEdge => ({ from, to });
+
+/** A NUL byte in the first 4 KB is what marks a file as binary. */
+const NUL = String.fromCharCode(0);
+
+describe("extractImports — JavaScript / TypeScript", () => {
+  test("resolves every supported import form to intra-repo edges", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "index.ts": `import { a } from "./src/a.js";\nimport fs from "node:fs";\n`,
+      "src/a.ts": `export { b } from "./b.js";\n`,
+      "src/b.ts": `const c = require("./sub");\nimport("./b.js");\n`,
+      "src/sub/index.ts": `import "../../index.js";\n`,
+    });
+
+    const result = extractImports(root, codeFiles);
+
+    assert.deepEqual(result.edges, [
+      e("index.ts", "src/a.ts"), //          import ... from
+      e("src/a.ts", "src/b.ts"), //          export ... from
+      e("src/b.ts", "src/sub/index.ts"), //  require() -> directory index
+      e("src/sub/index.ts", "index.ts"), //  bare side-effect import, ../.. resolution
+    ]);
+    assert.equal(result.filesScanned, 4);
+    assert.equal(result.externalImports, 1); // node:fs
+  });
+
+  test("rewrites a '.js' specifier onto the '.ts' file that produces it", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "a.ts": `import "./b.js";\n`,
+      "b.ts": "export const b = 1;\n",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [e("a.ts", "b.ts")]);
+  });
+
+  test("resolves an extensionless specifier and a directory index", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "a.ts": `import "./b";\nimport "./dir";\n`,
+      "b.tsx": "export const b = 1;\n",
+      "dir/index.js": "module.exports = {};\n",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [e("a.ts", "b.tsx"), e("a.ts", "dir/index.js")]);
+  });
+
+  test("counts bare and repo-escaping specifiers as external instead of edging them", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "a.ts": `import "react";\nimport "@scope/pkg";\nimport "../outside.js";\nimport "./missing.js";\n`,
+    });
+    const result = extractImports(root, codeFiles);
+    assert.deepEqual(result.edges, []);
+    assert.equal(result.externalImports, 4);
+  });
+
+  test("ignores self-imports", () => {
+    const { root, codeFiles } = makeCodeRepo({ "a.ts": `import "./a.js";\n` });
+    const result = extractImports(root, codeFiles);
+    assert.deepEqual(result.edges, []);
+    assert.equal(result.externalImports, 0);
+  });
+
+  test("de-duplicates repeated edges between the same pair", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "a.ts": `import { x } from "./b.js";\nimport { y } from "./b.js";\nconst z = require("./b");\n`,
+      "b.ts": "export const x = 1, y = 2;\n",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [e("a.ts", "b.ts")]);
+  });
+
+  test("skips binary and missing files without crashing", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "a.ts": `import "./b.js";\n`,
+      "b.ts": "export const b = 1;\n",
+      "blob.js": `${NUL}${NUL}import "./a.js";`,
+    });
+
+    const result = extractImports(root, [...codeFiles, "deleted.ts"]);
+
+    assert.equal(result.filesScanned, 2); // blob.js is binary, deleted.ts does not exist
+    assert.deepEqual(result.edges, [e("a.ts", "b.ts")]);
+  });
+});
+
+describe("extractImports — Python", () => {
+  test("resolves absolute, relative and package imports", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "main.py": "import pkg.mod\nfrom pkg import helper\nimport os\n",
+      "pkg/__init__.py": "from .mod import thing\n",
+      "pkg/mod.py": "from . import util\nfrom ..main import go\n",
+      "pkg/util.py": "",
+    });
+
+    const result = extractImports(root, codeFiles);
+
+    assert.deepEqual(result.edges, [
+      e("main.py", "pkg/__init__.py"), //    from pkg import helper -> package __init__
+      e("main.py", "pkg/mod.py"), //         import pkg.mod
+      e("pkg/__init__.py", "pkg/mod.py"), // from .mod import thing
+      e("pkg/mod.py", "main.py"), //         from ..main import go
+      e("pkg/mod.py", "pkg/util.py"), //     from . import util
+    ]);
+    assert.equal(result.externalImports, 1); // os
+    assert.equal(result.filesScanned, 4);
+  });
+
+  test("'from . import a, b' edges to each sibling submodule", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "pkg/__init__.py": "",
+      "pkg/mod.py": "from . import alpha, beta as b\n",
+      "pkg/alpha.py": "",
+      "pkg/beta.py": "",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [
+      e("pkg/mod.py", "pkg/alpha.py"),
+      e("pkg/mod.py", "pkg/beta.py"),
+    ]);
+  });
+
+  test("handles multiple modules on one import line", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "main.py": "import alpha, beta, json\n",
+      "alpha.py": "",
+      "beta.py": "",
+    });
+    const result = extractImports(root, codeFiles);
+    assert.deepEqual(result.edges, [e("main.py", "alpha.py"), e("main.py", "beta.py")]);
+    assert.equal(result.externalImports, 1); // json
+  });
+
+  test("ignores commented-out imports", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "main.py": "# import secret\n  # from . import secret\nimport real\n",
+      "real.py": "",
+      "secret.py": "",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [e("main.py", "real.py")]);
+  });
+
+  test("resolves a .pyi stub", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "main.py": "import stub\n",
+      "stub.pyi": "",
+    });
+    assert.deepEqual(extractImports(root, codeFiles).edges, [e("main.py", "stub.pyi")]);
+  });
+});
+
+describe("extractImports — determinism", () => {
+  test("edges are sorted and stable across runs and input orderings", () => {
+    const { root, codeFiles } = makeCodeRepo({
+      "z.ts": `import "./m.js";\n`,
+      "m.ts": `import "./a.js";\n`,
+      "a.ts": `import "./z.js";\n`,
+    });
+
+    const first = extractImports(root, codeFiles);
+    const second = extractImports(root, [...codeFiles].reverse());
+
+    assert.deepEqual(first.edges, [e("a.ts", "z.ts"), e("m.ts", "a.ts"), e("z.ts", "m.ts")]);
+    assert.deepEqual(second.edges, first.edges);
+  });
+});
+
+describe("collapseToModules", () => {
+  test("drops intra-module edges and de-duplicates the rest", () => {
+    const codeFiles = ["index.ts", "src/lib/a.ts", "src/lib/b.ts", "src/tools/t.ts", "src/tools/u.ts"];
+    const edges = [
+      e("src/lib/a.ts", "src/lib/b.ts"), //  intra-module -> dropped
+      e("src/tools/t.ts", "src/lib/a.ts"),
+      e("src/tools/u.ts", "src/lib/b.ts"), // collapses onto the same module edge
+      e("index.ts", "src/tools/t.ts"),
+    ];
+
+    assert.deepEqual(collapseToModules(codeFiles, edges), {
+      nodes: ["(root)", "src/lib", "src/tools"],
+      edges: [e("(root)", "src/tools"), e("src/tools", "src/lib")],
+    });
+  });
+
+  test("lists modules that have no edges", () => {
+    const { nodes } = collapseToModules(["src/lib/a.ts", "docs/x.ts"], []);
+    assert.deepEqual(nodes, ["docs", "src/lib"]);
+  });
+
+  test("is stable regardless of input ordering", () => {
+    const codeFiles = ["src/a/x.ts", "src/b/y.ts", "src/c/z.ts"];
+    const edges = [e("src/c/z.ts", "src/a/x.ts"), e("src/a/x.ts", "src/b/y.ts")];
+    assert.deepEqual(
+      collapseToModules([...codeFiles].reverse(), [...edges].reverse()),
+      collapseToModules(codeFiles, edges),
+    );
+  });
+});
diff --git a/test/mermaid.test.ts b/test/mermaid.test.ts
new file mode 100644
index 0000000..a23fb9b
--- /dev/null
+++ b/test/mermaid.test.ts
@@ -0,0 +1,139 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { renderFlowchart, type RenderOptions } from "../src/lib/mermaid.js";
+import type { ImportEdge } from "../src/types.js";
+
+const e = (from: string, to: string): ImportEdge => ({ from, to });
+
+const opts = (overrides: Partial<RenderOptions> = {}): RenderOptions => ({
+  repoName: "demo",
+  level: "high",
+  codeFiles: ["src/lib/a.ts", "src/lib/b.ts", "src/tools/t.ts"],
+  edges: [e("src/tools/t.ts", "src/lib/a.ts")],
+  ...overrides,
+});
+
+describe("renderFlowchart — high level", () => {
+  test("emits one node per module with a role hint, file count and role styling", () => {
+    assert.equal(
+      renderFlowchart(opts()),
+      [
+        "flowchart TD",
+        "    %% demo — high-level architecture (DRAFT, refine me)",
+        '    n0["src/lib · library code · 2 files"]',
+        '    n1["src/tools · tool implementations · 1 file"]',
+        "    n1 --> n0",
+        "    class n0,n1 shared",
+        "    classDef shared fill:#79706e,color:#ffffff,stroke:#5d5654",
+      ].join("\n"),
+    );
+  });
+
+  test("omits the role placeholder and styling for directories with no hint", () => {
+    const mermaid = renderFlowchart(opts({ codeFiles: ["widgets/a.ts"], edges: [] }));
+    assert.ok(mermaid.includes('n0["widgets · 1 file"]'), mermaid);
+    assert.ok(!mermaid.includes("model to infer"), mermaid);
+    assert.ok(!mermaid.includes("classDef"), mermaid);
+  });
+
+  test("emits a classDef only for categories actually present", () => {
+    const mermaid = renderFlowchart(
+      opts({ codeFiles: ["src/ui/a.ts", "src/db/b.ts", "widgets/c.ts"], edges: [] }),
+    );
+    // Sorted nodes: n0=src/db (data), n1=src/ui (ui), n2=widgets (uncategorized).
+    assert.ok(mermaid.includes(" class n0 data"), mermaid);
+    assert.ok(mermaid.includes(" class n1 ui"), mermaid);
+    assert.equal((mermaid.match(/classDef /g) ?? []).length, 2);
+    // Every class statement references a defined classDef.
+    for (const m of mermaid.matchAll(/class n\d+(?:,n\d+)* (\w+)/g)) {
+      assert.ok(mermaid.includes(`classDef ${m[1]} `), `classDef missing for ${m[1]}`);
+    }
+  });
+
+  test("drops edges whose endpoints collapse into the same module", () => {
+    const mermaid = renderFlowchart(
+      opts({ codeFiles: ["src/lib/a.ts", "src/lib/b.ts"], edges: [e("src/lib/a.ts", "src/lib/b.ts")] }),
+    );
+    assert.ok(!mermaid.includes("-->"), mermaid);
+  });
+
+  test("class statements never appear at detail level", () => {
+    const mermaid = renderFlowchart(opts({ level: "detail" }));
+    assert.ok(!mermaid.includes("classDef"), mermaid);
+  });
+
+  test("is stable when the input ordering changes", () => {
+    const base = opts({
+      codeFiles: ["src/a/x.ts", "src/b/y.ts", "src/c/z.ts"],
+      edges: [e("src/c/z.ts", "src/a/x.ts"), e("src/a/x.ts", "src/b/y.ts")],
+    });
+    const shuffled: RenderOptions = {
+      ...base,
+      codeFiles: [...base.codeFiles].reverse(),
+      edges: [...base.edges].reverse(),
+    };
+    assert.equal(renderFlowchart(shuffled), renderFlowchart(base));
+  });
+});
+
+describe("renderFlowchart — detail level", () => {
+  test("groups file nodes into balanced per-module subgraphs", () => {
+    assert.equal(
+      renderFlowchart(opts({ level: "detail" })),
+      [
+        "flowchart TD",
+        "    %% demo — detail-level architecture (DRAFT, refine me)",
+        '    subgraph g0["src/lib"]',
+        '        n0["a.ts"]',
+        '        n1["b.ts"]',
+        "    end",
+        '    subgraph g1["src/tools"]',
+        '        n2["t.ts"]',
+        "    end",
+        "    n2 --> n0",
+      ].join("\n"),
+    );
+  });
+
+  test("every subgraph is closed", () => {
+    const mermaid = renderFlowchart(opts({ level: "detail" }));
+    const opens = mermaid.split("\n").filter((l) => l.trim().startsWith("subgraph")).length;
+    const closes = mermaid.split("\n").filter((l) => l.trim() === "end").length;
+    assert.equal(opens, closes);
+  });
+
+  test("keeps file-level edges instead of collapsing them", () => {
+    const mermaid = renderFlowchart(
+      opts({ level: "detail", codeFiles: ["src/lib/a.ts", "src/lib/b.ts"], edges: [e("src/lib/a.ts", "src/lib/b.ts")] }),
+    );
+    assert.ok(mermaid.includes("n0 --> n1"), mermaid);
+  });
+});
+
+describe("renderFlowchart — label safety", () => {
+  test("strips characters that would break a Mermaid label", () => {
+    const mermaid = renderFlowchart(opts({ repoName: 'my"repo"\n[weird]{x}|y<z>' }));
+    assert.equal(mermaid.split("\n")[1], "    %% my'repo' weirdxyz — high-level architecture (DRAFT, refine me)");
+  });
+
+  test("every node label stays on a single line with balanced quotes", () => {
+    const mermaid = renderFlowchart(opts({ repoName: "a\nb" }));
+    for (const line of mermaid.split("\n")) {
+      assert.equal((line.match(/"/g) ?? []).length % 2, 0, line);
+    }
+  });
+});
+
+describe("renderFlowchart — common shape", () => {
+  test("both levels start with a flowchart declaration", () => {
+    assert.ok(renderFlowchart(opts({ level: "high" })).startsWith("flowchart TD\n"));
+    assert.ok(renderFlowchart(opts({ level: "detail" })).startsWith("flowchart TD\n"));
+  });
+
+  test("an empty repo still produces a valid header", () => {
+    assert.equal(
+      renderFlowchart(opts({ codeFiles: [], edges: [] })),
+      ["flowchart TD", "    %% demo — high-level architecture (DRAFT, refine me)"].join("\n"),
+    );
+  });
+});
diff --git a/test/paths.test.ts b/test/paths.test.ts
new file mode 100644
index 0000000..6a2aeb0
--- /dev/null
+++ b/test/paths.test.ts
@@ -0,0 +1,110 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import {
+  basename,
+  extname,
+  isCodeFile,
+  joinPosix,
+  moduleKey,
+  posixDirname,
+  posixNormalize,
+  stripCodeExt,
+} from "../src/lib/paths.js";
+
+describe("extname", () => {
+  test("returns a lowercased extension", () => {
+    assert.equal(extname("src/a.ts"), ".ts");
+    assert.equal(extname("SRC/A.TS"), ".ts");
+  });
+
+  test("returns '' when the only dot is in a directory name", () => {
+    assert.equal(extname("my.dir/file"), "");
+    assert.equal(extname("file"), "");
+  });
+
+  test("dotfiles have no usable extension for our purposes", () => {
+    // extname(".gitignore") technically returns the whole name, but the only
+    // consumer is isCodeFile, which rejects it — pin that behaviour.
+    assert.equal(isCodeFile(".gitignore"), false);
+    assert.equal(extname("src/.env"), ".env");
+  });
+});
+
+describe("posixNormalize", () => {
+  test("drops '.' and empty segments", () => {
+    assert.equal(posixNormalize("a/./b"), "a/b");
+    assert.equal(posixNormalize("/a//b"), "a/b");
+    assert.equal(posixNormalize(""), "");
+  });
+
+  test("resolves '..' against earlier segments", () => {
+    assert.equal(posixNormalize("a/b/../c"), "a/c");
+    assert.equal(posixNormalize("a/b/c/../../d"), "a/d");
+  });
+
+  test("keeps leading '..' so callers can detect escapes above the repo root", () => {
+    assert.equal(posixNormalize("../a"), "../a");
+    assert.equal(posixNormalize("a/../../b"), "../b");
+  });
+});
+
+describe("posixDirname / joinPosix / basename", () => {
+  test("posixDirname returns '' at the root", () => {
+    assert.equal(posixDirname("a/b/c.ts"), "a/b");
+    assert.equal(posixDirname("c.ts"), "");
+  });
+
+  test("joinPosix skips the separator when either side is empty", () => {
+    assert.equal(joinPosix("a", "b"), "a/b");
+    assert.equal(joinPosix("", "b"), "b");
+    assert.equal(joinPosix("a", ""), "a");
+  });
+
+  test("basename takes the last segment", () => {
+    assert.equal(basename("a/b/c.ts"), "c.ts");
+    assert.equal(basename("c.ts"), "c.ts");
+  });
+});
+
+describe("stripCodeExt", () => {
+  test("strips JS/TS extensions only", () => {
+    assert.equal(stripCodeExt("a/b.js"), "a/b");
+    assert.equal(stripCodeExt("a/b.tsx"), "a/b");
+    assert.equal(stripCodeExt("a/b.py"), "a/b.py"); // Python resolution appends, never strips
+    assert.equal(stripCodeExt("a/b"), "a/b");
+  });
+});
+
+describe("isCodeFile", () => {
+  test("accepts the v1 language set and rejects everything else", () => {
+    for (const f of ["a.ts", "a.tsx", "a.mts", "a.cts", "a.js", "a.jsx", "a.mjs", "a.cjs", "a.py", "a.pyi"]) {
+      assert.equal(isCodeFile(f), true, f);
+    }
+    for (const f of ["a.md", "a.json", "a.go", "a.css", "Makefile"]) {
+      assert.equal(isCodeFile(f), false, f);
+    }
+  });
+});
+
+describe("moduleKey", () => {
+  test("root-level files collapse to (root)", () => {
+    assert.equal(moduleKey("README.md"), "(root)");
+    assert.equal(moduleKey("index.ts"), "(root)");
+  });
+
+  test("container directories key one level deeper", () => {
+    assert.equal(moduleKey("src/lib/paths.ts"), "src/lib");
+    assert.equal(moduleKey("src/lib/deep/nested.ts"), "src/lib");
+    assert.equal(moduleKey("packages/core/src/x.ts"), "packages/core");
+  });
+
+  test("non-container directories key at the top level", () => {
+    assert.equal(moduleKey("docs/guide/intro.md"), "docs");
+    assert.equal(moduleKey("test/helpers/fixture.ts"), "test");
+  });
+
+  test("a file directly inside a container keys to the container itself", () => {
+    // "src/index.ts" has no second directory level to descend into.
+    assert.equal(moduleKey("src/index.ts"), "src");
+  });
+});
diff --git a/test/renderDiagram.test.ts b/test/renderDiagram.test.ts
new file mode 100644
index 0000000..4f918a2
--- /dev/null
+++ b/test/renderDiagram.test.ts
@@ -0,0 +1,124 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, readFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { runRenderDiagram } from "../src/tools/renderDiagram.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+const MERMAID = 'flowchart TD\n    n0["src/lib · library code · 2 files"]\n    n0 --> n0\n';
+const DOT = 'digraph "demo" {\n    "src/tools" -> "src/lib";\n}\n';
+
+describe("runRenderDiagram — mermaid (default)", () => {
+  test("writes sibling .html and .mermaid files and returns absolute paths", () => {
+    const out = join(makeRepo({}), "docs", "architecture");
+    const result = runRenderDiagram(MERMAID, out);
+
+    assert.equal(result.htmlPath, resolve(`${out}.html`));
+    assert.equal(result.sourcePath, resolve(`${out}.mermaid`));
+    assert.equal(result.format, "mermaid");
+    assert.ok(existsSync(result.htmlPath));
+    assert.ok(existsSync(result.sourcePath));
+  });
+
+  test("creates missing parent directories", () => {
+    const out = join(makeRepo({}), "deeply", "nested", "arch");
+    assert.ok(existsSync(runRenderDiagram(MERMAID, out).htmlPath));
+  });
+
+  test("the source file is the diagram verbatim", () => {
+    const out = join(makeRepo({}), "arch");
+    assert.equal(readFileSync(runRenderDiagram(MERMAID, out).sourcePath, "utf8"), MERMAID);
+  });
+
+  test("strips a supplied .html/.mermaid/.dot extension instead of doubling it", () => {
+    const base = join(makeRepo({}), "arch");
+    for (const supplied of [`${base}.html`, `${base}.mermaid`, `${base}.dot`, `${base}.HTML`]) {
+      const result = runRenderDiagram(MERMAID, supplied);
+      assert.equal(result.htmlPath, resolve(`${base}.html`));
+      assert.equal(result.sourcePath, resolve(`${base}.mermaid`));
+    }
+  });
+
+  test("the HTML embeds the diagram and titles itself from the file name", () => {
+    const out = join(makeRepo({}), "my-repo");
+    const html = readFileSync(runRenderDiagram(MERMAID, out).htmlPath, "utf8");
+
+    assert.match(html, /^<!doctype html>/);
+    assert.match(html, /<title>my-repo — architecture<\/title>/);
+    assert.ok(html.includes('<pre class="mermaid">'));
+    assert.ok(html.includes("flowchart TD"));
+    assert.ok(html.includes("mermaid.esm.min.mjs"), "expected the Mermaid CDN renderer");
+    assert.ok(!html.includes("viz-standalone"), "mermaid page must not pull the Viz renderer");
+  });
+
+  test("escapes HTML-significant characters in the rendered source blocks", () => {
+    const out = join(makeRepo({}), "arch");
+    const html = readFileSync(runRenderDiagram("flowchart TD\n    a --> b\n    %% <b>&\n", out).htmlPath, "utf8");
+
+    assert.ok(html.includes("%% &lt;b&gt;&amp;"), "expected < > & to be entity-escaped");
+    // Mermaid arrows are escaped too, so "-->" never closes an HTML comment.
+    assert.ok(html.includes("a --&gt; b"));
+  });
+
+  test("a '</script>' in the diagram cannot break out of the inlined script block", () => {
+    const out = join(makeRepo({}), "arch");
+    const evil = "flowchart TD\n    %% </script><img src=x onerror=alert(1)>\n";
+    const html = readFileSync(runRenderDiagram(evil, out).htmlPath, "utf8");
+
+    // The payload is inlined as `const SRC = <json>` — a raw </script> there would
+    // close the block early and make the rest of the diagram live HTML.
+    assert.ok(!html.includes("</script><img"), "diagram text broke out of the script block");
+    assert.ok(html.includes("\\u003c/script>"), "expected '<' to be escaped in the JSON payload");
+  });
+});
+
+describe("runRenderDiagram — dot", () => {
+  test("writes .dot as the source sibling and reports the format", () => {
+    const out = join(makeRepo({}), "arch");
+    const result = runRenderDiagram(DOT, out, "dot");
+
+    assert.equal(result.htmlPath, resolve(`${out}.html`));
+    assert.equal(result.sourcePath, resolve(`${out}.dot`));
+    assert.equal(result.format, "dot");
+    assert.equal(readFileSync(result.sourcePath, "utf8"), DOT);
+  });
+
+  test("the HTML uses the Viz renderer, not Mermaid", () => {
+    const out = join(makeRepo({}), "arch");
+    const html = readFileSync(runRenderDiagram(DOT, out, "dot").htmlPath, "utf8");
+
+    assert.ok(html.includes("@viz-js/viz"), "expected the Viz CDN renderer");
+    assert.ok(html.includes('id="graph"'));
+    assert.ok(!html.includes('<pre class="mermaid">'), "dot page must not declare a mermaid block");
+    assert.ok(!html.includes("mermaid.esm.min.mjs"));
+    // The raw source is still viewable, escaped.
+    assert.ok(html.includes("digraph &quot;demo&quot;") || html.includes('digraph "demo"'));
+  });
+
+  test("a '</script>' in the DOT source cannot break out of the script block", () => {
+    const out = join(makeRepo({}), "arch");
+    const evil = 'digraph "x" {\n    a [label="</script><img src=x onerror=alert(1)>"];\n}\n';
+    const html = readFileSync(runRenderDiagram(evil, out, "dot").htmlPath, "utf8");
+
+    assert.ok(!html.includes("</script><img"), "diagram text broke out of the script block");
+    assert.ok(html.includes("\\u003c/script>"), "expected '<' to be escaped in the JSON payload");
+  });
+});
+
+describe("runRenderDiagram — error paths", () => {
+  test("refuses to render an empty diagram", () => {
+    const out = join(makeRepo({}), "arch");
+    assert.throws(() => runRenderDiagram("", out), /Refusing to render an empty diagram/);
+    assert.throws(() => runRenderDiagram("   \n ", out), /Refusing to render an empty diagram/);
+    assert.ok(!existsSync(`${out}.html`));
+  });
+
+  test("reports an unwritable output path as a clear error", () => {
+    // A path whose parent is an existing *file* cannot be created as a directory.
+    const root = makeRepo({ "blocker.txt": "" });
+    assert.throws(
+      () => runRenderDiagram(MERMAID, join(root, "blocker.txt", "arch")),
+      /Could not write diagram files/,
+    );
+  });
+});
diff --git a/test/roles.test.ts b/test/roles.test.ts
new file mode 100644
index 0000000..e34a92a
--- /dev/null
+++ b/test/roles.test.ts
@@ -0,0 +1,77 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { CATEGORY_STYLE, roleCategory, roleGuess } from "../src/lib/roles.js";
+
+describe("roleGuess", () => {
+  test("maps a known directory name to a hint", () => {
+    assert.equal(roleGuess("tools"), "tool implementations");
+    assert.equal(roleGuess("api"), "API layer");
+  });
+
+  test("uses only the last path segment of a module key", () => {
+    assert.equal(roleGuess("src/lib"), "library code");
+    assert.equal(roleGuess("packages/core/utils"), "utility helpers");
+  });
+
+  test("is case-insensitive", () => {
+    assert.equal(roleGuess("Components"), "UI components");
+    assert.equal(roleGuess("src/DB"), "database layer");
+  });
+
+  test("falls back to a placeholder the model is expected to replace", () => {
+    // The diagram renderer keys off this "(role" prefix to omit the placeholder.
+    assert.ok(roleGuess("widgets").startsWith("(role"));
+    assert.ok(roleGuess("(root)").startsWith("(role"));
+  });
+
+  test("singular and plural spellings agree", () => {
+    for (const [a, b] of [
+      ["strategy", "strategies"],
+      ["agent", "agents"],
+      ["service", "services"],
+      ["util", "utils"],
+      ["config", "configs"],
+    ]) {
+      assert.equal(roleGuess(a), roleGuess(b), `${a} vs ${b}`);
+    }
+  });
+});
+
+describe("roleCategory", () => {
+  test("maps directory names into visual families", () => {
+    assert.equal(roleCategory("src/ui"), "ui");
+    assert.equal(roleCategory("src/db"), "data");
+    assert.equal(roleCategory("api"), "api");
+    assert.equal(roleCategory("src/lib"), "shared");
+    assert.equal(roleCategory("__tests__"), "test");
+    assert.equal(roleCategory("scripts"), "infra");
+  });
+
+  test("uses the last segment, case-insensitively", () => {
+    assert.equal(roleCategory("packages/core/Components"), "ui");
+  });
+
+  test("returns null when there is no hint", () => {
+    assert.equal(roleCategory("widgets"), null);
+    assert.equal(roleCategory("(root)"), null);
+  });
+
+  test("every category used by roleCategory has a style", () => {
+    // Sample one key per family; a missing palette entry would break both emitters.
+    for (const key of ["ui", "api", "core", "data", "lib", "test", "docs", "config"]) {
+      const cat = roleCategory(key);
+      assert.ok(cat, `expected a category for '${key}'`);
+      const style = CATEGORY_STYLE[cat!];
+      assert.match(style.fill, /^#[0-9a-f]{6}$/i);
+      assert.match(style.stroke, /^#[0-9a-f]{6}$/i);
+    }
+  });
+
+  test("anything roleGuess knows, roleCategory also categorizes", () => {
+    // Keep the two tables in sync: a hint without a family would render unstyled.
+    for (const key of ["broker", "gateway", "monitoring", "migrations", "middleware", "resources", "spec", "bin"]) {
+      assert.ok(!roleGuess(key).startsWith("(role"), `roleGuess lost '${key}'`);
+      assert.notEqual(roleCategory(key), null, `roleCategory missing '${key}'`);
+    }
+  });
+});
diff --git a/test/rules.test.ts b/test/rules.test.ts
new file mode 100644
index 0000000..75f7b62
--- /dev/null
+++ b/test/rules.test.ts
@@ -0,0 +1,122 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { join } from "node:path";
+import { DEFAULT_RULES, findConfig, loadRules } from "../src/lib/rules.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+describe("findConfig", () => {
+  test("returns null when no config is present", () => {
+    assert.equal(findConfig(makeRepo({ "README.md": "" })), null);
+  });
+
+  test("prefers .yml over .yaml over .json", () => {
+    const all = makeRepo({
+      ".cartographer.yml": "rules: {}\n",
+      ".cartographer.yaml": "rules: {}\n",
+      ".cartographer.json": "{}",
+    });
+    assert.equal(findConfig(all), join(all, ".cartographer.yml"));
+
+    const noYml = makeRepo({ ".cartographer.yaml": "rules: {}\n", ".cartographer.json": "{}" });
+    assert.equal(findConfig(noYml), join(noYml, ".cartographer.yaml"));
+
+    const jsonOnly = makeRepo({ ".cartographer.json": "{}" });
+    assert.equal(findConfig(jsonOnly), join(jsonOnly, ".cartographer.json"));
+  });
+});
+
+describe("loadRules", () => {
+  test("parses a full YAML config", () => {
+    const root = makeRepo({
+      ".cartographer.yml": [
+        "rules:",
+        "  forbidden:",
+        '    - from: "src/ui/**"',
+        '      to: "src/db/**"',
+        '      reason: "no direct db access from the UI"',
+        '    - from: "a/**"',
+        '      to: "b/**"',
+        "      level: warn",
+        "  cycles: error",
+        "diagram:",
+        "  level: detail",
+        "  outPath: docs/arch",
+      ].join("\n"),
+    });
+
+    assert.deepEqual(loadRules(join(root, ".cartographer.yml")), {
+      forbidden: [
+        { from: "src/ui/**", to: "src/db/**", reason: "no direct db access from the UI", level: "error" },
+        { from: "a/**", to: "b/**", reason: "forbidden dependency", level: "warn" },
+      ],
+      cycles: "error",
+      diagram: { level: "detail", outPath: "docs/arch", format: "mermaid" },
+    });
+  });
+
+  test("parses an equivalent JSON config", () => {
+    const root = makeRepo({
+      ".cartographer.json": JSON.stringify({
+        rules: { forbidden: [{ from: "x/**", to: "y/**" }], cycles: "warn" },
+        diagram: { level: "high", outPath: "out/arch" },
+      }),
+    });
+
+    assert.deepEqual(loadRules(join(root, ".cartographer.json")), {
+      forbidden: [{ from: "x/**", to: "y/**", reason: "forbidden dependency", level: "error" }],
+      cycles: "warn",
+      diagram: { level: "high", outPath: "out/arch", format: "mermaid" },
+    });
+  });
+
+  test("fills in defaults for everything omitted", () => {
+    const root = makeRepo({ ".cartographer.yml": "rules: {}\n" });
+    assert.deepEqual(loadRules(join(root, ".cartographer.yml")), DEFAULT_RULES);
+  });
+
+  test("an unknown cycles severity falls back to the default", () => {
+    const root = makeRepo({ ".cartographer.yml": "rules:\n  cycles: loud\n" });
+    assert.equal(loadRules(join(root, ".cartographer.yml")).cycles, DEFAULT_RULES.cycles);
+  });
+
+  test("an unknown diagram level falls back to 'high'", () => {
+    const root = makeRepo({ ".cartographer.yml": "diagram:\n  level: extreme\n" });
+    assert.equal(loadRules(join(root, ".cartographer.yml")).diagram.level, "high");
+  });
+
+  test("parses diagram.format and falls back to 'mermaid' on unknown values", () => {
+    const dot = makeRepo({ ".cartographer.yml": "diagram:\n  format: dot\n" });
+    assert.equal(loadRules(join(dot, ".cartographer.yml")).diagram.format, "dot");
+
+    const unknown = makeRepo({ ".cartographer.yml": "diagram:\n  format: plantuml\n" });
+    assert.equal(loadRules(join(unknown, ".cartographer.yml")).diagram.format, "mermaid");
+  });
+
+  test("any level other than 'warn' is treated as an error", () => {
+    const root = makeRepo({
+      ".cartographer.yml": 'rules:\n  forbidden:\n    - from: "a"\n      to: "b"\n      level: nitpick\n',
+    });
+    assert.equal(loadRules(join(root, ".cartographer.yml")).forbidden[0].level, "error");
+  });
+
+  test("throws when a forbidden rule is missing 'from' or 'to'", () => {
+    const root = makeRepo({ ".cartographer.yml": 'rules:\n  forbidden:\n    - from: "a/**"\n' });
+    assert.throws(
+      () => loadRules(join(root, ".cartographer.yml")),
+      /rules\.forbidden\[0\] must have string 'from' and 'to'/,
+    );
+  });
+
+  test("throws on an empty or non-mapping config", () => {
+    const empty = makeRepo({ ".cartographer.yml": "" });
+    assert.throws(() => loadRules(join(empty, ".cartographer.yml")), /empty or not a mapping/);
+
+    const scalar = makeRepo({ ".cartographer.yml": "just-a-string\n" });
+    assert.throws(() => loadRules(join(scalar, ".cartographer.yml")), /empty or not a mapping/);
+  });
+
+  test("throws on malformed JSON", () => {
+    const root = makeRepo({ ".cartographer.json": "{ not json" });
+    assert.throws(() => loadRules(join(root, ".cartographer.json")));
+  });
+});
diff --git a/test/walk.test.ts b/test/walk.test.ts
new file mode 100644
index 0000000..645b340
--- /dev/null
+++ b/test/walk.test.ts
@@ -0,0 +1,139 @@
+import { describe, test } from "node:test";
+import assert from "node:assert/strict";
+import { join } from "node:path";
+import { descendPastWrapper, resolveRepoRoot, walk } from "../src/lib/walk.js";
+import { makeRepo } from "./helpers/fixture.js";
+
+describe("walk", () => {
+  test("returns sorted, posix-separated repo-relative paths", () => {
+    const root = makeRepo({
+      "src/deep/b.py": "",
+      "src/a.ts": "",
+      "README.md": "",
+    });
+    const result = walk(root);
+    assert.deepEqual(result.files, ["README.md", "src/a.ts", "src/deep/b.py"]);
+    assert.deepEqual(result.dirs, ["src", "src/deep"]);
+    assert.equal(result.truncated, false);
+  });
+
+  test("skips build, dependency and cache directories", () => {
+    const root = makeRepo({
+      "src/a.ts": "",
+      "node_modules/pkg/index.js": "",
+      "dist/a.js": "",
+      "build/a.js": "",
+      "out/a.js": "",
+      "coverage/a.js": "",
+      "vendor/a.js": "",
+      "venv/a.py": "",
+      "__pycache__/a.pyc": "",
+      "target/a.js": "",
+    });
+    const result = walk(root);
+    assert.deepEqual(result.files, ["src/a.ts"]);
+    assert.deepEqual(result.dirs, ["src"]);
+  });
+
+  test("skips hidden directories but keeps hidden files", () => {
+    const root = makeRepo({
+      ".git/config": "",
+      ".venv/lib/x.py": "",
+      ".gitignore": "node_modules/\n",
+      "src/a.ts": "",
+    });
+    const result = walk(root);
+    assert.deepEqual(result.files, [".gitignore", "src/a.ts"]);
+    assert.deepEqual(result.dirs, ["src"]);
+  });
+
+  test("excludes those directories at any depth, not just the root", () => {
+    const root = makeRepo({
+      "packages/app/src/a.ts": "",
+      "packages/app/node_modules/dep/index.js": "",
+      "packages/app/dist/a.js": "",
+    });
+    assert.deepEqual(walk(root).files, ["packages/app/src/a.ts"]);
+  });
+
+  test("an empty directory yields empty results", () => {
+    assert.deepEqual(walk(makeRepo({})), { files: [], dirs: [], truncated: false });
+  });
+
+  test("is deterministic across runs", () => {
+    const root = makeRepo({ "b.ts": "", "a.ts": "", "z/y/x.ts": "" });
+    assert.deepEqual(walk(root), walk(root));
+  });
+});
+
+describe("descendPastWrapper", () => {
+  test("steps past a zip-style wrapper folder (no files, one subdirectory)", () => {
+    const root = makeRepo({ "my-repo-main/src/a.ts": "", "my-repo-main/README.md": "" });
+    assert.deepEqual(descendPastWrapper(root), {
+      root: join(root, "my-repo-main"),
+      descended: ["my-repo-main"],
+    });
+  });
+
+  test("steps past nested wrappers, bounded", () => {
+    const root = makeRepo({ "outer/inner/src/a.ts": "" });
+    const result = descendPastWrapper(root);
+    assert.deepEqual(result.descended, ["outer", "inner"]);
+    assert.equal(result.root, join(root, "outer", "inner"));
+  });
+
+  test("does not descend when the directory has any file", () => {
+    const root = makeRepo({ "README.md": "", "src/a.ts": "" });
+    assert.deepEqual(descendPastWrapper(root), { root, descended: [] });
+  });
+
+  test("does not descend when there are two visible subdirectories", () => {
+    const root = makeRepo({ "a/x.ts": "", "b/y.ts": "" });
+    assert.deepEqual(descendPastWrapper(root), { root, descended: [] });
+  });
+
+  test("does not mistake a lone source container for a wrapper", () => {
+    // A repo whose root is just src/ (no README yet) must keep src-relative paths.
+    for (const container of ["src", "lib", "packages"]) {
+      const root = makeRepo({ [`${container}/a.ts`]: "" });
+      assert.deepEqual(descendPastWrapper(root), { root, descended: [] }, container);
+    }
+  });
+
+  test("stops at a container found inside a wrapper", () => {
+    const root = makeRepo({ "repo-main/src/a.ts": "" });
+    assert.deepEqual(descendPastWrapper(root), {
+      root: join(root, "repo-main"),
+      descended: ["repo-main"],
+    });
+  });
+
+  test("ignores hidden and excluded directories when deciding", () => {
+    // .git and node_modules alongside the wrapper must not block the descent.
+    const root = makeRepo({
+      "repo-main/src/a.ts": "",
+      ".git/config": "",
+      "node_modules/pkg/index.js": "",
+    });
+    assert.deepEqual(descendPastWrapper(root).descended, ["repo-main"]);
+  });
+});
+
+describe("resolveRepoRoot", () => {
+  test("returns the descended root with an explanatory note", () => {
+    const root = makeRepo({ "repo-main/src/a.ts": "" });
+    const result = resolveRepoRoot(root);
+    assert.equal(result.root, join(root, "repo-main"));
+    assert.equal(result.notes.length, 1);
+    assert.match(result.notes[0], /wrapper folder/);
+  });
+
+  test("is a no-op with no notes for a normal repo", () => {
+    const root = makeRepo({ "README.md": "", "src/a.ts": "" });
+    assert.deepEqual(resolveRepoRoot(root), { root, notes: [] });
+  });
+
+  test("still rejects a missing path with a clear error", () => {
+    assert.throws(() => resolveRepoRoot(join(makeRepo({}), "nope")), /Path does not exist/);
+  });
+});
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..b4972a4
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,15 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "lib": ["ES2022"],
+    "module": "Node16",
+    "moduleResolution": "Node16",
+    "types": ["node"],
+    "outDir": "dist",
+    "rootDir": "src",
+    "strict": true,
+    "esModuleInterop": true,
+    "skipLibCheck": true
+  },
+  "include": ["src"]
+}
\ No newline at end of file
diff --git a/tsconfig.test.json b/tsconfig.test.json
new file mode 100644
index 0000000..b4b234d
--- /dev/null
+++ b/tsconfig.test.json
@@ -0,0 +1,10 @@
+// Type-checks the tests alongside src without emitting. The build (tsconfig.json)
+// deliberately excludes test/ so nothing test-related ends up in dist/.
+{
+  "extends": "./tsconfig.json",
+  "compilerOptions": {
+    "noEmit": true,
+    "rootDir": "."
+  },
+  "include": ["src", "test"]
+}
