diff --git a/.claude/skills/code-visualizer/README.md b/.claude/skills/code-visualizer/README.md index 6cb4e3f002..0743aabc35 100644 --- a/.claude/skills/code-visualizer/README.md +++ b/.claude/skills/code-visualizer/README.md @@ -1,97 +1,164 @@ # Code Visualizer -Auto-generates and maintains visual code flow diagrams from Python module analysis. +Auto-generates and maintains visual code flow diagrams from **multi-language** +module analysis. Supports **Python, TypeScript/JavaScript, Rust, and Go** out +of the box, with a brick-style architecture that makes adding a new language +a single-file change. ## Quick Start -Simply describe what you want: - -``` -Generate a code flow diagram for the auth module +```bash +# Generate one mermaid diagram per detected language, plus a combined view +python amplifier-bundle/skills/code-visualizer/scripts/visualizer.py . \ + --output docs/diagrams --combined ``` +Or just describe what you want: + ``` -Check if my architecture diagrams are up to date +Generate code flow diagrams for this repo ``` ``` -Show what architecture changes this PR introduces +Check if my architecture diagrams are up to date ``` ## Features -### Auto-Generation +### Multi-Language Auto-Detection + +The dispatcher walks the target path, buckets files by extension, and routes +each language to its own analyzer: -Analyzes Python imports and generates mermaid diagrams: +| Language | Extensions | +| --------------------- | -------------------------------------------- | +| Python | `.py` | +| TypeScript/JavaScript | `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs` | +| Rust | `.rs` | +| Go | `.go` | + +Mixed-language repos produce one diagram per detected language plus an +optional `--combined` mermaid view with one `subgraph` per language. + +### Auto-Generated Diagrams ```mermaid flowchart TD - main[main.py] --> auth[auth/] - main --> api[api/] - auth --> models[models.py] + main_py["main.py"] --> auth_py["auth.py"] + main_py --> api_py["api.py"] + auth_py --> models_py["models.py"] ``` ### Staleness Detection -Warns when diagrams become out of sync with code: +Walks all source files matching detected languages' extensions and compares +max-mtime against the diagram mtime — works the same way for every supported +language. ``` -STALE: README.md diagram (last updated: Jan 1, code changed: Jan 15) -Missing: new_module.py, api/v2.py +STALE: docs/diagrams/architecture-python.mmd (sources newer than diagram) +FRESH: docs/diagrams/architecture-typescript.mmd ``` -### PR Impact Analysis +## How It Works -Shows architecture changes in pull requests: +1. **Dispatch**: Detect languages by file extension, skipping `IGNORE_DIRS` + (`.git`, `node_modules`, `.venv`, `dist`, `build`, `target`, …) and + symlinks. +2. **Analyze**: Per-language analyzers (`python_analyzer`, `ts_analyzer`, + `rust_analyzer`, `go_analyzer`) each expose a single `normalize(paths) -> +Graph` entry point. +3. **Render**: A language-blind renderer turns each `Graph` into mermaid. +4. **Monitor**: A generalized staleness detector compares max-mtime across + matching extensions. -- New modules added -- Changed dependencies -- Deleted relationships +## Architecture -## How It Works +``` +code-visualizer +├── scripts/ +│ ├── graph.py # Node / Edge / Graph dataclasses (data contract) +│ ├── dispatcher.py # Language detection + routing +│ ├── python_analyzer.py # ast-based +│ ├── ts_analyzer.py # regex-based (.ts/.tsx/.js/.jsx/.mjs/.cjs) +│ ├── rust_analyzer.py # regex-based +│ ├── go_analyzer.py # regex-based +│ ├── mermaid_renderer.py # language-blind +│ ├── staleness.py +│ └── visualizer.py # CLI +└── tests/ +``` -1. **Analyze**: Parse Python files for imports and classes -2. **Generate**: Create mermaid diagrams from relationships (delegates to mermaid-diagram-generator) -3. **Monitor**: Compare timestamps to detect staleness -4. **Report**: Provide freshness status and recommendations +Each analyzer is a self-contained brick. **No shared inheritance.** The only +coupling is the `Graph` data contract. -## Skill Architecture +## CLI ``` -code-visualizer -├── Analyzes: Python AST for imports/classes -├── Detects: Stale diagrams via timestamps -└── Delegates to: - ├── mermaid-diagram-generator (syntax) - └── visualization-architect (complex diagrams) +python visualizer.py [--output DIR] [--basename NAME] + [--check-staleness] [--combined] ``` -## Limitations (Important) +Outputs: + +- `-python.mmd` +- `-typescript.mmd` +- `-rust.mmd` +- `-go.mmd` +- `-combined.mmd` (with `--combined`) + +Files are only written for languages actually detected. + +## Adding a New Language + +1. Create `scripts/_analyzer.py` exposing + `normalize(paths) -> Graph`. +2. Register the extension(s) and module name in `dispatcher.LANGUAGES`. +3. Add `tests/test__analyzer.py`. -- **Staleness is timestamp-based**: 70-80% accuracy, false positives common -- **Python-only**: No TypeScript/JS/Rust support -- **Static analysis**: Dynamic imports not detected -- **Import-centric**: Internal logic changes invisible +That's the entire change. The renderer, staleness detector, and CLI consume +the language-blind `Graph` and need no modification. See **Extending** in +`SKILL.md` for the full recipe. + +## Limitations + +- **Static heuristics**: Regex-based extraction for TS/JS/Rust/Go covers + common forms; some edge syntax is documented in source. +- **Import-centric**: Edges are imports/uses only. No call graphs. +- **External imports**: Rendered as ghost target nodes; not resolved. +- **Cross-language edges**: Out of MVP scope; combined view is per-subgraph. +- **Shell scripts**: Not first-class; ignored. + +See `SKILL.md` for the full limitation list and security model. + +## Testing + +```bash +pytest amplifier-bundle/skills/code-visualizer/tests -q +``` -See SKILL.md for complete limitations and accuracy expectations. +The skill ships unit tests for each analyzer, the dispatcher, the renderer, +and the staleness detector, plus a smoke test that runs the dispatcher +against the repo root and asserts non-empty mermaid output for both Python +and TypeScript/JavaScript. ## Philosophy Alignment -| Principle | How This Skill Follows It | -| ----------------------- | ------------------------------------------------------------------- | -| **Ruthless Simplicity** | Timestamp-based staleness is "good enough" for 90% of cases | -| **Zero-BS** | Real AST parsing, no mock data, honest about limitations | -| **Modular Design** | Single brick, delegates diagram syntax to mermaid-diagram-generator | +| Principle | How v2.0 follows it | +| ----------------------- | ----------------------------------------------------------------------------------- | +| **Ruthless Simplicity** | Stdlib-only. Regex over tree-sitter. Max-mtime over semantic diff. | +| **Zero-BS** | Real parsers; honest about regex edge cases. | +| **Modular Design** | Each analyzer is a brick with one `normalize()` stud. | +| **Brick Composition** | Renderer / dispatcher / staleness are independent bricks sharing only the contract. | ## Integration Works with: -- `mermaid-diagram-generator` skill for diagram syntax +- `mermaid-diagram-generator` skill for diagram syntax helpers - `visualization-architect` agent for complex diagrams -- PR review workflow for impact analysis ## Dependencies -- **Required**: mermaid-diagram-generator skill -- **Recommended**: Python 3.8+, Git for enhanced staleness detection +- **Required**: Python 3.11+ (stdlib only). +- **Optional**: `mermaid-diagram-generator` skill for advanced styling. diff --git a/.claude/skills/code-visualizer/SKILL.md b/.claude/skills/code-visualizer/SKILL.md index bcc83b8233..ddf8e5f29d 100644 --- a/.claude/skills/code-visualizer/SKILL.md +++ b/.claude/skills/code-visualizer/SKILL.md @@ -1,10 +1,12 @@ --- name: code-visualizer -version: 1.1.0 +version: 2.0.0 description: | - Auto-generates code flow diagrams from Python module analysis. + Auto-generates code flow diagrams from multi-language module analysis. Detects when architecture diagrams become stale (code changed, diagram didn't). - Use when: creating new modules, reviewing PRs for architecture impact, or checking diagram freshness. + Supports Python, TypeScript/JavaScript, Rust, and Go out of the box. + Use when: creating new modules, reviewing PRs for architecture impact, or + checking diagram freshness across polyglot repositories. Generates mermaid diagrams showing imports, dependencies, and module relationships. invokes: skills: @@ -17,562 +19,399 @@ invokes: ## Purpose -Automatically generate and maintain visual code flow diagrams. This skill analyzes Python module structure, detects import relationships, and generates mermaid diagrams. It also monitors for staleness when code changes but diagrams don't. +Automatically generate and maintain visual code flow diagrams across multiple +programming languages. The skill auto-detects which languages are present in a +target path, analyzes each one with a dedicated analyzer, and emits one +mermaid diagram per language plus an optional combined high-level view. It +also detects when committed diagrams are stale relative to the source they +describe. + +## What's New in 2.0.0 + +- **Multi-language support**: Python, TypeScript/JavaScript, Rust, and Go. +- **Language dispatcher**: Detects languages by file extension and routes to + per-language analyzers. +- **Language-blind renderer**: A single mermaid renderer consumes a normalized + graph; the renderer never inspects language semantics. +- **One diagram per language** plus an optional `--combined` view that places + each language in its own mermaid `subgraph`. +- **Generalized staleness**: Walks all source files matching detected + languages' extensions and compares max-mtime against the diagram mtime. +- **Brick-style architecture**: Each language analyzer is a self-contained + module that exposes a single `normalize()` function. No shared inheritance. + +## Supported Languages + +| Language | Extensions | Analyzer | Parser | Notes | +| --------------------- | -------------------------------------------- | ----------------- | ------ | ---------------------------------------------------------------- | +| Python | `.py` | `python_analyzer` | `ast` | Extracts `import` and `from … import …`. | +| TypeScript/JavaScript | `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs` | `ts_analyzer` | regex | Extracts `import … from`, `require(...)`, dynamic `import(...)`. | +| Rust | `.rs` | `rust_analyzer` | regex | Extracts `use crate::…`, `use super::…`, `mod …`. | +| Go | `.go` | `go_analyzer` | regex | Extracts single and grouped `import` declarations. | + +Languages outside this table are skipped silently. See **Extending** below to +add new ones. -## Philosophy Alignment - -This skill embodies amplihack's core philosophy: - -### Ruthless Simplicity - -- **Single responsibility**: Visualize code structure - nothing more -- **Minimal dependencies**: Uses only Python AST for analysis, delegates diagram syntax to mermaid-diagram-generator -- **No over-engineering**: Timestamp-based staleness is simple and "good enough" for 90% of cases - -### Zero-BS Implementation - -- **Real analysis**: Actually parses Python AST to extract imports - no mock data -- **Honest limitations**: Staleness detection is timestamp-based, not semantic (see Limitations section) -- **Working code**: All algorithms shown are functional, not pseudocode - -### Modular Design (Bricks & Studs) - -- **This skill is one brick**: Code analysis and staleness detection -- **Delegates to other bricks**: mermaid-diagram-generator for syntax, visualization-architect for complex diagrams -- **Clear studs (public contract)**: Analyze modules, generate diagrams, check freshness - -## Skill Delegation Architecture +## Architecture ``` -code-visualizer (this skill) -├── Responsibilities: -│ ├── Python module analysis (AST parsing) -│ ├── Import relationship extraction -│ ├── Staleness detection (timestamp-based) -│ └── Orchestration of diagram generation -│ -└── Delegates to: - ├── mermaid-diagram-generator skill - │ ├── Mermaid syntax generation - │ ├── Diagram formatting and styling - │ └── Markdown embedding - │ - └── visualization-architect agent - ├── Complex multi-level architecture - ├── ASCII art alternatives - └── Cross-module dependency graphs +amplifier-bundle/skills/code-visualizer/ +├── SKILL.md +├── README.md +└── scripts/ + ├── __init__.py + ├── graph.py # Normalized data contract (Node, Edge, Graph) + ├── python_analyzer.py # normalize(paths) -> Graph + ├── ts_analyzer.py # normalize(paths) -> Graph + ├── rust_analyzer.py # normalize(paths) -> Graph + ├── go_analyzer.py # normalize(paths) -> Graph + ├── dispatcher.py # detect languages, route, return dict[lang, Graph] + ├── mermaid_renderer.py # render(graph) / render_combined(graphs) + ├── staleness.py # is_stale(target, diagram, languages) + └── visualizer.py # CLI entry point ``` -**Invocation Pattern:** +### Data Contract (`graph.py`) ```python -# code-visualizer analyzes code structure -modules = analyze_python_modules("src/") -relationships = extract_import_relationships(modules) - -# Then delegates to mermaid-diagram-generator for syntax -Skill(skill="mermaid-diagram-generator") -# Provide: Module relationships, diagram type (flowchart/class), styling preferences -# Receive: Valid mermaid syntax ready for embedding - -# For complex architectures, delegates to visualization-architect -Task(subagent_type="visualization-architect", prompt="Create multi-level diagram for...") -``` - -## When to Use This Skill - -- **New Module Creation**: Auto-generate architecture diagram for new modules -- **PR Reviews**: Show architecture impact of proposed changes -- **Staleness Detection**: Check if existing diagrams reflect current code -- **Dependency Analysis**: Visualize import relationships -- **Refactoring**: Understand module dependencies before changes - -## Quick Start - -### Generate Diagram for Module - -``` -User: Generate a code flow diagram for the authentication module +@dataclass(frozen=True) +class Node: + id: str # mermaid-safe identifier + label: str # human-readable label (e.g. "src/auth/oauth.py") + language: str # "python" | "typescript" | "rust" | "go" + file_path: str # absolute path on disk + +@dataclass(frozen=True) +class Edge: + src: str # Node.id of source + dst: str # Node.id of destination + kind: str # "import" | "require" | "use" | "mod" | "dynamic_import" + +@dataclass(frozen=True) +class Graph: + language: str + nodes: tuple[Node, ...] + edges: tuple[Edge, ...] ``` -### Check Diagram Freshness - -``` -User: Are my architecture diagrams up to date? -``` - -### Show PR Impact - -``` -User: What architecture changes does this PR introduce? -``` - -## Core Capabilities - -### 1. Module Analysis - -Analyzes Python files to extract: - -- Import statements (internal and external) -- Class definitions and inheritance -- Function exports (`__all__`) -- Module dependencies - -### 2. Diagram Generation - -Creates mermaid diagrams showing: - -- Module relationships (flowchart) -- Class hierarchies (class diagram) -- Data flow between components -- Dependency graphs +Analyzers may **import** these dataclasses but must not inherit from any +shared class. The data contract is the only coupling. -### 3. Staleness Detection +### Per-Language Analyzers -Compares: - -- File modification timestamps -- Git history for changes -- Diagram content vs actual code structure -- Missing modules in diagrams - -## Analysis Process - -### Step 1: Discover Modules +Each analyzer is a self-contained brick exposing exactly one entry point: ```python -# Scan target directory for Python modules -modules = glob("**/*.py") -packages = identify_packages(modules) +def normalize(paths: Iterable[Path]) -> Graph: ... ``` -### Step 2: Extract Relationships +The function: -For each module: +1. Reads each file with `encoding="utf-8", errors="ignore"`. +2. Skips files larger than ~5 MB. +3. Wraps parsing in `try/except` and skips files that fail to parse. +4. Returns a `Graph` whose `language` field matches the analyzer. -1. Parse import statements -2. Identify local vs external imports -3. Build dependency graph -4. Detect circular dependencies +### Dispatcher -### Step 3: Generate Diagram +The dispatcher uses a registry that maps language name → extensions + module +name (string). It loads analyzers lazily via `importlib.import_module` so +adding a new language never requires touching the dispatcher's import +statements. -```mermaid -flowchart TD - subgraph core["Core Modules"] - auth[auth.py] - users[users.py] - api[api.py] - end - - subgraph utils["Utilities"] - helpers[helpers.py] - validators[validators.py] - end +```python +from scripts.dispatcher import analyze - api --> auth - api --> users - auth --> helpers - users --> validators +graphs: dict[str, Graph] = analyze(target_path) +# {"python": Graph(...), "typescript": Graph(...)} ``` -### Step 4: Check Freshness +The dispatcher: -Compare diagram timestamps with source files: +- Walks `target_path` with `os.walk(..., followlinks=False)`. +- Skips `IGNORE_DIRS` (`.git`, `node_modules`, `.venv`, `venv`, `__pycache__`, + `dist`, `build`, `target`, `.mypy_cache`, `.pytest_cache`, `.tox`). +- Buckets files by extension into language groups. +- Calls each language's `normalize()` with its file list. +- Returns a `dict[language_name, Graph]` for languages that produced any + files. -- Diagram older than sources = STALE -- Missing modules in diagram = INCOMPLETE -- Extra modules in diagram = OUTDATED +### Mermaid Renderer -## Diagram Types +The renderer is language-blind: -### Module Dependency Graph - -Best for: Showing import relationships between files +```python +from scripts.mermaid_renderer import render, render_combined -```mermaid -flowchart LR - main[main.py] --> auth[auth/] - main --> api[api/] - auth --> models[models.py] - api --> auth +per_language: str = render(graph) # one diagram for one language +combined: str = render_combined(graphs) # one diagram, one subgraph/lang ``` -### Class Hierarchy - -Best for: Showing inheritance and composition +Node IDs are sanitized (`[^A-Za-z0-9_] -> _`) and labels with quotes are +escaped to prevent diagram-syntax injection. -```mermaid -classDiagram - class BaseService { - +process() - } - class AuthService { - +login() - +logout() - } - BaseService <|-- AuthService -``` +### Staleness Detection -### Data Flow - -Best for: Showing how data moves through system +```python +from scripts.staleness import is_stale -```mermaid -flowchart TD - Request[HTTP Request] --> Validate{Validate} - Validate -->|Valid| Process[Process] - Validate -->|Invalid| Error[Return Error] - Process --> Response[HTTP Response] +stale = is_stale( + target_path=Path("src/"), + diagram_path=Path("docs/architecture-python.mmd"), + languages=["python"], +) ``` -## Staleness Detection - -### How It Works - -1. **Find Diagrams**: Locate mermaid diagrams in README.md, ARCHITECTURE.md -2. **Extract Modules**: Parse diagram for referenced modules -3. **Compare**: Check if all current modules are represented -4. **Report**: Generate freshness report - -### Freshness Report Format - -```markdown -## Diagram Freshness Report - -### Status: STALE - -**Diagrams Checked**: 3 -**Fresh**: 1 -**Stale**: 2 - -### Details +Returns `True` if any source file with a matching language extension has an +mtime newer than `diagram_path`. Generalizes the previous Python-only +behavior. -| File | Last Updated | Code Changed | Status | -| ------------ | ------------ | ------------ | ------ | -| README.md | 2025-01-01 | 2025-01-15 | STALE | -| docs/ARCH.md | 2025-01-10 | 2025-01-10 | FRESH | +## CLI -### Missing from Diagrams +The skill ships a single executable: `scripts/visualizer.py`. -- `new_module.py` (added 2025-01-12) -- `api/v2.py` (added 2025-01-14) - -### Recommended Actions - -1. Update README.md architecture diagram -2. Add new_module.py to dependency graph ``` - -## PR Architecture Impact - -### What It Shows - -For a given PR or set of changes: - -1. New modules/files added -2. Changed import relationships -3. Deleted dependencies -4. Modified class hierarchies - -### Impact Diagram - -```mermaid -flowchart TD - subgraph added["New"] - style added fill:#90EE90 - new_api[api/v2.py] - end - - subgraph modified["Modified"] - style modified fill:#FFE4B5 - auth[auth.py] - end - - subgraph existing["Unchanged"] - users[users.py] - models[models.py] - end - - new_api --> auth - auth --> models - users --> models +python visualizer.py [--output DIR] [--basename NAME] + [--check-staleness] [--combined] ``` -## Integration with Other Skills - -### Mermaid Diagram Generator +| Flag | Default | Purpose | +| ------------------- | -------------- | --------------------------------------------------------------------- | +| `` | _required_ | Directory to analyze. Must exist and be a directory. | +| `--output DIR` | `./diagrams` | Output directory for `.mmd` files. | +| `--basename NAME` | `architecture` | Filename stem. Validated against `^[A-Za-z0-9._-]+$`. | +| `--check-staleness` | off | Print staleness report for existing diagrams; exit non-zero if stale. | +| `--combined` | off | Also write `-combined.mmd` containing all languages. | -This skill uses `mermaid-diagram-generator` for: +### Output Files -- Syntax generation -- Diagram formatting -- Embedding in markdown +| File | Contents | +| --------------------------------------------- | ------------------------------------------------------ | +| `-python.mmd` | Mermaid diagram for Python modules and their imports. | +| `-typescript.mmd` | Mermaid diagram for TS/JS files and their imports. | +| `-rust.mmd` | Mermaid diagram for Rust modules and `use` edges. | +| `-go.mmd` | Mermaid diagram for Go packages and `import` edges. | +| `-combined.mmd` (with `--combined`) | One diagram with one `subgraph` per detected language. | -### Visualization Architect Agent +Files are only written for languages that were actually detected. -Delegates to `visualization-architect` for: - -- Complex architecture visualization -- ASCII art alternatives -- Multi-level diagrams - -## Usage Examples - -### Example 1: New Module Diagram - -``` -User: I just created a new payment module. Generate an architecture diagram. - -Claude: -1. Analyzes payment/ directory -2. Extracts imports and dependencies -3. Generates mermaid flowchart -4. Suggests where to embed (README.md) -``` +## Quick Start -### Example 2: Check Staleness +### Generate diagrams for a polyglot repo -``` -User: Are my diagrams up to date? - -Claude: -1. Finds all mermaid diagrams in docs -2. Compares with current codebase -3. Reports stale diagrams -4. Lists missing modules -5. Suggests updates +```bash +python amplifier-bundle/skills/code-visualizer/scripts/visualizer.py . \ + --output docs/diagrams --combined ``` -### Example 3: PR Impact +Output (for this repo, which contains Python and JS): ``` -User: Show architecture impact of this PR - -Claude: -1. Gets changed files from PR -2. Identifies new/modified/deleted modules -3. Generates impact diagram -4. Highlights dependency changes +docs/diagrams/architecture-python.mmd +docs/diagrams/architecture-typescript.mmd +docs/diagrams/architecture-combined.mmd ``` -## Detection Algorithms - -### Import Analysis +### Check freshness in CI -```python -# Extract imports from Python file -import ast - -def extract_imports(file_path): - """Extract import statements from Python file.""" - tree = ast.parse(Path(file_path).read_text()) - imports = [] - for node in ast.walk(tree): - if isinstance(node, ast.Import): - for alias in node.names: - imports.append(alias.name) - elif isinstance(node, ast.ImportFrom): - if node.module: - imports.append(node.module) - return imports +```bash +python amplifier-bundle/skills/code-visualizer/scripts/visualizer.py src/ \ + --output docs/diagrams --check-staleness +# exits 1 if any per-language diagram is older than its source set ``` -### Staleness Check +### Generate for a single language -```python -def check_staleness(diagram_file, source_dir): - """Check if diagram is stale compared to source.""" - diagram_mtime = Path(diagram_file).stat().st_mtime +Provide a path that only contains files of one language; the dispatcher will +detect a single language and emit a single `.mmd`: - for source in Path(source_dir).rglob("*.py"): - if source.stat().st_mtime > diagram_mtime: - return True, source # Stale - - return False, None # Fresh +```bash +python visualizer.py src/auth/ # Python-only -> architecture-python.mmd ``` -## Best Practices - -### When to Update Diagrams +## Auto-Detection Rules -1. **New modules**: Add to dependency graph -2. **Changed imports**: Update relationships -3. **Deleted files**: Remove from diagrams -4. **Architectural changes**: Regenerate completely +1. The dispatcher walks ``, skipping `IGNORE_DIRS` and symlinks. +2. Files are bucketed by extension into one of the supported languages. +3. A language is "detected" if at least one file matches. +4. Each detected language is analyzed independently. +5. With `--combined`, the renderer composes one mermaid diagram with one + `subgraph` per detected language. Cross-language edges are not inferred in + the MVP. -### Diagram Placement +## Example Output -| Diagram Type | Recommended Location | -| --------------------- | -------------------- | -| Module overview | README.md | -| Detailed architecture | docs/ARCHITECTURE.md | -| Package structure | package/README.md | -| API flow | api/README.md | +For a repo with: -### Naming Conventions - -````markdown -## Architecture +- `src/api.py` importing `src/auth.py` +- `web/index.ts` importing `web/utils.ts` - - - +`architecture-python.mmd`: ```mermaid flowchart TD - ... + src_api_py["src/api.py"] + src_auth_py["src/auth.py"] + src_api_py --> src_auth_py ``` -```` - -## Success Criteria - -A good visualization: - -- [ ] Shows all current modules -- [ ] Reflects actual import relationships -- [ ] Uses appropriate diagram type -- [ ] Placed in discoverable location -- [ ] Includes freshness metadata -- [ ] Clear and not overcrowded - -## Limitations - -**IMPORTANT**: Understand these limitations before relying on this skill: - -### Staleness Detection Limitations - -1. **Timestamp-based, not semantic**: Detection compares file modification times, not actual code changes - - A file touched but not meaningfully changed will trigger "stale" - - Reformatting code triggers false positives - - Git operations that update mtime trigger false positives -2. **Cannot detect logic changes**: Adding a function that doesn't change imports won't be detected - - Internal refactoring within a module is invisible - - Changes to function signatures not reflected - - New class methods added without import changes won't show +`architecture-typescript.mmd`: -3. **Import-centric view**: Only tracks import relationships - - Runtime dependencies (dependency injection) not detected - - Configuration-based connections invisible - - Duck typing relationships not captured - -### Scope Limitations - -1. **Python-only**: Currently only analyzes Python files - - No TypeScript, JavaScript, Rust, Go support - - Multi-language projects partially covered - -2. **Static analysis only**: No runtime information - - Dynamic imports (`__import__`, `importlib`) not detected - - Conditional imports may be missed - - Plugin architectures not fully represented - -3. **Single-project scope**: Cannot analyze cross-repository dependencies - - External package internals not shown - - Monorepo relationships require manual configuration - -### Accuracy Expectations - -| Scenario | Accuracy | Notes | -| ----------------------------- | -------- | --------------------------- | -| New module detection | 95%+ | Reliable for Python modules | -| Import relationship mapping | 90%+ | Misses dynamic imports | -| Staleness detection | 70-80% | False positives common | -| Circular dependency detection | 85%+ | May miss complex cycles | -| Class hierarchy extraction | 85%+ | Mixins can be tricky | - -### When NOT to Use This Skill - -- **Security-critical dependency audits**: Use proper security scanning tools -- **Runtime dependency analysis**: Use profilers or dynamic analysis tools -- **Cross-language projects**: Manual analysis may be more accurate -- **Heavily dynamic codebases**: Plugin architectures, metaprogramming - -## Dependencies - -This skill requires: - -1. **mermaid-diagram-generator skill**: Must be available for diagram syntax generation -2. **Python 3.8+**: For AST parsing features used -3. **Git (optional)**: For enhanced staleness detection using git history - -If mermaid-diagram-generator is unavailable, this skill will provide raw relationship data but cannot generate embedded diagrams. - -## PR Review Integration - -### How Diagrams Appear in PRs - -When reviewing PRs, this skill generates impact diagrams that can be added to PR descriptions: - -**PR Description Template:** - -````markdown -## Architecture Impact - - +```mermaid +flowchart TD + web_index_ts["web/index.ts"] + web_utils_ts["web/utils.ts"] + web_index_ts --> web_utils_ts +``` -### Changed Dependencies +`architecture-combined.mmd`: ```mermaid -flowchart LR - subgraph changed["Modified Modules"] - style changed fill:#FFE4B5 - auth[auth/service.py] - api[api/routes.py] - end - - subgraph added["New Modules"] - style added fill:#90EE90 - oauth[auth/oauth.py] +flowchart TD + subgraph python ["python"] + src_api_py["src/api.py"] + src_auth_py["src/auth.py"] + src_api_py --> src_auth_py end - - subgraph unchanged["Existing"] - models[models/user.py] - db[db/connection.py] + subgraph typescript ["typescript"] + web_index_ts["web/index.ts"] + web_utils_ts["web/utils.ts"] + web_index_ts --> web_utils_ts end - - oauth --> auth - auth --> models - api --> auth - api --> db ``` -### Impact Summary - -- **New modules**: 1 (oauth.py) -- **Modified modules**: 2 (auth/service.py, api/routes.py) -- **New dependencies**: oauth.py -> auth/service.py -- **Diagrams to update**: README.md (STALE) -```` +> Note: the renderer emits the `subgraph ["