Understand-Anything Documentation

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about.

RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy Understand-Anything on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name understand-anything --restart always egonex-ai/understand-anything:latest

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

bash
/plugin marketplace add Egonex-AI/Understand-Anything
/plugin install understand-anything

Using 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

bash
/understand

A 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 /understand analyzes 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:

bash
# Generate Chinese content (็Ÿฅ่ฏ†ๅ›พ่Š‚็‚นๆ่ฟฐๅ’Œ Dashboard UI)
/understand --language zh

# Supported languages: en (default), zh, zh-TW, ja, ko, ru

On 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

bash
/understand-dashboard

An 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

bash
# 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)

bash
/plugin marketplace add Egonex-AI/Understand-Anything
/plugin install understand-anything

One-line install (Codex / OpenCode / OpenClaw / Antigravity / Gemini CLI / Pi Agent / Vibe CLI / VS Code Copilot / Hermes / Cline / KIMI CLI / Trae / Nanobot / Kiro)

macOS / Linux:

bash
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 codex

Windows (PowerShell):

powershell
iwr -useb https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.ps1 | iex

The 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

bash
copilot plugin install Egonex-AI/Understand-Anything:understand-anything-plugin

Kiro CLI / IDE

bash
curl -fsSL https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/main/install.sh | bash -s kiro

After installation:

  • Kiro CLI: kiro-cli chat --agent understand "Analyze this project"
  • Kiro IDE: The skills are symlinked into ~/.kiro/skills/ and the understand agent 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.)

gitignore
.ua/intermediate/
.ua/diff-overlay.json

Keep 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.

bash
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:

bash
npx https://github.com/Egonex-AI/Understand-Anything/releases/latest/download/understand-anything-viewer.tgz /path/to/analyzed/project

The 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 importMap during 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:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Run the tests (pnpm --filter @understand-anything/core test)
  4. 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

text
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
โ””โ”€โ”€ .gitignore

Key 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

typescript
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)

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ๐Ÿ” 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, and name fields
  • 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

text
.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.json

Auto-sync flow:

  1. Skill starts โ†’ reads meta.json โ†’ gets last analyzed commit hash
  2. Runs git diff <last-hash>..HEAD --name-only โ†’ gets changed files
  3. If no changes โ†’ serves existing graph
  4. If changes โ†’ re-analyzes only changed files โ†’ merges into existing graph โ†’ updates meta

Plugin System

typescript
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)

  1. Project scaffolding โ€” monorepo, TypeScript config, build setup
  2. Core: Knowledge graph schema + JSON persistence
  3. Core: LLM analysis engine (file-by-file analysis using prompts)
  4. Core: tree-sitter integration for structural analysis
  5. Skill: /understand command โ€” analyze + persist graph
  6. Dashboard: Basic React app that reads and renders the graph
  7. Dashboard: Graph view with React Flow
  8. Dashboard: Code viewer with Monaco Editor

Phase 2: Intelligence

  1. Natural language search across graph nodes
  2. Skill: /understand-chat โ€” terminal Q&A
  3. Dashboard: Chat panel with context-aware Q&A
  4. Staleness detection + incremental updates
  5. Layer auto-detection (group nodes into logical layers)

Phase 3: Learn Mode

  1. Tour generation โ€” guided project walkthrough
  2. Contextual explanations โ€” click-to-explain
  3. Language-specific lessons in context of the user's code
  4. Persona modes (non-technical / junior / experienced)

Phase 4: Advanced

  1. Skill: /understand-diff โ€” PR/diff analysis
  2. Skill: /understand-explain โ€” deep-dive on specific files
  3. Skill: /understand-onboard โ€” onboarding guide generation
  4. Community plugin system
  5. Embedding-based semantic search (optional enhancement)

Verification

How to test end-to-end:

  1. Skill analysis: Run /understand on a sample project โ†’ verify .understand-anything/knowledge-graph.json is generated with correct schema
  2. Incremental update: Modify a file โ†’ run /understand again โ†’ verify only the changed file is re-analyzed
  3. Dashboard: Open http://localhost:5173 โ†’ verify graph renders, nodes are clickable, search works
  4. Chat: Ask a question in the chat panel โ†’ verify it returns a relevant answer using the knowledge graph
  5. Learn mode: Start the tour โ†’ verify it walks through the project step by step
  6. 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 IntersectionObserver scroll animations
  • GitHub Actions for CI/CD to gh-pages branch

Source & Deployment

  • Source: homepage/ directory on main branch
  • Build output: deployed to gh-pages branch 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.jpg with dark gradient overlay

3. Dashboard Showcase

  • Label: "See your codebase come alive"
  • overview.png in a stylized browser frame with gold glow shadow
  • Fade-in on scroll

4. Feature Cards (3 columns)

Staggered fade-in animation:

  1. Interactive Knowledge Graph โ€” "Visualize files, functions, and dependencies as an explorable graph with smart layout."
  2. Plain-English Summaries โ€” "Every node explained in language anyone can understand โ€” from junior devs to product managers."
  3. 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
  • "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-shadow with 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:

  1. Same files, all platforms โ€” no template markers, no build step, no platform-specific variants
  2. model: inherit โ€” agents use the parent session's model, making them platform-agnostic
  3. AI-driven installation โ€” .{platform}/INSTALL.md files that the AI agent reads and executes
  4. 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:

text
agents/
  project-scanner.md          # agent definition
  file-analyzer.md
  architecture-analyzer.md
  tour-builder.md
  graph-reviewer.md
skills/understand/
  SKILL.md                    # dispatches named agents

After:

text
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.md

The 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:

yaml
# 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:

text
Fetch and follow instructions from https://raw.githubusercontent.com/Egonex-AI/Understand-Anything/refs/heads/main/understand-anything-plugin/.codex/INSTALL.md

The 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

  • platforms/platform-config.json โ€” same files everywhere
  • platforms/build.mjs โ€” no build step
  • {{MARKER}} template markers โ€” no templating
  • scripts/install-*.sh โ€” AI agent follows INSTALL.md
  • dist-platforms/ โ€” no generated output

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:

  1. Agent prompts use TS-specific examples and concepts (e.g., "barrel files", "type guards", "generics")
  2. Tree-sitter plugin only ships TS/JS grammar support โ€” structural analysis silently fails for other languages
  3. 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 in packages/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

typescript
// 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

typescript
// 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

text
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.ts

All built-in configs auto-registered on import.

2. GenericTreeSitterPlugin

Replaces the current TS-only TreeSitterPlugin with a config-driven version.

typescript
// 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 TreeSitterPlugin deleted, replaced by GenericTreeSitterPlugin + TS/JS configs
  • PluginRegistry unchanged
  • 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

text
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.md

Base Prompt Changes

All TS-specific examples removed from base prompts. Replaced with injection point:

markdown
## Language-Specific Guidance

{{LANGUAGE_CONTEXT}}

Language Markdown Format

Each language file contains:

markdown
# 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

  1. Project scanner detects languages present in the codebase
  2. File-analyzer: inject matching language .md for that file's language
  3. Tour-builder: inject all detected languages' .md files
  4. 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 โ€” use LanguageRegistry.getById(id).displayName
  • Delete hardcoded concept patterns โ€” use LanguageConfig.concepts from registry
  • Language lesson generation becomes config-driven

5. Testing Strategy

Unit Tests

  1. LanguageConfig validation โ€” Each config has all required fields, non-empty nodeTypes
  2. LanguageRegistry โ€” Registration, lookup by extension/id, duplicate handling
  3. GenericTreeSitterPlugin per language โ€” Small fixture file per language verifying function/class/import extraction
  4. Language lesson generation โ€” Concepts sourced from config

Integration Tests

  1. Multi-language project โ€” Mixed TS + Python fixture, verify graph contains nodes from both languages
  2. Prompt injection โ€” Correct language .md injected 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.json output 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:

json
{
  "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:

text
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:

json
{
  "projectRoot": "/path/to/project",
  "allProjectFiles": ["src/index.ts", "src/utils.ts", "...500 paths..."],
  "batchFiles": [
    {"path": "src/index.ts", "language": "typescript", "sizeLines": 150}
  ]
}

After:

json
{
  "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 imports array in each file result becomes: batchImportData[file.path] mapped to import edge objects with resolvedPath already populated, isExternal: false

SKILL.md Phase 2 change

Remove the allProjectFiles injection from the batch dispatch prompt. Replace with a per-batch batchImportData slice:

text
For each batch, slice importData from the importMap read in Phase 1:
batchImportData = { [file.path]: importMap[file.path] ?? [] }
  for each file in this batch

Token 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)

markdown
## 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>.md per detected language)
  • Remove: Step 3 (Framework addendum injection โ€” read ./frameworks/<framework-id>.md per 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 contains edges to function/class nodes)
  • After edges: only imports and calls edge 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:

text
File nodes:
[list of {id, filePath, summary, tags} for all file-type nodes]

In Phase 5 dispatch prompt template, update all three payload specs:

text
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:

  1. 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
  2. Runs the script against assembled-graph.json
  3. If issues.length === 0: proceed to Phase 7 (save)
  4. 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:

  1. C5 first โ€” gate the reviewer, lowest risk, immediate 58K token savings per run
  2. C4 โ€” slim Phase 5 payload, no scanner changes, no quality risk
  3. C3 โ€” remove addendums from batches, add inline hints
  4. 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

  1. Extend Understand Anything to analyze any file type, not just code
  2. Support both holistic project enrichment (non-code files enrich code graphs) and standalone analysis (docs-only repos, SQL schema collections, IaC projects)
  3. 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 -> pipeline
  • route -> endpoint, doc -> document, setting -> config, infra -> resource

New edge type aliases:

  • describes -> documents, creates -> provisions, exposes -> serves

Plugin Architecture Changes

Generalized AnalyzerPlugin Interface

typescript
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

typescript
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

  1. Scan ALL file types (remove code-only filter)
  2. Tag each file with category: code, config, docs, infra, data, script, markup
  3. 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

  1. Layer grouping by category โ€” non-code nodes cluster separately from code nodes
  2. Legend update with 8 new node types
  3. Filter controls โ€” checkboxes to show/hide each file category

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 StructuralAnalysis fields are optional
  • resolveImports becomes optional on AnalyzerPlugin
  • Existing LanguageConfig entries 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."

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 6
  • homepage/src/components/Install.astro โ€” update platform note
  • homepage/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-domain works 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

  1. Business Domain (top) โ€” e.g., "Purchasing", "Logistics", "Warehouse Management"
  2. Business Flow (mid) โ€” e.g., "Create Order", "Process Refund"
  3. 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

typescript
// 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

typescript
{
  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

typescript
{
  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)

text
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.json

Token cost: ~10-20% of a full /understand scan.

Path 2: Derive from existing graph

text
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.json

Very 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:

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:

  1. Runs understand-anything-plugin/skills/understand-domain/extract-domain-context.py
  2. Checks for existing knowledge-graph.json
  3. If exists โ†’ passes both domain-context.json + graph data to domain-analyzer agent
  4. If not โ†’ passes only domain-context.json
  5. Agent outputs domain-graph.json
  6. Cleans up intermediate files
  7. 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.json exists
  • 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_domain edges between them
    • Click domain: Expands to show flows as horizontal lanes
    • Click flow: Shows step-by-step trace left-to-right

Domain Cluster Rendering

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  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

text
POST /api/orders
  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  โ”‚ Validate  โ”‚โ”€โ”€โ”€โ†’โ”‚ Check        โ”‚โ”€โ”€โ”€โ†’โ”‚ Calculate  โ”‚โ”€โ”€โ”€โ†’โ”‚ Persist   โ”‚โ”€โ”€โ”€โ†’โ”‚ Send       โ”‚
  โ”‚ Input     โ”‚    โ”‚ Inventory    โ”‚    โ”‚ Pricing    โ”‚    โ”‚ Order     โ”‚    โ”‚ Confirm    โ”‚
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  • Steps connected left-to-right by flow_step edges (ordered by weight)
  • Entry point label at the left as flow trigger
  • Clicking a step โ†’ sidebar shows detail + link to structural view

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 --full flag to force Path 1 (rescan even if graph exists)

Execution Flow

text
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-dashboard

Domain 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 weight values 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 /understand first for richer context, then /understand-domain"

Dashboard Resilience

  • If domainMeta missing on a domain node, sidebar shows only summary/tags
  • If domain-graph.json fails validation entirely, fall back to structural view with warning banner
  • Partial graphs render what's valid

Normalization Aliases for Domain Types

typescript
// 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"