feat(visualize): add interactive HTML graph explorer; British-English doc sweep

Interactive Viewer (primary)
────────────────────────────
codebase_graph_visualize now accepts mode="mermaid" (default, existing
behaviour — text Mermaid diagram) or mode="interactive". Interactive
mode generates a self-contained HTML page and opens it in the user's
default browser via the `open` npm package (cross-platform: macOS,
Linux, Windows). Cytoscape.js 3.30.2 + Dagre 0.8.5 + cytoscape-dagre
2.5.0 are vendored under src/assets/ — no CDN, works offline.

Features:
- File view — every source file as a node, imports as edges, language
  colour-coded, circular deps highlighted in red.
- Symbol view toggle — functions/classes/methods as nodes with call
  edges (confidence-styled). Embedded when the symbol graph fits under
  20k symbols / 60k call edges; above that threshold the file view
  remains usable and a banner directs users to codebase_impact /
  codebase_symbols for symbol-level queries.
- Sidebar on node click — imports, dependents, per-file symbol list
  (first 30 + link to codebase_symbols), action buttons for blast
  radius and call flow.
- Right-click any node → blast radius overlay (reverse-transitive
  closure). Call-flow button on the sidebar for forward traversal.
- Live search across files and symbols, six Cytoscape layouts
  (Dagre / force / concentric / breadth-first / grid / circle),
  PNG export (filename sanitised for cross-platform safety).
- `open: false` parameter skips auto-launch and just returns the file
  path — useful in headless environments.

Viewer is XSS-safe by construction: all DOM built with createElement
+ textContent (no innerHTML anywhere); embedded JSON escapes every
"<" as \u003c so a stray </script> in a file path or symbol name
cannot break out of the script-type="application/json" container.

New files:
- src/assets/{cytoscape.min.js,dagre.min.js,cytoscape-dagre.js,
  viewer-template.html,viewer-styles.css,viewer-app.js}
- scripts/copy-assets.mjs — postbuild copier (tsc does not handle
  non-TS files); wired into npm run build and prepublishOnly
- src/services/graph-visualize-html.ts — HTML builder with scale-cap
  logic (MAX_SYMBOLS / MAX_EDGES / MAX_SYMS_PER_FILE) and parallel
  per-file Qdrant payload loading
- src/services/graph-visualize-browser.ts — temp-file write +
  cross-platform open wrapper
- tests/unit/graph-visualize-html.test.ts — 5 tests (self-contained,
  escape-safety, symbolMode omitted/capped, cycle marking)
- tests/unit/graph-visualize-browser.test.ts — 4 tests (deterministic
  path, overwrite, success + failure paths)

New runtime dependency: open@^10.2.0 (Sindre Sorhus, zero transitive
deps, cross-platform).

British-English doc sweep (secondary)
─────────────────────────────────────
Switched all project docs to British English spelling:
  behavior → behaviour                organized → organised
  color-coded → colour-coded          initialization → initialisation
  visualization → visualisation       customization → customisation
  recognized → recognised             optimized → optimised
  acknowledgment → acknowledgement    finalize → finalise
  analyzing → analysing               apologizing → apologising
  sexualized → sexualised

Affected files: README, DEVELOPER, AGENTS, CLAUDE, GEMINI, SECURITY,
CONTRIBUTING, CODE_OF_CONDUCT, agents/codebase-explorer.md,
skills/codebase-exploration/{SKILL.md,references/tool-reference.md},
skills/codebase-management/references/tool-reference.md.

Also surfaced Impact Analysis in the top-level README paragraph.

Docs
────
- README: "Interactive graph explorer" subsection under Impact Analysis,
  tool-table row updated.
- DEVELOPER.md: architecture section under codebase_graph_visualize
  covering asset layout, data flow, cap logic, XSS-safety invariants.
- AGENTS.md / CLAUDE.md / GEMINI.md: new "User asks for a visual /
  interactive / shareable graph" row in the tool-routing table.
- skills/codebase-exploration/: SKILL.md bullet + tool-reference.md
  full mode description.
- CHANGELOG.md: "Interactive Graph Explorer" section under Unreleased.

Quality gates (all green)
─────────────────────────
- Biome lint: clean
- TypeScript (tsc): clean
- Unit tests: 685/685
- Integration tests: 154/154 (real Qdrant + Ollama)
- CodeRabbit: No findings (1 fix applied — filename sanitisation)
- Snyk code test: 0 issues

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Giancarlo Erra
2026-04-23 16:04:41 +01:00
parent 4e41b4604e
commit 50d8853ea6
29 changed files with 5615 additions and 2603 deletions
+4 -3
View File
@@ -42,10 +42,10 @@ before reading any files directly.
Once search results clearly point to 1–3 files, read only the relevant sections.
Never read a file just to find out if it's relevant — search first.
5. **Use `codebase_graph_circular` when debugging unexpected behavior.**
5. **Use `codebase_graph_circular` when debugging unexpected behaviour.**
Circular dependencies cause subtle runtime issues; check for them proactively.
Also run `codebase_graph_circular` when you notice import-related errors or unexpected
initialization order.
initialisation order.
6. **Check `codebase_status` if search returns no results.**
The project may not be indexed yet. Run `codebase_index` if needed, then wait for
@@ -78,7 +78,8 @@ before reading any files directly.
| **What functions/classes exist in this file?** | `codebase_symbols file=path` |
| **Search for symbols by name across the project** | `codebase_symbols query=X` |
| Spot architectural problems | `codebase_graph_circular`, `codebase_graph_stats` |
| Visualise module structure | `codebase_graph_visualize` |
| Visualise module structure (text / Mermaid) | `codebase_graph_visualize` |
| **User asks for a visual / interactive / shareable graph** | `codebase_graph_visualize mode="interactive"` — opens a self-contained HTML page with file + symbol views, blast-radius overlay, search, PNG export. Works offline (vendored Cytoscape). |
| Verify index is up to date | `codebase_status` |
| Discover what project knowledge (schemas, specs, configs) is available | `codebase_context` |
| Find database tables, API endpoints, infra configs | `codebase_context_search` |
+12
View File
@@ -23,6 +23,18 @@ This project uses [Conventional Commits](https://www.conventionalcommits.org/) a
* **Symbol graph crashed on prototype-key collisions** (e.g. a method named `constructor`, `toString`, or `hasOwnProperty`). The shard maps used `shard[name]` bracket access on a plain `{}`, which returned `Object.prototype.constructor` (a function) and threw `existing.push is not a function` during persistence. Fixed by guarding all shard reads with `Object.hasOwn` in `services/code-graph.ts` and `services/symbol-graph-incremental.ts`. Added a regression test in `tests/integration/symbol-graph-incremental.test.ts`.
* **`tests/unit/logger.test.ts` was order-dependent on the shell environment.** `currentLevel` was frozen at module load, so `SOCRATICODE_LOG_LEVEL=debug` in the developer shell broke the "does not emit debug at info level" assertion. `services/logger.ts` now exposes `setLogLevel` / `getLogLevel`, and the test pins the level in `beforeEach` / restores in `afterEach`.
### Interactive Graph Explorer
* **Interactive HTML graph viewer** — `codebase_graph_visualize` now accepts a `mode` parameter. Default `"mermaid"` keeps the existing text-diagram behaviour; new `"interactive"` mode generates a self-contained HTML page (vendored Cytoscape.js + Dagre — no CDN, works offline) and opens it in the user's default browser via the `open` npm package. The page includes:
* **File view** (every source file as a node, imports as edges, language colour-coded, circular deps highlighted in red)
* **Symbol view** toggle (functions / classes / methods as nodes, call edges between them — available when the symbol graph fits under the embed caps of 20k symbols / 60k call edges; above that the file view remains and a banner directs users to `codebase_impact` for symbol-level queries)
* **Sidebar** with imports / dependents / per-file symbols (first 30 shown, link to `codebase_symbols` for the rest) + action buttons for blast radius and call flow
* **Right-click** a node → highlight its blast radius (reverse-transitive closure)
* Live search, six Cytoscape layouts (Dagre / force / concentric / breadth-first / grid / circle), PNG export, hover tooltips
* `open: false` parameter skips auto-launch — just returns the file path (useful in headless environments)
* **`open` added as a runtime dependency** for cross-platform browser launching (macOS, Linux, Windows).
* **Vendored Cytoscape.js 3.30.2 + Dagre 0.8.5 + cytoscape-dagre 2.5.0** under `src/assets/` (copied to `dist/assets/` on build). Total ≈ 650 KB; inlined into the HTML at generation time — zero network dependency at view time.
### Performance
* **Per-file incremental symbol-graph updates wired into the watcher / `codebase_update`** (Phase F). When a `SymbolGraphMeta` already exists for the project AND ≤ 50 files changed, `services/indexer.ts` now calls `rebuildGraph(path, { skipSymbolGraph: true })` plus `updateChangedFilesSymbolGraph(...)`, which patches only the affected name shards (≤ 27) and reverse-call shards (≤ 256). Above the threshold or on first index it falls back to a full rebuild. End-to-end measurement on a 1000-file synthetic repo: full rebuild **6.55 s**, single-file Phase F update **197 ms** (≈33×). See `DEVELOPER.md` § "Real-world benchmark numbers" and `tests/integration/symbol-graph-scale.test.ts`.
+4 -3
View File
@@ -42,10 +42,10 @@ before reading any files directly.
Once search results clearly point to 1–3 files, read only the relevant sections.
Never read a file just to find out if it's relevant — search first.
5. **Use `codebase_graph_circular` when debugging unexpected behavior.**
5. **Use `codebase_graph_circular` when debugging unexpected behaviour.**
Circular dependencies cause subtle runtime issues; check for them proactively.
Also run `codebase_graph_circular` when you notice import-related errors or unexpected
initialization order.
initialisation order.
6. **Check `codebase_status` if search returns no results.**
The project may not be indexed yet. Run `codebase_index` if needed, then wait for
@@ -78,7 +78,8 @@ before reading any files directly.
| **What functions/classes exist in this file?** | `codebase_symbols file=path` |
| **Search for symbols by name across the project** | `codebase_symbols query=X` |
| Spot architectural problems | `codebase_graph_circular`, `codebase_graph_stats` |
| Visualise module structure | `codebase_graph_visualize` |
| Visualise module structure (text / Mermaid) | `codebase_graph_visualize` |
| **User asks for a visual / interactive / shareable graph** | `codebase_graph_visualize mode="interactive"` — opens a self-contained HTML page with file + symbol views, blast-radius overlay, search, PNG export. Works offline (vendored Cytoscape). |
| Verify index is up to date | `codebase_status` |
| Discover what project knowledge (schemas, specs, configs) is available | `codebase_context` |
| Find database tables, API endpoints, infra configs | `codebase_context_search` |
+12 -12
View File
@@ -14,20 +14,20 @@ diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
Examples of behaviour that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
* Accepting responsibility and apologising to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
Examples of unacceptable behaviour include:
* The use of sexualized language or imagery, and sexual attention or advances of
* The use of sexualised language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
@@ -39,8 +39,8 @@ Examples of unacceptable behavior include:
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
acceptable behaviour and will take appropriate and fair corrective action in
response to any behaviour that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
@@ -58,7 +58,7 @@ representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
Instances of abusive, harassing, or otherwise unacceptable behaviour may be
reported to the project maintainer at **giancarlo@altaire.com**.
All complaints will be reviewed and investigated promptly and fairly. The
@@ -72,19 +72,19 @@ the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
**Community Impact**: Use of inappropriate language or other behaviour deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
behaviour was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
**Consequence**: A warning with consequences for continued behaviour. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
@@ -94,7 +94,7 @@ ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
sustained inappropriate behaviour.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
@@ -105,7 +105,7 @@ Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
standards, including sustained inappropriate behaviour, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
+1 -1
View File
@@ -51,7 +51,7 @@ See the [Developer Guide](DEVELOPER.md) for architecture details, data flows, an
Use the [Bug Report](https://github.com/giancarloerra/socraticode/issues/new?template=bug_report.yml) issue template. Include:
- Steps to reproduce
- Expected vs actual behavior
- Expected vs actual behaviour
- Your environment (OS, Node.js version, embedding provider, MCP host)
- Log output if available (set `SOCRATICODE_LOG_LEVEL=debug`)
+50 -4
View File
@@ -861,6 +861,17 @@ TypeScript / JavaScript / TSX, Python, Go, Rust, Java, Kotlin, Scala, C#, C, C++
`SymbolGraphMeta.unresolvedEdgePct` exposes how much of the call graph is fuzzy — useful as a quality signal.
#### Accepted limits — what the call graph does not see
The call graph is built from static analysis without type inference. These classes of call patterns are silently absent from the graph **by design**:
- **Dynamic dispatch** — Python `getattr(obj, name)(...)`, JavaScript `obj[key](...)`, `eval`, language-level reflection. The callee is only known at runtime; the static extractor captures the literal call sites it can see and nothing more.
- **Method resolution without receiver type** — `obj.foo()` resolves by the bare name `foo` against every dependency that exports a `foo`. Receiver type is informational in the output, never a pruning filter. Two unrelated classes with a `foo` method both appear as candidates on an ambiguous edge (`confidence: "multiple-candidates"`).
- **Macros** — Rust (`println!`, custom `macro_rules!`) and C / C++ preprocessor macros are not expanded. Macro invocations are captured as calls to the macro *name*, not to whatever the expansion actually calls.
- **Framework magic** — Dependency injection (Spring `@Autowired`, Angular DI, NestJS providers), ORM metaprogramming (Rails `has_many`, ActiveRecord callbacks), decorator-driven routing where the handler is never named at a call site (Django class-based view dispatch, some FastAPI patterns), and similar indirection goes through the framework rather than through a direct call. A method that is only called via `@Autowired` will show zero callers in `codebase_impact`.
`SymbolGraphMeta.unresolvedEdgePct` is the quality signal for this class of limit: consistently high values (>20%) indicate either heavy framework magic in the codebase or a language where extractor coverage is incomplete. Users running `codebase_impact` on a service-oriented codebase with heavy DI should treat "zero callers" as a hint to double-check, not a guarantee.
#### Per-file incremental updates (Phase F)
`services/symbol-graph-incremental.ts` exports `updateChangedFilesSymbolGraph(projectId, projectPath, fileGraph, changedRelPaths, removedRelPaths)`. Given a freshly-rebuilt file-import graph and a small list of changed/removed paths, it:
@@ -1052,7 +1063,7 @@ Parameters:
projectPath?: string — Absolute path (defaults to cwd)
extraExtensions?: string — Comma-separated extra extensions
Behavior: Starts graph build in the background (fire-and-forget).
Behaviour: Starts graph build in the background (fire-and-forget).
If a build is already in progress, returns current progress instead.
Uses concurrency guard — duplicate callers share the same build.
@@ -1087,11 +1098,46 @@ Returns: List of circular dependency chains (up to 20 displayed)
#### `codebase_graph_visualize`
```
Parameters:
projectPath?: string — Absolute path (defaults to cwd)
projectPath?: string — Absolute path (defaults to cwd)
mode?: "mermaid" | "interactive" — Output mode (default "mermaid")
open?: boolean — In interactive mode, auto-open the browser (default true)
Returns: Mermaid diagram of the dependency graph, color-coded by language
Returns:
- mode=mermaid → Mermaid diagram (text), colour-coded by language
- mode=interactive → Self-contained HTML file path + auto-opened browser window
```
The interactive mode generates a full-featured graph explorer backed by
vendored Cytoscape.js + Dagre assets — no CDN, works offline. Architecture:
1. `services/graph-visualize-html.ts::buildInteractiveGraphHtml()` loads
the assets once (module-level cache), builds `VizData` from the file
graph plus — when a `SymbolGraphMeta` exists and the totals fit under
the caps (`MAX_SYMBOLS=20000`, `MAX_EDGES=60000`) — the symbol graph
via parallel `loadFilePayload()` batches. Per-file symbol lists are
embedded unconditionally (capped at `MAX_SYMS_PER_FILE=200` per file).
2. Assets are spliced into `viewer-template.html` (CSS, Cytoscape,
Dagre, cytoscape-dagre plugin, `viewer-app.js`, and graph data as
JSON inside `<script type="application/json">`). Every `<` in the
JSON is escaped to `\u003c` so a stray `</script>` in a symbol name
cannot break out.
3. `services/graph-visualize-browser.ts::writeInteractiveGraphFile()`
writes to `os.tmpdir()/socraticode-graph/${projectId}.html` —
deterministic path per project, overwritten on each call.
4. `openInBrowser()` uses the `open` npm package (no new transitive
deps; wraps `open` on macOS, `xdg-open` on Linux, `start` on
Windows). Failure is soft — the tool output still includes the file
path so the user can open it manually.
5. The viewer (`viewer-app.js`) uses `document.createElement` +
`textContent` exclusively (no `innerHTML`) so data fields with
HTML-looking content are neutral.
When the symbol graph overflows the caps, the HTML still renders the
file view; the Symbols toggle is shown but explicitly disabled with a
banner directing the user to `codebase_impact` / `codebase_symbols` for
symbol-level queries. Per-file symbol lists in the sidebar remain
available regardless of total graph size.
#### `codebase_graph_remove`
```
Parameters:
@@ -1379,7 +1425,7 @@ Make sure the project has been indexed first (`codebase_index`). Check the statu
### Code graph returns empty
The code graph uses ast-grep for AST-based import extraction. It works for 18+ languages. If a file has no recognized imports (or uses non-standard import patterns), it may appear as an orphan node.
The code graph uses ast-grep for AST-based import extraction. It works for 18+ languages. If a file has no recognised imports (or uses non-standard import patterns), it may appear as an orphan node.
### Large codebase is slow to index
+4 -3
View File
@@ -42,10 +42,10 @@ before reading any files directly.
Once search results clearly point to 1–3 files, read only the relevant sections.
Never read a file just to find out if it's relevant — search first.
5. **Use `codebase_graph_circular` when debugging unexpected behavior.**
5. **Use `codebase_graph_circular` when debugging unexpected behaviour.**
Circular dependencies cause subtle runtime issues; check for them proactively.
Also run `codebase_graph_circular` when you notice import-related errors or unexpected
initialization order.
initialisation order.
6. **Check `codebase_status` if search returns no results.**
The project may not be indexed yet. Run `codebase_index` if needed, then wait for
@@ -78,7 +78,8 @@ before reading any files directly.
| **What functions/classes exist in this file?** | `codebase_symbols file=path` |
| **Search for symbols by name across the project** | `codebase_symbols query=X` |
| Spot architectural problems | `codebase_graph_circular`, `codebase_graph_stats` |
| Visualise module structure | `codebase_graph_visualize` |
| Visualise module structure (text / Mermaid) | `codebase_graph_visualize` |
| **User asks for a visual / interactive / shareable graph** | `codebase_graph_visualize mode="interactive"` — opens a self-contained HTML page with file + symbol views, blast-radius overlay, search, PNG export. Works offline (vendored Cytoscape). |
| Verify index is up to date | `codebase_status` |
| Discover what project knowledge (schemas, specs, configs) is available | `codebase_context` |
| Find database tables, API endpoints, infra configs | `codebase_context_search` |
+85 -12
View File
@@ -34,7 +34,7 @@
>
> 💬 Questions or just want to chat? Join us on [Discord](https://discord.gg/5DrMXfNG).
**One thing, done well: deep codebase intelligence — zero setup, no bloat, fully automatic.** SocratiCode gives AI assistants deep semantic understanding of your codebase — hybrid search, cross-project search, polyglot code dependency graphs, and searchable context artifacts (database schemas, API specs, infra configs, architecture docs). Zero configuration — add it to **any MCP host**, or install the native **plugin** for Claude Code, Cursor, VS Code Copilot, Codex or Gemini CLI. It manages everything automatically.
**One thing, done well: deep codebase intelligence — zero setup, no bloat, fully automatic.** SocratiCode gives AI assistants deep semantic understanding of your codebase — hybrid search, cross-project search, polyglot code dependency graphs, **symbol-level Impact Analysis** (the blast radius of any file or function change — use it BEFORE refactoring), an **interactive HTML graph explorer** for visual navigation, and searchable context artifacts (database schemas, API specs, infra configs, architecture docs). Zero configuration — add it to **any MCP host**, or install the native **plugin** for Claude Code, Cursor, VS Code Copilot, Codex or Gemini CLI. It manages everything automatically.
**Production-ready**, battle-tested on **enterprise-level** large repositories (up to and over **~40 million lines of code**). **Batched**, automatic **resumable** indexing checkpoints progress — pauses, crashes, restarts, and interruptions don't lose work. The file watcher keeps the **index automatically updated** at every file change and across sessions. **Multi-agent ready** — multiple AI agents can work on the same codebase simultaneously, sharing a single index with automatic coordination and zero configuration.
@@ -42,7 +42,7 @@
> **☁️ SocratiCode Cloud (private beta)** — Hosted, shared team index built on the same engine as the open-source version, plus SSO, audit logs, branch-aware indexing, and VPC / air-gapped deployment options. The open-source core remains free forever. [Request early access →](https://socraticode.cloud)
The first Qdrant‑based MCP/Claude Plugin/Skill that pairs auto‑managed, zero‑config local Docker deployment with **AST‑aware code chunking, hybrid semantic + BM25 (RRF‑fused) code search**, polyglot dependency **graphs** with circular‑dependency visualization, and searchable **infra/API/database artifacts** in a single focused, zero-config and easy to use code intelligence engine.
The first Qdrant‑based MCP/Claude Plugin/Skill that pairs auto‑managed, zero‑config local Docker deployment with **AST‑aware code chunking, hybrid semantic + BM25 (RRF‑fused) code search**, polyglot dependency **graphs** with circular‑dependency visualisation, **symbol‑level Impact Analysis** (blast‑radius & call‑flow tracing across 18 languages), and searchable **infra/API/database artifacts** in a single focused, zero-config and easy to use code intelligence engine.
> **Benchmarked on VS Code (2.45M lines):** SocratiCode uses **61% less context**, **84% fewer tool calls**, and is **37x faster** than grep‑based exploration — tested live with Claude Opus 4.6. [See the full benchmark →](#real-world-benchmark-vs-code-245m-lines-of-code-with-claude-opus-46)
@@ -303,7 +303,7 @@ User: "What files depend on the auth middleware?"
User: "Show me the dependency graph"
→ codebase_graph_visualize {}
Returns a Mermaid diagram color-coded by language
Returns a Mermaid diagram colour-coded by language
User: "Are there any circular dependencies?"
→ codebase_graph_circular {}
@@ -399,10 +399,10 @@ before reading any files directly.
Once search results clearly point to 1–3 files, read only the relevant sections.
Never read a file just to find out if it's relevant — search first.
5. **Use `codebase_graph_circular` when debugging unexpected behavior.**
5. **Use `codebase_graph_circular` when debugging unexpected behaviour.**
Circular dependencies cause subtle runtime issues; check for them proactively.
Also run `codebase_graph_circular` when you notice import-related errors or unexpected
initialization order.
initialisation order.
6. **Check `codebase_status` if search returns no results.**
The project may not be indexed yet. Run `codebase_index` if needed, then wait for
@@ -490,7 +490,7 @@ Or from within Claude Code:
/plugin update socraticode@socraticode
```
**Configuring environment variables:** SocratiCode works with zero config for most users (local Ollama + managed Qdrant). If you need cloud embeddings, a remote Qdrant, or other customization:
**Configuring environment variables:** SocratiCode works with zero config for most users (local Ollama + managed Qdrant). If you need cloud embeddings, a remote Qdrant, or other customisation:
1. **Claude Code settings** (recommended) — add to `~/.claude/settings.json`:
```json
@@ -810,7 +810,7 @@ Once connected, 21 tools are available to your AI assistant:
| `codebase_graph_query` | Query imports and dependents for a specific file |
| `codebase_graph_stats` | Get graph statistics (most connected files, orphans, language breakdown) |
| `codebase_graph_circular` | Detect circular dependencies |
| `codebase_graph_visualize` | Generate a Mermaid diagram of the dependency graph |
| `codebase_graph_visualize` | Generate a Mermaid diagram (`mode=mermaid`, default) or an interactive HTML explorer (`mode=interactive`) of the dependency graph. Interactive mode writes a self-contained page (vendored Cytoscape.js + Dagre, works offline) and opens it in your default browser — file + symbol views, blast-radius overlay, live search, PNG export. |
| `codebase_graph_status` | Check graph build progress or persisted graph metadata |
| `codebase_graph_remove` | Remove a project's persisted code graph (waits for in-flight graph build to finish first) |
@@ -826,6 +826,21 @@ and methods call which. Use these tools BEFORE refactoring, renaming, or deletin
| `codebase_symbol` | 360° view of one symbol — its definition, callers, and callees |
| `codebase_symbols` | List symbols in a file or search by name across the project |
> **Accepted limits.** The call graph is static-analysis-based — no type inference. Dynamic dispatch (`getattr`, `obj[key](...)`, reflection, `eval`), unexpanded macros, and framework magic (Spring `@Autowired`, Angular DI, Rails `has_many`, decorator-driven routing) are invisible. Callers that reach a method only through these mechanisms will not appear in `codebase_impact`. Treat "zero callers" as a hint to double-check on DI-heavy codebases. `codebase_graph_status` reports `unresolvedEdgePct` as a quality signal. See [DEVELOPER.md § Impact Analysis](DEVELOPER.md) for the full list.
#### Interactive graph explorer
Ask your AI *"show me an interactive graph of this project"* (or invoke `codebase_graph_visualize` with `mode: "interactive"`) and SocratiCode generates a self-contained HTML page and opens it in your default browser:
- **File view** — every source file as a node, imports as edges, language-coloured, circular deps in red.
- **Symbol view** — toggle to see functions/classes/methods as nodes with call edges (available when the symbol graph fits within the embed cap; above that threshold the file view remains and the banner points at `codebase_impact` for symbol-level queries).
- **Sidebar** — click a node to see imports / dependents / symbols-in-file / line numbers, with action buttons for blast radius and call flow.
- **Right-click any node** → highlights its reverse-transitive closure (who breaks if this changes).
- **Live search** filters and centres matching nodes. **Layout switcher** — Dagre / force-directed / concentric / breadth-first / grid / circle. **Export PNG** produces a shareable image.
- **Offline-safe** — Cytoscape.js + Dagre are vendored inside the SocratiCode package. No CDN, no network, works in air-gapped environments.
The output is a single HTML file (written to the OS temp dir, one per project) that you can also commit to a PR or share on Slack.
#### Management
| Tool | Description |
@@ -959,7 +974,7 @@ Without artifacts, the agent only sees source code. With artifacts, it has the f
{
"name": "event-storming",
"path": "./docs/event-storming/",
"description": "Event storming output — domain events, commands, aggregates, policies, and read models. Check before adding new domain behavior to see how it fits the existing event flows."
"description": "Event storming output — domain events, commands, aggregates, policies, and read models. Check before adding new domain behaviour to see how it fits the existing event flows."
}
]
}
@@ -982,6 +997,64 @@ Without artifacts, the agent only sees source code. With artifacts, it has the f
## Environment Variables
SocratiCode reads configuration from environment variables. The way you pass them depends on your MCP host — the key name and file format differ across the three main config flavours. If env vars appear to be ignored, check the host's config format first — most "it's not picking up my settings" issues are a mismatched key.
### Passing env vars by host
| Host | Config file | Env-var syntax |
|------|-------------|---------|
| Claude Code / Claude Desktop / Windsurf / Cline / Roo Code / Cursor / VS Code Copilot | MCP JSON (`mcpServers` or `servers`) | `"env": { "KEY": "value" }` |
| **OpenCode** | `opencode.json` / `opencode.jsonc` ([schema](https://opencode.ai/config.json)) | **`"environment": { "KEY": "value" }`** — *not* `"env"`, which is silently ignored |
| **OpenAI Codex CLI** | `~/.codex/config.toml` ([reference](https://developers.openai.com/codex/config-reference/)) | **Nested TOML table** — a `[mcp_servers.NAME.env]` block with `KEY = "value"` lines. Inline `env = { ... }` is *not* the Codex form. |
Worked examples with a few env vars set:
**Standard MCP JSON** — Claude Code, Claude Desktop, Windsurf, Cline, Roo Code, Cursor, VS Code Copilot:
```json
"socraticode": {
"command": "npx",
"args": ["-y", "socraticode"],
"env": {
"QDRANT_MODE": "external",
"QDRANT_URL": "https://xyz.qdrant.io"
}
}
```
**OpenCode** — note `environment`, not `env`:
```jsonc
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"socraticode": {
"type": "local",
"command": ["npx", "-y", "socraticode"],
"enabled": true,
"environment": {
"QDRANT_MODE": "external",
"QDRANT_URL": "https://xyz.qdrant.io"
}
}
}
}
```
**OpenAI Codex CLI** — env vars go in a separate `[mcp_servers.NAME.env]` table:
```toml
[mcp_servers.socraticode]
command = "npx"
args = ["-y", "socraticode"]
[mcp_servers.socraticode.env]
QDRANT_MODE = "external"
QDRANT_URL = "https://xyz.qdrant.io"
```
The rest of this section documents the variables themselves. Pass them using whichever syntax matches your host.
### Embedding Provider
| Variable | Default | Description |
@@ -1019,7 +1092,7 @@ Without artifacts, the agent only sees source code. With artifacts, it has the f
| `QDRANT_HOST` | `localhost` | Qdrant hostname (alternative to `QDRANT_URL` for non-HTTPS external instances) |
| `QDRANT_API_KEY` | *(none)* | Qdrant API key (required for Qdrant Cloud and other authenticated deployments) |
### Indexing Behavior
### Indexing Behaviour
| Variable | Default | Description |
|----------|---------|-------------|
@@ -1124,9 +1197,9 @@ Running a head-to-head comparison against the VS Code codebase (~2.45 million li
### When hybrid search wins
**Natural-language and conceptual queries** — Queries like *"Where do we handle database connection pooling?"* or *"How does this library implement exponential backoff?"* describe behavior rather than naming a function. Evaluations on repository-level benchmarks (RepoEval, SWE-bench) show that AST-aware semantic retrieval improves recall by up to 4.3 points and downstream code-generation accuracy by ~2.7 points compared to fixed line-based chunks. Agentic evaluations on real open-source repos show a 70% win rate for hybrid search over vanilla grep on hard, conceptual questions — with 56% fewer search operations and ~60,000 fewer tokens per complex query.
**Natural-language and conceptual queries** — Queries like *"Where do we handle database connection pooling?"* or *"How does this library implement exponential backoff?"* describe behaviour rather than naming a function. Evaluations on repository-level benchmarks (RepoEval, SWE-bench) show that AST-aware semantic retrieval improves recall by up to 4.3 points and downstream code-generation accuracy by ~2.7 points compared to fixed line-based chunks. Agentic evaluations on real open-source repos show a 70% win rate for hybrid search over vanilla grep on hard, conceptual questions — with 56% fewer search operations and ~60,000 fewer tokens per complex query.
**Large repos and monorepos** — At multi-million LOC scale, full-text scans become expensive. Production search engines report ~20% relevance improvement from BM25F ranking over previous approaches, and use it as the first-stage retriever for semantic reranking. Hybrid search backed by inverted and vector indexes avoids full scans entirely, making it both faster and more precise at scale. Industry practitioners explicitly note that grep and find "don't scale well to millions of files" and that optimized embedding-based indexes can be faster at that scale.
**Large repos and monorepos** — At multi-million LOC scale, full-text scans become expensive. Production search engines report ~20% relevance improvement from BM25F ranking over previous approaches, and use it as the first-stage retriever for semantic reranking. Hybrid search backed by inverted and vector indexes avoids full scans entirely, making it both faster and more precise at scale. Industry practitioners explicitly note that grep and find "don't scale well to millions of files" and that optimised embedding-based indexes can be faster at that scale.
**Cross-file and cross-language reasoning** — Finding all code paths that eventually call an internal helper across services, or mapping a natural-language spec to implementations in Go and SQL, requires understanding that goes beyond string matching. Evaluations show that hybrid pipelines with tree-sitter parsing and dependency context outperform grep when naming is non-obvious and semantic understanding is needed. AST-based chunking with learned retrievers improves retrieval in cross-language benchmarks, and multi-vector semantic models show large gains over BM25 alone across diverse code search tasks (AppsRetrieval, CodeSearchNet, CosQA) where queries are in natural language and targets span many languages.
@@ -1275,7 +1348,7 @@ SocratiCode is dual-licensed:
If you modify SocratiCode and offer it as a network service, you must release
your modifications under AGPL-3.0.
- **Commercial** — For organizations that need to use SocratiCode in proprietary
- **Commercial** — For organisations that need to use SocratiCode in proprietary
products or services without AGPL obligations. See [LICENSE-COMMERCIAL](LICENSE-COMMERCIAL)
or contact [giancarlo@altaire.com](mailto:giancarlo@altaire.com).
+1 -1
View File
@@ -13,7 +13,7 @@ Instead, email **[giancarlo@altaire.com](mailto:giancarlo@altaire.com)** with:
- Potential impact
- Any suggested fixes (optional)
You will receive an acknowledgment within 48 hours and a detailed response within 7 days indicating next steps.
You will receive an acknowledgement within 48 hours and a detailed response within 7 days indicating next steps.
## Scope
+2 -2
View File
@@ -3,7 +3,7 @@ name: codebase-explorer
description: >-
Deep codebase exploration using SocratiCode. Combines semantic search,
dependency graphs, and context artifacts to answer questions about code
structure and behavior. Use when delegating complex codebase understanding
structure and behaviour. Use when delegating complex codebase understanding
tasks that require tracing through multiple files and dependencies.
<example>
@@ -35,7 +35,7 @@ Never open a file just to check if it's relevant. Always search first.
4. **Read files only after narrowing down.** Once search results point to 1-3 specific files, read the relevant sections.
5. **Check for architectural issues.** Use `codebase_graph_circular` to detect circular dependencies when debugging unexpected behavior.
5. **Check for architectural issues.** Use `codebase_graph_circular` to detect circular dependencies when debugging unexpected behaviour.
6. **Synthesize findings.** Present clear, structured answers with specific file paths and line references. Explain the relationships between components.
+3 -2531
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -9,13 +9,13 @@
"socraticode": "dist/index.js"
},
"scripts": {
"build": "tsc",
"build": "tsc && node scripts/copy-assets.mjs",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"lint": "biome check src/ tests/",
"lint:fix": "biome check --write src/ tests/",
"release": "release-it",
"prepublishOnly": "tsc",
"prepublishOnly": "tsc && node scripts/copy-assets.mjs",
"release:dry": "release-it --dry-run",
"test": "vitest run",
"test:unit": "vitest run tests/unit/",
@@ -84,6 +84,7 @@
"glob": "^11.0.1",
"ignore": "^7.0.3",
"ollama": "^0.5.14",
"open": "^10.2.0",
"openai": "^6.22.0",
"proper-lockfile": "^4.1.2",
"zod": "^3.24.2"
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
//
// Copy src/assets/ → dist/assets/ after tsc compile.
// tsc does not copy non-TS files; this keeps the vendored Cytoscape + Dagre
// bundles available to the interactive graph visualiser at runtime.
import { cp, mkdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const src = path.join(root, "src", "assets");
const dst = path.join(root, "dist", "assets");
await mkdir(dst, { recursive: true });
await cp(src, dst, { recursive: true, force: true });
process.stdout.write(`copy-assets: ${src} → ${dst}\n`);
+6 -5
View File
@@ -3,10 +3,10 @@ name: codebase-exploration
description: >-
Explore and understand codebases using SocratiCode semantic search, dependency graphs,
and context artifacts. Use when exploring code, understanding architecture, finding
functions/types, analyzing dependencies, searching database schemas or API specs,
functions/types, analysing dependencies, searching database schemas or API specs,
or when socraticode/codebase_search tools are available. Activates when the user asks
about code structure, wants to find where a feature lives, or needs to understand
how code is organized.
how code is organised.
---
# SocratiCode Codebase Exploration
@@ -35,8 +35,8 @@ Use `codebase_graph_query` to see what a file imports and what depends on it **b
- **`codebase_graph_query`** — imports and dependents for any file (pass relative path)
- **`codebase_graph_stats`** — architecture overview: total files, edges, most connected files, orphans, language breakdown
- **`codebase_graph_circular`** — find circular dependencies (these cause subtle runtime bugs; check proactively when debugging unexpected behavior)
- **`codebase_graph_visualize`** — Mermaid diagram color-coded by language, circular deps highlighted in red
- **`codebase_graph_circular`** — find circular dependencies (these cause subtle runtime bugs; check proactively when debugging unexpected behaviour)
- **`codebase_graph_visualize`** — Mermaid diagram colour-coded by language, circular deps highlighted in red. Pass `mode: "interactive"` to open a self-contained HTML explorer (file + symbol views, blast-radius overlay, search, PNG export — works offline) instead.
The graph is auto-built after indexing. Use `codebase_graph_status` to check if the graph is ready.
@@ -76,7 +76,8 @@ Run `codebase_context` early to see what's available. Use `codebase_context_sear
| See what a file imports or what depends on it | `codebase_graph_query` |
| Get architecture overview (files, edges, most connected) | `codebase_graph_stats` |
| Spot circular dependencies | `codebase_graph_circular` |
| Visualize module structure | `codebase_graph_visualize` |
| Visualise module structure (text / Mermaid) | `codebase_graph_visualize` |
| User asks for a visual / interactive / shareable graph | `codebase_graph_visualize mode="interactive"` |
| Check graph build status | `codebase_graph_status` |
| Verify index is up to date | `codebase_status` |
| Discover available schemas, specs, configs | `codebase_context` |
@@ -15,7 +15,7 @@ Semantic search across an indexed codebase. Only use after `codebase_index` is c
**Returns:** Ranked code chunks with file paths, line numbers, language, and RRF scores.
**Key behaviors:**
**Key behaviours:**
- Uses hybrid semantic + keyword (BM25) search with Reciprocal Rank Fusion
- Warns if indexing is in progress (results will be incomplete during full index)
- Warns if file watcher is not active (results may be stale)
@@ -41,7 +41,7 @@ Check index status: chunk count, indexing progress, last completed operation, fi
- Code graph status (files, edges, last built, cached in memory)
- Context artifacts status
**Key behaviors:**
**Key behaviours:**
- Call every ~60 seconds during indexing to poll progress AND keep the MCP connection alive
- Detects both same-process and cross-process indexing
@@ -58,7 +58,7 @@ Query the dependency graph for a specific file.
**Returns:** Two lists: what this file imports (→) and what depends on it (←).
**Key behaviors:**
**Key behaviours:**
- Requires graph to exist (auto-built after indexing, or use `codebase_graph_build`)
- Auto-starts file watcher on query
- Use relative paths (not absolute)
@@ -87,7 +87,7 @@ Find circular dependencies in the codebase.
**Returns:** List of circular dependency chains (up to 20, with total count).
**Key behaviors:**
**Key behaviours:**
- Detects transitive circular dependencies
- Useful for debugging subtle runtime issues caused by import cycles
@@ -95,17 +95,27 @@ Find circular dependencies in the codebase.
## codebase_graph_visualize
Generate a Mermaid diagram of the dependency graph.
Visualise the dependency graph. Two modes:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `projectPath` | string | no | cwd | Absolute path to the project directory |
| `mode` | `"mermaid" \| "interactive"` | no | `"mermaid"` | Output format |
| `open` | boolean | no | `true` | In interactive mode, auto-open the browser |
**Returns:** Mermaid flowchart code block. Nodes color-coded by language, circular dependency edges highlighted in red.
**mode="mermaid"** (default) — returns a Mermaid flowchart code block. Nodes colour-coded by language, circular dependency edges highlighted in red. Renders inline in markdown viewers, VS Code, GitHub.
**Key behaviors:**
- Can be rendered in markdown viewers, VS Code, GitHub, etc.
- Shows file count and edge count
**mode="interactive"** — generates a self-contained HTML page (vendored Cytoscape.js + Dagre, works offline) written to the OS temp dir and opened in the user's default browser.
- File view and (when available) Symbol view toggle
- Click a node → sidebar with imports / dependents / symbols / line numbers
- Right-click → blast radius overlay (reverse-transitive closure)
- Live search, six layouts, PNG export
- Shareable file — commit to a PR or attach to chat
**Key behaviours:**
- Interactive mode always includes the file view; the symbol view toggle is available when the symbol graph fits under embed caps (≤ 20k symbols / ≤ 60k call edges). Above that cap, the HTML still works — use `codebase_impact` / `codebase_symbols` for symbol-level queries.
- Browser auto-open is best-effort. If it fails (headless environments, blocked browsers) the tool output still includes the file path.
- Choose this mode when the user asks for a visual, interactive, or shareable graph.
---
@@ -119,7 +129,7 @@ Check graph build status and progress.
**Returns:** If building: phase, file progress, elapsed time. If ready: node/edge counts, last built timestamp, cache status, last build duration.
**Key behaviors:**
**Key behaviours:**
- Use to poll progress after `codebase_graph_build`
- Shows build errors if last build failed
@@ -151,7 +161,7 @@ Semantic search across context artifacts.
**Returns:** Artifact content chunks with artifact name, file path, line ranges, and scores.
**Key behaviors:**
**Key behaviours:**
- Auto-indexes artifacts on first use (no manual step needed)
- Auto-detects stale artifacts and re-indexes changed ones
- Works with any text-based artifact: SQL, OpenAPI, Terraform, K8s, YAML, markdown, etc.
@@ -181,7 +191,7 @@ Display information about SocratiCode and all its tools.
### Graph tips
- The graph is auto-built after `codebase_index` — usually no need to call `codebase_graph_build` manually
- `codebase_graph_visualize` generates Mermaid that renders in GitHub, VS Code, and most markdown viewers
- Check `codebase_graph_circular` when debugging mysterious behavior — circular deps cause subtle issues
- Check `codebase_graph_circular` when debugging mysterious behaviour — circular deps cause subtle issues
### Context artifact tips
- `codebase_context_search` auto-indexes on first use — just search, no setup needed
@@ -11,7 +11,7 @@ Start indexing a codebase in the background. Returns immediately.
**Returns:** Confirmation that indexing started, with instructions to poll `codebase_status`.
**Key behaviors:**
**Key behaviours:**
- Runs asynchronously — does NOT block. Returns immediately.
- Auto-starts file watcher upon completion (if not cancelled)
- Ensures Docker/Qdrant/Ollama infrastructure is running first
@@ -33,7 +33,7 @@ Incrementally update an existing index. Only re-indexes changed files.
**Returns:** Statistics: files added/updated/removed, chunks created.
**Key behaviors:**
**Key behaviours:**
- Runs synchronously (blocking), unlike `codebase_index`
- Only processes files changed since last index (via content hash comparison)
- Auto-starts file watcher if not already active
@@ -51,7 +51,7 @@ Remove a project's entire index from the vector database.
**Returns:** Confirmation of removal.
**Key behaviors:**
**Key behaviours:**
- **Destructive** — cannot be undone
- Safely stops file watcher (same-process and cross-process)
- Cancels in-progress indexing and drains current batch
@@ -70,7 +70,7 @@ Gracefully stop an in-progress indexing operation.
**Returns:** Confirmation with current phase and batch info.
**Key behaviors:**
**Key behaviours:**
- Current batch finishes and checkpoints — all progress preserved
- Re-run `codebase_index` to resume from where it left off
- Handles both same-process and cross-process (orphan) indexing
@@ -90,7 +90,7 @@ Start/stop/status of live file watching.
**Returns:** Action result or list of watched projects.
**Key behaviors:**
**Key behaviours:**
- `start`: Runs catch-up incremental update first, then starts debounced file watcher
- `stop`: Stops same-process watcher (cross-process watchers unaffected)
- `status`: Lists all watched projects including cross-process watchers
@@ -111,7 +111,7 @@ Build the dependency graph using AST-based static analysis.
**Returns:** Confirmation that build started. Poll with `codebase_graph_status`.
**Key behaviors:**
**Key behaviours:**
- Runs asynchronously in background
- Auto-built during `codebase_index` (usually no need to call manually)
- Concurrency guard: if already building, shows progress
@@ -130,7 +130,7 @@ Remove a project's persisted code graph.
**Returns:** Confirmation of removal.
**Key behaviors:**
**Key behaviours:**
- **Destructive** — cannot be undone
- Waits for in-flight builds before deletion
- Graph auto-rebuilds during next `codebase_index`
@@ -159,7 +159,7 @@ Index or re-index all context artifacts.
**Returns:** Summary: artifacts indexed with chunk counts, any errors.
**Key behaviors:**
**Key behaviours:**
- Runs synchronously (blocking)
- Usually auto-triggered by `codebase_context_search` on first use
- Reports individual artifact errors without stopping the whole operation
@@ -176,7 +176,7 @@ Remove all indexed context artifacts.
**Returns:** Confirmation of removal.
**Key behaviors:**
**Key behaviours:**
- **Destructive** — cannot be undone
- Blocked while indexing is in progress (wait for finish or use `codebase_stop`)
- Removes ALL artifacts (not selective)
@@ -193,7 +193,7 @@ Check infrastructure health: Docker, Qdrant, Ollama, embedding model.
**Returns:** Status for each component with [OK]/[MISSING] indicators.
**Key behaviors:**
**Key behaviours:**
- Checks Docker availability
- Checks Qdrant (managed container or external endpoint)
- Checks embedding provider health (Ollama, OpenAI, or Google)
+397
View File
@@ -0,0 +1,397 @@
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("dagre"));
else if(typeof define === 'function' && define.amd)
define(["dagre"], factory);
else if(typeof exports === 'object')
exports["cytoscapeDagre"] = factory(require("dagre"));
else
root["cytoscapeDagre"] = factory(root["dagre"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE__4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
var impl = __webpack_require__(1); // registers the extension on a cytoscape lib ref
var register = function register(cytoscape) {
if (!cytoscape) {
return;
} // can't register if cytoscape unspecified
cytoscape('layout', 'dagre', impl); // register with cytoscape.js
};
if (typeof cytoscape !== 'undefined') {
// expose to global cytoscape (i.e. window.cytoscape)
register(cytoscape);
}
module.exports = register;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var isFunction = function isFunction(o) {
return typeof o === 'function';
};
var defaults = __webpack_require__(2);
var assign = __webpack_require__(3);
var dagre = __webpack_require__(4); // constructor
// options : object containing layout options
function DagreLayout(options) {
this.options = assign({}, defaults, options);
} // runs the layout
DagreLayout.prototype.run = function () {
var options = this.options;
var layout = this;
var cy = options.cy; // cy is automatically populated for us in the constructor
var eles = options.eles;
var getVal = function getVal(ele, val) {
return isFunction(val) ? val.apply(ele, [ele]) : val;
};
var bb = options.boundingBox || {
x1: 0,
y1: 0,
w: cy.width(),
h: cy.height()
};
if (bb.x2 === undefined) {
bb.x2 = bb.x1 + bb.w;
}
if (bb.w === undefined) {
bb.w = bb.x2 - bb.x1;
}
if (bb.y2 === undefined) {
bb.y2 = bb.y1 + bb.h;
}
if (bb.h === undefined) {
bb.h = bb.y2 - bb.y1;
}
var g = new dagre.graphlib.Graph({
multigraph: true,
compound: true
});
var gObj = {};
var setGObj = function setGObj(name, val) {
if (val != null) {
gObj[name] = val;
}
};
setGObj('nodesep', options.nodeSep);
setGObj('edgesep', options.edgeSep);
setGObj('ranksep', options.rankSep);
setGObj('rankdir', options.rankDir);
setGObj('align', options.align);
setGObj('ranker', options.ranker);
setGObj('acyclicer', options.acyclicer);
g.setGraph(gObj);
g.setDefaultEdgeLabel(function () {
return {};
});
g.setDefaultNodeLabel(function () {
return {};
}); // add nodes to dagre
var nodes = eles.nodes();
if (isFunction(options.sort)) {
nodes = nodes.sort(options.sort);
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var nbb = node.layoutDimensions(options);
g.setNode(node.id(), {
width: nbb.w,
height: nbb.h,
name: node.id()
}); // console.log( g.node(node.id()) );
} // set compound parents
for (var _i = 0; _i < nodes.length; _i++) {
var _node = nodes[_i];
if (_node.isChild()) {
g.setParent(_node.id(), _node.parent().id());
}
} // add edges to dagre
var edges = eles.edges().stdFilter(function (edge) {
return !edge.source().isParent() && !edge.target().isParent(); // dagre can't handle edges on compound nodes
});
if (isFunction(options.sort)) {
edges = edges.sort(options.sort);
}
for (var _i2 = 0; _i2 < edges.length; _i2++) {
var edge = edges[_i2];
g.setEdge(edge.source().id(), edge.target().id(), {
minlen: getVal(edge, options.minLen),
weight: getVal(edge, options.edgeWeight),
name: edge.id()
}, edge.id()); // console.log( g.edge(edge.source().id(), edge.target().id(), edge.id()) );
}
dagre.layout(g);
var gNodeIds = g.nodes();
for (var _i3 = 0; _i3 < gNodeIds.length; _i3++) {
var id = gNodeIds[_i3];
var n = g.node(id);
cy.getElementById(id).scratch().dagre = n;
}
var dagreBB;
if (options.boundingBox) {
dagreBB = {
x1: Infinity,
x2: -Infinity,
y1: Infinity,
y2: -Infinity
};
nodes.forEach(function (node) {
var dModel = node.scratch().dagre;
dagreBB.x1 = Math.min(dagreBB.x1, dModel.x);
dagreBB.x2 = Math.max(dagreBB.x2, dModel.x);
dagreBB.y1 = Math.min(dagreBB.y1, dModel.y);
dagreBB.y2 = Math.max(dagreBB.y2, dModel.y);
});
dagreBB.w = dagreBB.x2 - dagreBB.x1;
dagreBB.h = dagreBB.y2 - dagreBB.y1;
} else {
dagreBB = bb;
}
var constrainPos = function constrainPos(p) {
if (options.boundingBox) {
var xPct = dagreBB.w === 0 ? 0 : (p.x - dagreBB.x1) / dagreBB.w;
var yPct = dagreBB.h === 0 ? 0 : (p.y - dagreBB.y1) / dagreBB.h;
return {
x: bb.x1 + xPct * bb.w,
y: bb.y1 + yPct * bb.h
};
} else {
return p;
}
};
nodes.layoutPositions(layout, options, function (ele) {
ele = _typeof(ele) === "object" ? ele : this;
var dModel = ele.scratch().dagre;
return constrainPos({
x: dModel.x,
y: dModel.y
});
});
return this; // chaining
};
module.exports = DagreLayout;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
var defaults = {
// dagre algo options, uses default value on undefined
nodeSep: undefined,
// the separation between adjacent nodes in the same rank
edgeSep: undefined,
// the separation between adjacent edges in the same rank
rankSep: undefined,
// the separation between adjacent nodes in the same rank
rankDir: undefined,
// 'TB' for top to bottom flow, 'LR' for left to right,
align: undefined,
// alignment for rank nodes. Can be 'UL', 'UR', 'DL', or 'DR', where U = up, D = down, L = left, and R = right
acyclicer: undefined,
// If set to 'greedy', uses a greedy heuristic for finding a feedback arc set for a graph.
// A feedback arc set is a set of edges that can be removed to make a graph acyclic.
ranker: undefined,
// Type of algorithm to assigns a rank to each node in the input graph.
// Possible values: network-simplex, tight-tree or longest-path
minLen: function minLen(edge) {
return 1;
},
// number of ranks to keep between the source and target of the edge
edgeWeight: function edgeWeight(edge) {
return 1;
},
// higher weight edges are generally made shorter and straighter than lower weight edges
// general layout options
fit: true,
// whether to fit to viewport
padding: 30,
// fit padding
spacingFactor: undefined,
// Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
nodeDimensionsIncludeLabels: false,
// whether labels should be included in determining the space used by a node
animate: false,
// whether to transition the node positions
animateFilter: function animateFilter(node, i) {
return true;
},
// whether to animate specific nodes when animation is on; non-animated nodes immediately go to their final positions
animationDuration: 500,
// duration of animation in ms if enabled
animationEasing: undefined,
// easing of animation if enabled
boundingBox: undefined,
// constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
transform: function transform(node, pos) {
return pos;
},
// a function that applies a transform to the final node position
ready: function ready() {},
// on layoutready
sort: undefined,
// a sorting function to order the nodes and edges; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
// because cytoscape dagre creates a directed graph, and directed graphs use the node order as a tie breaker when
// defining the topology of a graph, this sort function can help ensure the correct order of the nodes/edges.
// this feature is most useful when adding and removing the same nodes and edges multiple times in a graph.
stop: function stop() {} // on layoutstop
};
module.exports = defaults;
/***/ }),
/* 3 */
/***/ (function(module, exports) {
// Simple, internal Object.assign() polyfill for options objects etc.
module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
for (var _len = arguments.length, srcs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
srcs[_key - 1] = arguments[_key];
}
srcs.forEach(function (src) {
Object.keys(src).forEach(function (k) {
return tgt[k] = src[k];
});
});
return tgt;
};
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__4__;
/***/ })
/******/ ]);
});
+32
View File
File diff suppressed because one or more lines are too long
+3809
View File
File diff suppressed because one or more lines are too long
+402
View File
@@ -0,0 +1,402 @@
/* SocratiCode interactive graph viewer — app logic
* Loaded after Cytoscape + Dagre + cytoscape-dagre are on window.
* Reads embedded graph data from window.__SOCRATICODE_DATA__.
*
* All DOM rendering uses createElement + textContent for XSS safety — no
* innerHTML is used anywhere, so data fields with HTML-looking content
* (rare but possible in symbol names) cannot escape into markup.
*/
(function () {
"use strict";
const DATA = window.__SOCRATICODE_DATA__;
if (!DATA) throw new Error("Missing __SOCRATICODE_DATA__");
// Language → colour palette (kept in sync with Mermaid generator)
const LANG_COLORS = {
typescript: "#3178C6", javascript: "#F7DF1E", python: "#3776AB",
java: "#ED8B00", kotlin: "#7F52FF", go: "#00ADD8",
rust: "#CE422B", ruby: "#CC342D", php: "#777BB4",
swift: "#FA7343", c: "#A8B9CC", cpp: "#00599C",
csharp: "#239120", scala: "#DC322F", dart: "#0175C2",
lua: "#2C2D72", shell: "#4EAA25", html: "#E34F26",
css: "#1572B6", json: "#808080",
};
const FALLBACK_COLOR = "#607D8B";
const colourFor = (lang) => LANG_COLORS[lang] || FALLBACK_COLOR;
// Symbol-kind → colour
const KIND_COLORS = {
function: "#3b82f6", class: "#a855f7", method: "#06b6d4",
constructor: "#0891b2", interface: "#f59e0b", trait: "#f59e0b",
enum: "#ec4899", module: "#6b7280", struct: "#a855f7", variable: "#84cc16",
};
// ── Tiny DOM builder (XSS-safe — all text via textContent) ───────
function h(tag, attrs, ...children) {
const el = document.createElement(tag);
if (attrs) {
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k === "class") el.className = v;
else if (k === "style") el.setAttribute("style", v);
else if (k.startsWith("data-")) el.setAttribute(k, String(v));
else if (k === "title") el.title = String(v);
else if (k === "disabled") el.disabled = true;
else el[k] = v;
}
}
for (const c of children) {
if (c == null || c === false) continue;
el.appendChild(typeof c === "string" || typeof c === "number" ? document.createTextNode(String(c)) : c);
}
return el;
}
// ── Register layouts ──────────────────────────────────────────────
if (window.cytoscapeDagre) window.cytoscapeDagre(cytoscape);
// ── Build Cytoscape elements from data ───────────────────────────
const FILE_NODES = DATA.files.map((f) => ({
group: "nodes",
data: {
id: `f::${f.id}`,
label: f.label,
nodeType: "file",
file: f.id,
language: f.language,
deps: f.deps,
dependents: f.dependents,
symbolCount: f.symbolCount || 0,
},
}));
const FILE_EDGES = DATA.fileEdges.map((e, i) => ({
group: "edges",
data: {
id: `fe${i}`,
source: `f::${e.source}`,
target: `f::${e.target}`,
edgeType: e.type,
cyclic: e.cyclic,
scope: "file",
},
classes: `${e.cyclic ? "cyclic" : ""} ${e.type === "dynamic-import" ? "dynamic" : ""}`.trim(),
}));
const SYMBOL_NODES = (DATA.symbols || []).map((s) => ({
group: "nodes",
data: {
id: `s::${s.id}`,
label: s.name,
nodeType: "symbol",
qualifiedName: s.qualifiedName,
kind: s.kind,
file: s.file,
line: s.line,
},
}));
const SYMBOL_EDGES = (DATA.symbolEdges || []).map((e, i) => ({
group: "edges",
data: {
id: `se${i}`,
source: `s::${e.source}`,
target: `s::${e.target}`,
confidence: e.confidence,
scope: "symbol",
},
classes: `conf-${e.confidence}`,
}));
// ── Cytoscape style ──────────────────────────────────────────────
const STYLE = [
{
selector: 'node[nodeType = "file"]',
style: {
"background-color": (ele) => colourFor(ele.data("language")),
"label": "data(label)",
"font-size": 10, "color": "#1f2937", "text-valign": "bottom",
"text-margin-y": 4, "text-background-color": "#fff",
"text-background-opacity": 0.8, "text-background-padding": 2,
"width": (ele) => 14 + Math.min(30, (ele.data("dependents") || 0) * 2),
"height": (ele) => 14 + Math.min(30, (ele.data("dependents") || 0) * 2),
"border-width": 1, "border-color": "#0f172a",
},
},
{
selector: 'node[nodeType = "symbol"]',
style: {
"background-color": (ele) => KIND_COLORS[ele.data("kind")] || "#64748b",
"label": "data(label)",
"font-size": 10, "color": "#1f2937", "text-valign": "bottom",
"text-margin-y": 4, "shape": "round-rectangle",
"width": 40, "height": 18,
"border-width": 1, "border-color": "#0f172a",
},
},
{
selector: "edge",
style: {
"width": 1.5, "line-color": "#cbd5e1",
"target-arrow-color": "#cbd5e1", "target-arrow-shape": "triangle",
"curve-style": "bezier", "arrow-scale": 0.8,
},
},
{ selector: "edge.dynamic", style: { "line-style": "dashed" } },
{ selector: "edge.cyclic", style: { "line-color": "#dc2626", "target-arrow-color": "#dc2626", "width": 2.5, "line-style": "dashed" } },
{ selector: "edge.conf-multiple-candidates", style: { "line-style": "dashed", "line-color": "#a78bfa", "target-arrow-color": "#a78bfa" } },
{ selector: "edge.conf-unresolved", style: { "line-style": "dotted", "line-color": "#94a3b8", "target-arrow-color": "#94a3b8" } },
{ selector: ".faded", style: { "opacity": 0.15, "text-opacity": 0.1 } },
{
selector: ".highlight",
style: {
"background-color": "#ef4444", "border-color": "#991b1b",
"border-width": 2, "z-index": 999,
},
},
{
selector: ".highlight-flow",
style: {
"background-color": "#3b82f6", "border-color": "#1e40af",
"border-width": 2, "z-index": 999,
},
},
{ selector: "edge.highlight-edge", style: { "line-color": "#ef4444", "target-arrow-color": "#ef4444", "width": 3, "z-index": 999 } },
{ selector: "edge.highlight-flow-edge", style: { "line-color": "#3b82f6", "target-arrow-color": "#3b82f6", "width": 3, "z-index": 999 } },
];
// ── Instantiate Cytoscape ────────────────────────────────────────
const cy = cytoscape({
container: document.getElementById("cy"),
elements: [...FILE_NODES, ...FILE_EDGES],
style: STYLE,
wheelSensitivity: 0.2,
minZoom: 0.1,
maxZoom: 3,
});
// ── Layout runner ────────────────────────────────────────────────
let currentView = "files";
let currentLayout = DATA.files.length > 200 ? "dagre" : "cose";
function runLayout(name) {
currentLayout = name;
const opts = { name, animate: true, animationDuration: 300, fit: true, padding: 30 };
if (name === "dagre") { opts.rankDir = "LR"; opts.nodeSep = 20; opts.rankSep = 60; }
if (name === "cose") { opts.nodeRepulsion = 8000; opts.idealEdgeLength = 80; }
cy.layout(opts).run();
}
// ── View toggle ──────────────────────────────────────────────────
function switchView(next) {
if (next === currentView) return;
currentView = next;
clearHighlights();
closeSidebar();
cy.elements().remove();
if (next === "files") cy.add([...FILE_NODES, ...FILE_EDGES]);
else cy.add([...SYMBOL_NODES, ...SYMBOL_EDGES]);
document.querySelectorAll(".view-toggle button").forEach((b) => b.classList.toggle("active", b.dataset.view === next));
runLayout(currentLayout);
}
// ── Highlighting ─────────────────────────────────────────────────
function clearHighlights() { cy.elements().removeClass("faded highlight highlight-flow highlight-edge highlight-flow-edge"); }
function bfsHighlight(rootId, direction) {
clearHighlights();
const root = cy.getElementById(rootId);
if (root.empty()) return;
const visited = new Set([rootId]);
const queue = [rootId];
const edges = [];
while (queue.length) {
const id = queue.shift();
const neighbours = direction === "reverse" ? cy.getElementById(id).incomers() : cy.getElementById(id).outgoers();
neighbours.edges().forEach((e) => edges.push(e.id()));
neighbours.nodes().forEach((n) => { if (!visited.has(n.id())) { visited.add(n.id()); queue.push(n.id()); } });
}
cy.elements().addClass("faded");
const nodeClass = direction === "reverse" ? "highlight" : "highlight-flow";
const edgeClass = direction === "reverse" ? "highlight-edge" : "highlight-flow-edge";
visited.forEach((id) => cy.getElementById(id).removeClass("faded").addClass(nodeClass));
edges.forEach((id) => cy.getElementById(id).removeClass("faded").addClass(edgeClass));
}
const highlightImpact = (id) => bfsHighlight(id, "reverse");
const highlightFlow = (id) => bfsHighlight(id, "forward");
// ── Sidebar (safe DOM builders — no innerHTML) ───────────────────
const sidebar = document.getElementById("sidebar");
function clearSidebar() { while (sidebar.firstChild) sidebar.removeChild(sidebar.firstChild); }
function closeSidebar() {
clearSidebar();
sidebar.className = "empty";
sidebar.appendChild(document.createTextNode("Click a node to see details"));
}
function actionBar(nodeId) {
return h("div", { class: "actions" },
h("button", { "data-action": "impact", "data-id": nodeId }, "Blast radius"),
h("button", { class: "flow", "data-action": "flow", "data-id": nodeId }, "Call flow"),
h("button", { class: "reset", "data-action": "reset" }, "Clear"),
);
}
function metaRow(label, value) {
return h("div", { class: "meta" }, h("strong", null, `${label}: `), String(value));
}
function openFile(id) {
const file = DATA.files.find((f) => f.id === id);
if (!file) return closeSidebar();
const color = colourFor(file.language);
const syms = (DATA.symbolsByFile && DATA.symbolsByFile[id]) || [];
const preview = syms.slice(0, 30);
clearSidebar();
sidebar.className = "";
sidebar.appendChild(h("h2", null, file.label));
sidebar.appendChild(h("div", { style: "font-size:11px;color:#6b7280;margin-bottom:8px;word-break:break-all;" }, file.id));
sidebar.appendChild(h("span", { class: "lang-badge", style: `background:${color}` }, file.language));
const connections = h("div", { class: "section" },
h("h3", null, "Connections"),
h("div", { class: "meta" },
"imports: ", h("strong", null, String(file.deps)),
" · imported by: ", h("strong", null, String(file.dependents)),
" · symbols: ", h("strong", null, String(file.symbolCount || 0)),
),
);
sidebar.appendChild(connections);
if (syms.length > 0) {
const section = h("div", { class: "section" },
h("h3", null, `Symbols (${syms.length})`),
);
const ul = h("ul", null);
for (const s of preview) {
const li = h("li", { "data-symbol-id": s.id, title: `${s.qualifiedName}:${s.line}` },
h("span", { style: `color:${KIND_COLORS[s.kind] || "#64748b"};font-weight:600;` }, s.kind),
" ",
s.name,
h("span", { style: "color:#94a3b8" }, `:${s.line}`),
);
ul.appendChild(li);
}
section.appendChild(ul);
if (syms.length > preview.length) {
section.appendChild(h("div", { style: "color:#9ca3af;font-size:11px;margin-top:4px" },
`+ ${syms.length - preview.length} more — use codebase_symbols to list all`));
}
sidebar.appendChild(section);
}
sidebar.appendChild(actionBar(`f::${file.id}`));
}
function openSymbol(id) {
const sym = (DATA.symbols || []).find((s) => s.id === id);
if (!sym) return closeSidebar();
clearSidebar();
sidebar.className = "";
sidebar.appendChild(h("h2", null, sym.name));
sidebar.appendChild(h("span", { class: "kind-badge" }, sym.kind));
sidebar.appendChild(metaRow("Qualified", sym.qualifiedName));
sidebar.appendChild(h("div", { class: "meta" }, h("strong", null, "File: "), h("code", null, sym.file)));
sidebar.appendChild(metaRow("Line", sym.line));
sidebar.appendChild(actionBar(`s::${sym.id}`));
}
// ── Event wiring ─────────────────────────────────────────────────
cy.on("tap", "node", (evt) => {
const n = evt.target;
if (n.data("nodeType") === "file") openFile(n.data("file"));
else openSymbol(n.id().slice(3));
});
cy.on("tap", (evt) => { if (evt.target === cy) { closeSidebar(); clearHighlights(); } });
sidebar.addEventListener("click", (evt) => {
const btn = evt.target.closest("button[data-action]");
if (btn) {
const action = btn.dataset.action;
if (action === "impact") highlightImpact(btn.dataset.id);
else if (action === "flow") highlightFlow(btn.dataset.id);
else if (action === "reset") clearHighlights();
return;
}
const li = evt.target.closest("li[data-symbol-id]");
if (li && currentView === "symbols") {
const cyNode = cy.getElementById(`s::${li.dataset.symbolId}`);
if (!cyNode.empty()) cy.animate({ center: { eles: cyNode }, zoom: 1.3 }, { duration: 300 });
}
});
// ── Toolbar wiring ───────────────────────────────────────────────
document.getElementById("layout").addEventListener("change", (e) => runLayout(e.target.value));
document.querySelectorAll(".view-toggle button").forEach((b) => b.addEventListener("click", () => switchView(b.dataset.view)));
document.getElementById("fit").addEventListener("click", () => cy.fit(undefined, 30));
document.getElementById("reset").addEventListener("click", () => { clearHighlights(); closeSidebar(); cy.fit(undefined, 30); });
document.getElementById("export").addEventListener("click", () => {
const png = cy.png({ full: true, scale: 2, bg: "#f8fafc" });
const a = document.createElement("a");
// Sanitise the project name for cross-platform filesystem safety:
// strip characters forbidden on Windows (<>:"/\\|?*), control chars,
// collapse whitespace, cap length, and fall back to "graph" if empty.
const rawName = String(DATA.project.name || "graph");
const safeName = rawName.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").trim().slice(0, 120) || "graph";
a.href = png; a.download = `${safeName}.png`; a.click();
});
// ── Live search ──────────────────────────────────────────────────
document.getElementById("search").addEventListener("input", (e) => {
const q = e.target.value.trim().toLowerCase();
clearHighlights();
if (!q) return;
const matches = cy.nodes().filter((n) => {
const label = (n.data("label") || "").toLowerCase();
const file = (n.data("file") || "").toLowerCase();
const qn = (n.data("qualifiedName") || "").toLowerCase();
return label.includes(q) || file.includes(q) || qn.includes(q);
});
if (matches.length === 0) return;
cy.elements().addClass("faded");
matches.removeClass("faded").addClass("highlight");
if (matches.length <= 20) cy.animate({ fit: { eles: matches, padding: 80 } }, { duration: 300 });
});
// ── Tooltip on hover ─────────────────────────────────────────────
const tooltip = document.getElementById("tooltip");
cy.on("mouseover", "node", (evt) => {
const n = evt.target;
const pos = evt.renderedPosition || n.renderedPosition();
tooltip.textContent = n.data("nodeType") === "file"
? `${n.data("file")} — ${n.data("language")}`
: `${n.data("qualifiedName")} — ${n.data("kind")} @ ${n.data("file")}:${n.data("line")}`;
tooltip.style.left = `${pos.x + 14}px`;
tooltip.style.top = `${pos.y + 14}px`;
tooltip.style.opacity = "1";
});
cy.on("mouseout", "node", () => { tooltip.style.opacity = "0"; });
// Right-click node → blast radius
cy.on("cxttap", "node", (evt) => highlightImpact(evt.target.id()));
// ── Symbols-unavailable banner ───────────────────────────────────
const banner = document.getElementById("banner");
if (DATA.symbolMode !== "full") {
banner.classList.add("visible");
banner.textContent = DATA.symbolMode === "omitted"
? `Symbol view disabled: ${DATA.symbolOmitReason || "no symbol graph available"}. Run codebase_graph_build first.`
: `Symbol view partial (${DATA.symbolOmitReason}). Use codebase_symbols / codebase_impact for full detail.`;
if (DATA.symbolMode === "omitted") {
document.querySelectorAll('.view-toggle button[data-view="symbols"]').forEach((b) => { b.disabled = true; b.title = "No symbol graph available"; });
}
}
// ── Initial layout + sidebar ─────────────────────────────────────
runLayout(currentLayout);
closeSidebar();
})();
+91
View File
@@ -0,0 +1,91 @@
/* SocratiCode interactive graph viewer — styles */
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; width: 100%; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; color: #1f2937; overflow: hidden; }
body { display: flex; flex-direction: column; }
/* ── top bar ─────────────────────────────────────────────────────── */
header {
display: flex; align-items: center; gap: 12px;
padding: 10px 16px; background: #0f172a; color: #e2e8f0;
border-bottom: 1px solid #1e293b; flex-shrink: 0;
}
header h1 { font-size: 15px; font-weight: 600; letter-spacing: -0.01em; }
header h1 .proj { color: #fbbf24; }
header .stats { font-size: 12px; color: #94a3b8; margin-left: 4px; }
header .sep { width: 1px; height: 18px; background: #334155; }
header .spacer { flex: 1; }
.toolbar { display: flex; gap: 6px; align-items: center; }
.toolbar label { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; }
.toolbar select, .toolbar input, .toolbar button {
background: #1e293b; color: #e2e8f0; border: 1px solid #334155;
padding: 5px 10px; border-radius: 4px; font-size: 12px; font-family: inherit;
outline: none;
}
.toolbar select:hover, .toolbar button:hover { background: #334155; cursor: pointer; }
.toolbar select:focus, .toolbar input:focus { border-color: #60a5fa; }
.toolbar input { width: 200px; }
.toolbar button.primary { background: #2563eb; border-color: #2563eb; }
.toolbar button.primary:hover { background: #1d4ed8; }
.toolbar button:disabled { opacity: 0.4; cursor: not-allowed; }
.view-toggle { display: inline-flex; border: 1px solid #334155; border-radius: 4px; overflow: hidden; }
.view-toggle button { border: none; border-radius: 0; padding: 5px 10px; }
.view-toggle button.active { background: #2563eb; color: #fff; }
/* ── main area ───────────────────────────────────────────────────── */
main { flex: 1; display: flex; min-height: 0; position: relative; }
#cy { flex: 1; background: #f8fafc; min-width: 0; }
#sidebar {
width: 340px; background: #fff; border-left: 1px solid #e5e7eb;
padding: 16px; overflow-y: auto; flex-shrink: 0;
font-size: 13px; line-height: 1.5;
}
#sidebar.empty { color: #94a3b8; font-style: italic; text-align: center; padding-top: 80px; }
#sidebar h2 { font-size: 14px; font-weight: 600; margin-bottom: 4px; word-break: break-all; }
#sidebar .kind-badge {
display: inline-block; padding: 2px 8px; border-radius: 10px;
font-size: 11px; font-weight: 500; margin-bottom: 8px;
background: #e0e7ff; color: #3730a3;
}
#sidebar .lang-badge {
display: inline-block; padding: 2px 8px; border-radius: 10px;
font-size: 11px; font-weight: 500; margin-bottom: 8px; color: #fff;
}
#sidebar .meta { color: #6b7280; font-size: 12px; margin-bottom: 12px; }
#sidebar .meta strong { color: #1f2937; }
#sidebar .section { margin-top: 14px; }
#sidebar .section h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 6px; }
#sidebar ul { list-style: none; }
#sidebar li { padding: 4px 8px; border-radius: 3px; cursor: pointer; font-family: ui-monospace, "SF Mono", Consolas, monospace; font-size: 12px; color: #334155; }
#sidebar li:hover { background: #f1f5f9; color: #0f172a; }
#sidebar .actions { margin-top: 14px; display: flex; gap: 6px; flex-wrap: wrap; }
#sidebar .actions button {
background: #fee2e2; color: #991b1b; border: 1px solid #fecaca;
padding: 5px 10px; border-radius: 4px; font-size: 12px; font-family: inherit; cursor: pointer;
}
#sidebar .actions button:hover { background: #fecaca; }
#sidebar .actions button.flow { background: #dbeafe; color: #1e40af; border-color: #bfdbfe; }
#sidebar .actions button.flow:hover { background: #bfdbfe; }
#sidebar .actions button.reset { background: #f3f4f6; color: #374151; border-color: #e5e7eb; }
#sidebar .actions button.reset:hover { background: #e5e7eb; }
#sidebar .actions button.truncated-note { background: transparent; border: none; color: #9ca3af; font-size: 11px; cursor: default; padding: 5px 0; }
/* ── banner (symbol-mode not available) ─────────────────────────── */
#banner {
position: absolute; top: 12px; left: 50%; transform: translateX(-50%);
background: #fef3c7; color: #92400e; border: 1px solid #fde68a;
padding: 8px 14px; border-radius: 6px; font-size: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.08); z-index: 10;
display: none;
}
#banner.visible { display: block; }
/* ── hover tooltip ──────────────────────────────────────────────── */
#tooltip {
position: absolute; background: #1f2937; color: #f9fafb;
padding: 6px 10px; border-radius: 4px; font-size: 12px;
pointer-events: none; opacity: 0; transition: opacity 0.1s;
max-width: 300px; word-break: break-all; z-index: 20;
}
+54
View File
@@ -0,0 +1,54 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{TITLE}}</title>
<style>{{STYLES}}</style>
</head>
<body>
<header>
<h1>SocratiCode <span class="proj">{{PROJECT_NAME}}</span> <span class="stats">{{STATS}}</span></h1>
<div class="sep"></div>
<div class="toolbar view-toggle" title="Switch between file-level and symbol-level graph">
<button data-view="files" class="active">Files</button>
<button data-view="symbols">Symbols</button>
</div>
<div class="sep"></div>
<div class="toolbar">
<label for="layout">Layout</label>
<select id="layout">
<option value="dagre">Hierarchical (Dagre)</option>
<option value="cose">Force-directed</option>
<option value="concentric">Concentric</option>
<option value="breadthfirst">Breadth-first</option>
<option value="grid">Grid</option>
<option value="circle">Circle</option>
</select>
</div>
<div class="spacer"></div>
<div class="toolbar">
<input id="search" type="text" placeholder="Search files / symbols…" autocomplete="off">
<button id="fit" title="Fit the whole graph into view">Fit</button>
<button id="reset" title="Clear highlights and recenter">Reset</button>
<button id="export" class="primary" title="Export the current view as a PNG image">Export PNG</button>
</div>
</header>
<main>
<div id="cy"></div>
<aside id="sidebar" class="empty">Click a node to see details</aside>
<div id="banner"></div>
<div id="tooltip"></div>
</main>
<script>{{CYTOSCAPE}}</script>
<script>{{DAGRE}}</script>
<script>{{CYTOSCAPE_DAGRE}}</script>
<script id="socraticode-data" type="application/json">{{DATA_JSON}}</script>
<script>
// Parse the embedded JSON from a <script type="application/json"> — safest
// channel for arbitrary strings; no template interpolation into JS.
window.__SOCRATICODE_DATA__ = JSON.parse(document.getElementById("socraticode-data").textContent);
</script>
<script>{{APP}}</script>
</body>
</html>
+13 -1
View File
@@ -232,12 +232,24 @@ server.tool(
server.tool(
"codebase_graph_visualize",
"Generate a visual Mermaid diagram of the code dependency graph, color-coded by language with circular dependencies highlighted.",
[
"Visualise the code dependency graph. Two modes:",
" • mode=\"mermaid\" (default) — returns a Mermaid diagram (text) colour-coded by language, circular deps highlighted. Best for inline rendering inside chat, GitHub, or editors that render Mermaid.",
" • mode=\"interactive\" — writes a self-contained HTML page (vendored Cytoscape.js + Dagre, works offline) and opens it in the user's default browser. Shows the file graph and, when a symbol graph is available and fits, a Symbols toggle with the symbol-level call graph. Interactions: click node for sidebar with imports/dependents/symbols list; right-click node to highlight its blast radius (reverse-transitive closure); live search; layout switcher (Dagre / force / concentric / breadth-first / grid / circle); PNG export. Use this when the user asks for a visual/interactive view, wants to explore visually, or needs a shareable diagram.",
].join("\n"),
{
projectPath: z
.string()
.describe("Absolute path to the project directory.")
.optional(),
mode: z
.enum(["mermaid", "interactive"])
.describe("\"mermaid\" (default — text diagram) or \"interactive\" (browser-based explorer).")
.optional(),
open: z
.boolean()
.describe("In interactive mode, whether to auto-open the browser. Default true. Set false to just get the file path (useful in headless environments).")
.optional(),
},
async (args) => ({
content: [{ type: "text", text: await handleGraphTool("codebase_graph_visualize", args) }],
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
/**
* Cross-platform helpers for the interactive graph viewer:
* 1. Write a generated HTML document to a stable path inside the OS
* temp directory (one file per project, deterministic by projectId).
* 2. Open that path in the user's default browser using the `open`
* package — handles macOS (`open`), Linux (`xdg-open`), and
* Windows (`start`) with zero external deps.
*
* `open` is called with `wait: false` so the call returns immediately;
* on headless Linux systems where no browser is registered the function
* swallows the error and lets the caller surface the path instead.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import open from "open";
import { logger } from "./logger.js";
/** Write HTML to a deterministic file under the OS temp dir. */
export async function writeInteractiveGraphFile(
projectId: string,
html: string,
): Promise<string> {
const dir = path.join(os.tmpdir(), "socraticode-graph");
await fs.mkdir(dir, { recursive: true });
const file = path.join(dir, `${projectId}.html`);
await fs.writeFile(file, html, "utf-8");
logger.info("Wrote interactive graph HTML", { file, bytes: html.length });
return file;
}
/** Open the given file path in the user's default browser (best-effort). */
export async function openInBrowser(filePath: string): Promise<{ opened: boolean; error?: string }> {
try {
await open(filePath, { wait: false });
return { opened: true };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.warn("Failed to open browser — user can open manually", { filePath, error: message });
return { opened: false, error: message };
}
}
+315
View File
@@ -0,0 +1,315 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
/**
* Interactive HTML graph visualiser.
*
* Builds a single self-contained HTML file that renders the project's
* file-import graph (and, when available, the symbol-level call graph)
* using a vendored Cytoscape.js + Dagre layout, so the file works offline
* without any CDN access.
*
* The generated page contains:
* - The file-import graph as the primary view (always available).
* - A "Symbols" toggle that switches to the symbol-level call graph,
* available when the symbol graph fits within the embed caps.
* - Per-file symbol lists in the sidebar (names, kinds, line numbers).
* - Blast-radius and call-flow overlays (click or right-click a node).
* - Live search across files and symbols, six layouts, PNG export.
*
* Scale caps (to keep the HTML payload bounded for gigantic repos):
* - Symbol graph embedded only if `symbolCount <= MAX_SYMBOLS` and
* `edgeCount <= MAX_EDGES`. Above either cap the symbol toggle is
* disabled and a banner explains why; the file view still works.
* - Per-file symbol list always embedded (capped at `MAX_SYMS_PER_FILE`
* per file — the sidebar shows the first N and a "use codebase_symbols
* for full list" note).
*/
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { getLanguageFromExtension } from "../constants.js";
import type { CodeGraph } from "../types.js";
import { findCircularDependencies } from "./graph-analysis.js";
import { logger } from "./logger.js";
import { loadFilePayload, loadSymbolGraphMeta } from "./symbol-graph-store.js";
// ── Assets locator ────────────────────────────────────────────────────
// Works in dev (tsx, src/) and prod (node, dist/): assets sit alongside
// the services directory in both layouts thanks to `scripts/copy-assets.mjs`.
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ASSETS_DIR = path.join(__dirname, "..", "assets");
// ── Caps ──────────────────────────────────────────────────────────────
const MAX_SYMBOLS = 20_000; // total symbols embedded in the Symbols view
const MAX_EDGES = 60_000; // total call edges embedded in the Symbols view
const MAX_SYMS_PER_FILE = 200; // per-file list shown in the sidebar
const PARALLEL_LOAD_BATCH = 20; // Qdrant payload fetches in parallel
// ── Data contract (matches viewer-app.js) ─────────────────────────────
export interface VizFile {
id: string; // relative path
label: string; // basename
language: string;
deps: number;
dependents: number;
symbolCount: number; // full count, even if list was truncated
}
export interface VizFileEdge {
source: string;
target: string;
type: "import" | "re-export" | "dynamic-import";
cyclic: boolean;
}
export interface VizSymbol {
id: string;
file: string;
name: string;
qualifiedName: string;
kind: string;
line: number;
}
export interface VizSymbolEdge {
source: string; // symbol id
target: string; // symbol id (first candidate)
confidence: "unique" | "multiple-candidates" | "local" | "unresolved";
}
export interface VizData {
project: { name: string; files: number; edges: number; symbols: number | null; callEdges: number | null; builtAt: string | null };
files: VizFile[];
fileEdges: VizFileEdge[];
symbols: VizSymbol[];
symbolEdges: VizSymbolEdge[];
/** Per-file symbol list for the sidebar; capped to MAX_SYMS_PER_FILE */
symbolsByFile: Record<string, VizSymbol[]>;
symbolMode: "full" | "omitted" | "capped";
symbolOmitReason?: string;
}
// ── Cached assets (read once per process) ─────────────────────────────
let _assetCache: { cytoscape: string; dagre: string; cytoscapeDagre: string; styles: string; app: string; template: string } | null = null;
async function loadAssets(): Promise<NonNullable<typeof _assetCache>> {
if (_assetCache) return _assetCache;
const [cytoscape, dagre, cytoscapeDagre, styles, app, template] = await Promise.all([
fs.readFile(path.join(ASSETS_DIR, "cytoscape.min.js"), "utf-8"),
fs.readFile(path.join(ASSETS_DIR, "dagre.min.js"), "utf-8"),
fs.readFile(path.join(ASSETS_DIR, "cytoscape-dagre.js"), "utf-8"),
fs.readFile(path.join(ASSETS_DIR, "viewer-styles.css"), "utf-8"),
fs.readFile(path.join(ASSETS_DIR, "viewer-app.js"), "utf-8"),
fs.readFile(path.join(ASSETS_DIR, "viewer-template.html"), "utf-8"),
]);
_assetCache = { cytoscape, dagre, cytoscapeDagre, styles, app, template };
return _assetCache;
}
/** Reset the asset cache (for tests / hot-reload). */
export function resetVisualizeAssetCache(): void {
_assetCache = null;
}
// ── Symbol-data loader ────────────────────────────────────────────────
interface SymbolLoadResult {
mode: "full" | "omitted" | "capped";
reason?: string;
symbols: VizSymbol[];
symbolEdges: VizSymbolEdge[];
symbolsByFile: Record<string, VizSymbol[]>;
perFileCount: Record<string, number>;
symbolCount: number | null;
edgeCount: number | null;
builtAt: number | null;
}
async function loadSymbolDataForViz(
projectId: string,
fileGraph: CodeGraph,
): Promise<SymbolLoadResult> {
const meta = await loadSymbolGraphMeta(projectId).catch(() => null);
if (!meta) {
return { mode: "omitted", reason: "no symbol graph meta", symbols: [], symbolEdges: [], symbolsByFile: {}, perFileCount: {}, symbolCount: null, edgeCount: null, builtAt: null };
}
const exceedsSymbols = meta.symbolCount > MAX_SYMBOLS;
const exceedsEdges = meta.edgeCount > MAX_EDGES;
const symbols: VizSymbol[] = [];
const symbolEdges: VizSymbolEdge[] = [];
const symbolsByFile: Record<string, VizSymbol[]> = {};
const perFileCount: Record<string, number> = {};
// Load per-file payloads in bounded parallel batches.
for (let i = 0; i < fileGraph.nodes.length; i += PARALLEL_LOAD_BATCH) {
const batch = fileGraph.nodes.slice(i, i + PARALLEL_LOAD_BATCH);
const payloads = await Promise.all(
batch.map((n) => loadFilePayload(projectId, n.relativePath).catch(() => null)),
);
for (const payload of payloads) {
if (!payload) continue;
perFileCount[payload.file] = payload.symbols.length;
const vizSymbols = payload.symbols.slice(0, MAX_SYMS_PER_FILE).map((s) => ({
id: s.id, file: payload.file, name: s.name, qualifiedName: s.qualifiedName, kind: s.kind, line: s.line,
}));
symbolsByFile[payload.file] = vizSymbols;
if (!exceedsSymbols) {
// Embed all symbols from the file into the top-level list (no cap there)
for (const s of payload.symbols) {
symbols.push({ id: s.id, file: payload.file, name: s.name, qualifiedName: s.qualifiedName, kind: s.kind, line: s.line });
}
}
if (!exceedsEdges) {
for (const e of payload.outgoingCalls) {
const target = e.calleeCandidates[0];
if (!target) continue;
symbolEdges.push({ source: e.callerId, target, confidence: e.confidence });
}
}
}
}
if (exceedsSymbols || exceedsEdges) {
const parts: string[] = [];
if (exceedsSymbols) parts.push(`${meta.symbolCount.toLocaleString()} symbols > ${MAX_SYMBOLS.toLocaleString()} cap`);
if (exceedsEdges) parts.push(`${meta.edgeCount.toLocaleString()} call edges > ${MAX_EDGES.toLocaleString()} cap`);
return {
mode: "capped",
reason: parts.join(", "),
symbols: [], symbolEdges: [], symbolsByFile, perFileCount,
symbolCount: meta.symbolCount, edgeCount: meta.edgeCount, builtAt: meta.builtAt,
};
}
return {
mode: "full",
symbols, symbolEdges, symbolsByFile, perFileCount,
symbolCount: meta.symbolCount, edgeCount: meta.edgeCount, builtAt: meta.builtAt,
};
}
// ── File-graph → viz data ─────────────────────────────────────────────
function buildFileVizData(graph: CodeGraph): { files: VizFile[]; fileEdges: VizFileEdge[] } {
// Circular-dependency edge set for highlighting
const cyclicEdgeKeys = new Set<string>();
const cycles = findCircularDependencies(graph);
for (const cycle of cycles) {
for (let i = 0; i < cycle.length - 1; i++) cyclicEdgeKeys.add(`${cycle[i]}->${cycle[i + 1]}`);
}
const files: VizFile[] = graph.nodes.map((n) => ({
id: n.relativePath,
label: path.basename(n.relativePath),
language: getLanguageFromExtension(path.extname(n.relativePath).toLowerCase()),
deps: n.dependencies.length,
dependents: n.dependents.length,
symbolCount: 0,
}));
// Dedupe edges (graph edges may repeat on multi-import files)
const seen = new Set<string>();
const fileEdges: VizFileEdge[] = [];
for (const e of graph.edges) {
const key = `${e.source}->${e.target}`;
if (seen.has(key)) continue;
seen.add(key);
fileEdges.push({ source: e.source, target: e.target, type: e.type, cyclic: cyclicEdgeKeys.has(key) });
}
return { files, fileEdges };
}
// ── HTML escapers ─────────────────────────────────────────────────────
/** Escape text for safe interpolation into HTML text content / attrs. */
function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] as string);
}
/**
* Serialize data for embedding inside a <script type="application/json">
* block. Escapes every `<` as the JSON unicode escape `\u003c` so the HTML
* parser cannot see a stray `</script>` anywhere inside the payload.
*/
function toEmbeddedJson(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}
// ── Public API ────────────────────────────────────────────────────────
export interface InteractiveHtmlOptions {
projectPath: string;
projectName: string;
projectId: string;
graph: CodeGraph;
}
/**
* Build the interactive HTML viewer for a project as a single
* self-contained string. Includes the file-import graph unconditionally
* and the symbol-level call graph when it fits within the embed caps.
*/
export async function buildInteractiveGraphHtml(opts: InteractiveHtmlOptions): Promise<{ html: string; stats: { files: number; fileEdges: number; symbolMode: string; symbols: number; symbolEdges: number } }> {
const assets = await loadAssets();
const { files, fileEdges } = buildFileVizData(opts.graph);
const sym = await loadSymbolDataForViz(opts.projectId, opts.graph);
// Attach full symbol counts to file viz rows
for (const f of files) f.symbolCount = sym.perFileCount[f.id] ?? 0;
const data: VizData = {
project: {
name: opts.projectName,
files: files.length,
edges: fileEdges.length,
symbols: sym.symbolCount,
callEdges: sym.edgeCount,
builtAt: sym.builtAt ? new Date(sym.builtAt).toISOString() : null,
},
files,
fileEdges,
symbols: sym.symbols,
symbolEdges: sym.symbolEdges,
symbolsByFile: sym.symbolsByFile,
symbolMode: sym.mode,
symbolOmitReason: sym.reason,
};
const statsLine = sym.mode === "full"
? `${files.length} files · ${fileEdges.length} edges · ${sym.symbolCount ?? 0} symbols · ${sym.edgeCount ?? 0} calls`
: `${files.length} files · ${fileEdges.length} edges`;
const html = assets.template
.replace(/\{\{TITLE\}\}/g, escapeHtml(`${opts.projectName} — SocratiCode graph`))
.replace(/\{\{PROJECT_NAME\}\}/g, escapeHtml(opts.projectName))
.replace(/\{\{STATS\}\}/g, escapeHtml(statsLine))
.replace("{{STYLES}}", assets.styles)
.replace("{{CYTOSCAPE}}", assets.cytoscape)
.replace("{{DAGRE}}", assets.dagre)
.replace("{{CYTOSCAPE_DAGRE}}", assets.cytoscapeDagre)
.replace("{{DATA_JSON}}", toEmbeddedJson(data))
.replace("{{APP}}", assets.app);
logger.info("Built interactive graph HTML", {
project: opts.projectName,
files: files.length,
fileEdges: fileEdges.length,
symbolMode: sym.mode,
symbols: sym.symbols.length,
symbolEdges: sym.symbolEdges.length,
htmlBytes: html.length,
});
return {
html,
stats: {
files: files.length,
fileEdges: fileEdges.length,
symbolMode: sym.mode,
symbols: sym.symbols.length,
symbolEdges: sym.symbolEdges.length,
},
};
}
+39
View File
@@ -13,6 +13,8 @@ import {
listSymbols,
looksLikeFilePath,
} from "../services/graph-impact.js";
import { openInBrowser, writeInteractiveGraphFile } from "../services/graph-visualize-browser.js";
import { buildInteractiveGraphHtml } from "../services/graph-visualize-html.js";
import { logger } from "../services/logger.js";
import { getSymbolGraphCache } from "../services/symbol-graph-cache.js";
import { ensureWatcherStarted } from "../services/watcher.js";
@@ -171,6 +173,43 @@ export async function handleGraphTool(
return "No graph data available. Run codebase_graph_build first.";
}
const rawMode = String(args.mode ?? "mermaid").toLowerCase();
if (rawMode !== "mermaid" && rawMode !== "interactive") {
return `Invalid mode "${rawMode}". Must be "mermaid" (default — returns Mermaid text) or "interactive" (generates a self-contained HTML page and opens it in the browser).`;
}
if (rawMode === "interactive") {
const projectId = projectIdFromPath(projectPath);
const projectName = path.basename(projectPath);
const { html, stats } = await buildInteractiveGraphHtml({ projectPath, projectName, projectId, graph });
const file = await writeInteractiveGraphFile(projectId, html);
const noOpenRequested = args.open === false || args.open === "false";
const openResult = noOpenRequested ? { opened: false as const } : await openInBrowser(file);
const lines = [
`Interactive dependency graph for: ${projectPath}`,
`File written: ${file}`,
`Stats: ${stats.files} files · ${stats.fileEdges} edges · symbol view: ${stats.symbolMode}${stats.symbolMode === "full" ? ` (${stats.symbols} symbols / ${stats.symbolEdges} calls)` : ""}`,
];
if (noOpenRequested) {
lines.push("", "Browser auto-open skipped (open=false). Open the file above manually.");
} else if (openResult.opened) {
lines.push("", "Opened in your default browser. If nothing appears, open the file path above manually.");
} else {
lines.push("", `Could not auto-open a browser (${openResult.error}). Open the file path above manually.`);
}
lines.push(
"",
"Interactions:",
" • Click a node → sidebar with file/symbol details, symbols list, and action buttons.",
" • Right-click a node → highlight its blast radius (reverse-transitive closure).",
" • Toggle Files ↔ Symbols at the top (Symbols disabled on gigantic repos — use codebase_impact for those).",
" • Search box filters nodes live; layout dropdown switches between Dagre / force / concentric / grid.",
" • Export PNG button produces a shareable image of the current view.",
);
return lines.join("\n");
}
const mermaid = generateMermaidDiagram(graph);
return [
`Dependency graph for: ${projectPath}`,
+1 -1
View File
@@ -214,7 +214,7 @@ export async function handleManageTool(
" codebase_graph_query — Imports & dependents for a file.",
" codebase_graph_stats — Graph stats: files, edges, most connected, orphans.",
" codebase_graph_circular — Find circular dependencies.",
" codebase_graph_visualize — Mermaid diagram, color-coded by language.",
" codebase_graph_visualize — Mermaid diagram (default) or interactive HTML explorer (mode=\"interactive\"), colour-coded by language.",
" codebase_graph_status — Poll graph build progress.",
" codebase_graph_remove — Delete a project's graph.",
"",
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("open", () => ({ default: vi.fn().mockResolvedValue(undefined) }));
import openMock from "open";
import { openInBrowser, writeInteractiveGraphFile } from "../../src/services/graph-visualize-browser.js";
describe("writeInteractiveGraphFile", () => {
const written: string[] = [];
afterEach(async () => {
for (const f of written.splice(0)) await fs.rm(f, { force: true });
});
it("writes to a deterministic path keyed by projectId", async () => {
const html = "<!doctype html><html></html>";
const p1 = await writeInteractiveGraphFile("proj-abc", html);
written.push(p1);
expect(p1).toBe(path.join(os.tmpdir(), "socraticode-graph", "proj-abc.html"));
const read = await fs.readFile(p1, "utf-8");
expect(read).toBe(html);
});
it("overwrites on a second call for the same project", async () => {
const a = await writeInteractiveGraphFile("proj-overwrite", "<html>v1</html>");
written.push(a);
const b = await writeInteractiveGraphFile("proj-overwrite", "<html>v2</html>");
expect(a).toBe(b);
const read = await fs.readFile(b, "utf-8");
expect(read).toBe("<html>v2</html>");
});
});
describe("openInBrowser", () => {
beforeEach(() => { vi.clearAllMocks(); });
it("returns opened:true when the `open` package succeeds", async () => {
vi.mocked(openMock).mockResolvedValueOnce(undefined as unknown as never);
const result = await openInBrowser("/tmp/x.html");
expect(result.opened).toBe(true);
expect(openMock).toHaveBeenCalledWith("/tmp/x.html", { wait: false });
});
it("returns opened:false + error on failure (headless env, blocked, etc.)", async () => {
vi.mocked(openMock).mockRejectedValueOnce(new Error("xdg-open missing"));
const result = await openInBrowser("/tmp/x.html");
expect(result.opened).toBe(false);
expect(result.error).toContain("xdg-open");
});
});
+124
View File
@@ -0,0 +1,124 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { CodeGraph } from "../../src/types.js";
// Mock the symbol-graph loader before importing the module under test —
// buildInteractiveGraphHtml calls into Qdrant via symbol-graph-store, which
// we don't want to hit from a pure unit test.
vi.mock("../../src/services/symbol-graph-store.js", () => ({
loadSymbolGraphMeta: vi.fn().mockResolvedValue(null),
loadFilePayload: vi.fn().mockResolvedValue(null),
}));
import { buildInteractiveGraphHtml, resetVisualizeAssetCache } from "../../src/services/graph-visualize-html.js";
import { loadFilePayload, loadSymbolGraphMeta } from "../../src/services/symbol-graph-store.js";
const SAMPLE_GRAPH: CodeGraph = {
nodes: [
{ filePath: "/proj/a.ts", relativePath: "a.ts", imports: ["./b"], exports: [], dependencies: ["b.ts"], dependents: [] },
{ filePath: "/proj/b.ts", relativePath: "b.ts", imports: ["./c"], exports: [], dependencies: ["c.ts"], dependents: ["a.ts"] },
{ filePath: "/proj/c.ts", relativePath: "c.ts", imports: [], exports: [], dependencies: [], dependents: ["b.ts"] },
],
edges: [
{ source: "a.ts", target: "b.ts", type: "import" },
{ source: "b.ts", target: "c.ts", type: "import" },
],
};
describe("graph-visualize-html", () => {
beforeEach(() => {
resetVisualizeAssetCache();
vi.mocked(loadSymbolGraphMeta).mockResolvedValue(null);
vi.mocked(loadFilePayload).mockResolvedValue(null);
});
it("builds a self-contained HTML page for a file-only graph", async () => {
const { html, stats } = await buildInteractiveGraphHtml({
projectPath: "/proj", projectName: "sample", projectId: "p1", graph: SAMPLE_GRAPH,
});
expect(html.startsWith("<!doctype html>")).toBe(true);
expect(html).toContain("</html>");
// Vendored Cytoscape + Dagre are inlined, not CDN references
expect(html).not.toContain("cdn.jsdelivr.net");
expect(html).not.toContain("unpkg.com");
expect(html).toContain("Cytoscape");
// Embedded data channel exists
expect(html).toContain('id="socraticode-data"');
// Project name appears in the header
expect(html).toContain("sample");
expect(stats.files).toBe(3);
expect(stats.fileEdges).toBe(2);
expect(stats.symbolMode).toBe("omitted");
});
it("escapes every '<' inside embedded JSON so a stray </script> cannot break out", async () => {
const maliciousGraph: CodeGraph = {
nodes: [{
filePath: "/proj/weird.ts", relativePath: "weird</script><script>alert(1)</script>.ts",
imports: [], exports: [], dependencies: [], dependents: [],
}],
edges: [],
};
const { html } = await buildInteractiveGraphHtml({
projectPath: "/proj", projectName: "x", projectId: "p1", graph: maliciousGraph,
});
// Raw </script> must not appear inside the embedded-data <script> block.
// Extract the JSON block and verify.
const match = html.match(/<script id="socraticode-data"[^>]*>([\s\S]*?)<\/script>/);
expect(match).toBeTruthy();
const jsonText = match?.[1] ?? "";
expect(jsonText.includes("</script>")).toBe(false);
// The escape form we chose is \u003c (Unicode escape for '<').
expect(jsonText).toContain("\\u003c");
});
it("omits the symbol graph when no meta is present and notes reason", async () => {
vi.mocked(loadSymbolGraphMeta).mockResolvedValue(null);
const { html, stats } = await buildInteractiveGraphHtml({
projectPath: "/proj", projectName: "sample", projectId: "p1", graph: SAMPLE_GRAPH,
});
expect(stats.symbolMode).toBe("omitted");
expect(stats.symbols).toBe(0);
expect(stats.symbolEdges).toBe(0);
// Data payload records the mode
expect(html).toContain('"symbolMode":"omitted"');
});
it("flags symbolMode=capped when symbol counts exceed embed caps", async () => {
vi.mocked(loadSymbolGraphMeta).mockResolvedValue({
projectId: "p1",
symbolCount: 999_999, edgeCount: 999_999, fileCount: 3,
unresolvedEdgePct: 0, builtAt: Date.now(), schemaVersion: 1,
});
vi.mocked(loadFilePayload).mockResolvedValue({
file: "a.ts", language: "typescript", contentHash: "x",
symbols: [], outgoingCalls: [],
});
const { html, stats } = await buildInteractiveGraphHtml({
projectPath: "/proj", projectName: "big", projectId: "p1", graph: SAMPLE_GRAPH,
});
expect(stats.symbolMode).toBe("capped");
expect(html).toContain('"symbolMode":"capped"');
});
it("marks edges that belong to a cycle as cyclic:true", async () => {
const cyclic: CodeGraph = {
nodes: [
{ filePath: "/proj/x.ts", relativePath: "x.ts", imports: ["./y"], exports: [], dependencies: ["y.ts"], dependents: ["y.ts"] },
{ filePath: "/proj/y.ts", relativePath: "y.ts", imports: ["./x"], exports: [], dependencies: ["x.ts"], dependents: ["x.ts"] },
],
edges: [
{ source: "x.ts", target: "y.ts", type: "import" },
{ source: "y.ts", target: "x.ts", type: "import" },
],
};
const { html } = await buildInteractiveGraphHtml({
projectPath: "/proj", projectName: "cycle", projectId: "p1", graph: cyclic,
});
expect(html).toContain('"cyclic":true');
});
});