Turn complex codebases into clear, navigable architecture diagrams with Claude Code.
TypeScript aiarchitectureclaude-codeclaude-code-skillclicodebase-visualizationdeveloper-toolsdiagramsdocumentationmermaid
feat: v2 perspective class tree — nested architecture with recursive analysis
hitkooa9cc5c323927
diff --git a/README.md b/README.mdindex e61faa5..c84ecb4 100644--- a/README.md+++ b/README.md@@ -7,6 +7,8 @@> `omm setup` → `/omm-scan` → done. Your architecture docs write themselves.+<video src="https://github.com/user-attachments/assets/2de6c496-b9a6-4734-8059-282ab130c1bc" width="100%" autoplay loop muted playsinline></video>+## Why?diff --git a/docs/screenshot.png b/docs/screenshot.pngindex ed6cffd..cd2999e 100644Binary files a/docs/screenshot.png and b/docs/screenshot.png differdiff --git a/skills/omm-scan/SKILL.md b/skills/omm-scan/SKILL.mdindex 3d4eeb8..5948573 100644--- a/skills/omm-scan/SKILL.md+++ b/skills/omm-scan/SKILL.md@@ -1,271 +1,181 @@---name: omm-scan-description: Scan codebase architecture and generate/update .omm/ documentation. Without arguments does a full scan; with arguments focuses on a specific topic and auto-links to parent diagrams. Use when the user says "omm scan", "scan architecture", "update architecture", "refresh diagrams", "omm scan auth flow", "analyze the payment module", or "dive into auth".-argument-hint: "[topic]"+description: Scan codebase architecture and generate/update .omm/ documentation. Use when the user says "omm scan", "scan architecture", "update architecture", "refresh diagrams".----# omm-scan — Architecture Scanner (Full + Focused)+# omm-scan — Perspective-Based Architecture Scanner## Purpose-Analyze the codebase and generate/update `.omm/` architecture documentation using the `omm` CLI.-Operates in two modes based on whether arguments are provided.+Analyze the codebase and generate `.omm/` architecture documentation using **perspective-driven recursive analysis**.-## Prerequisites+- A **perspective** is a top-level element — a distinct way to look at the architecture.+- Each element in a diagram gets analyzed recursively. If it has internal structure, it becomes a **child element** (subdirectory with its own diagram). If not, it stays a leaf.+- The filesystem determines nesting. Element IDs in diagrams match child directory names. The viewer resolves groups from the filesystem.-Ensure the `omm` CLI is available:+## Prerequisites```bashcommand -v omm || npm install -g oh-my-mermaid```-If the install command fails (permission denied), tell the user:-"Please run `npm install -g oh-my-mermaid` in your terminal, then try again."--## Mode Detection--- **No arguments** (`/omm-scan`): Full scan mode — analyze entire codebase-- **With arguments** (`/omm-scan auth flow`): Focused mode — analyze specific topic only+If the install fails, tell the user: "Please run `npm install -g oh-my-mermaid` in your terminal, then try again."----## A. Full Scan Mode (no arguments)--### Step 1: Check Existing State+## Step 0: Check Language```bash-omm list+omm config language```-For each existing class, read current content:-```bash-omm <class> description-omm <class> diagram-```+Write field content (description, context, constraint, concern, todo, note) in the configured language. Default is English. Element IDs, directory names, and diagram node IDs are always English kebab-case.-### Step 2: Explore the Codebase+## Step 1: Explore the CodebaseUse Glob and Read to understand the project:-- Read `package.json`, `tsconfig.json`, or equivalent config files++- Read `package.json`, `pyproject.toml`, or equivalent manifests- List top-level directories to identify module boundaries- Read key entry points (main, index, app files)-- Look for route definitions, service layers, database connections+- Look for route definitions, service layers, database connections, external integrations++## Step 2: Select Perspectives-### Step 3: Generate/Update Classes+From the catalog below, choose which perspectives are meaningful for this codebase.-**First run (no existing classes):** Create classes based on what a person new to this codebase most needs to understand. Always start with `overall-architecture`, then add perspectives from this list based on what exists in the code:+### Perspective Catalog-| Class name | When to create | What it answers |-|---|---|---|-| `overall-architecture` | Always | What exists and how pieces relate |+| Perspective | When to create | What it answers |+| --- | --- | --- |+| `overall-architecture` | **Always** | What exists and how pieces relate || `request-lifecycle` | Any server/API | How a request enters and gets handled end-to-end |-| `data-flow` | Any data processing | Where data comes from, transforms, and lands |-| `auth-flow` | Any auth/session logic | How identity is established and propagated |+| `data-flow` | Any data processing, DB usage | Where data comes from, transforms, and lands || `dependency-map` | Complex module graph | What depends on what, what's shared |-| `state-transitions` | Stateful features | How state changes and what triggers it || `external-integrations` | External APIs/services | What the system connects to and why |+| `state-transitions` | Stateful features (frontend or backend) | How state changes and what triggers it |+| `route-page-map` | Frontend with routing | Page structure and navigation flow |+| `command-surface` | CLI tools | Command hierarchy and dispatch |+| `extension-points` | Plugin/extension systems | Extension architecture and registry |+| `pipeline` | ML/data pipelines | Stage topology and data flow |+| `orchestration` | Event-driven/queue systems | Publisher, subscriber, broker topology |+| `storage` | 2+ storage systems | Storage topology (DB, cache, queue, object store) |-Only create a class if it meaningfully exists in the code. 3-5 classes is usually right; avoid forcing perspectives that don't exist.+Don't force perspectives that don't exist in the code.-**Subsequent runs:** Compare existing docs against current code, update only what changed.+## Step 3: Generate Perspectives with Recursive Drill-Down-For each class, call the CLI with **each field separately**:+For each selected perspective, follow this recursive process:-```bash-omm <class> description - <<'EOF'-(1-2 sentences: what this diagram shows AND who should read it)-- e.g., "Shows how an HTTP request flows from entry point to response. Start here if you want to understand how the API handles a request."-EOF+### 3a. Write the perspective diagram++Element IDs match child directory names. The viewer resolves nesting from the filesystem.-omm <class> diagram - <<'MERMAID'+```bash+omm write <perspective> diagram - <<'MERMAID'graph LR- (Accurate mermaid diagram based on actual code)+ renderer["Renderer\nsrc/renderer/"]+ renderer -->|"IPC invoke/on"| main-process["Main Process\nsrc/main/"]+ main-process -->|"spawn PTY"| engine-system["Engine System\nsrc/main/engine/"]+ main-process -->|"read/write JSON"| data-store["Data Store\nsrc/main/store.ts"]+ main-process -->|"xterm.js"| terminal-dock["Terminal Dock\nsrc/renderer/src/panel/"]MERMAID--omm <class> context - <<'EOF'-(The most important field for human understanding: WHY this architecture exists)-- Key decisions made and why (e.g., "Chose event-driven over direct calls to decouple billing from orders")-- Constraints that shaped the design (e.g., "Must support offline mode — hence local-first storage")-- Alternatives considered and rejected-- Historical reasons if relevant-EOF--omm <class> constraint - <<'EOF'-(Rules that MUST be followed when changing this area)-- e.g., "API layer must never import from repository directly — always go through service"-EOF--omm <class> concern - <<'EOF'-(Risks, technical debt, known issues a reader should be aware of)-- e.g., "Auth service is a single point of failure — no fallback if it's down"-EOF--omm <class> todo - <<'EOF'-(Concrete next steps or planned improvements)-- e.g., "Add caching layer between service and repository"-EOF--omm <class> note - <<'EOF'-(Anything else a new reader would want to know that doesn't fit above)-EOF```-### Step 4: Cross-References--Use `@class-name` in the label to mark a node as a drill-down into another class. Use a short node ID and put `@class-name` as the label:+### 3b. Write the other 6 fields-```mermaid-graph LR- client["Browser Client\nsrc/client/"]- client -->|"HTTP request"| api["@api-layer"]- client -->|"authenticate"| auth["@auth-flow"]-```+Each as a separate `omm write` command: description, context, constraint, concern, todo, note.-The viewer detects `@` in the label and renders the node as an expandable sub-group. Do NOT add a file path to `@ref` nodes — they represent a whole sub-diagram, not a single file.+### 3c. Recursive drill-down: analyze every element-### Step 5: Summarize+**For every element in the diagram:**-Report what was created/updated and suggest `omm view` to view.+1. **Analyze** the code it represents (Glob + Read the relevant files/directories)----+2. **Write description for every node — no exceptions.** This creates the element directory. Optionally write other fields (context, constraint, concern, todo, note) if relevant — Write in the configured language.-## B. Focused Mode (with arguments)+ ```bash+ omm write <perspective>/<element-name> description - <<'EOF'+ (what this element does, which files/dirs it covers)+ EOF+ ```-### Step 1: Parse Topic+3. **Decide leaf or group:**+ - **Distinct internal components found** → write a diagram and recurse deeper (it becomes a group)+ - **No meaningful sub-components** (single file, trivial wrapper, external system) → write remaining fields only (it stays a leaf)-Convert `$ARGUMENTS` to a kebab-case class name:-- "auth flow" → `auth-flow`-- "payment service" → `payment-service`-- "database schema" → `database-schema`+4. **If group** — write diagram and recurse:-### Step 2: Deep Analysis+ ```bash+ omm write <perspective>/<element-name> diagram - <<'MERMAID'+ graph LR+ (internal elements)+ MERMAID+ ```-Focus Glob and Read on code related to the topic:-- Search for files matching the topic (e.g., `*auth*`, `*payment*`)-- Trace imports and dependencies from those files-- Understand the full flow for this specific concern+ Then repeat step 3c for each element in this diagram.-### Step 3: Create/Update Class+### Example recursion-Generate all fields via CLI (same as full scan, but for this one class only).+```text+overall-architecture (perspective)+ elements: renderer, main-process, engine-system, data-store, terminal-dock-### Step 4: Auto-Link to Parent+ → analyze renderer (src/renderer/)+ → finds: App.tsx, components/, hooks/, stores/, world/+ → group → write diagram with: components, stores, world+ → analyze components → 15 .tsx files, no sub-structure → leaf+ → analyze stores → 4 zustand stores → leaf+ → analyze world → OfficeCanvas + PixiJS logic → leaf-This is the key differentiator from full scan:+ → analyze main-process (src/main/)+ → finds: ipc.ts, auth/, engine/, terminal-session-service.ts, store.ts+ → group → write diagram with: auth, engine, terminal-session+ → analyze auth → auth-service.ts, callback-server.ts → leaf+ → analyze engine → claude-code.ts, codex.ts → leaf-1. Run `omm list` to get existing classes-2. For each existing class, run `omm <class> diagram` to read its diagram-3. Check if the new class is already referenced as `@new-class` in a label-4. If NOT referenced, find the logical parent (usually `overall-architecture`) and update its diagram to include a node with `@new-class` as the label+ → analyze data-store (src/main/store.ts)+ → single file → leaf-Example: After creating `auth-flow`, update `overall-architecture`:-```bash-# Read current parent diagram-omm overall-architecture diagram-# Add @auth-flow reference and rewrite-omm overall-architecture diagram - <<'MERMAID'-graph LR- Client --> auth["@auth-flow"]- ...existing nodes...-MERMAID+ → analyze terminal-dock (src/renderer/src/panel/)+ → TerminalDock.tsx, DockManager → leaf```-### Step 5: Verify and Summarize+## Step 4: Summarize-```bash-omm refs <new-class>-```--Report: "auth-flow created, @auth-flow added to overall-architecture"-------### Nested Architecture Analysis--When analyzing the codebase, identify sub-systems that are complex enough to warrant their own diagram (5+ nodes). Create separate classes for these and reference them with `@class-name` in the parent diagram.--**When to nest:**-- A module has 5+ internal components with their own relationships-- A subsystem has distinct layers or flows worth documenting separately-- A feature area (auth, billing, data pipeline) has its own internal architecture--**How to nest:**-1. Create a new class: `omm <child-class> diagram - <<'MERMAID'...MERMAID`-2. In the parent diagram, add a node with `@child-class` as the label (e.g. `auth["@auth-flow"]`)-3. Fill all 7 fields for the child class (description, constraint, concern, context, todo, note)--**Example:**-If `overall-architecture` has an auth subsystem with 8+ nodes:-- Create `auth-flow` class with its own detailed diagram-- In `overall-architecture` diagram: `Client --> auth["@auth-flow"]`-- The viewer detects `@` in the label and renders it as an expandable sub-group--### Edge Labels--Every edge MUST have a meaningful label. The label should answer **"why does this connection exist?"** — not just the protocol.--**Format:** `A -->|"label"| B`--**What to include in labels (priority order):**-1. The purpose/intent: what does this relationship accomplish?-2. What data/result flows: what is actually transferred?-3. Protocol/method only if it adds clarity (HTTP, IPC, Event, etc.)--**Good examples:**-```mermaid-Client -->|"login request (HTTP POST)"| AuthService-AuthService -->|"issue session token"| Client-AuthService -->|"verify user exists"| UserRepository-OrderService -->|"request payment authorization"| PaymentGateway-PaymentGateway -->|"authorization result callback"| OrderService-EventBus -->|"emit: order.completed"| NotificationService-```--**Bad examples (avoid):**-```mermaid-A --> B-Client --> Server-AuthService -->|"HTTP"| UserRepository-```+Report what was created/updated and suggest `omm view` to view.-The test: if you remove the label, does the reader lose important understanding? If yes, the label is good. If the label is just a protocol name, it's probably not enough.+## Diagram Rules-## Rules (Both Modes)+- **Element IDs must match the child directory name.** Use kebab-case: `main-process`, `data-store`, `terminal-dock`.+- **Element labels use two-line format**: name + file path, separated by `\n`:-- Write all content (node labels, edge labels, field text) in **English by default**. If the user wrote in another language, match that language throughout.-- ONLY document what actually exists in the code. Do not invent or speculate.-- **Node labels must use two-line format**: concept name on the first line, file/directory path on the second line, separated by `\n`:+ ```text+ main-process["Main Process\nsrc/main/"]+ auth-service["Auth Service\nsrc/auth/service.ts"]```- auth_service["Auth Service\nsrc/auth/service.ts"]- user_repo["User Repository\nsrc/user/repository.ts"]- payment_module["Payment Module\nsrc/payment/"]- ```- - First line: role/responsibility in plain language (what it does)- - Second line: actual path relative to project root (where to find it)- - The viewer renders the path smaller and muted below the concept name- - For modules/folders, use the directory path (e.g., `src/payment/`)- - For single files, use the file path (e.g., `src/auth/service.ts`)-- Keep diagrams readable — 5-15 nodes max per diagram.++- Every edge must have a meaningful label: `A -->|"why this connection exists"| B`+- More elements in one diagram means you should recurse deeper.- Use `graph LR` for most diagrams, `graph TD` for hierarchies.-- Do NOT rewrite classes that haven't changed.-- Do NOT delete classes — only report if obsolete.-- Write each field separately (constraint, concern, context, todo, note) — do NOT combine them.-- Use `omm diff <class>` after updating to verify changes.-- Use `classDef` to visually distinguish node roles — apply only when the distinction genuinely helps a reader:-- | Class | Color | When to use |- |---|---|---|- | `external` | muted gray `#585b70` | Third-party services, APIs outside your codebase (DB, S3, Stripe, etc.) |- | `concern` | red `#f38ba8` | Nodes that are a known risk or bottleneck (single point of failure, legacy code) |- | `entry` | blue `#89b4fa` | Entry points (HTTP handler, CLI, queue consumer) |- | `store` | green `#a6e3a1` | Persistent storage (DB, cache, file system) |+- Use `classDef` for visual distinction when helpful:- ```+ | Style | Color | When to use |+ | --- | --- | --- |+ | `external` | `#585b70` | Third-party services outside your codebase |+ | `concern` | `#f38ba8` | Known risk or bottleneck |+ | `entry` | `#89b4fa` | Entry points (HTTP handler, CLI, queue consumer) |+ | `store` | `#a6e3a1` | Persistent storage (DB, cache, file system) |++ ```textclassDef external fill:#585b70,stroke:#585b70,color:#cdd6f4classDef concern fill:#f38ba8,stroke:#f38ba8,color:#1e1e2eclassDef entry fill:#89b4fa,stroke:#89b4fa,color:#1e1e2eclassDef store fill:#a6e3a1,stroke:#a6e3a1,color:#1e1e2e```- Do not overuse — if everything has a color, nothing stands out.-- Do NOT create circular `@`references. A child class must never `@`-reference its parent. If `overall-architecture` has `auth["@auth-flow"]`, then `auth-flow`'s diagram must NOT reference `@overall-architecture`. Use `context.md` to describe the parent relationship instead.+## General Rules++- **Write each field as a separate `omm write` command.** Each `omm write` must be its own Bash tool call.+- Do not rewrite elements that haven't changed.+- Do not create circular references. A child element must never reference its parent.diff --git a/src/cli.ts b/src/cli.tsindex 446098d..dc0ced8 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -19,8 +19,11 @@ import { commandSetup } from './commands/setup.js';import { commandUpdate } from './commands/update.js';import { commandOrg } from './commands/org.js';import { commandValidate } from './commands/validate.js';+import { commandTree } from './commands/tree.js';+import { commandRead, commandWrite } from './commands/read-write.js';+import { commandConfig } from './commands/config.js';-const GLOBAL_COMMANDS = ['init', 'setup', 'update', 'list', 'show', 'delete', 'status', 'diff', 'refs', 'validate', 'view', 'login', 'logout', 'push', 'pull', 'link', 'share', 'org', 'help'];+const GLOBAL_COMMANDS = ['init', 'setup', 'update', 'list', 'show', 'delete', 'status', 'diff', 'refs', 'validate', 'view', 'login', 'logout', 'push', 'pull', 'link', 'share', 'org', 'read', 'write', 'tree', 'config', 'help'];function printHelp(): void {const help = `@@ -32,20 +35,18 @@ Usage:omm setup --list Show detected platformsomm setup --teardown Unregister from all platformsomm update Update CLI + plugins to latest version- omm list List all classes- omm show <class> Show all fields for a class- omm delete <class> Delete a class- omm status Show overview of all classes- omm diff <class> Compare current vs previous diagram- omm refs <class> Show classes that reference this class- omm refs --reverse <class> Show classes this class references- omm validate [class] Validate diagram(s) for syntax and conventions+ omm list List perspectives+ omm tree <path> Show element tree+ omm read <path> <field> Read a field (stdout)+ omm write <path> <field> <text|-> Write a field+ omm show <path> Show all fields for an element+ omm delete <path> Delete an element+ omm status Show overview of all elements+ omm diff <path> Compare current vs previous diagram+ omm refs <path> Show elements that reference this element+ omm validate [path] Validate diagram(s) for syntax and conventionsomm view [--port <port>] Start web viewer (default: 3000)- omm <class> <field> Read a field (stdout)- omm <class> <field> <content> Write a field- omm <class> <field> - Write a field from stdin-Cloud:omm login Log in to omm.devomm logout Log out@@ -57,6 +58,7 @@ Cloud:omm org switch <slug> Set default organizationomm org members [slug] View members (opens web)+Paths: use / for nested elements (e.g. overall-architecture/main-process)Fields: description, diagram, constraint, concern, context, todo, note`;process.stdout.write(help.trim() + '\n');@@ -70,6 +72,14 @@ async function main(): Promise<void> {return;}+ if (args[0] === '--version' || args[0] === '-v' || args[0] === 'version') {+ const { createRequire } = await import('node:module');+ const require = createRequire(import.meta.url);+ const pkg = require('../package.json');+ process.stdout.write(`omm ${pkg.version}\n`);+ return;+ }+const cmd = args[0];switch (cmd) {@@ -89,9 +99,25 @@ async function main(): Promise<void> {commandList();return;+ case 'tree':+ commandTree(args[1]);+ return;++ case 'config':+ commandConfig(args.slice(1));+ return;++ case 'read':+ commandRead(args[1], args[2]);+ return;++ case 'write':+ await commandWrite(args[1], args[2], args.slice(3));+ return;+case 'show':if (!args[1]) {- process.stderr.write('error: omm show <class>\n');+ process.stderr.write('error: omm show <path>\n');process.exit(1);}commandShow(args[1]);@@ -99,7 +125,7 @@ async function main(): Promise<void> {case 'delete':if (!args[1]) {- process.stderr.write('error: omm delete <class>\n');+ process.stderr.write('error: omm delete <path>\n');process.exit(1);}commandDelete(args[1]);@@ -178,12 +204,15 @@ async function main(): Promise<void> {return;default:- // Class-field pattern: omm <class> <field> [content]+ // Legacy alias: omm <path> <field> [content] → read/writeif (args.length >= 2 && !GLOBAL_COMMANDS.includes(cmd)) {- const className = cmd;+ const targetPath = cmd;const field = args[1];- const content = args.length >= 3 ? args.slice(2).join(' ') : undefined;- await commandClassField(className, field, content);+ if (args.length >= 3) {+ await commandWrite(targetPath, field, args.slice(2));+ } else {+ commandRead(targetPath, field);+ }return;}diff --git a/src/commands/class-field.ts b/src/commands/class-field.tsindex 03b6ec6..0e93d89 100644--- a/src/commands/class-field.ts+++ b/src/commands/class-field.ts@@ -23,7 +23,7 @@ export async function commandClassField(className: string, field: string, contenif (content === undefined) {if (!ensureOmmForRead()) return;if (!classExists(className)) {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}const value = readField(className, typedField);diff --git a/src/commands/config.ts b/src/commands/config.tsnew file mode 100644index 0000000..77b7ff0--- /dev/null+++ b/src/commands/config.ts@@ -0,0 +1,60 @@+/**+ * omm config <key> [value] — read/write project config (.omm/config.yaml)+ *+ * Usage:+ * omm config Show all config+ * omm config language Show language setting+ * omm config language ko Set language to ko+ */++import fs from 'node:fs';+import path from 'node:path';+import YAML from 'yaml';+import { ensureOmmForWrite, getOmmDir } from '../lib/store.js';+import type { OmmConfig } from '../types.js';++const CONFIG_FILE = 'config.yaml';++function readConfig(cwd?: string): OmmConfig {+ const filePath = path.join(getOmmDir(cwd), CONFIG_FILE);+ if (!fs.existsSync(filePath)) return { version: '0.1.0' };+ return YAML.parse(fs.readFileSync(filePath, 'utf-8')) as OmmConfig;+}++function writeConfig(config: OmmConfig, cwd?: string): void {+ ensureOmmForWrite(cwd);+ const filePath = path.join(getOmmDir(cwd), CONFIG_FILE);+ fs.writeFileSync(filePath, YAML.stringify(config), 'utf-8');+}++export function commandConfig(args: string[]): void {+ const key = args[0];+ const value = args[1];++ // omm config — show all+ if (!key) {+ const config = readConfig();+ process.stdout.write(YAML.stringify(config));+ return;+ }++ // omm config <key> — read+ if (!value) {+ const config = readConfig();+ const val = (config as Record<string, unknown>)[key];+ if (val !== undefined) {+ process.stdout.write(String(val) + '\n');+ } else {+ // Show defaults+ const defaults: Record<string, string> = { language: 'English' };+ process.stdout.write((defaults[key] ?? '(not set)') + '\n');+ }+ return;+ }++ // omm config <key> <value> — write+ const config = readConfig();+ (config as Record<string, unknown>)[key] = value;+ writeConfig(config);+ process.stderr.write(`config: ${key}=${value}\n`);+}diff --git a/src/commands/delete.ts b/src/commands/delete.tsindex ac82c40..b15c38f 100644--- a/src/commands/delete.ts+++ b/src/commands/delete.ts@@ -3,9 +3,9 @@ import { ensureOmmForRead, deleteClass } from '../lib/store.js';export function commandDelete(className: string): void {if (!ensureOmmForRead()) return;if (deleteClass(className)) {- process.stderr.write(`deleted class '${className}'\n`);+ process.stderr.write(`deleted element '${className}'\n`);} else {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}}diff --git a/src/commands/diff.ts b/src/commands/diff.tsindex edccf79..20829da 100644--- a/src/commands/diff.ts+++ b/src/commands/diff.ts@@ -5,7 +5,7 @@ export function commandDiff(className: string): void {if (!ensureOmmForRead()) return;if (!classExists(className)) {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}diff --git a/src/commands/list.ts b/src/commands/list.tsindex 1569114..c96f9ba 100644--- a/src/commands/list.ts+++ b/src/commands/list.ts@@ -3,7 +3,7 @@ import { listClasses } from '../lib/store.js';export function commandList(): void {const classes = listClasses();if (classes.length === 0) {- process.stderr.write('No classes found.\n');+ process.stderr.write('No perspectives found.\n');return;}process.stdout.write(classes.join('\n') + '\n');diff --git a/src/commands/read-write.ts b/src/commands/read-write.tsnew file mode 100644index 0000000..07a2264--- /dev/null+++ b/src/commands/read-write.ts@@ -0,0 +1,79 @@+/**+ * omm read <path> <field> — read a field+ * omm write <path> <field> <text|-> — write a field+ *+ * Paths use / for nesting: overall-architecture/main-process+ */++import {+ isValidField,+ ensureOmmForRead,+ readField,+ writeField,+ readNodeField,+ writeNodeField,+} from '../lib/store.js';+import type { Field } from '../types.js';++function parsePath(targetPath: string): { perspective: string; nodePath: string[] } {+ const parts = targetPath.split('/');+ return { perspective: parts[0], nodePath: parts.slice(1) };+}++export function commandRead(targetPath?: string, field?: string): void {+ if (!targetPath || !field) {+ process.stderr.write('error: omm read <path> <field>\n');+ process.exit(1);+ }+ if (!isValidField(field)) {+ process.stderr.write(`error: invalid field '${field}'. Valid: description, diagram, constraint, concern, context, todo, note\n`);+ process.exit(1);+ }+ if (!ensureOmmForRead()) return;++ const { perspective, nodePath } = parsePath(targetPath);+ const content = nodePath.length === 0+ ? readField(perspective, field as Field)+ : readNodeField(perspective, nodePath, field as Field);++ if (content) {+ process.stdout.write(content);+ }+}++export async function commandWrite(targetPath?: string, field?: string, contentArgs?: string[]): Promise<void> {+ if (!targetPath || !field) {+ process.stderr.write('error: omm write <path> <field> <content|->\n');+ process.exit(1);+ }+ if (!isValidField(field)) {+ process.stderr.write(`error: invalid field '${field}'. Valid: description, diagram, constraint, concern, context, todo, note\n`);+ process.exit(1);+ }++ const args = contentArgs ?? [];+ let content: string;++ if (args.length === 0) {+ process.stderr.write('error: omm write <path> <field> <content|->\n');+ process.exit(1);+ return;+ }++ if (args[0] === '-') {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) {+ chunks.push(chunk);+ }+ content = Buffer.concat(chunks).toString('utf-8');+ } else {+ content = args.join(' ');+ }++ const { perspective, nodePath } = parsePath(targetPath);+ if (nodePath.length === 0) {+ writeField(perspective, field as Field, content);+ } else {+ writeNodeField(perspective, nodePath, field as Field, content);+ }+}diff --git a/src/commands/refs.ts b/src/commands/refs.tsindex a75796c..965e350 100644--- a/src/commands/refs.ts+++ b/src/commands/refs.ts@@ -5,7 +5,7 @@ export function commandRefs(className: string, reverse: boolean): void {if (!ensureOmmForRead()) return;if (!classExists(className)) {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}@@ -13,7 +13,7 @@ export function commandRefs(className: string, reverse: boolean): void {// Show what this class references (outgoing)const refs = getOutgoingRefs(className);if (refs.length === 0) {- process.stdout.write(`${className} does not reference any other class.\n`);+ process.stdout.write(`${className} does not reference any other element.\n`);return;}process.stdout.write(`${className} references:\n`);@@ -24,7 +24,7 @@ export function commandRefs(className: string, reverse: boolean): void {// Show what references this class (incoming)const refs = getIncomingRefs(className);if (refs.length === 0) {- process.stdout.write(`No class references ${className}.\n`);+ process.stdout.write(`No element references ${className}.\n`);return;}process.stdout.write(`Referenced by:\n`);diff --git a/src/commands/show.ts b/src/commands/show.tsindex e203055..c6d8729 100644--- a/src/commands/show.ts+++ b/src/commands/show.ts@@ -5,7 +5,7 @@ export function commandShow(className: string): void {if (!ensureOmmForRead()) return;const data = showClass(className);if (!data) {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}diff --git a/src/commands/status.ts b/src/commands/status.tsindex 22cb64b..07f947f 100644--- a/src/commands/status.ts+++ b/src/commands/status.ts@@ -5,11 +5,11 @@ export function commandStatus(): void {const classes = listClasses();if (classes.length === 0) {- process.stdout.write('No classes found. Run /omm-init to scan your codebase.\n');+ process.stdout.write('No perspectives found. Run /omm-scan to generate.\n');return;}- process.stdout.write(`Classes: ${classes.length}\n\n`);+ process.stdout.write(`Perspectives: ${classes.length}\n\n`);for (const cls of classes) {const meta = readMeta(cls);diff --git a/src/commands/tree.ts b/src/commands/tree.tsnew file mode 100644index 0000000..66d0d40--- /dev/null+++ b/src/commands/tree.ts@@ -0,0 +1,45 @@+/**+ * omm tree <path> — show element hierarchy as indented tree.+ */++import { ensureOmmForRead, listNodes, listClasses } from '../lib/store.js';++function printTree(perspective: string, nodePath: string[], prefix: string, isLast: boolean, isRoot: boolean): void {+ const name = nodePath.length === 0 ? perspective : nodePath[nodePath.length - 1];++ if (isRoot) {+ process.stdout.write(name + '\n');+ } else {+ process.stdout.write(prefix + (isLast ? '└── ' : '├── ') + name + '\n');+ }++ const children = listNodes(perspective, nodePath);+ const childPrefix = isRoot ? '' : prefix + (isLast ? ' ' : '│ ');++ for (let i = 0; i < children.length; i++) {+ const childPath = [...nodePath, children[i]];+ printTree(perspective, childPath, childPrefix, i === children.length - 1, false);+ }+}++export function commandTree(targetPath?: string): void {+ if (!ensureOmmForRead()) return;++ if (!targetPath) {+ const perspectives = listClasses();+ if (perspectives.length === 0) {+ process.stderr.write('No perspectives found. Run /omm-scan to generate.\n');+ return;+ }+ for (const persp of perspectives) {+ printTree(persp, [], '', true, true);+ process.stdout.write('\n');+ }+ return;+ }++ const parts = targetPath.split('/');+ const perspective = parts[0];+ const nodePath = parts.slice(1);+ printTree(perspective, nodePath, '', true, true);+}diff --git a/src/commands/validate.ts b/src/commands/validate.tsindex 48d4256..b84a40c 100644--- a/src/commands/validate.ts+++ b/src/commands/validate.ts@@ -33,7 +33,7 @@ export function commandValidate(className?: string): void {if (className) {if (!classExists(className)) {- process.stderr.write(`error: class '${className}' not found\n`);+ process.stderr.write(`error: element '${className}' not found\n`);process.exit(1);}const { errors } = validateClass(className, allClasses);diff --git a/src/index.ts b/src/index.tsindex c0494bb..ed472ae 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,7 +1,8 @@// oh-my-mermaid public APIexport { initOmm, ensureOmmForRead, ensureOmmForWrite, listClasses, readField, writeField, showClass, deleteClass, classExists } from './lib/store.js';+export { listPerspectives, listNodes, readNodeField, writeNodeField, showNode, nodeDir, readNodeMeta } from './lib/store.js';export { diffMermaid, parseMermaid, formatDiff } from './lib/diff.js';export { extractRefs, getIncomingRefs, getOutgoingRefs, buildRefGraph } from './lib/refs.js';export { validateDiagram, VALID_CLASSDEF_NAMES, CLASSDEF_PALETTE } from './lib/validate.js';export { VALID_FIELDS, FIELD_FILES } from './types.js';-export type { Field, ClassMeta, ClassData, DiffResult, RefEntry, OmmConfig, ValidationIssue, ValidationResult } from './types.js';+export type { Field, ClassMeta, ClassData, DiffResult, RefEntry, OmmConfig, ValidationIssue, ValidationResult, NodeKind } from './types.js';diff --git a/src/lib/store.ts b/src/lib/store.tsindex 1d47668..5b6e4c3 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -77,11 +77,162 @@ export function listClasses(cwd?: string): string[] {const dir = getOmmDir(cwd);if (!fs.existsSync(dir)) return [];return fs.readdirSync(dir, { withFileTypes: true })- .filter(d => d.isDirectory())+ .filter(d => d.isDirectory() && !d.name.startsWith('.')).map(d => d.name).sort();}+// --- Perspective + Nested Element operations (direct nesting, no nodes/ dir) ---++/** Resolve filesystem path for a nested element: .omm/<perspective>/<child>/<grandchild> */+export function nodeDir(perspective: string, nodePath: string[], cwd?: string): string {+ return path.join(classDir(perspective, cwd), ...nodePath);+}++function ensureNodeDir(perspective: string, nodePath: string[], cwd?: string): string {+ const dir = nodeDir(perspective, nodePath, cwd);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true });+ }+ return dir;+}++/** List top-level perspectives */+export function listPerspectives(cwd?: string): string[] {+ return listClasses(cwd);+}++/** List child elements under a perspective or nested path */+export function listNodes(perspective: string, nodePath: string[] = [], cwd?: string): string[] {+ const dir = nodePath.length === 0+ ? classDir(perspective, cwd)+ : nodeDir(perspective, nodePath, cwd);+ if (!fs.existsSync(dir)) return [];+ return fs.readdirSync(dir, { withFileTypes: true })+ .filter(d => d.isDirectory() && !d.name.startsWith('.'))+ .map(d => d.name)+ .sort();+}++/** Read a field from a nested element */+export function readNodeField(perspective: string, nodePath: string[], field: Field, cwd?: string): string | null {+ const dir = nodeDir(perspective, nodePath, cwd);+ const filePath = path.join(dir, FIELD_FILES[field]);+ if (!fs.existsSync(filePath)) return null;+ return fs.readFileSync(filePath, 'utf-8');+}++/** Write a field to a nested element */+export function writeNodeField(+ perspective: string,+ nodePath: string[],+ field: Field,+ content: string,+ cwd?: string,+): number {+ ensureOmmForWrite(cwd);+ ensureClassDir(perspective, cwd);+ const dir = ensureNodeDir(perspective, nodePath, cwd);+ const filePath = path.join(dir, FIELD_FILES[field]);++ if (field === 'diagram') {+ const prev = readNodeField(perspective, nodePath, 'diagram', cwd);+ if (prev !== null) {+ const meta = readNodeMeta(perspective, nodePath, cwd);+ if (meta) {+ meta.prev_diagram = prev;+ writeNodeMeta(perspective, nodePath, meta, cwd);+ }+ }+ }++ fs.writeFileSync(filePath, content, 'utf-8');++ const fullPath = [perspective, ...nodePath].join('/');+ const meta = readNodeMeta(perspective, nodePath, cwd) ?? createNodeMeta(+ nodePath.length === 0 ? 'perspective' : 'nested-class',+ nodePath[nodePath.length - 1] ?? perspective,+ field,+ nodePath.length > 0 ? nodePath.slice(0, -1) : undefined,+ );+ meta.updated = new Date().toISOString();+ meta.update_count = (meta.update_count ?? 0) + 1;+ meta.last_field = field;+ writeNodeMeta(perspective, nodePath, meta, cwd);++ if (nodePath.length > 0) {+ const parentNodePath = nodePath.slice(0, -1);+ const childName = nodePath[nodePath.length - 1];+ const parentMeta = readNodeMeta(perspective, parentNodePath, cwd) ?? createNodeMeta(+ parentNodePath.length === 0 ? 'perspective' : 'nested-class',+ parentNodePath.length === 0 ? perspective : parentNodePath[parentNodePath.length - 1],+ field,+ parentNodePath.length > 0 ? parentNodePath.slice(0, -1) : undefined,+ );+ if (!parentMeta.children) parentMeta.children = [];+ if (!parentMeta.children.includes(childName)) {+ parentMeta.children.push(childName);+ parentMeta.children.sort();+ writeNodeMeta(perspective, parentNodePath, parentMeta, cwd);+ }+ }++ const bytes = Buffer.byteLength(content, 'utf-8');+ process.stderr.write(`wrote ${fullPath}/${FIELD_FILES[field]} (${bytes} bytes)\n`);+ return bytes;+}++function createNodeMeta(kind: import('../types.js').NodeKind, title: string, field: Field, parentPath?: string[]): ClassMeta {+ const now = new Date().toISOString();+ return {+ created: now,+ updated: now,+ update_count: 0,+ last_field: field,+ kind,+ title,+ children: [],+ parentPath: parentPath,+ };+}++export function readNodeMeta(perspective: string, nodePath: string[], cwd?: string): ClassMeta | null {+ const dir = nodePath.length === 0+ ? classDir(perspective, cwd)+ : nodeDir(perspective, nodePath, cwd);+ const filePath = path.join(dir, META_FILE);+ if (!fs.existsSync(filePath)) return null;+ return YAML.parse(fs.readFileSync(filePath, 'utf-8')) as ClassMeta;+}++function writeNodeMeta(perspective: string, nodePath: string[], meta: ClassMeta, cwd?: string): void {+ const dir = nodePath.length === 0+ ? ensureClassDir(perspective, cwd)+ : ensureNodeDir(perspective, nodePath, cwd);+ const filePath = path.join(dir, META_FILE);+ fs.writeFileSync(filePath, YAML.stringify(meta), 'utf-8');+}++/** Show all fields for a nested element */+export function showNode(perspective: string, nodePath: string[], cwd?: string): ClassData | null {+ const dir = nodePath.length === 0+ ? classDir(perspective, cwd)+ : nodeDir(perspective, nodePath, cwd);+ if (!fs.existsSync(dir)) return null;+ const name = nodePath.length === 0 ? perspective : nodePath.join('/');+ return {+ name,+ description: readNodeField(perspective, nodePath, 'description', cwd) ?? undefined,+ diagram: readNodeField(perspective, nodePath, 'diagram', cwd) ?? undefined,+ constraint: readNodeField(perspective, nodePath, 'constraint', cwd) ?? undefined,+ concern: readNodeField(perspective, nodePath, 'concern', cwd) ?? undefined,+ context: readNodeField(perspective, nodePath, 'context', cwd) ?? undefined,+ todo: readNodeField(perspective, nodePath, 'todo', cwd) ?? undefined,+ note: readNodeField(perspective, nodePath, 'note', cwd) ?? undefined,+ meta: readNodeMeta(perspective, nodePath, cwd) ?? undefined,+ };+}+export function deleteClass(className: string, cwd?: string): boolean {const dir = classDir(className, cwd);if (!fs.existsSync(dir)) return false;diff --git a/src/server/api.ts b/src/server/api.tsindex 6f1c5a4..936e724 100644--- a/src/server/api.ts+++ b/src/server/api.ts@@ -1,5 +1,5 @@import type { IncomingMessage, ServerResponse } from 'node:http';-import { listClasses, showClass, readMeta, readField } from '../lib/store.js';+import { listClasses, showClass, readMeta, readField, listNodes, showNode } from '../lib/store.js';import { diffMermaid } from '../lib/diff.js';import { getIncomingRefs, getOutgoingRefs } from '../lib/refs.js';@@ -56,5 +56,37 @@ export function handleApi(req: IncomingMessage, res: ServerResponse): boolean {return true;}+ // GET /api/class/:perspective/nodes+ const nodesMatch = path.match(/^\/api\/class\/([^/]+)\/nodes$/);+ if (nodesMatch) {+ const children = listNodes(nodesMatch[1]);+ json(res, { perspective: nodesMatch[1], children });+ return true;+ }++ // GET /api/class/:perspective/node/:path++ const nodeMatch = path.match(/^\/api\/class\/([^/]+)\/node\/(.+)$/);+ if (nodeMatch) {+ const perspective = nodeMatch[1];+ const nodePath = nodeMatch[2].split('/');+ const lastSegment = nodePath[nodePath.length - 1];++ if (lastSegment === 'nodes') {+ const parentPath = nodePath.slice(0, -1);+ const children = listNodes(perspective, parentPath);+ json(res, { perspective, path: parentPath, children });+ return true;+ }++ const data = showNode(perspective, nodePath);+ if (!data) {+ json(res, { error: 'node not found' }, 404);+ } else {+ const children = listNodes(perspective, nodePath);+ json(res, { ...data, children });+ }+ return true;+ }+return false;}diff --git a/src/server/viewer.html b/src/server/viewer.htmlindex 6eda89a..c290359 100644--- a/src/server/viewer.html+++ b/src/server/viewer.html@@ -230,6 +230,57 @@ body.light .grp-node.selected > .grp-border { stroke: #4f46e5 !important; filterbody.light .reg-node:hover .nshape { stroke: #000 !important; filter: drop-shadow(0 0 6px rgba(0,0,0,0.3)); }body.light .reg-node.selected .nshape { stroke: #4f46e5 !important; filter: drop-shadow(0 0 8px rgba(79,70,229,0.4)); }body.light .reg-node:hover .nshape { stroke: #000 !important; }++#mobile-nav-btn { display: none; }+#mobile-overlay { display: none; }++/* Mobile responsive */+@media (max-width: 768px) {+ #nav-sidebar {+ transform: translateX(-100%);+ transition: transform .22s cubic-bezier(.4,0,.2,1);+ z-index: 500;+ }+ #nav-sidebar.mobile-open { transform: translateX(0); }+ #canvas-wrap { left: 0 !important; margin-left: 0 !important; }+ #mobile-nav-btn {+ display: flex; align-items: center; gap: 8px;+ position: fixed; top: 10px; left: 10px; z-index: 400;+ background: rgba(0,0,0,0.75); border: 1px solid #333;+ border-radius: 6px; padding: 6px 12px;+ color: #fff; font-size: 13px; font-family: var(--mono);+ cursor: pointer; backdrop-filter: blur(8px);+ }+ #mobile-nav-btn span { font-size: 16px; }+ #mobile-overlay {+ display: none; position: fixed; inset: 0; z-index: 450;+ background: rgba(0,0,0,0.5);+ }+ #mobile-overlay.show { display: block; }+ #sidebar {+ top: auto; right: 0; bottom: 0; left: 0;+ width: 100%; height: 50vh;+ max-height: 70vh;+ border-left: none; border-top: 1px solid var(--border);+ border-radius: 12px 12px 0 0;+ transform: translateY(100%);+ }+ #sidebar.open { transform: translateY(0); }+ #sb-head {+ position: relative;+ padding: 12px 20px 10px;+ }+ #sb-head::before {+ content: '';+ position: absolute;+ top: 6px; left: 50%;+ transform: translateX(-50%);+ width: 36px; height: 4px;+ background: #444; border-radius: 2px;+ }+ .hud { right: 8px; top: 8px; }+ .hud .hbtn { width: 28px; height: 28px; font-size: 12px; }+}</style></head><body>@@ -238,6 +289,8 @@ body.light .reg-node:hover .nshape { stroke: #000 !important; }<div id="nav-list"></div></div>+<div id="mobile-nav-btn" onclick="toggleMobileNav()"><span>☰</span><span id="mobile-title">omm</span></div>+<div id="mobile-overlay" onclick="toggleMobileNav()"></div><div id="canvas-wrap"><div class="float-controls"><button class="hbtn" onclick="zoomOut()">−</button>@@ -406,9 +459,10 @@ function smoothPath(pts) {// _expandedGlobal prevents same class from expanding in multiple brancheslet _expandedGlobal = new Set();-function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {+function renderGroup(cls, classesData, allClasses, level, seen = new Set(), scopedPath) {if (seen.has(cls)) return null;seen = new Set(seen); seen.add(cls);+ if (!scopedPath) scopedPath = cls; // level 0: scopedPath = perspective namelet labelOverlay = ''; // centered labels for sub-groups, rendered outside grp-innerconst data = classesData[cls];@@ -419,22 +473,27 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {if (!nodes.length) return null;// padding around the group content- const PAD_L = 16, PAD_R = 20, PAD_T = level===0 ? 20 : 22, PAD_B = 16;+ const PAD_L = 16, PAD_R = 20, PAD_T = 20, PAD_B = 16;// For level 0: expand @ref nodes as sub-groupsconst subGroups = {}; // nodeId -> { cls, W, H, svgContent }const nodeDims = {}; // nodeId -> { width, height }+ // Determine children of current element for subgroup resolution+ const currentChildren = (level === 0 ? (childrenByPerspective[cls] || []) : (classesData[cls]?.children || []));+for (const n of nodes) {- const refCls = n.isRef ? (n.refTarget || n.id) : null;- if (level < maxDepth && refCls && allClasses.includes(refCls) && !seen.has(refCls) && !_expandedGlobal.has(refCls)) {+ // Resolve subgroup: @ref (legacy) OR node ID is a child of current element with its own diagram+ const refCls = n.isRef ? (n.refTarget || n.id) : (currentChildren.includes(n.id) && classesData[n.id]?.diagram ? n.id : null);+ if (level < maxDepth && refCls && classesData[refCls]?.diagram && !seen.has(refCls) && !_expandedGlobal.has(refCls)) {_expandedGlobal.add(refCls);- const sub = renderGroup(refCls, classesData, allClasses, level+1, seen);+ const childScopedPath = scopedPath + '/' + refCls;+ const sub = renderGroup(refCls, classesData, allClasses, level+1, seen, childScopedPath);if (sub) {// Scale down to fit max box. At small scales, edge overflow becomes negligible.const MAX_W = 320, MAX_H = 220, PAD = 12;const fs = Math.min((MAX_W - PAD*2) / sub.W, (MAX_H - PAD*2) / sub.H, 1);- subGroups[n.id] = { cls: refCls, ...sub, fitScale: fs };+ subGroups[n.id] = { cls: refCls, scopedPath: childScopedPath, ...sub, fitScale: fs };nodeDims[n.id] = { width: sub.W * fs + PAD * 2, height: sub.H * fs + PAD * 2 };}}@@ -443,8 +502,8 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {const [mainLbl] = lbl.split('\n');const hasPath = lbl.includes('\n');const maxW = nodes.length > 10 ? 160 : 220;- const w = Math.min(maxW, Math.max(80, tw(mainLbl, level===0?'12px Inter,system-ui':'11px Inter,system-ui') + 44));- const baseH = n.shape==='diamond' ? 42 : (level===0 ? 38 : 34);+ const w = Math.min(maxW, Math.max(80, tw(mainLbl, '12px Inter,system-ui') + 44));+ const baseH = n.shape==='diamond' ? 42 : 38;nodeDims[n.id] = {width: w, height: hasPath ? baseH + 14 : baseH};}}@@ -478,8 +537,8 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {const dense = nodes.length > 10;function buildGraph(rd) {const g = new dagre.graphlib.Graph();- const nsep = level===0 ? (dense ? 20 : 32) : (dense ? 16 : 24);- const rsep = level===0 ? (dense ? 28 : 44) : (dense ? 22 : 32);+ const nsep = dense ? 20 : 32;+ const rsep = dense ? 28 : 44;g.setGraph({rankdir: rd, nodesep:nsep, ranksep:rsep, marginx:PAD_L, marginy:PAD_T});g.setDefaultEdgeLabel(() => ({}));for (const n of nodes) {@@ -555,7 +614,7 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {d = smoothPath(pts);mid = pts[Math.floor(pts.length/2)];}- const ec = level===0 ? th.edgeColor0 : th.edgeColor1;+ const ec = th.edgeColor0;const mk = `${uid}m${i}`;svg += `<defs><marker id="${mk}" markerWidth="6" markerHeight="5" refX="5" refY="2.5" orient="auto" markerUnits="userSpaceOnUse"><path d="M0,0.5 L0,4.5 L6,2.5 z" fill="${ec}"/></marker></defs>@@ -578,16 +637,15 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {if (sg) {// ── sub-group: dashed boundary + nested content ──- const safeId = esc(sg.cls);- const isRef = n.label.startsWith('@');+ const safeId = esc(sg.cls); // short name for display+ const scopedId = esc(sg.scopedPath || sg.cls); // full path for selectionconst refSubStroke = th.subStroke;- const refDash = '';const fs = sg.fitScale;const PAD = 12;const boxW = sg.W * fs + PAD * 2, boxH = sg.H * fs + PAD * 2;const clipId = `${uid}clip_${n.id}`;svg += `<defs><clipPath id="${clipId}"><rect x="-2" y="-16" width="${r1(boxW+4)}" height="${r1(boxH+18)}" rx="6"/></clipPath></defs>`;- svg += `<g class="grp-node" clip-path="url(#${clipId})" onclick="event.stopPropagation();window.__openSb('${safeId}')" data-cls="${safeId}" data-depth="${level+1}" transform="translate(${nx},${ny})">`;+ svg += `<g class="grp-node" clip-path="url(#${clipId})" onclick="event.stopPropagation();window.__openSb('${scopedId}')" data-cls="${scopedId}" data-depth="${level+1}" transform="translate(${nx},${ny})">`;svg += `<rect class="grp-border" width="${r1(boxW)}" height="${r1(boxH)}" rx="5"fill="${th.subFill}" stroke="${refSubStroke}" stroke-width="2"/>`;const _slW = tw(fmtLabel(sg.cls), '600 9px "Plus Jakarta Sans",Inter,system-ui') + 12;@@ -611,8 +669,8 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {const rawLbl = n.label.replace(/^@/,'');const [mainLbl, pathLbl] = rawLbl.split('\n');const cx = r1(pos.x), cy = r1(pos.y);- const fs = level===0 ? 12 : 11;- const safeId = esc(n.id);+ const fs = 12;+ const nodeScopedId = esc(scopedPath + '/' + n.id);let shape = '';if (n.shape==='diamond') {shape = `<polygon class="nshape" points="${cx},${ny} ${nx+dim.width},${cy} ${cx},${ny+dim.height} ${nx},${cy}"@@ -625,14 +683,14 @@ function renderGroup(cls, classesData, allClasses, level, seen = new Set()) {rx="4" fill="${st.bg}" stroke="${st.border}" stroke-width="2" ${da}/>`;}if (pathLbl) {- svg += `<g class="reg-node" data-cls="${safeId}" onclick="event.stopPropagation();window.__openSb('${safeId}')">${shape}+ svg += `<g class="reg-node" data-cls="${nodeScopedId}" onclick="event.stopPropagation();window.__openSb('${nodeScopedId}')">${shape}<text class="node-lbl" x="${cx}" y="${r1(cy - 7)}" text-anchor="middle" dominant-baseline="central"font-family="Inter,system-ui,sans-serif" font-size="${fs}" fill="${st.text}">${esc(mainLbl)}</text><text class="node-path" x="${cx}" y="${r1(cy + 7)}" text-anchor="middle" dominant-baseline="central"font-family="'SF Mono','Fira Code',monospace" font-size="9" fill="${st.text}" opacity="0.45">${esc(pathLbl)}</text></g>`;} else {- svg += `<g class="reg-node" data-cls="${safeId}" onclick="event.stopPropagation();window.__openSb('${safeId}')">${shape}+ svg += `<g class="reg-node" data-cls="${nodeScopedId}" onclick="event.stopPropagation();window.__openSb('${nodeScopedId}')">${shape}<text class="node-lbl" x="${cx}" y="${cy}" text-anchor="middle" dominant-baseline="central"font-family="Inter,system-ui,sans-serif" font-size="${fs}" fill="${st.text}">${esc(mainLbl)}</text></g>`;@@ -852,17 +910,19 @@ function focusGroup(cls) {const svgW = rect.width / vpScale;const svgH = rect.height / vpScale;- // Available viewport (account for right sidebar overlay)- const sbW = sidebar.classList.contains('open') ? 400 : 0;+ // Available viewport (account for sidebar: right panel on desktop, bottom drawer on mobile)+ const isMobile = window.innerWidth <= 768;+ const sbW = (!isMobile && sidebar.classList.contains('open')) ? 400 : 0;+ const sbH = (isMobile && sidebar.classList.contains('open')) ? window.innerHeight * 0.5 : 0;const availW = canvasWrap.clientWidth - sbW - 60;- const availH = canvasWrap.clientHeight - 60;+ const availH = canvasWrap.clientHeight - sbH - 60;// Target scale to fit element with paddingconst targetScale = Math.min(MAX_SCALE, Math.max(0.15, Math.min(availW / svgW, availH / svgH) * 0.85));- // Center in available viewport+ // Center in available viewport (account for sidebar/drawer)const centerX = (canvasWrap.clientWidth - sbW) / 2;- const centerY = canvasWrap.clientHeight / 2;+ const centerY = (canvasWrap.clientHeight - sbH) / 2;const toX = centerX - svgCenterX * targetScale;const toY = centerY - svgCenterY * targetScale;@@ -958,17 +1018,28 @@ canvasWrap.addEventListener('click', e => {// ── sidebar ───────────────────────────────────────────────window.__openSb = function(cls) {- if (!classes.includes(cls)) return;- // highlight+ // Resolve: try full scoped path, then short name, then fallback to parent perspective+ var shortName = cls.includes('/') ? cls.split('/').pop() : cls;+ var dataKey = classesData[cls] ? cls : (classesData[shortName] ? shortName : null);+ if (!dataKey && cls.includes('/')) {+ // Fallback: show parent perspective for nodes without their own element data+ dataKey = cls.split('/')[0];+ }+ if (!dataKey || !classesData[dataKey]) return;+ // highlight using scoped cls for DOM, dataKey for datadocument.querySelectorAll('.grp-node,.reg-node').forEach(el=>el.classList.remove('selected'));document.querySelectorAll(`[data-cls="${CSS.escape(cls)}"]`).forEach(el=>el.classList.add('selected'));selectedCls=cls;document.querySelectorAll('.nav-item').forEach(el => {el.classList.toggle('active', el.getAttribute('data-nav') === cls);});- openSidebar(cls);- // Wait for sidebar transition to complete (250ms) before focusing- setTimeout(() => focusGroup(cls), 260);+ var sidebarAlreadyOpen = sidebar.classList.contains('open');+ openSidebar(dataKey);+ if (sidebarAlreadyOpen) {+ focusGroup(cls);+ } else {+ setTimeout(() => focusGroup(cls), 260);+ }// Cloud mode: notify parent frame of selectionif (window.parent !== window) {window.parent.postMessage({ type: 'class-selected', className: cls }, '*');@@ -978,7 +1049,7 @@ window.__openSb = function(cls) {function openSidebar(cls) {const data=classesData[cls]||{}, refs=refsData[cls]||{};sbTitle.textContent=fmtLabel(cls);- sbDiagram.innerHTML = data.diagram ? (renderFlatSVG(data.diagram)||'') : '';+ sbDiagram.innerHTML = '';const md=t=>t?marked.parse(t):'';const sec=(title,body,ex='')=>body?`<div class="sb-sec ${ex}"><div class="sb-sec-title">${title}</div><div class="sb-sec-body">${body}</div></div>`:'';let html='';@@ -1011,6 +1082,38 @@ function closeSidebar() {selectedCls=null;document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));}++// Mobile: swipe down to close drawer+(function() {+ var startY = 0, currentY = 0, dragging = false;+ sidebar.addEventListener('touchstart', function(e) {+ if (!sidebar.classList.contains('open')) return;+ var t = e.touches[0];+ startY = t.clientY;+ currentY = startY;+ dragging = true;+ sidebar.style.transition = 'none';+ }, { passive: true });+ sidebar.addEventListener('touchmove', function(e) {+ if (!dragging) return;+ currentY = e.touches[0].clientY;+ var dy = currentY - startY;+ if (dy > 0) {+ sidebar.style.transform = 'translateY(' + dy + 'px)';+ }+ }, { passive: true });+ sidebar.addEventListener('touchend', function() {+ if (!dragging) return;+ dragging = false;+ sidebar.style.transition = '';+ var dy = currentY - startY;+ if (dy > 80) {+ closeSidebar();+ } else {+ sidebar.style.transform = '';+ }+ });+})();function clearFocusExempt() {document.querySelectorAll('#canvas [data-cls].focus-exempt').forEach(el => el.classList.remove('focus-exempt'));}@@ -1172,6 +1275,72 @@ function buildNavTree() {targets.forEach(r => { navInCount[r]++; });}+ // v2: if any perspective has children, use perspective nav with nested items+ const hasNested = Object.values(childrenByPerspective).some(c => c && c.length > 0);+ if (hasNested) {+ function addNavChildren(parentScopedPath, children, basePrefix) {+ children.forEach(function(child, j) {+ var isLast = j === children.length - 1;+ var childScoped = parentScopedPath + '/' + child;+ addNavItem(childScoped, basePrefix, isLast, child);+ // Recurse: check if this child has sub-children in classesData+ var childData = classesData[child];+ if (childData && childData.children && childData.children.length > 0) {+ var subPrefix = basePrefix + (isLast ? ' ' : '│ ');+ addNavChildren(childScoped, childData.children, subPrefix);+ }+ });+ }+ originalPerspectives.forEach((persp, i) => {+ const isLastPersp = i === originalPerspectives.length - 1;+ const children = childrenByPerspective[persp] || [];+ const hasChildren = children.length > 0;++ // Create perspective row with expand/fold toggle+ const btn = document.createElement('button');+ btn.setAttribute('data-nav', persp);+ btn.className = 'nav-item nav-root';+ btn.onclick = () => { window.__openSb(persp); if(window.innerWidth<=768){var n=document.getElementById('nav-sidebar'),o=document.getElementById('mobile-overlay');if(n)n.classList.remove('mobile-open');if(o)o.classList.remove('show');} };++ if (hasChildren) {+ const toggle = document.createElement('span');+ toggle.className = 'nav-toggle';+ toggle.textContent = '▾';+ toggle.style.cssText = 'cursor:pointer;margin-right:6px;font-size:13px;color:inherit;user-select:none';+ toggle.onclick = function(e) {+ e.stopPropagation();+ const container = btn.nextElementSibling;+ if (!container) return;+ const collapsed = container.style.display === 'none';+ container.style.display = collapsed ? '' : 'none';+ toggle.textContent = collapsed ? '▾' : '▸';+ };+ btn.appendChild(toggle);+ }++ const labelSpan = document.createElement('span');+ labelSpan.textContent = persp;+ btn.appendChild(labelSpan);+ navList.appendChild(btn);++ if (hasChildren) {+ const container = document.createElement('div');+ container.className = 'nav-persp-children';+ var childPrefix = isLastPersp ? ' ' : '│ ';+ // Collect children into container by temporarily redirecting addNavItem+ const origAppend = navList.appendChild.bind(navList);+ const tempItems = [];+ addNavChildren(persp, children, childPrefix);+ // Move the just-appended children from navList into container+ while (navList.lastChild && navList.lastChild !== btn) {+ container.insertBefore(navList.lastChild, container.firstChild);+ }+ navList.appendChild(container);+ }+ });+ return;+ }+let roots = classes.filter(c => navInCount[c] === 0);if (roots.length === 0) {// Circular refs — pick class with most outgoing refs as root@@ -1198,14 +1367,14 @@ function buildNavTree() {roots.forEach((r, i) => renderNode(r, '', i === roots.length - 1));}-function addNavItem(name, prefix, isLast) {+function addNavItem(name, prefix, isLast, displayLabel) {const btn = document.createElement('button');btn.setAttribute('data-nav', name);- btn.onclick = () => window.__openSb(name);+ btn.onclick = () => { window.__openSb(name); if(window.innerWidth<=768){var n=document.getElementById('nav-sidebar'),o=document.getElementById('mobile-overlay');if(n)n.classList.remove('mobile-open');if(o)o.classList.remove('show');} };if (prefix === '') {btn.className = 'nav-item nav-root';- btn.textContent = name;+ btn.textContent = displayLabel || name;} else {btn.className = 'nav-item';const pre = document.createElement('span');@@ -1222,32 +1391,92 @@ function addNavItem(name, prefix, isLast) {btn.appendChild(pre);const label = document.createElement('span');label.className = 'nav-label';- label.textContent = name;+ label.textContent = displayLabel || name;btn.appendChild(label);}navList.appendChild(btn);}+// ── nested element support ────────────────────────────────+var childrenByPerspective = {};+var originalPerspectives = []; // top-level only, before short names pollute classes++async function loadNodeData(perspective, childName) {+ var key = perspective + '/' + childName;+ if (classesData[key]) return classesData[key];+ var data = await api('/api/class/' + perspective + '/node/' + childName);+ if (data && !data.error) {+ classesData[key] = data;+ // Short name in classesData ONLY for renderGroup ref lookup+ // Do NOT add to classes array — only perspectives belong there+ classesData[childName] = data;+ // Also load this element's children (depth 2+)+ if (data.children && data.children.length > 0) {+ var subLoads = [];+ for (var sub of data.children) {+ subLoads.push(loadSubNodeData(perspective, childName + '/' + sub, sub));+ }+ await Promise.all(subLoads);+ }+ }+ return data;+}++async function loadSubNodeData(perspective, subPath, shortName) {+ if (classesData[perspective + '/' + subPath]) return;+ var data = await api('/api/class/' + perspective + '/node/' + subPath);+ if (data && !data.error) {+ classesData[perspective + '/' + subPath] = data;+ classesData[shortName] = data;+ // Recurse for deeper children+ if (data.children && data.children.length > 0) {+ var deepLoads = [];+ for (var sub of data.children) {+ deepLoads.push(loadSubNodeData(perspective, subPath + '/' + sub, sub));+ }+ await Promise.all(deepLoads);+ }+ }+}+// ── init ──────────────────────────────────────────────────async function init() {applyTheme();classes = await api('/api/classes');if (!classes.length) {- canvasEl.innerHTML=`<div class="empty-state" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)"><p>No classes found.<br>Run <code>/omm-scan</code> in Claude Code.</p></div>`;+ canvasEl.innerHTML=`<div class="empty-state" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)"><p>No perspectives found.<br>Run <code>/omm-scan</code> in Claude Code.</p></div>`;return;}- const [da,ra] = await Promise.all([+ const [da,ra,na] = await Promise.all([Promise.all(classes.map(c=>api(`/api/class/${c}`))),Promise.all(classes.map(c=>api(`/api/class/${c}/refs`))),+ Promise.all(classes.map(c=>api(`/api/class/${c}/nodes`))),]);- classes.forEach((c,i)=>{classesData[c]=da[i];refsData[c]=ra[i];});+ originalPerspectives = [...classes];+ classes.forEach((c,i)=>{+ classesData[c]=da[i];+ refsData[c]=ra[i];+ childrenByPerspective[c]=(na[i]&&na[i].children)||[];+ });++ // Pre-load nested element data for all children+ var nodeLoads = [];+ for (var persp of Object.keys(childrenByPerspective)) {+ for (var child of childrenByPerspective[persp]) {+ nodeLoads.push(loadNodeData(persp, child));+ }+ }+ await Promise.all(nodeLoads);// Set project name and build nav tree- navTitle.textContent = window.__projectName || 'omm';+ var projName = window.__projectName || 'omm';+ navTitle.textContent = projName;+ var mobileTitle = document.getElementById('mobile-title');+ if (mobileTitle) mobileTitle.textContent = projName;buildNavTree();- const result = buildCanvas(classes, classesData, refsData);+ const result = buildCanvas(originalPerspectives, classesData, refsData);if (result) {canvasEl.innerHTML = result.html;svgW = result.W; svgH = result.H;@@ -1271,6 +1500,14 @@ async function init() {});}+window.toggleMobileNav = function() {+ const nav = document.getElementById('nav-sidebar');+ const overlay = document.getElementById('mobile-overlay');+ const isOpen = nav.classList.contains('mobile-open');+ nav.classList.toggle('mobile-open', !isOpen);+ overlay.classList.toggle('show', !isOpen);+};+function setupLiveReload() {if (!window.EventSource) return;diff --git a/src/types.ts b/src/types.tsindex 7f7c275..0f0fa46 100644--- a/src/types.ts+++ b/src/types.ts@@ -11,6 +11,8 @@ export const FIELD_FILES: Record<Field, string> = {note: 'note.md',};+export type NodeKind = 'perspective' | 'nested-class';+export interface ClassMeta {created: string;updated: string;@@ -19,6 +21,10 @@ export interface ClassMeta {git_commit?: string;git_branch?: string;prev_diagram?: string;+ kind?: NodeKind;+ title?: string;+ children?: string[];+ parentPath?: string[];}export interface ClassData {@@ -36,6 +42,7 @@ export interface ClassData {export interface OmmConfig {version: string;theme?: string;+ language?: string;}export interface DiffResult {