File: README.md
Understand Anything
You just joined a new team. The codebase is 200,000 lines of code. Where do you even start?
Understand Anything is a Claude Code Plugin that analyzes your project with a multi-agent pipeline, builds a knowledge graph of every file, function, class, and dependency, then gives you an interactive dashboard to explore it all visually. Stop reading code blind. Start seeing the big picture.
The goal isn't a graph that wows you with how complex your codebase is โ it's a graph that quietly teaches you how every piece fits together.
โจ Features
[!NOTE]
Want to skip the reading? Try the live demo in our homepage โ a fully interactive dashboard you can pan, zoom, search, and explore right in your browser.
Explore the structural graph
Navigate your codebase as an interactive knowledge graph โ every file, function, and class is a node you can click, search, and explore. Select any node to see plain-English summaries, relationships, and guided tours.
Understand business logic
Switch to the domain view and see how your code maps to real business processes โ domains, flows, and steps laid out as a horizontal graph.
Analyze knowledge bases
Point /understand-knowledge at a Karpathy-pattern LLM wiki and get a force-directed knowledge graph with community clustering. The deterministic parser extracts wikilinks and categories from index.md, then LLM agents discover implicit relationships, extract entities, and surface claims โ turning your wiki into a navigable graph of interconnected ideas.
| ๐งญ Guided Tours
Auto-generated walkthroughs of the architecture, ordered by dependency. Learn the codebase in the right order. | ๐ Fuzzy & Semantic Search
Find anything by name or by meaning. Search "which parts handle auth?" and get relevant results across the graph. |
| --- | --- |
| ๐ Diff Impact Analysis
See which parts of the system your changes affect before you commit. Understand ripple effects across the codebase. | ๐ญ Persona-Adaptive UI
The dashboard adjusts its detail level based on who you are โ junior dev, PM, or power user. |
| ๐๏ธ Layer Visualization
Automatic grouping by architectural layer โ API, Service, Data, UI, Utility โ with color-coded legend. | ๐ Language Concepts
12 programming patterns (generics, closures, decorators, etc.) explained in context wherever they appear. |
๐ Quick Start
1. Install the plugin
/plugin marketplace add Egonex-AI/Understand-Anything
/plugin install understand-anythingUsing a local model? For privacy or enterprise setups, point your platform at a local model provider such as Ollama โ follow their integration guide to change the model provider.
2. Analyze your codebase
/understandA multi-agent pipeline scans your project, extracts every file, function, class, and dependency, then builds a knowledge graph saved to .ua/knowledge-graph.json. (Projects that already have a .understand-anything/ directory keep using it โ it stays the data directory when present, so nothing needs migrating.)
Heads up on token usage: The initial
/understandanalyzes your whole codebase and can consume a significant number of tokens on large projects. We recommend running it on a token plan / subscription, or using a local model (see above) for initialization. Subsequent runs are incremental by default โ only changed files are re-analyzed โ so they use far fewer tokens.
Localized output: Use --language to generate content in your preferred language:
# Generate Chinese content (็ฅ่ฏๅพ่็นๆ่ฟฐๅ Dashboard UI)
/understand --language zh
# Supported languages: en (default), zh, zh-TW, ja, ko, ruOn the first run in a project โ when you don't pass --language and no language is stored yet โ /understand detects the language you're conversing in. If it isn't English, it asks you to confirm (or override) before generating; English conversations are unaffected. Your choice is saved to .ua/config.json and reused on every later run.
The --language parameter affects:
- Node summaries and descriptions in the knowledge graph
- Dashboard UI labels, buttons, and tooltips
- Guided tour explanations
3. Explore the dashboard
/understand-dashboardAn interactive web dashboard opens with your codebase visualized as a graph โ color-coded by architectural layer, searchable, and clickable. Select any node to see its code, relationships, and a plain-English explanation.
4. Keep learning
# Ask anything about the codebase
/understand-chat How does the payment flow work?
# Analyze impact of your current changes
/understand-diff
# Deep-dive into a specific file or function
/understand-explain src/auth/login.ts
# Generate an onboarding guide for new team members
/understand-onboard
# Extract business domain knowledge (domains, flows, steps)
/understand-domain
# Analyze a Karpathy-pattern LLM wiki knowledge base
/understand-knowledge ~/path/to/wiki
# Re-run anytime โ incremental by default (only re-analyzes changed files)
/understand
# Auto-update on every commit via a post-commit hook
/understand --auto-update
# Scope to a subdirectory (for huge monorepos)
/understand src/frontend๐ Multi-Platform Installation
Understand-Anything works across multiple AI coding platforms.
Claude Code (Native)
/plugin marketplace add Egonex-AI/Understand-Anything
/plugin install understand-anythingOne-line install (Codex / OpenCode / OpenClaw / Antigravity / Gemini CLI / Pi Agent / Vibe CLI / VS Code Copilot / Hermes / Cline / KIMI CLI / Trae / Nanobot / Kiro)
macOS / Linux:
curl -fsSL https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.sh | bash
# or skip the prompt by passing the platform:
curl -fsSL https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.sh | bash -s codexWindows (PowerShell):
iwr -useb https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.ps1 | iexThe installer clones the repo to ~/.understand-anything/repo and creates the right symlinks for the chosen platform. Restart your CLI/IDE afterwards.
Note on invoking skills: the invocation prefix differs per platform. Most platforms use slash commands (
/understand), but Codex uses$instead โ type$understand, not/understand. If neither prefix is recognized on your platform, just ask in plain language: "Use the understand skill to analyze this project."
- Supported `` values:
gemini,codex,opencode,pi,openclaw,antigravity,vibe,vscode,hermes,cline,kimi,trae,nanobot,kiro - Update later:
./install.sh --update - Uninstall:
./install.sh --uninstall
Cursor
Cursor auto-discovers the plugin via .cursor-plugin/plugin.json when this repo is cloned. No manual installation needed โ just clone and open in Cursor.
If auto-discovery doesn't pick it up, install it manually: open Cursor Settings โ Plugins, paste https://github.com/Egonex-AI/Understand-Anything into the search field, and add it from there.
VS Code + GitHub Copilot
VS Code with GitHub Copilot (v1.108+) auto-discovers the plugin via .copilot-plugin/plugin.json when this repo is cloned. No manual installation needed โ just clone and open in VS Code.
For personal skills (available across all projects), run the install.sh above with the vscode platform.
Copilot CLI
copilot plugin install Egonex-AI/Understand-Anything:understand-anything-pluginKiro CLI / IDE
curl -fsSL https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.sh | bash -s kiroAfter installation:
- Kiro CLI:
kiro-cli chat --agent understand "Analyze this project" - Kiro IDE: The skills are symlinked into
~/.kiro/skills/and theunderstandagent is written to~/.kiro/agents/understand.json, so both are available after restarting the IDE.
For personal skills (available across all projects), run the install.sh above with the kiro platform.
Platform Compatibility
| Platform | Status | Install Method |
|---|---|---|
| Claude Code | โ Native | Plugin marketplace |
| Cursor | โ Supported | Auto-discovery |
| VS Code + GitHub Copilot | โ Supported | Auto-discovery |
| Copilot CLI | โ Supported | Plugin install |
| Codex | โ Supported | install.sh codex |
| OpenCode | โ Supported | install.sh opencode |
| OpenClaw | โ Supported | install.sh openclaw |
| Antigravity | โ Supported | install.sh antigravity |
| Gemini CLI | โ Supported | install.sh gemini |
| Pi Agent | โ Supported | install.sh pi |
| Vibe CLI | โ Supported | install.sh vibe |
| Hermes | โ Supported | install.sh hermes |
| Cline | โ Supported | install.sh cline |
| KIMI CLI | โ Supported | install.sh kimi |
| Trae | โ Supported | install.sh trae |
| Nanobot | โ Supported | install.sh nanobot |
| Kiro CLI / IDE | โ Supported | install.sh kiro |
๐ฆ Share the Graph with Your Team
The graph is just JSON โ commit it once, and teammates skip the pipeline. Good for onboarding, PR reviews, and docs-as-code.
Example: GoogleCloudPlatform/microservices-demo โ Go / Java / Python / Node reference with a committed graph.
What to commit: everything in .ua/ except intermediate/ and diff-overlay.json (those are local scratch). (Legacy projects use .understand-anything/ โ substitute that directory name below if it's the one present.)
.ua/intermediate/
.ua/diff-overlay.jsonKeep it fresh: enable /understand --auto-update โ a post-commit hook incrementally patches the graph so each commit lands with a matching graph. Or re-run /understand manually before releases.
Large graphs (10 MB+): track with git-lfs.
git lfs install
git lfs track ".ua/*.json"
git add .gitattributes .ua/View the dashboard without Claude Code
Once a graph has been generated and committed, anyone on the team can open it with one command โ no Claude Code, no LLM, no API key. Only Node.js (>= 18) is required:
npx https://github.com/Egonex-AI/Understand-Anything/releases/latest/download/understand-anything-viewer.tgz /path/to/analyzed/projectThe terminal prints a tokenized URL (http://127.0.0.1:5173/?token=โฆ) and opens the full interactive dashboard in your browser. The project directory (default: current directory) must contain the committed data directory (.ua/, or legacy .understand-anything/). Everything is served read-only from local disk โ no LLM calls, no data leaves your machine.
Working from a clone instead? pnpm install && pnpm --filter @understand-anything/core build, then GRAPH_DIR=/path/to/analyzed/project pnpm dev:dashboard does the same via the Vite dev server.
๐ง Under the Hood
Tree-sitter + LLM hybrid
Static analysis and LLMs do what each does best:
- Tree-sitter (deterministic) โ parses source into a concrete syntax tree and extracts structural facts: imports, exports, function/class definitions, call sites, inheritance. Pre-resolved into an
importMapduring the scan phase and passed to file-analyzers so they don't re-derive imports from source. Same input โ same output, every run. Also powers fingerprint-based change detection for incremental updates. - LLM (semantic) โ reads the parsed structure alongside the original source to produce what parsers can't: plain-English summaries, tags, architectural layer assignments, business-domain mapping, guided tours, language concept callouts.
This split is why the graph is reproducible on the structural side (the same code always yields the same edges) while still capturing intent on the semantic side (what a file is for, not just what it imports).
Multi-Agent Pipeline
The /understand command orchestrates 5 specialized agents, and /understand-domain adds a 6th:
| Agent | Role |
|---|---|
project-scanner |
Discover files, detect languages and frameworks |
file-analyzer |
Extract functions, classes, imports; produce graph nodes and edges |
architecture-analyzer |
Identify architectural layers |
tour-builder |
Generate guided learning tours |
graph-reviewer |
Validate graph completeness and referential integrity (runs inline by default; use --review for full LLM review) |
domain-analyzer |
Extract business domains, flows, and process steps (used by /understand-domain) |
article-analyzer |
Extract entities, claims, and implicit relationships from wiki articles (used by /understand-knowledge) |
File analyzers run in parallel (up to 5 concurrent, 20-30 files per batch). Supports incremental updates โ only re-analyzes files that changed since the last run.
๐ฅ Community
A community-made walkthrough by Better Stack.
Made a video, blog post, or tutorial? Open an issue or PR โ happy to feature it here.
๐ค Contributing
Contributions are welcome! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/my-feature) - Run the tests (
pnpm --filter @understand-anything/core test) - Commit your changes and open a pull request
Please open an issue first for major changes so we can discuss the approach.
Star History
File: docs/superpowers/specs/2026-03-14-understand-anything-design.md
Understand Anything โ Design & Implementation Plan
Context
AI coding tools have made writing code easy, but understanding code remains hard. Junior developers, non-programmers (PMs, designers), and even experienced devs working in unfamiliar languages struggle to comprehend codebases they didn't write โ or that AI wrote for them. The only entity that "understands" the code is the AI itself.
Understand Anything bridges this gap: an open-source tool that combines LLM intelligence with static analysis to produce an interactive, multi-persona dashboard for understanding any codebase. It runs as a Claude Code skill (leveraging the active session) and serves a rich web dashboard.
Architecture: Monorepo with Shared Core
understand-anything/
โโโ packages/
โ โโโ core/ # Shared analysis engine
โ โ โโโ analyzer/ # LLM + tree-sitter analysis
โ โ โโโ graph/ # Knowledge graph builder & schema
โ โ โโโ plugins/ # Plugin system for language analyzers
โ โ โโโ persistence/ # JSON read/write, staleness detection
โ โโโ skill/ # Claude Code skill (5 commands)
โ โโโ dashboard/ # React + TypeScript multi-panel workspace
โโโ plugins/ # Built-in language analyzer plugins
โ โโโ tree-sitter/ # Tree-sitter based multi-language analyzer
โโโ docs/
โ โโโ plans/
โโโ package.json # Monorepo root (pnpm workspaces)
โโโ tsconfig.json
โโโ .gitignoreKey decisions:
- Monorepo (pnpm workspaces) โ skill and dashboard share the core analysis engine
- JSON interchange โ knowledge graph is a JSON file, readable by both skill and dashboard
- Committable + auto-sync โ graph persists in
.understand-anything/, can be committed to git, auto-detects staleness via git diff
Knowledge Graph Schema
interface KnowledgeGraph {
version: string;
project: ProjectMeta;
nodes: GraphNode[];
edges: GraphEdge[];
layers: Layer[];
tour: TourStep[];
}
interface ProjectMeta {
name: string;
languages: string[];
frameworks: string[];
analyzedAt: string; // ISO timestamp
gitCommitHash: string; // For staleness detection
}
interface GraphNode {
id: string;
type: "file" | "function" | "class" | "module" | "concept";
name: string;
filePath?: string;
lineRange?: [number, number];
summary: string; // Plain-English description
tags: string[]; // Searchable tags
complexity: "simple" | "moderate" | "complex";
languageNotes?: string; // Language-specific explanations
}
interface GraphEdge {
source: string;
target: string;
type: EdgeType;
direction: "forward" | "backward" | "bidirectional";
description?: string;
weight: number; // 0-1 importance
}
type EdgeType =
// Structural
| "imports" | "exports" | "contains" | "inherits" | "implements"
// Behavioral
| "calls" | "subscribes" | "publishes" | "middleware"
// Data flow
| "reads_from" | "writes_to" | "transforms" | "validates"
// Dependencies
| "depends_on" | "tested_by" | "configures"
// Semantic
| "related" | "similar_to";
interface Layer {
id: string;
name: string; // e.g., "API Layer", "Data Layer"
nodeIds: string[];
}
interface TourStep {
order: number;
title: string;
nodeIds: string[]; // Nodes to highlight
languageLesson?: string; // Optional language concept explanation
}Dashboard: Multi-Panel Workspace (React + TypeScript)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ Natural Language Search: "communication layer" โ
โโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ GRAPH VIEW โ CODE VIEWER โ
โ (React Flow) โ (Monaco Editor, read-only) โ
โ โ โ
โ Interactive node โ Source code + syntax highlight โ
โ graph. Click to โ LLM annotations inline. โ
โ select. Search โ โ
โ highlights. โ โ
โโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ CHAT PANEL โ LEARN PANEL โ
โ โ โ
โ Context-aware Q&A โ Tour mode + Contextual mode โ
โ about selected โ Language lessons in context โ
โ nodes / project. โ of YOUR code. โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโTech stack:
- React 18 + TypeScript + Vite
- React Flow โ graph visualization (built for node graphs, better than raw D3 for this)
- Monaco Editor โ code viewer with syntax highlighting (same as VS Code)
- TailwindCSS โ styling
- Zustand โ state management (lightweight, no boilerplate)
Persona modes:
- Non-technical: High-level concept nodes, code viewer hidden, learn panel expanded
- Junior dev: All panels, learn panel prominent, complexity indicators
- Experienced dev: Code viewer prominent, chat panel for deep dives
Natural language search:
- Searches against node
tags,summary, andnamefields - Uses embedding similarity if available, falls back to keyword matching
- Highlights matching nodes in the graph, filters the list
Claude Code Skill Commands
| Command | Description |
|---|---|
/understand |
Full analysis (or incremental update if graph exists) + open dashboard |
/understand-chat "<query>" |
In-terminal Q&A using the knowledge graph |
/understand-diff |
Analyze current PR/diff โ explain changes, affected areas, risks |
/understand-explain |
Deep-dive explanation of a specific file or function |
/understand-onboard |
Generate structured onboarding guide for new team members |
LLM strategy:
- Inside Claude Code โ uses the active Claude session (zero extra cost)
- Standalone dashboard โ users provide Claude API key for chat features
- Graph browsing, search, and learn mode work offline (pre-generated data)
Persistence & Staleness Detection
.understand-anything/
โโโ knowledge-graph.json # The full graph (committable)
โโโ meta.json # Analysis metadata
โ {
โ "lastAnalyzedAt": "2026-03-14T...",
โ "gitCommitHash": "abc123",
โ "version": "1.0.0",
โ "analyzedFiles": 47
โ }
โโโ cache/ # Per-file analysis cache
โ โโโ src__index.ts.json
โ โโโ src__auth__login.ts.json
โโโ tours/
โโโ default-tour.jsonAuto-sync flow:
- Skill starts โ reads
meta.jsonโ gets last analyzed commit hash - Runs
git diff <last-hash>..HEAD --name-onlyโ gets changed files - If no changes โ serves existing graph
- If changes โ re-analyzes only changed files โ merges into existing graph โ updates meta
Plugin System
interface AnalyzerPlugin {
name: string;
languages: string[];
analyzeFile(filePath: string, content: string): StructuralAnalysis;
resolveImports(filePath: string, content: string): ImportResolution[];
extractCallGraph?(filePath: string, content: string): CallGraphEntry[];
}Day 1: tree-sitter plugin โ uses node-tree-sitter with language grammars for:
- TypeScript/JavaScript, Python, Go, Java, Rust, C/C++
- Extracts: function/class boundaries, import/export statements, call sites
- Combined with LLM analysis for semantic understanding
Future: community plugins for language-specific deep analysis.
Implementation Phases
Phase 1: Foundation (MVP)
- Project scaffolding โ monorepo, TypeScript config, build setup
- Core: Knowledge graph schema + JSON persistence
- Core: LLM analysis engine (file-by-file analysis using prompts)
- Core: tree-sitter integration for structural analysis
- Skill:
/understandcommand โ analyze + persist graph - Dashboard: Basic React app that reads and renders the graph
- Dashboard: Graph view with React Flow
- Dashboard: Code viewer with Monaco Editor
Phase 2: Intelligence
- Natural language search across graph nodes
- Skill:
/understand-chatโ terminal Q&A - Dashboard: Chat panel with context-aware Q&A
- Staleness detection + incremental updates
- Layer auto-detection (group nodes into logical layers)
Phase 3: Learn Mode
- Tour generation โ guided project walkthrough
- Contextual explanations โ click-to-explain
- Language-specific lessons in context of the user's code
- Persona modes (non-technical / junior / experienced)
Phase 4: Advanced
- Skill:
/understand-diffโ PR/diff analysis - Skill:
/understand-explainโ deep-dive on specific files - Skill:
/understand-onboardโ onboarding guide generation - Community plugin system
- Embedding-based semantic search (optional enhancement)
Verification
How to test end-to-end:
- Skill analysis: Run
/understandon a sample project โ verify.understand-anything/knowledge-graph.jsonis generated with correct schema - Incremental update: Modify a file โ run
/understandagain โ verify only the changed file is re-analyzed - Dashboard: Open
http://localhost:5173โ verify graph renders, nodes are clickable, search works - Chat: Ask a question in the chat panel โ verify it returns a relevant answer using the knowledge graph
- Learn mode: Start the tour โ verify it walks through the project step by step
- Tree-sitter: Analyze a TypeScript file โ verify function boundaries and import relationships match the actual code
Test projects to validate against:
- A small TypeScript project (the tool itself)
- A Python Flask/Django API
- A Go microservice
- A mixed-language monorepo
File: docs/superpowers/specs/2026-03-15-homepage-design.md
Understand Anything โ Project Homepage Design
Date: 2026-03-15
Goal: Attract new users to the Understand Anything Claude Code plugin
Approach: "The Reveal" โ cinematic scroll-driven single-page site
Tech Stack
- Astro (static site generator, zero JS framework overhead)
- Self-hosted fonts (no Google Fonts CDN dependency โ works in China)
- CSS with variables matching dashboard theme
- Vanilla JS for
IntersectionObserverscroll animations - GitHub Actions for CI/CD to
gh-pagesbranch
Source & Deployment
- Source:
homepage/directory onmainbranch - Build output: deployed to
gh-pagesbranch via GitHub Actions - URL:
understand-anything.com
Page Structure (scroll order)
1. Nav Bar
Minimal floating nav. Logo/wordmark left, GitHub star button + "Get Started" CTA right. Transparent, becomes solid on scroll.
2. Hero (full viewport)
- Headline: "Understand Any Codebase"
- Subheadline: "Turn 200,000 lines of code into an interactive knowledge graph you can explore, search, and learn from โ powered by multi-agent AI analysis."
- CTA: "Get Started" (gold button, scrolls to install section)
- Secondary: "View on GitHub" (text link)
- Background:
hero.jpgwith dark gradient overlay
3. Dashboard Showcase
- Label: "See your codebase come alive"
overview.pngin a stylized browser frame with gold glow shadow- Fade-in on scroll
4. Feature Cards (3 columns)
Staggered fade-in animation:
- Interactive Knowledge Graph โ "Visualize files, functions, and dependencies as an explorable graph with smart layout."
- Plain-English Summaries โ "Every node explained in language anyone can understand โ from junior devs to product managers."
- Guided Tours โ "AI-generated walkthroughs that teach you the codebase step by step."
5. Install CTA
- Headline: "Get started in 30 seconds"
- Code block:text
/plugin marketplace add Egonex-AI/Understand-Anything /plugin install understand-anything /understand - "Works with Claude Code" note
6. Footer
- "Understand Anything" wordmark
- GitHub link, license
- "Built as a Claude Code plugin"
Visual Design System
Colors (matching dashboard)
| Token | Value | Usage |
|---|---|---|
--bg |
#0a0a0a |
Page background |
--surface |
#141414 |
Card backgrounds |
--border |
#1a1a1a |
Borders, dividers |
--accent |
#d4a574 |
Gold/amber primary accent |
--text |
#e8e2d8 |
Primary text (warm white) |
--text-muted |
#8a8578 |
Secondary text |
Typography (self-hosted, with fallbacks)
- Headings: DM Serif Display โ Georgia, "Times New Roman", serif
- Body: Inter โ -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif
- Code: JetBrains Mono โ "SF Mono", "Cascadia Code", "Fira Code", monospace
- Hero headline: ~4rem serif with subtle text-shadow glow
Effects
- Gold glow on dashboard screenshot frame (
box-shadowwith gold at low opacity) - Subtle noise texture overlay (SVG, matching dashboard)
- Scroll-triggered fade+slide-up animations (CSS
@keyframes+IntersectionObserver) - CTA button: gold background with hover glow pulse
- Cards: glass-morphism with
backdrop-filter: blur - Responsive: 768px (tablet), 480px (mobile)
File: docs/superpowers/specs/2026-03-18-multi-platform-simple-design.md
Multi-Platform Skill Support โ Simplified Design
Date: 2026-03-18
Status: Approved
Goal: Make Understand-Anything skills work across Codex, OpenClaw, OpenCode, and Cursor with zero build step โ same files everywhere.
Design Principles
Follows the obra/superpowers pattern:
- Same files, all platforms โ no template markers, no build step, no platform-specific variants
model: inheritโ agents use the parent session's model, making them platform-agnostic- AI-driven installation โ
.{platform}/INSTALL.mdfiles that the AI agent reads and executes - Self-contained skills โ pipeline prompt templates live inside the skill directory, not in a separate
agents/folder
Change 1: Move Pipeline Agents Into Skill
The 5 pipeline agents (project-scanner, file-analyzer, architecture-analyzer, tour-builder, graph-reviewer) are used exclusively by the /understand skill. They become prompt templates co-located with the skill:
Before:
agents/
project-scanner.md # agent definition
file-analyzer.md
architecture-analyzer.md
tour-builder.md
graph-reviewer.md
skills/understand/
SKILL.md # dispatches named agentsAfter:
skills/understand/
SKILL.md # dispatches subagents using templates
project-scanner-prompt.md # prompt template (no agent frontmatter)
file-analyzer-prompt.md
architecture-analyzer-prompt.md
tour-builder-prompt.md
graph-reviewer-prompt.mdThe prompt template files retain the full instruction content but drop the agent frontmatter (name, tools, model). The SKILL.md dispatch changes from "Dispatch the project-scanner agent" to "Dispatch a subagent using the template at ./project-scanner-prompt.md".
Context Cost
Reading templates through the main session adds ~11K tokens total (~5.5% of 200K context). This is sequential (one template at a time), and context compression reclaims earlier content. Acceptable trade-off for portability.
Change 2: New Registered Agent โ knowledge-graph-guide
Create a reusable agent that any skill or user can invoke to work with knowledge graphs:
# agents/knowledge-graph-guide.md
---
name: knowledge-graph-guide
Use this agent when users need help understanding, querying, or working
with an Understand-Anything knowledge graph. Guides users through graph
structure, node/edge relationships, layer architecture, tours, and
dashboard usage.
model: inherit
---This agent knows:
- The KnowledgeGraph JSON schema (nodes, edges, layers, tours)
- The 5 node types and 18 edge types
- How to navigate and query the graph
- How to use the interactive dashboard
- How to interpret architectural layers and guided tours
Change 3: Platform Installation Files
Each platform gets an INSTALL.md that the AI agent can fetch and follow:
| File | Platform | Install Mechanism |
|---|---|---|
.codex/INSTALL.md |
Codex | git clone + symlink to ~/.agents/skills/ |
.opencode/INSTALL.md |
OpenCode | Plugin config in opencode.json |
.openclaw/INSTALL.md |
OpenClaw | git clone + symlink to ~/.openclaw/skills/ |
.cursor/INSTALL.md |
Cursor | git clone + symlink to .cursor/plugins/ |
User tells the agent one line:
Fetch and follow instructions from https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/refs/heads/main/understand-anything-plugin/.codex/INSTALL.mdThe agent executes the clone + symlink/config automatically.
Change 4: README Update
Add a "Multi-Platform Installation" section to README.md with one-liner per platform.
File Summary
| Action | Files |
|---|---|
| Delete | agents/project-scanner.md, agents/file-analyzer.md, agents/architecture-analyzer.md, agents/tour-builder.md, agents/graph-reviewer.md |
| Create | skills/understand/project-scanner-prompt.md, skills/understand/file-analyzer-prompt.md, skills/understand/architecture-analyzer-prompt.md, skills/understand/tour-builder-prompt.md, skills/understand/graph-reviewer-prompt.md |
| Create | agents/knowledge-graph-guide.md |
| Create | .codex/INSTALL.md, .opencode/INSTALL.md, .openclaw/INSTALL.md, .cursor/INSTALL.md |
| Modify | skills/understand/SKILL.md (dispatch references) |
| Modify | README.md (multi-platform section) |
What We Don't Need
โ same files everywhereplatforms/platform-config.jsonโ no build stepplatforms/build.mjsโ no templating{{MARKER}}template markersโ AI agent follows INSTALL.mdscripts/install-*.shโ no generated outputdist-platforms/
Platform Compatibility
| Platform | Install Method | Agent Discovery | Skill Discovery |
|---|---|---|---|
| Claude Code | Marketplace (existing) | agents/ dir |
skills/ dir |
| Codex | INSTALL.md โ symlink | N/A (templates in skill) | ~/.agents/skills/ |
| OpenCode | INSTALL.md โ plugin config | N/A (templates in skill) | Plugin auto-registers |
| OpenClaw | INSTALL.md โ symlink | N/A (templates in skill) | ~/.openclaw/skills/ |
| Cursor | INSTALL.md โ symlink | agents/ dir |
.cursor/plugins/ |
File: docs/superpowers/specs/2026-03-21-language-agnostic-design.md
Language-Agnostic Support Design
Date: 2026-03-21
Status: Approved
Issue: Make Understand-Anything codebase-aware and language-agnostic instead of TypeScript-heavy
Problem
The tool's agent prompts, tree-sitter plugin, and language lesson system are heavily biased toward TypeScript/JavaScript. Non-TS codebases get degraded analysis because:
- Agent prompts use TS-specific examples and concepts (e.g., "barrel files", "type guards", "generics")
- Tree-sitter plugin only ships TS/JS grammar support โ structural analysis silently fails for other languages
- Language lesson detection hardcodes TS-specific concept patterns and display names
The architecture (PluginRegistry, GraphBuilder, dashboard, search) is already language-neutral. The bias is in shipped content, not the framework.
Decisions
- Scope: All three layers โ prompts, tree-sitter plugins, language framework
- Languages (v1): TypeScript, JavaScript, Python, Go, Java, Rust, C/C++, C#, Ruby, PHP, Swift, Kotlin
- Architecture: Config-first with code escape hatch (hybrid)
- Prompt strategy: Base prompt + per-language markdown snippet files in a
languages/folder - Config location: Prompt snippets in
skills/understand/languages/, tree-sitter configs inpackages/core/src/languages/ - Multi-language projects: Per-file language analysis + project-level multi-language summary
- Language detection: Auto-detect from file extensions only (no manual override for v1)
Design
1. LanguageConfig Type & Registry
LanguageConfig Interface
// packages/core/src/languages/types.ts
interface LanguageConfig {
id: string; // e.g., "python"
displayName: string; // e.g., "Python"
extensions: string[]; // e.g., [".py", ".pyi"]
treeSitter: {
grammarPackage: string; // npm package name
nodeTypes: {
function: string[]; // e.g., ["function_definition"]
class: string[]; // e.g., ["class_definition"]
import: string[]; // e.g., ["import_statement", "import_from_statement"]
export: string[]; // e.g., ["export_statement"] or [] for languages without exports
typeAnnotation: string[]; // e.g., ["type"] for Python type hints
};
};
concepts: string[]; // e.g., ["decorators", "list comprehensions", "generators"]
filePatterns?: Record<string, string>; // special files, e.g., {"config": "pyproject.toml"}
customAnalyzer?: (node: SyntaxNode) => AnalysisResult; // escape hatch for unusual AST shapes
}Language Registry
// packages/core/src/languages/registry.ts
class LanguageRegistry {
private configs: Map<string, LanguageConfig>;
register(config: LanguageConfig): void;
getByExtension(ext: string): LanguageConfig | null;
getById(id: string): LanguageConfig;
getAll(): LanguageConfig[];
}File Structure
packages/core/src/languages/
โโโ types.ts
โโโ registry.ts
โโโ index.ts
โโโ configs/
โ โโโ typescript.ts
โ โโโ javascript.ts
โ โโโ python.ts
โ โโโ go.ts
โ โโโ java.ts
โ โโโ rust.ts
โ โโโ cpp.ts
โ โโโ csharp.ts
โ โโโ ruby.ts
โ โโโ php.ts
โ โโโ swift.ts
โ โโโ kotlin.tsAll built-in configs auto-registered on import.
2. GenericTreeSitterPlugin
Replaces the current TS-only TreeSitterPlugin with a config-driven version.
// packages/core/src/plugins/generic-tree-sitter-plugin.ts
class GenericTreeSitterPlugin implements AnalyzerPlugin {
private registry: LanguageRegistry;
canAnalyze(filePath: string): boolean {
return this.registry.getByExtension(path.extname(filePath)) !== null;
}
async analyzeFile(filePath: string, content: string): Promise<FileAnalysis> {
const config = this.registry.getByExtension(path.extname(filePath));
// Custom analyzer escape hatch
if (config.customAnalyzer) {
return config.customAnalyzer(tree.rootNode);
}
// Generic extraction driven by config.treeSitter.nodeTypes
const functions = this.extractNodes(tree, config.treeSitter.nodeTypes.function);
const classes = this.extractNodes(tree, config.treeSitter.nodeTypes.class);
const imports = this.extractNodes(tree, config.treeSitter.nodeTypes.import);
const exports = this.extractNodes(tree, config.treeSitter.nodeTypes.export);
// ...
}
private extractNodes(tree: Tree, nodeTypes: string[]): NodeInfo[] {
// Walk AST, collect all nodes matching any of the given types
}
}Migration
- Current
TreeSitterPlugindeleted, replaced byGenericTreeSitterPlugin+ TS/JS configs PluginRegistryunchanged- Existing tests updated to use new plugin
WASM Grammar Loading
- Each grammar loaded lazily on first use and cached
- WASM files bundled in
packages/core/src/languages/grammars/or fetched from tree-sitter's official WASM builds
3. Language-Aware Prompts
File Structure
skills/understand/
โโโ file-analyzer-prompt.md # Base prompt (language-neutral)
โโโ tour-builder-prompt.md
โโโ project-scanner-prompt.md
โโโ languages/
โ โโโ typescript.md
โ โโโ javascript.md
โ โโโ python.md
โ โโโ go.md
โ โโโ java.md
โ โโโ rust.md
โ โโโ cpp.md
โ โโโ csharp.md
โ โโโ ruby.md
โ โโโ php.md
โ โโโ swift.md
โ โโโ kotlin.mdBase Prompt Changes
All TS-specific examples removed from base prompts. Replaced with injection point:
## Language-Specific Guidance
{{LANGUAGE_CONTEXT}}Language Markdown Format
Each language file contains:
# Python
## Key Concepts
- Decorators, comprehensions, generators, context managers, type hints, dunder methods
## Import Patterns
- `import module`, `from module import name`, relative imports
## Notable File Patterns
- `__init__.py` (package initializer), `conftest.py` (pytest), `pyproject.toml` (config)
## Example Summary Style
> "FastAPI route handler that accepts a Pydantic model, validates input..."Injection Logic
- Project scanner detects languages present in the codebase
- File-analyzer: inject matching language
.mdfor that file's language - Tour-builder: inject all detected languages'
.mdfiles - Project-scanner: inject all detected languages' key concepts for project-level summary
Multi-Language Projects
Project-scanner prompt gets a combined section listing all detected languages with their key concepts.
4. Language Lesson Updates
- Delete
LANGUAGE_DISPLAY_NAMESโ useLanguageRegistry.getById(id).displayName - Delete hardcoded concept patterns โ use
LanguageConfig.conceptsfrom registry - Language lesson generation becomes config-driven
5. Testing Strategy
Unit Tests
- LanguageConfig validation โ Each config has all required fields, non-empty nodeTypes
- LanguageRegistry โ Registration, lookup by extension/id, duplicate handling
- GenericTreeSitterPlugin per language โ Small fixture file per language verifying function/class/import extraction
- Language lesson generation โ Concepts sourced from config
Integration Tests
- Multi-language project โ Mixed TS + Python fixture, verify graph contains nodes from both languages
- Prompt injection โ Correct language
.mdinjected based on detected language
Migration Tests
- Current tree-sitter-plugin tests rewritten for GenericTreeSitterPlugin with TS config
- Must produce identical results to validate non-breaking migration
6. Error Handling & Graceful Degradation
Key Principle
Every file always gets analyzed. Tree-sitter is an enhancement, not a gate. The LLM is the primary analyzer; structural analysis enriches it.
Unknown Language
- Tree-sitter skipped (returns
null) - LLM analysis still runs โ file gets summary, tags, graph node
- Debug log:
"No language config for .xyz, skipping structural analysis"
Missing WASM Grammar
- Warning logged, that language degrades to LLM-only
- Other languages unaffected
Malformed Language Config
- Validated at registration time via Zod schema
- Invalid config throws at startup โ fail fast
File: docs/superpowers/specs/2026-03-27-token-reduction-design.md
Token Reduction Design
Date: 2026-03-27
Status: Draft
Goal: Reduce total token cost of /understand by ~85-90% on large codebases (200+ files)
Problem
For large codebases, the /understand pipeline spends the vast majority of its tokens on repeated context injection. The same data is sent to every subagent independently, even when that data could be computed once and shared.
Token cost breakdown (500-file TypeScript+React project, baseline)
| Source | Phase | Tokens (input) | % of total |
|---|---|---|---|
allProjectFiles list ร 67 batches |
Phase 2 | ~167,000 | ~50% |
file-analyzer-prompt.md ร 67 batches |
Phase 2 | ~134,000 | ~40% |
| Language/framework addendums ร 67 batches | Phase 2 | ~68,000 | ~20% |
| Tour builder payload (all nodes + edges) | Phase 5 | ~80,000 | ~24% |
| Graph reviewer (assembled graph + inventory) | Phase 6 | ~58,000 | ~17% |
| Architecture analyzer payload | Phase 4 | ~22,000 | ~7% |
| Total | ~529,000 |
The root cause: Phase 2 runs 67 batches (at 5-10 files each), and every single batch receives the full 500-file list for import resolution. The file list alone costs ~2,500 tokens ร 67 repetitions = 167,000 tokens on input, doing work that is entirely redundant between batches.
Goals
- Reduce total input tokens by 85%+ on a 500-file project
- No degradation in graph quality for standard projects
- Preserve the
--full/ incremental / scope flags - Maintain backward compatibility with existing
knowledge-graph.jsonoutput schema
Changes
Five changes compose the full approach (C1โC5). Each is independent and can be shipped separately, but all five are needed for the full reduction.
C1 โ Pre-resolve imports in the project scanner
Root cause addressed: allProjectFiles (the entire file list) is injected into every file-analyzer batch solely so each batch's extraction script can resolve relative imports. This is redundant: the full file list is available during Phase 1, and import resolution is deterministic. It should happen once, not 67 times.
Change: Extend the Phase 1 scanner script to also parse import statements from every source file and resolve relative imports against the discovered file list. The resolved results are written into scan-result.json as a new importMap field. File-analyzer batches then receive only their own batch's pre-resolved imports โ not the full file list.
Scanner output addition
scan-result.json gains:
{
"importMap": {
"src/index.ts": ["src/utils.ts", "src/config.ts"],
"src/utils.ts": [],
"src/components/App.tsx": ["src/hooks/useAuth.ts", "src/store/index.ts"]
}
}- Keys are project-relative paths (matching
files[*].path) - Values are resolved project-relative paths only (external/unresolvable imports are omitted)
- External imports (
node_modules, unresolvable paths) are excluded from the map entirely
Scanner script additions (Phase 1 Step 8)
After the existing 7 steps, the scanner script adds a new step:
Step 8 โ Import Resolution
For each file in the discovered source list:
1. Read the file content
2. Extract import statements (language-specific patterns per Step 3's language detection):
- TypeScript/JavaScript: `import ... from '...'`, `require('...')`
- Python: `import ...`, `from ... import ...`
- Go: `import "..."` blocks
- Rust: `use ...` statements
- Java/Kotlin: `import ...` statements
- Ruby: `require`, `require_relative`
3. For each relative import (starts with `./` or `../`):
a. Compute the resolved path from the current file's directory
b. Normalize to project-relative format
c. Try common extension variants if the import has no extension:
`.ts`, `.tsx`, `.js`, `.jsx`, `/index.ts`, `/index.js`, `/index.tsx`
d. If any variant exists in the discovered file list, record it; otherwise skip
4. For absolute imports (no `.` prefix): skip (external package)
Output the full importMap in the JSON result.File-analyzer input schema change
Before:
{
"projectRoot": "/path/to/project",
"allProjectFiles": ["src/index.ts", "src/utils.ts", "...500 paths..."],
"batchFiles": [
{"path": "src/index.ts", "language": "typescript", "sizeLines": 150}
]
}After:
{
"projectRoot": "/path/to/project",
"batchFiles": [
{"path": "src/index.ts", "language": "typescript", "sizeLines": 150}
],
"batchImportData": {
"src/index.ts": ["src/utils.ts", "src/config.ts"],
"src/components/App.tsx": ["src/hooks/useAuth.ts"]
}
}allProjectFiles is removed entirely. batchImportData contains only the pre-resolved imports for the files in this batch (sliced from importMap by the orchestrator).
File-analyzer extraction script change
The extraction script no longer performs import resolution. It:
- Still extracts: functions, classes, exports, metrics (unchanged)
- For imports: reads
batchImportData[file.path]from the input JSON โ no cross-referencing needed - The
importsarray in each file result becomes:batchImportData[file.path]mapped to import edge objects withresolvedPathalready populated,isExternal: false
SKILL.md Phase 2 change
Remove the allProjectFiles injection from the batch dispatch prompt. Replace with a per-batch batchImportData slice:
For each batch, slice importData from the importMap read in Phase 1:
batchImportData = { [file.path]: importMap[file.path] ?? [] }
for each file in this batchToken savings estimate
| Batches | Tokens/batch | Total | |
|---|---|---|---|
| Before | 67 | ~2,500 (file list) | ~167,500 |
| After (C1 alone) | 67 | ~200 (batch importData) | ~13,400 |
| Savings | ~154,100 |
C2 โ Increase batch size from 5-10 to 20-30 files
Root cause addressed: Every batch incurs the full cost of file-analyzer-prompt.md (~2,000 tokens) plus the batch dispatch overhead. With 67 batches, this adds up even without allProjectFiles. Fewer, larger batches directly reduce this repetition.
Change: In SKILL.md Phase 2, change the batch size guidance:
- Before: "Batch the file list from Phase 1 into groups of 5-10 files each"
- After: "Batch the file list from Phase 1 into groups of 20-30 files each (aim for ~25 per batch)"
Also update the concurrency limit from 3 to 5 concurrent batches. Fewer total batches means we can afford more parallelism without overwhelming the system.
Trade-offs
| Smaller batches (current) | Larger batches (new) | |
|---|---|---|
| Files per batch | 5-10 | 20-30 |
| Total batches (500 files) | ~67 | ~20 |
| Prompt repetition | 67ร | 20ร |
| Quality risk | Lower (focused) | Slightly higher (more files per subagent) |
| Concurrency | 3 | 5 |
Quality risk is low: each subagent still operates on distinct, non-overlapping file groups. The extraction script is deterministic regardless of batch size. Semantic analysis (summaries, tags) may be marginally less focused, but the quality difference is negligible in practice for well-structured files.
Token savings estimate (combined with C1)
| Batches | Tokens/batch (prompt) | Total | |
|---|---|---|---|
| Before (C1 only) | 67 | ~2,000 | ~134,000 |
| After (C1+C2) | 20 | ~2,000 | ~40,000 |
| Savings from C2 | ~94,000 |
C1+C2 combined eliminate ~248,000 tokens from Phase 2 (down from ~301,500 to ~53,500, a ~82% Phase 2 reduction).
C3 โ Remove language/framework addendums from file-analyzer batches
Root cause addressed: languages/typescript.md (~600 tokens) and frameworks/react.md (~700 tokens) are read and injected into every file-analyzer batch prompt. For a TypeScript+React project with 20 batches (after C2), this costs 20 ร 1,300 = 26,000 additional tokens โ and the model already has deep knowledge of these languages from training.
Change: Stop injecting addendum files into Phase 2 batch prompts entirely. The addendums remain injected into Phase 4 (architecture analyzer) where there is only one subagent call, making the cost acceptable.
Instead, add a compact "Language and Framework Hints" reference section directly into file-analyzer-prompt.md. This section is a distilled, one-time addition (~150 tokens total) that captures the most useful patterns from all addendums in a concise lookup table.
New section in `file-analyzer-prompt.md` (replace addendum injection)
## Language and Framework Quick Reference
Use these hints to improve tag and edge accuracy. These supplement your training knowledge.
| Signal | Tag(s) | Note |
|---|---|---|
| File in `hooks/`, exports function starting with `use` | `hook`, `service` | React custom hook |
| File in `contexts/`, exports a Provider | `service`, `state` | React context |
| File in `pages/` or `views/` | `ui`, `routing` | Page-level component |
| File in `store/`, `slices/`, `reducers/` | `state` | State management |
| File in `services/`, `api/` | `service` | Data-fetching / API client |
| `__init__.py` with re-exports | `entry-point`, `barrel` | Python package root |
| `manage.py` at project root | `entry-point` | Django management entry |
| File named `mod.rs` | `barrel` | Rust module barrel |
| File named `main.go` in `cmd/` | `entry-point` | Go binary entry |
For React: create `depends_on` edges from components to hooks they call. Create `publishes`/`subscribes` edges for Context provider/consumer patterns.SKILL.md Phase 2 change
Remove steps 2 and 3 from the "Build the combined prompt template" block:
- Remove: Step 2 (Language context injection โ read
./languages/<language-id>.mdper detected language) - Remove: Step 3 (Framework addendum injection โ read
./frameworks/<framework-id>.mdper detected framework) - Keep: Step 1 (Read the base template at
./file-analyzer-prompt.md)
The addendum injection steps remain unchanged in Phase 4 (architecture analyzer), since they run once.
Token savings estimate
| Batches | Addendum tokens/batch | Total | |
|---|---|---|---|
| Before (after C2) | 20 | ~1,300 (TS+React) | ~26,000 |
| After | 20 | ~150 (inline hints) | ~3,000 |
| Savings | ~23,000 |
C4 โ Slim Phase 4 and Phase 5 payloads
Root cause addressed: Phase 5 (tour builder) receives all nodes (file + function + class) and all edges (imports + contains + calls + exports + ...). For a 500-file project, this can include 1,500+ nodes and 3,000+ edges. Most of this data is not needed for tour design.
Phase 4 (Architecture Analyzer) โ minor trim
Phase 4 already only sends file-type nodes, which is correct. Minor change: explicitly strip languageNotes from each node object in the payload (it's not useful for layer assignment and can be verbose). Also strip name โ it is always derivable as the basename of filePath.
Before per node: {id, name, filePath, summary, tags, complexity, languageNotes?}
After per node: {id, filePath, summary, tags}
Savings: ~15-20% fewer tokens per node, ~3,000โ5,000 tokens total for Phase 4.
Phase 5 (Tour Builder) โ major trim
Three changes to what the orchestrator injects into the tour-builder subagent:
1. File nodes only (strip function/class nodes)
The tour references node IDs for wayfinding. In practice the tour always references file: nodes โ function and class nodes are visible in the dashboard's NodeInfo sidebar once a file is selected, but the tour itself navigates at the file level.
- Before: all nodes (file + function + class) โ for 500 files, maybe 1,500+ nodes
- After: file-type nodes only โ 500 nodes
2. Slim node format
The tour builder script only uses node IDs, names, and types for graph computation. Summaries and tags are used in Phase 2 (pedagogical narrative writing). Strip heavy optional fields from the injected payload:
- Before per node:
{id, name, filePath, summary, type, tags, complexity, languageNotes?} - After per node:
{id, name, filePath, summary, type}(drop tags, complexity, languageNotes)
3. Slim edges (imports + calls only) and slim layers
The tour's BFS traversal only traverses imports and calls edges. contains, exports, tested_by, depends_on, and other edge types add no value to the traversal and inflate the payload.
- Before edges: all edge types (~3,000+ edges including all
containsedges to function/class nodes) - After edges: only
importsandcallsedge types (~400โ800 edges for typical projects)
For layers, the tour builder uses layer data only to inform the tour's narrative arc (which layer to introduce first, second, etc.). It does not need the full nodeIds arrays โ those can be very large.
- Before per layer:
{id, name, description, nodeIds: [...hundreds of IDs]} - After per layer:
{id, name, description}(drop nodeIds)
Token savings estimate (Phase 5)
| Data | Before | After |
|---|---|---|
| Node count | ~1,500 ร ~180 chars | ~500 ร ~120 chars |
| Node tokens | ~67,500 | ~15,000 |
| Edge count | ~3,000 ร ~80 chars | ~600 ร ~80 chars |
| Edge tokens | ~60,000 | ~12,000 |
| Layer tokens | ~5,000 | ~500 |
| Phase 5 total | ~132,500 | ~27,500 |
| Savings | ~105,000 |
SKILL.md changes
In Phase 4 dispatch prompt template, update the file node format:
File nodes:
[list of {id, filePath, summary, tags} for all file-type nodes]In Phase 5 dispatch prompt template, update all three payload specs:
Nodes (file nodes only):
[list of {id, name, filePath, summary, type} for all file-type nodes only โ do NOT include function or class nodes]
Key edges (imports and calls only):
[list of edges where type is "imports" or "calls" only]
Layers:
[list of {id, name, description} โ omit nodeIds]C5 โ Gate the graph-reviewer subagent behind `--review`
Root cause addressed: The graph-reviewer subagent (Phase 6) reads the entire assembled graph (~500 nodes, all edges, layers, tour) and runs a LLM-powered validation. However, its Phase 1 is entirely a deterministic script, and its Phase 2 is a simple threshold decision: if issues.length === 0, approve. There is no LLM judgment needed for the happy path.
Change: By default, skip the graph-reviewer subagent. The orchestrator performs inline deterministic validation using a pre-written script. Only when --review is explicitly passed in $ARGUMENTS does the full LLM reviewer subagent run.
Default path (no `--review`)
In Phase 6, instead of dispatching the graph-reviewer subagent, the orchestrator:
- Writes a compact validation script inline (embedded in SKILL.md, ~50 lines of Node.js):
- Check: every edge source/target references a real node ID
- Check: every file node appears in exactly one layer
- Check: every tour step nodeId exists
- Check: no duplicate node IDs
- Check: required fields present on nodes and edges
- Runs the script against
assembled-graph.json - If
issues.length === 0: proceed to Phase 7 (save) - If
issues.length > 0: apply the same automated fixes as before (remove dangling edges, fill defaults), then save
This is sufficient for standard runs. The LLM reviewer adds value for catching subtle quality issues (generic summaries, orphan nodes, tour step coherence) โ but those are nice-to-have, not blocking.
`--review` path
When --review is in $ARGUMENTS, the full graph-reviewer subagent runs as it does today. No change to that code path.
Token savings estimate
| Path | Tokens |
|---|---|
| Current (always runs LLM reviewer) | ~58,000 input + ~500 output |
| Default (inline script, no LLM) | ~0 |
--review (unchanged) |
~58,000 (same as current) |
| Savings for default runs | ~58,500 |
Combined savings summary
| Change | Tokens before | Tokens after | Savings |
|---|---|---|---|
| C1+C2: import map + batch consolidation | ~301,500 | ~53,500 | ~248,000 |
| C3: remove addendums from batches | ~26,000 | ~3,000 | ~23,000 |
| C4: slim Phase 4+5 payloads | ~154,500 | ~33,000 | ~121,500 |
| C5: gate reviewer (default path) | ~58,500 | ~0 | ~58,500 |
| Total | ~540,500 | ~89,500 | ~451,000 (~83%) |
Estimates are for a 500-file TypeScript+React project. Actual savings scale with project size โ a 1,000-file project would see proportionally larger savings from C1+C2 (more batches = more repetition eliminated).
File changes
| File | Change |
|---|---|
skills/understand/project-scanner-prompt.md |
Add Step 8 (import resolution); add importMap to output schema |
skills/understand/file-analyzer-prompt.md |
Replace allProjectFiles with batchImportData in input schema; update extraction script to use pre-resolved imports; add compact Language/Framework Quick Reference section; remove addendum injection steps |
skills/understand/SKILL.md |
Phase 1: note importMap in scan result; Phase 2: remove addendum injection (steps 2+3), increase batch size 5-10โ20-30, increase concurrency 3โ5, replace allProjectFiles injection with batchImportData slice; Phase 4: slim node format in dispatch; Phase 5: file nodes only + slim edges + slim layers in dispatch; Phase 6: conditional reviewer โ default inline script, --review flag for LLM reviewer |
skills/understand/architecture-analyzer-prompt.md |
No change (addendums still injected here) |
skills/understand/tour-builder-prompt.md |
Update input schema to reflect file-only nodes, imports+calls-only edges, slim layer format |
skills/understand/graph-reviewer-prompt.md |
No change (only used when --review flag is passed) |
Risks and mitigations
| Risk | Likelihood | Mitigation |
|---|---|---|
| Scanner import resolution misses edge cases (complex re-exports, dynamic imports) | Medium | Log unresolved imports; file-analyzer still uses resolved data and creates edges only for confirmed matches. Missed imports = missing edges, which is same behavior as before for unresolvable imports |
| Larger batches (C2) reduce summary quality | Low | Summary quality is driven by the model's analysis of individual files. Batch size mainly affects how many files share one subagent's context window, not per-file quality. 20-30 files remains well within context limits |
| Stripping function/class nodes from tour (C4) breaks existing tour steps | None | Tour steps reference file: node IDs. No existing tour data references function/class nodes at the step level |
| Removing reviewer by default (C5) misses graph errors | Low | The inline deterministic script catches all critical structural issues (dangling refs, missing layers, duplicate IDs). The LLM reviewer's additional value is quality warnings (orphan nodes, generic summaries), which are non-blocking |
| Import map generation slows down Phase 1 | Low | The scanner script already reads all files for line counting. Import parsing adds one regex pass per file โ negligible overhead |
Phased rollout recommendation
Given the risk profile, implement in this order:
- C5 first โ gate the reviewer, lowest risk, immediate 58K token savings per run
- C4 โ slim Phase 5 payload, no scanner changes, no quality risk
- C3 โ remove addendums from batches, add inline hints
- C1+C2 together โ scanner changes and batch consolidation, test thoroughly on small/medium/large projects before releasing
File: docs/superpowers/specs/2026-03-28-understand-anything-extension-design.md
Understand Anything: Universal File Type Support
Date: 2026-03-28
Status: Approved
Approach: Big Bang โ all file types in one release
Goals
- Extend Understand Anything to analyze any file type, not just code
- Support both holistic project enrichment (non-code files enrich code graphs) and standalone analysis (docs-only repos, SQL schema collections, IaC projects)
- Maintain backward compatibility with existing code-only analysis
Supported File Types (26 new)
Documentation (3)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| Markdown | .md, .mdx |
LLM + regex heading extraction | document |
| reStructuredText | .rst |
LLM | document |
| Plain text | .txt |
LLM | document |
Configuration (5)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| YAML | .yaml, .yml |
yaml npm package |
config |
| JSON | .json, .jsonc |
JSON.parse / jsonc-parser |
config, schema |
| TOML | .toml |
@iarna/toml or similar |
config |
| .env | .env, .env.* |
Regex line parser | config |
| XML | .xml |
LLM (optionally fast-xml-parser) |
config |
Infrastructure & DevOps (7)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| Dockerfile | Dockerfile, Dockerfile.*, .dockerfile |
Custom instruction parser | service, pipeline |
| Docker Compose | docker-compose.yml, compose.yml |
YAML parser + service extraction | service |
| Terraform | .tf, .tfvars |
Regex block parser | resource |
| Kubernetes | K8s YAML (detected by apiVersion field) |
YAML + kind detection | service, resource |
| GitHub Actions | .github/workflows/*.yml |
YAML + job/step extraction | pipeline |
| Jenkinsfile | Jenkinsfile |
LLM (Groovy DSL) | pipeline |
| Makefile | Makefile, *.mk |
Regex target parser | pipeline |
Data & Schema (6)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| SQL | .sql |
Simple DDL parser | table, endpoint |
| GraphQL | .graphql, .gql |
Regex type/query parser | schema, endpoint |
| OpenAPI/Swagger | openapi.yaml, swagger.json |
YAML/JSON + path extraction | endpoint, schema |
| Protocol Buffers | .proto |
Regex message/service parser | schema |
| JSON Schema | *.schema.json |
JSON + $ref/$defs extraction |
schema |
| CSV/TSV | .csv, .tsv |
Header row extraction | table |
Shell & Scripts (3)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| Shell | .sh, .bash, .zsh |
Regex function parser | file, function |
| PowerShell | .ps1, .psm1 |
LLM | file, function |
| Batch | .bat, .cmd |
LLM | file |
Markup (2)
| Type | Extensions | Parser | Node Types |
|---|---|---|---|
| HTML | .html, .htm |
LLM (tag structure) | document |
| CSS/SCSS/Less | .css, .scss, .less |
LLM | file |
Schema Extensions
New Node Types (8)
Added to the existing file | function | class | module | concept:
| Node Type | Purpose | Example |
|---|---|---|
config |
Configuration files and key settings | package.json, tsconfig.json, env vars |
document |
Documentation, prose, guides | README.md, API docs |
service |
Deployable services/containers | Docker containers, K8s Deployments |
table |
Data tables, database objects | SQL tables, CSV datasets |
endpoint |
API routes, queries, mutations | REST paths, GraphQL queries |
pipeline |
CI/CD workflows, build steps | GitHub Actions jobs, Makefile targets |
schema |
Type definitions for data interchange | Protobuf messages, JSON Schema |
resource |
Infrastructure resources | Terraform resources, K8s ConfigMaps |
New Edge Types (8)
Added to the existing 18 edge types:
| Edge Type | Category | Meaning | Example |
|---|---|---|---|
deploys |
Infrastructure | Service deploys code | Dockerfile -> app source |
serves |
Infrastructure | Service exposes endpoint | K8s Service -> API endpoint |
migrates |
Data flow | Migration modifies table | SQL migration -> table |
documents |
Semantic | Doc describes code | README -> module |
provisions |
Infrastructure | IaC creates resource | Terraform -> AWS resource |
routes |
Behavioral | Routes traffic to service | nginx config -> service |
defines_schema |
Data flow | Defines data shape | Protobuf -> endpoint |
triggers |
Behavioral | Triggers pipeline/action | Git push -> GitHub Actions |
Schema Validation Auto-Fix Aliases
New node type aliases:
container->service,migration->table,workflow->pipelineroute->endpoint,doc->document,setting->config,infra->resource
New edge type aliases:
describes->documents,creates->provisions,exposes->serves
Plugin Architecture Changes
Generalized AnalyzerPlugin Interface
interface AnalyzerPlugin {
name: string;
languages: string[];
analyzeFile(filePath: string, content: string): StructuralAnalysis;
resolveImports?(filePath: string, content: string): ImportResolution[]; // Now optional
extractCallGraph?(filePath: string, content: string): CallGraphEntry[];
extractReferences?(filePath: string, content: string): ReferenceResolution[]; // NEW
}
interface ReferenceResolution {
source: string; // File making the reference
target: string; // Referenced file or identifier
type: string; // Reference type: "file", "image", "schema", "service"
line?: number;
}Extended StructuralAnalysis
interface StructuralAnalysis {
// Existing (unchanged)
functions: FunctionInfo[];
classes: ClassInfo[];
imports: ImportInfo[];
exports: ExportInfo[];
// New (all optional for backward compat)
sections?: SectionInfo[]; // Documents: headings, chapters
definitions?: DefinitionInfo[]; // Schemas: types, messages, tables
services?: ServiceInfo[]; // Infra: containers, deployments
endpoints?: EndpointInfo[]; // APIs: routes, queries
steps?: StepInfo[]; // Pipelines: jobs, stages, targets
resources?: ResourceInfo[]; // IaC: terraform resources, K8s objects
}Custom Parsers (12)
All lightweight โ mostly regex-based, minimal dependencies:
| Parser | Implementation | Extracts |
|---|---|---|
MarkdownParser |
Regex | Headings, links, code blocks, front matter |
YAMLParser |
yaml npm |
Key hierarchy, anchors, multi-doc |
JSONParser |
Built-in JSON.parse |
Key structure, $ref/$defs |
TOMLParser |
@iarna/toml |
Section structure |
EnvParser |
Regex | Variable names and references |
DockerfileParser |
Regex | FROM stages, EXPOSE ports, COPY sources |
SQLParser |
Regex | CREATE TABLE/VIEW/INDEX, columns, foreign keys |
GraphQLParser |
Regex | Types, queries, mutations, subscriptions |
ProtobufParser |
Regex | Messages, services, enums, RPCs |
TerraformParser |
Regex | Resources, modules, variables, outputs |
MakefileParser |
Regex | Targets, dependencies, variables |
ShellParser |
Regex | Functions, sourced files |
Agent Pipeline Changes
Project Scanner
- Scan ALL file types (remove code-only filter)
- Tag each file with category:
code,config,docs,infra,data,script,markup - Smart batch grouping: keep related files together (e.g., Dockerfile + docker-compose.yml)
File Analyzer
Type-aware prompt templates by category:
- Code: Current behavior (functions, classes, imports, call graph)
- Config: Extract key settings, what they configure, which code files they affect
- Documentation: Extract sections, key concepts, which code components are documented
- Infrastructure: Extract services, ports, volumes, dependencies, which code they deploy
- Data/Schema: Extract tables, columns, types, relationships, which code consumes this data
- Pipelines: Extract jobs, steps, triggers, which code/infra they build/deploy
Cross-Type Reference Resolution
Post-analysis step connecting:
- Dockerfile
COPY-> source code directories - CI config
run: npm test-> test files - K8s manifest
image:-> Dockerfile - SQL foreign keys -> other tables
- OpenAPI
$ref-> schema definitions - Markdown links -> referenced files
Architecture Analyzer
New pattern detection:
- Deployment topology: Dockerfile -> compose -> K8s chain
- Data flow: Schema -> migration -> API endpoint -> client code
- Documentation coverage: which modules have docs vs. not
- Configuration dependency: which config files affect which code paths
Tour Builder
Include non-code tour stops:
- Project README overview
- Dockerfile containerization
- SQL migration database schema
- CI/CD pipeline explanation
Dashboard Visualization
New Node Visual Styles
| Node Type | Shape | Color | Icon |
|---|---|---|---|
config |
Rounded rect | Teal (#5eead4) | Gear |
document |
Rounded rect | Sky blue (#7dd3fc) | Document |
service |
Hexagon | Violet (#a78bfa) | Container/Box |
table |
Rectangle | Emerald (#6ee7b7) | Grid |
endpoint |
Pill/Stadium | Orange (#fdba74) | Arrow-right |
pipeline |
Rounded rect | Rose (#fda4af) | Play/Workflow |
schema |
Diamond | Amber (#fcd34d) | Blueprint |
resource |
Cloud shape | Indigo (#a5b4fc) | Cloud |
Graph Layout
- Layer grouping by category โ non-code nodes cluster separately from code nodes
- Legend update with 8 new node types
- Filter controls โ checkboxes to show/hide each file category
Sidebar Enhancements
NodeInfo panel updates per node type:
- Config: key-value pairs, referencing code files
- Document: heading outline, linked code components
- Service: ports, volumes, dependencies, deployed code
- Table: columns, types, foreign key relationships
- Endpoint: HTTP method, path, request/response schema
- Pipeline: jobs, triggers, deployed targets
- Schema: fields, nested types, consumers
- Resource: provider, type, dependencies
ProjectOverview panel: add "File Types" breakdown (code vs. non-code distribution).
New Dependencies
yamlโ YAML parsing (already common, ~50KB)@iarna/tomlโ TOML parsing (~30KB)jsonc-parserโ JSON with comments (~20KB)
No tree-sitter WASM additions. All other parsers are regex-based with zero dependencies.
Backward Compatibility
- All new
StructuralAnalysisfields are optional resolveImportsbecomes optional onAnalyzerPlugin- Existing
LanguageConfigentries unchanged - Schema validation auto-fixes new type aliases
- Existing knowledge graphs remain valid (new types are additive)
File: docs/superpowers/specs/2026-03-29-homepage-update-design.md
Homepage Update Design โ 2026-03-29
Goal
Update the Astro homepage (homepage/) to reflect features added across v1.2.0, v1.3.0, and v2.0.0 releases. The README and homepage structure/layout stay unchanged.
Scope
Three areas to update:
1. Features Section โ Expand from 3 to 6 Cards
Current (3 cards):
- Interactive Knowledge Graph
- Plain-English Summaries
- Guided Tours
Updated (6 cards, 2 rows of 3):
| # | Title | Icon | Description |
|---|---|---|---|
| 1 | Interactive Knowledge Graph | โ |
Visualize files, functions, and dependencies as an explorable graph with hierarchical drill-down and smart layout. |
| 2 | Beyond Code Analysis | โฌก |
Analyze your entire project โ Dockerfiles, Terraform, SQL, Markdown, and 26+ file types mapped into one unified graph. |
| 3 | Smart Filtering & Search | โ |
Filter by node type, complexity, layer, or edge category. Fuzzy and semantic search to find anything instantly. |
| 4 | Export & Share | โ |
Export your knowledge graph as high-quality PNG, SVG, or filtered JSON โ ready for docs, presentations, or further analysis. |
| 5 | Dependency Path Finder | โฟ |
Find the shortest path between any two components. Understand how parts of your system connect at a glance. |
| 6 | Guided Tours & Onboarding | โ |
AI-generated walkthroughs that teach the codebase step by step, plus onboarding guides for new team members. |
2. Install Section
Update the note from Claude Code-only to multi-platform:
- Before: "Works with Claude Code โ Anthropic's official CLI for Claude."
- After: "Works with Claude Code, Codex, OpenCode, Gemini CLI, and more."
3. Footer
Update tagline:
- Before: "Built as a Claude Code plugin"
- After: "Built for AI coding assistants"
Files to Modify
homepage/src/components/Features.astroโ replace 3 cards with 6homepage/src/components/Install.astroโ update platform notehomepage/src/components/Footer.astroโ update tagline
Out of Scope
- README.md updates
- Showcase section / screenshot
- Nav component
- Hero section
- Layout / global CSS structure changes
File: docs/superpowers/specs/2026-04-01-business-domain-knowledge-design.md
Business Domain Knowledge Extraction โ Design Spec
Issue: #61
Date: 2026-04-01
Problem
The current knowledge graph shows file-level dependency relationships, but this has limited value โ you can already see imports in an IDE. When files are many, listing dependency edges doesn't reduce cognitive load; you still mentally reconstruct what the code does. What's needed is business domain knowledge: the logic and domain concepts embedded within the code, not the structural wiring.
Solution Overview
A new /understand-domain skill that extracts business domain knowledge and renders it as a horizontal flow graph in the dashboard. Two viewing modes: a high-level Domain view (default when available) and the existing Structural view, with a toggle to switch between them.
Architecture: Separate File, Shared Schema (Approach C)
Domain data lives in a separate file (domain-graph.json) using the same KnowledgeGraph type system โ extended with new node/edge types. The dashboard detects both files and offers a view toggle. Domain nodes can reference structural nodes by ID for drill-down.
Why separate files:
/understand-domainworks standalone (lightweight) or alongside full graph- Shared schema means search, validation, and filtering work for both
- No risk of polluting the structural graph
- Each file is independently valid
Section 1: Domain Graph Schema
Three-Level Hierarchy
- Business Domain (top) โ e.g., "Purchasing", "Logistics", "Warehouse Management"
- Business Flow (mid) โ e.g., "Create Order", "Process Refund"
- Business Step (leaf) โ e.g., "Validate input", "Check inventory", "Persist order"
New Node Types (3)
| Type | Purpose | Example |
|---|---|---|
domain |
Business domain cluster | "Order Management", "Logistics" |
flow |
A business process within a domain | "Create Order", "Process Refund" |
step |
A single step in a flow | "Validate order input" |
New Edge Types (4)
| Type | Purpose |
|---|---|
contains_flow |
domain โ flow |
flow_step |
flow โ step (ordered via weight field, e.g., 0.1, 0.2, ...) |
cross_domain |
domain โ domain (interaction between domains) |
implements |
step โ file/function node ID (reference into structural graph) |
Domain Node Structure
// domain node
{
id: "domain:order-management",
type: "domain",
name: "Order Management",
summary: "Handles the complete order lifecycle...",
tags: ["e-commerce", "core-business"],
complexity: "complex",
domainMeta?: {
entities: ["Order", "LineItem", "OrderStatus"],
businessRules: ["Orders require inventory check before confirmation"],
crossDomainInteractions: ["Triggers Logistics on order confirmed", "Reads from Customer Service for buyer info"]
}
}Flow Node Structure
{
id: "flow:create-order",
type: "flow",
name: "Create Order",
summary: "Customer submits a new order through the API",
tags: ["write-path", "api"],
complexity: "moderate",
domainMeta?: {
entryPoint: "POST /api/orders",
entryType: "http" | "cli" | "event" | "cron" | "manual"
}
}Step Node Structure
{
id: "step:create-order:validate-input",
type: "step",
name: "Validate order input",
summary: "Checks request body against order schema, rejects invalid payloads",
tags: ["validation"],
complexity: "simple",
filePath: "src/validators/order-validator.ts",
lineRange: [12, 45]
}File Output
Saved to .understand-anything/domain-graph.json โ same KnowledgeGraph shape, valid on its own.
Section 2: Analysis Pipeline
Two Paths, Same Output
Path 1: Lightweight scan (no existing graph)
File tree scan
โ Static entry point detection (tree-sitter)
โ Route definitions, exported handlers, main(), event listeners, cron decorators
โ Feed to LLM: file tree + detected entry points + sampled file contents
โ LLM outputs: domains, flows, steps, cross-domain interactions
โ Build domain-graph.jsonToken cost: ~10-20% of a full /understand scan.
Path 2: Derive from existing graph
Load knowledge-graph.json
โ Extract: all nodes, edges, layers, summaries, tour
โ Feed to LLM: graph data as structured context
โ LLM outputs: domains, flows, steps, cross-domain interactions
โ Build domain-graph.jsonVery cheap โ no file reading needed, LLM reasons over existing summaries and call edges.
Path Selection: /understand-domain checks if .understand-anything/knowledge-graph.json exists. If yes โ Path 2. If no โ Path 1.
Agent Structure
One new agent: domain-analyzer (opus model). Handles both paths. For large codebases, can batch by detected entry point groups.
Section 3: Preprocessing Script & Skill Integration
Script: `understand-anything-plugin/skills/understand-domain/extract-domain-context.py`
Bundled with the skill (not in scripts/ which is for development tooling). Runs before the LLM agent. Outputs .understand-anything/intermediate/domain-context.json:
{
"fileTree": ["src/api/orders.ts", "src/services/...", "..."],
"entryPoints": [
{
"file": "src/api/orders.ts",
"type": "http",
"method": "POST",
"path": "/api/orders",
"handler": "createOrder",
"lineRange": [15, 45],
"snippet": "async function createOrder(req, res) { ... }"
}
],
"fileSignatures": {
"src/services/order-service.ts": {
"exports": ["createOrder", "cancelOrder", "getOrderById"],
"imports": ["inventory-service", "pricing-service", "order-repo"],
"summary": null
}
}
}Python script (no heavy dependencies โ uses ast for Python, regex for other languages). Uses:
- Walk the file tree (respecting
.gitignore) - Detect entry points by pattern: route decorators,
app.get/post,export default handler,main(), event listeners - Extract function signatures and import/export lists per file
- Keep code snippets short (signature + first few lines, not full bodies)
Skill Integration
The /understand-domain skill markdown:
- Runs
understand-anything-plugin/skills/understand-domain/extract-domain-context.py - Checks for existing
knowledge-graph.json - If exists โ passes both
domain-context.json+ graph data to domain-analyzer agent - If not โ passes only
domain-context.json - Agent outputs
domain-graph.json - Cleans up intermediate files
- Auto-triggers
/understand-dashboard
Section 4: Dashboard โ Domain View
View Toggle
- Top-left corner: pill toggle โ "Domain" / "Structural"
- Domain view is default when
domain-graph.jsonexists - If only one graph file exists, no toggle shown
- Switching views preserves sidebar state
Horizontal Flow Layout
- Layout engine: Dagre with
rankdir: "LR"(left-to-right) - Zoom levels:
- Zoomed out: Domain clusters as large rounded rectangles,
cross_domainedges between them - Click domain: Expands to show flows as horizontal lanes
- Click flow: Shows step-by-step trace left-to-right
- Zoomed out: Domain clusters as large rounded rectangles,
Domain Cluster Rendering
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Order Management โ
โ "Handles the complete order..." โ
โ โ
โ Entities: Order, LineItem, Status โ
โ Flows: Create Order, Cancel Order โ
โ Rules: "Requires inventory check" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโcross_domainโโโ [Logistics]- Gold/amber border for domain clusters (matches existing theme)
- Shows summary, entity list, flow count on the cluster face
- Cross-domain edges: thick dashed lines with labels
Flow Trace Rendering
POST /api/orders
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโโโ
โ Validate โโโโโโ Check โโโโโโ Calculate โโโโโโ Persist โโโโโโ Send โ
โ Input โ โ Inventory โ โ Pricing โ โ Order โ โ Confirm โ
โโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโโโโ- Steps connected left-to-right by
flow_stepedges (ordered byweight) - Entry point label at the left as flow trigger
- Clicking a step โ sidebar shows detail + link to structural view
Sidebar Adaptations
Domain node selected: Summary, business rules, entities, cross-domain interactions, list of flows (clickable)
Flow node selected: Entry point info, step list in order, complexity
Step node selected: Description, "View in code" link (switches to structural view + navigates to file/function), previous/next step links
Drill-Down: Domain โ Structural
When a step has an implements edge referencing a structural node ID:
- "View implementation" button in sidebar
- Switches to structural view and navigates to that node
- Breadcrumb:
Domain: Order Management > Flow: Create Order > Step: Validate Input โ [structural view]
Section 5: Skill Definition
`/understand-domain` Skill
- File:
skills/understand-domain.md - Arguments: Optional
--fullflag to force Path 1 (rescan even if graph exists)
Execution Flow
1. Run scripts/extract-domain-context.mjs
2. Check for .understand-anything/knowledge-graph.json
โโโ Exists โ Path 2: load graph + domain-context.json
โโโ Missing โ Path 1: domain-context.json only
3. Invoke domain-analyzer agent (opus)
4. Validate output against schema
5. Save .understand-anything/domain-graph.json
6. Clean up intermediate/domain-context.json
7. Auto-trigger /understand-dashboardDomain Analyzer Agent
- File:
agents/domain-analyzer.md - Model: opus
- Input: Either (file tree + entry points) or (existing knowledge graph)
- Output: Complete domain graph JSON
Change Map
| Area | Changes |
|---|---|
packages/core/src/types.ts |
Add 3 node types, 4 edge types, domainMeta optional field |
packages/core/src/schema.ts |
Extend Zod schemas + aliases for new types |
packages/core/src/persistence/ |
Add loadDomainGraph() / saveDomainGraph() |
understand-anything-plugin/skills/understand-domain/extract-domain-context.py |
New preprocessing script (bundled with skill) |
agents/domain-analyzer.md |
New agent definition |
skills/understand-domain.md |
New skill definition |
packages/dashboard/src/store.ts |
Add domainGraph, viewMode state |
packages/dashboard/src/components/ |
New: DomainGraphView.tsx, DomainClusterNode.tsx, FlowTraceNode.tsx, StepNode.tsx |
packages/dashboard/src/components/ |
Modify: App.tsx (view toggle), NodeInfo.tsx (domain sidebar), FilterPanel.tsx (domain filters) |
packages/dashboard/src/utils/ |
New: domain-layout.ts (horizontal Dagre config) |
Section 6: Error Tolerance
Pipeline-Level Tolerance
| Stage | Error Handling |
|---|---|
| Preprocessing script | If tree-sitter fails on a file, skip and continue. Log skipped files. Entry point detection is best-effort. |
| LLM output parsing | Same strategy as existing parseTourGenerationResponse() โ extract JSON from markdown, handle partial responses. |
| Schema validation | Existing auto-fix pipeline: sanitize โ normalize (aliases) โ apply defaults โ validate. Drop broken nodes/edges, don't fail the whole graph. |
| Cross-graph references | implements edges pointing to non-existent structural node IDs โ keep edge but mark as unresolved. Dashboard shows step without drill-down link. |
Domain-Specific Validation Rules
- Domain with no flows: Warn, keep (summary/entities still useful)
- Flow with no steps: Warn, keep (entry point info still valuable)
- Steps with broken ordering: Re-number sequentially by array position if
weightvalues missing/duplicate - Orphan steps: Steps not connected to any flow โ attach to synthetic "Uncategorized" flow
- Duplicate domains: Merge by name similarity (fuzzy match), combine flows
- Empty domain graph: Error banner in dashboard: "Domain extraction failed โ try running
/understandfirst for richer context, then/understand-domain"
Dashboard Resilience
- If
domainMetamissing on a domain node, sidebar shows only summary/tags - If
domain-graph.jsonfails validation entirely, fall back to structural view with warning banner - Partial graphs render what's valid
Normalization Aliases for Domain Types
// Node type aliases
"business_domain" โ "domain"
"process" โ "flow"
"workflow" โ "flow"
"action" โ "step"
"task" โ "step"
// Edge type aliases
"has_flow" โ "contains_flow"
"next_step" โ "flow_step"
"interacts_with" โ "cross_domain"
"implemented_by" โ "implements"