Skip to content

An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.

feat(vault): add universal graph-builder skill

smixs0f31211c2ffc
diff --git a/vault/.claude/CLAUDE.md b/vault/.claude/CLAUDE.md
index 1451ef6..4c4f2f1 100644
--- a/vault/.claude/CLAUDE.md
+++ b/vault/.claude/CLAUDE.md
@@ -90,6 +90,7 @@ Run daily processing via `/process` command or automatically at 21:00.
|-------|---------|
| `dbrain-processor` | Main daily processing |
| `todoist-ai` | Task management via MCP |
+| `graph-builder` | Vault link analysis and building |
## Available Agents
@@ -151,6 +152,7 @@ Reports use Telegram HTML:
| `/weekly` | Generate weekly digest |
| `/align` | Check goal alignment |
| `/organize` | Organize vault |
+| `/graph` | Analyze vault links |
## /do Command Context
@@ -189,7 +191,23 @@ When invoked via /do, Claude receives arbitrary user requests. Common patterns:
For personal overrides: create `CLAUDE.local.md`
+## Graph Builder
+
+Analyze and maintain vault link structure. Use `/graph` command or invoke `graph-builder` skill.
+
+**Commands:**
+- `/graph analyze` — Full vault statistics
+- `/graph orphans` — List unconnected notes
+- `/graph suggest` — Get link suggestions
+- `/graph add` — Apply suggested links
+
+**Scripts:**
+- `uv run .claude/skills/graph-builder/scripts/analyze.py` — Graph analysis
+- `uv run .claude/skills/graph-builder/scripts/add_links.py` — Link suggestions
+
+See `skills/graph-builder/` for full documentation.
+
---
-*System Version: 2.1*
-*Updated: 2026-01-27*
+*System Version: 2.2*
+*Updated: 2026-01-30*
diff --git a/vault/.claude/skills/graph-builder/SKILL.md b/vault/.claude/skills/graph-builder/SKILL.md
new file mode 100644
index 0000000..a694e7f
--- /dev/null
+++ b/vault/.claude/skills/graph-builder/SKILL.md
@@ -0,0 +1,75 @@
+---
+name: graph-builder
+description: Analyze and build knowledge graph links in Obsidian vault. Find orphan notes, suggest connections, add backlinks, visualize link structure. Triggers on /graph, "analyze links", "find orphans", "suggest connections".
+---
+
+# Graph Builder
+
+Analyze vault link structure and build meaningful connections between notes.
+
+## Use Cases
+
+1. **Analyze** — Statistics and insights about vault graph
+2. **Find Orphans** — Notes without incoming/outgoing links
+3. **Suggest Links** — AI-powered connection recommendations
+4. **Add Links** — Batch link creation based on content analysis
+5. **Visualize** — Export graph data for visualization
+
+## Quick Commands
+
+| Command | Action |
+|---------|--------|
+| `/graph analyze` | Full vault analysis with stats |
+| `/graph orphans` | List unconnected notes |
+| `/graph suggest` | Get link suggestions |
+| `/graph add` | Apply suggested links |
+
+## Analysis Output
+
+```
+📊 Vault Graph Analysis
+
+Total notes: 247
+Total links: 892
+Orphan notes: 12
+Most connected: [[MEMORY]] (47 links)
+Weakest domain: learnings/ (avg 1.2 links/note)
+
+🔗 Suggested connections:
+• [[Project A]] ↔ [[Client X]] (mentioned 5x)
+• [[Idea B]] → [[MOC/Ideas]] (category match)
+```
+
+## Domain Configuration
+
+Domains are configured in `references/domains.md`. Default structure:
+
+- **daily/** — Daily journal entries
+- **thoughts/** — Processed ideas, reflections, learnings
+- **goals/** — Goal cascade files
+- **MOC/** — Maps of Content (index pages)
+- **projects/** — Project notes
+
+## Link Building Strategy
+
+1. **Entity extraction** — Find mentions of existing notes
+2. **Category mapping** — Connect notes to relevant MOCs
+3. **Temporal links** — Link daily entries to related thoughts
+4. **Cross-domain** — Bridge domains (project ↔ goal ↔ daily)
+
+## Scripts
+
+- `scripts/analyze.py` — Graph statistics and orphan detection
+- `scripts/add_links.py` — Batch link insertion
+
+## References
+
+- `references/domains.md` — Domain definitions and rules
+- `references/frontmatter.md` — Frontmatter schema for notes
+
+## Output Format
+
+Reports use plain markdown (for vault notes) or HTML (for Telegram).
+
+For vault: Standard markdown with [[wiki-links]]
+For Telegram: HTML tags (b, i, code only)
diff --git a/vault/.claude/skills/graph-builder/references/domains.md b/vault/.claude/skills/graph-builder/references/domains.md
new file mode 100644
index 0000000..47255f9
--- /dev/null
+++ b/vault/.claude/skills/graph-builder/references/domains.md
@@ -0,0 +1,82 @@
+# Domain Configuration
+
+Domains define the organizational structure of the vault. Each domain has specific linking rules and priorities.
+
+## Core Domains
+
+### daily/
+**Purpose:** Daily journal entries, raw captures
+**Format:** `YYYY-MM-DD.md`
+**Linking:**
+- Outgoing to thoughts/ when content is processed
+- Outgoing to projects/ when project mentioned
+- Should reference MOCs for categorization
+
+### thoughts/
+**Purpose:** Processed and refined ideas
+**Subdirectories:**
+- `ideas/` — Creative concepts, innovations
+- `reflections/` — Personal insights, lessons learned
+- `learnings/` — Knowledge captured from reading/experience
+- `projects/` — Project-specific notes
+
+**Linking:**
+- Incoming from daily/ (source entries)
+- Outgoing to MOC/ (categorization)
+- Cross-links within thoughts/ (related concepts)
+
+### goals/
+**Purpose:** Goal hierarchy and tracking
+**Files:**
+- `0-vision-3y.md` — Long-term vision
+- `1-yearly-YYYY.md` — Annual goals
+- `2-monthly.md` — Monthly priorities
+- `3-weekly.md` — Weekly focus
+
+**Linking:**
+- Incoming from thoughts/ (ideas aligned with goals)
+- Incoming from daily/ (progress updates)
+- Should be highly connected as navigation hubs
+
+### MOC/
+**Purpose:** Maps of Content — index pages
+**Linking:**
+- Incoming from all domains (everything should have a MOC)
+- Outgoing to related MOCs
+- Central navigation hubs
+
+### projects/
+**Purpose:** Active project documentation
+**Linking:**
+- Incoming from daily/ (work logs)
+- Incoming from thoughts/ (related ideas)
+- Outgoing to goals/ (alignment)
+
+## Link Priority Rules
+
+When suggesting links, prioritize:
+
+1. **Orphan → MOC** — Every note should belong to a Map of Content
+2. **Daily → Thought** — Processed entries link to their refined notes
+3. **Thought → Goal** — Ideas should align with goals
+4. **Cross-domain** — Bridge related concepts across domains
+
+## Custom Domains
+
+Add custom domains by creating subdirectories and documenting them here:
+
+```markdown
+### your-domain/
+**Purpose:** Description
+**Linking:** Rules for incoming/outgoing links
+```
+
+## Entity Patterns
+
+Common patterns to detect for auto-linking:
+
+- `[[Note Name]]` — Existing wiki-links
+- `@mention` — People/contacts (if contacts domain exists)
+- `#tag` — Tags that may map to notes
+- Project names — Match against projects/ directory
+- Dates — Link to daily/ entries
diff --git a/vault/.claude/skills/graph-builder/references/frontmatter.md b/vault/.claude/skills/graph-builder/references/frontmatter.md
new file mode 100644
index 0000000..e24cbcc
--- /dev/null
+++ b/vault/.claude/skills/graph-builder/references/frontmatter.md
@@ -0,0 +1,110 @@
+# Frontmatter Schema
+
+Standard YAML frontmatter for vault notes.
+
+## Basic Schema
+
+```yaml
+---
+title: Note Title
+created: YYYY-MM-DD
+modified: YYYY-MM-DD
+tags: [tag1, tag2]
+aliases: [alternate-name]
+---
+```
+
+## Extended Schema
+
+```yaml
+---
+title: Note Title
+created: YYYY-MM-DD
+modified: YYYY-MM-DD
+tags: [tag1, tag2]
+aliases: [alternate-name]
+type: idea | reflection | learning | project | moc | daily
+domain: thoughts | goals | projects | daily
+status: draft | active | archived
+links:
+ - "[[Related Note]]"
+ - "[[Another Note]]"
+---
+```
+
+## Field Definitions
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| title | string | Yes | Display title for the note |
+| created | date | Yes | Creation date (YYYY-MM-DD) |
+| modified | date | No | Last modification date |
+| tags | array | No | Categorization tags |
+| aliases | array | No | Alternative names for linking |
+| type | enum | No | Note type classification |
+| domain | enum | No | Primary domain |
+| status | enum | No | Note lifecycle status |
+| links | array | No | Explicit related notes |
+
+## Type Values
+
+- `idea` — Creative concept or innovation
+- `reflection` — Personal insight or lesson
+- `learning` — Knowledge from external source
+- `project` — Project documentation
+- `moc` — Map of Content index
+- `daily` — Daily journal entry
+
+## Status Values
+
+- `draft` — Work in progress
+- `active` — Current and maintained
+- `archived` — No longer active, kept for reference
+
+## Usage in Graph Analysis
+
+The graph analyzer uses frontmatter to:
+
+1. **Classify notes** by type and domain
+2. **Detect orphans** based on links field
+3. **Suggest connections** using tags and aliases
+4. **Track freshness** via modified date
+
+## Example Notes
+
+### Thought Note
+```yaml
+---
+title: API Design Principles
+created: 2025-01-15
+tags: [development, architecture]
+type: learning
+domain: thoughts
+---
+```
+
+### MOC Note
+```yaml
+---
+title: Development Index
+created: 2024-06-01
+modified: 2025-01-20
+tags: [index, development]
+type: moc
+aliases: [Dev MOC, Development Map]
+---
+```
+
+### Project Note
+```yaml
+---
+title: Project Alpha
+created: 2025-01-01
+tags: [project, active]
+type: project
+status: active
+links:
+ - "[[goals/3-weekly]]"
+ - "[[MOC/Projects]]"
+---
+```
diff --git a/vault/.claude/skills/graph-builder/scripts/add_links.py b/vault/.claude/skills/graph-builder/scripts/add_links.py
new file mode 100644
index 0000000..2a2669a
--- /dev/null
+++ b/vault/.claude/skills/graph-builder/scripts/add_links.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""
+Link Builder for Obsidian Vault
+
+Suggests and adds wiki-links based on content analysis.
+Run with: uv run add_links.py [vault_path] [--dry-run]
+"""
+
+import re
+import sys
+from pathlib import Path
+from collections import defaultdict
+
+
+def extract_existing_links(content: str) -> set[str]:
+ """Extract existing [[wiki-links]] from content."""
+ pattern = r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]'
+ return set(re.findall(pattern, content))
+
+
+def find_mentions(content: str, note_titles: set[str]) -> list[tuple[str, int]]:
+ """Find mentions of note titles in content without existing links."""
+ existing = extract_existing_links(content)
+ mentions = []
+
+ for title in note_titles:
+ if title in existing:
+ continue
+ if len(title) < 3: # Skip very short titles
+ continue
+
+ # Case-insensitive search for title
+ pattern = rf'\b{re.escape(title)}\b'
+ for match in re.finditer(pattern, content, re.IGNORECASE):
+ mentions.append((title, match.start()))
+
+ return mentions
+
+
+def suggest_moc_links(note_path: Path, moc_mapping: dict[str, str]) -> list[str]:
+ """Suggest MOC links based on domain/tags."""
+ suggestions = []
+ domain = note_path.parts[0] if len(note_path.parts) > 1 else None
+
+ if domain and domain in moc_mapping:
+ suggestions.append(moc_mapping[domain])
+
+ return suggestions
+
+
+def build_moc_mapping(vault_path: Path) -> dict[str, str]:
+ """Build mapping from domains to their MOC files."""
+ mapping = {}
+ moc_dir = vault_path / "MOC"
+
+ if moc_dir.exists():
+ for moc_file in moc_dir.glob("*.md"):
+ moc_name = moc_file.stem
+ # Map common domain patterns
+ domain_patterns = {
+ "ideas": "thoughts",
+ "learnings": "thoughts",
+ "reflections": "thoughts",
+ "projects": "projects",
+ "goals": "goals",
+ }
+ for pattern, domain in domain_patterns.items():
+ if pattern.lower() in moc_name.lower():
+ mapping[domain] = moc_name
+
+ return mapping
+
+
+def analyze_and_suggest(vault_path: Path) -> dict:
+ """Analyze vault and suggest new links."""
+ suggestions: dict[str, list[dict]] = defaultdict(list)
+
+ # Collect all note titles
+ md_files = list(vault_path.rglob("*.md"))
+ md_files = [
+ f for f in md_files
+ if not any(part.startswith('.') for part in f.relative_to(vault_path).parts)
+ ]
+
+ note_titles = {f.stem for f in md_files}
+ moc_mapping = build_moc_mapping(vault_path)
+
+ for md_file in md_files:
+ rel_path = md_file.relative_to(vault_path)
+ title = md_file.stem
+ content = md_file.read_text(encoding="utf-8", errors="ignore")
+
+ # Find unlinked mentions
+ mentions = find_mentions(content, note_titles - {title})
+ for mentioned_title, position in mentions:
+ suggestions[title].append({
+ "type": "mention",
+ "target": mentioned_title,
+ "position": position,
+ "reason": f"'{mentioned_title}' mentioned but not linked",
+ })
+
+ # Suggest MOC links for orphan notes
+ existing_links = extract_existing_links(content)
+ moc_suggestions = suggest_moc_links(rel_path, moc_mapping)
+ for moc in moc_suggestions:
+ if moc not in existing_links:
+ suggestions[title].append({
+ "type": "moc",
+ "target": moc,
+ "reason": f"Should link to [[{moc}]] MOC",
+ })
+
+ return dict(suggestions)
+
+
+def apply_link(file_path: Path, target: str, dry_run: bool = True) -> bool:
+ """Add a link to a note's related section."""
+ content = file_path.read_text(encoding="utf-8")
+
+ # Check if link already exists
+ if f"[[{target}]]" in content:
+ return False
+
+ # Find or create "Related" section
+ related_pattern = r'^## Related\s*$'
+ match = re.search(related_pattern, content, re.MULTILINE)
+
+ if match:
+ # Add to existing Related section
+ insert_pos = match.end()
+ new_content = content[:insert_pos] + f"\n- [[{target}]]" + content[insert_pos:]
+ else:
+ # Add Related section at end
+ new_content = content.rstrip() + f"\n\n## Related\n\n- [[{target}]]\n"
+
+ if dry_run:
+ print(f"[DRY RUN] Would add [[{target}]] to {file_path.name}")
+ return True
+
+ file_path.write_text(new_content, encoding="utf-8")
+ print(f"Added [[{target}]] to {file_path.name}")
+ return True
+
+
+def format_suggestions(suggestions: dict) -> str:
+ """Format suggestions as readable report."""
+ if not suggestions:
+ return "No link suggestions found. Vault is well-connected!"
+
+ lines = [
+ "# Link Suggestions",
+ "",
+ f"Found suggestions for {len(suggestions)} notes:",
+ "",
+ ]
+
+ for note, items in sorted(suggestions.items()):
+ lines.append(f"## [[{note}]]")
+ for item in items:
+ lines.append(f"- {item['type'].upper()}: Link to [[{item['target']}]]")
+ lines.append(f" - Reason: {item['reason']}")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def format_html(suggestions: dict) -> str:
+ """Format suggestions as Telegram HTML."""
+ if not suggestions:
+ return "✅ <b>No link suggestions</b>\n\nVault is well-connected!"
+
+ total = sum(len(v) for v in suggestions.values())
+
+ lines = [
+ f"🔗 <b>Link Suggestions</b>",
+ "",
+ f"<b>Found:</b> {total} suggestions for {len(suggestions)} notes",
+ "",
+ ]
+
+ # Show top 10 suggestions
+ count = 0
+ for note, items in sorted(suggestions.items(), key=lambda x: -len(x[1])):
+ if count >= 10:
+ remaining = total - count
+ lines.append(f"\n<i>... and {remaining} more suggestions</i>")
+ break
+ for item in items:
+ lines.append(f"• [[{note}]] → [[{item['target']}]]")
+ count += 1
+ if count >= 10:
+ break
+
+ return "\n".join(lines)
+
+
+def main():
+ dry_run = "--dry-run" in sys.argv or "-n" in sys.argv
+ apply_mode = "--apply" in sys.argv
+
+ # Get vault path
+ vault_path = None
+ for arg in sys.argv[1:]:
+ if not arg.startswith("-"):
+ vault_path = Path(arg)
+ break
+
+ if vault_path is None:
+ # Default: assume script is in vault/.claude/skills/graph-builder/scripts/
+ vault_path = Path(__file__).parent.parent.parent.parent.parent
+
+ if not vault_path.exists():
+ print(f"Error: Vault path not found: {vault_path}", file=sys.stderr)
+ sys.exit(1)
+
+ suggestions = analyze_and_suggest(vault_path)
+
+ if apply_mode:
+ # Apply all suggestions
+ applied = 0
+ for note, items in suggestions.items():
+ note_path = vault_path / f"{note}.md"
+ # Try to find the actual file
+ matches = list(vault_path.rglob(f"{note}.md"))
+ matches = [m for m in matches if not str(m).startswith('.')]
+
+ if matches:
+ note_path = matches[0]
+ for item in items:
+ if apply_link(note_path, item["target"], dry_run):
+ applied += 1
+
+ print(f"\n{'[DRY RUN] Would apply' if dry_run else 'Applied'} {applied} links")
+ else:
+ # Just report
+ if "--html" in sys.argv:
+ print(format_html(suggestions))
+ elif "--json" in sys.argv:
+ import json
+ print(json.dumps(suggestions, indent=2))
+ else:
+ print(format_suggestions(suggestions))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/vault/.claude/skills/graph-builder/scripts/analyze.py b/vault/.claude/skills/graph-builder/scripts/analyze.py
new file mode 100644
index 0000000..d85bb8f
--- /dev/null
+++ b/vault/.claude/skills/graph-builder/scripts/analyze.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""
+Graph Analyzer for Obsidian Vault
+
+Analyzes wiki-link structure and generates statistics.
+Run with: uv run analyze.py [vault_path]
+"""
+
+import re
+import sys
+from collections import defaultdict
+from pathlib import Path
+
+
+def extract_links(content: str) -> list[str]:
+ """Extract [[wiki-links]] from content."""
+ pattern = r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]'
+ return re.findall(pattern, content)
+
+
+def get_note_title(path: Path) -> str:
+ """Get note title from filename."""
+ return path.stem
+
+
+def analyze_vault(vault_path: Path) -> dict:
+ """Analyze vault link structure."""
+ notes: dict[str, dict] = {}
+ links_from: dict[str, set] = defaultdict(set) # note -> set of linked notes
+ links_to: dict[str, set] = defaultdict(set) # note -> set of notes linking to it
+
+ # Collect all markdown files
+ md_files = list(vault_path.rglob("*.md"))
+
+ # Skip hidden directories and .claude
+ md_files = [
+ f for f in md_files
+ if not any(part.startswith('.') for part in f.relative_to(vault_path).parts)
+ ]
+
+ # Build note index
+ for md_file in md_files:
+ rel_path = md_file.relative_to(vault_path)
+ title = get_note_title(md_file)
+ domain = str(rel_path.parts[0]) if len(rel_path.parts) > 1 else "root"
+
+ notes[title] = {
+ "path": str(rel_path),
+ "domain": domain,
+ "size": md_file.stat().st_size,
+ }
+
+ # Analyze links
+ for md_file in md_files:
+ title = get_note_title(md_file)
+ content = md_file.read_text(encoding="utf-8", errors="ignore")
+
+ for link in extract_links(content):
+ # Handle links with paths like [[folder/note]]
+ link_title = link.split("/")[-1] if "/" in link else link
+
+ links_from[title].add(link_title)
+ links_to[link_title].add(title)
+
+ # Calculate statistics
+ orphans = []
+ for title, info in notes.items():
+ incoming = len(links_to.get(title, set()))
+ outgoing = len(links_from.get(title, set()))
+ info["incoming"] = incoming
+ info["outgoing"] = outgoing
+ info["total_links"] = incoming + outgoing
+
+ # Orphan: no incoming AND no outgoing links
+ # Exclude MOC and root-level files from orphan detection
+ if incoming == 0 and outgoing == 0:
+ if info["domain"] not in ("MOC", "root"):
+ orphans.append(title)
+
+ # Domain statistics
+ domain_stats: dict[str, dict] = defaultdict(lambda: {"count": 0, "links": 0})
+ for title, info in notes.items():
+ domain = info["domain"]
+ domain_stats[domain]["count"] += 1
+ domain_stats[domain]["links"] += info["total_links"]
+
+ for domain in domain_stats:
+ count = domain_stats[domain]["count"]
+ if count > 0:
+ domain_stats[domain]["avg_links"] = domain_stats[domain]["links"] / count
+
+ # Most connected notes
+ most_connected = sorted(
+ notes.items(),
+ key=lambda x: x[1]["total_links"],
+ reverse=True
+ )[:10]
+
+ return {
+ "total_notes": len(notes),
+ "total_links": sum(len(v) for v in links_from.values()),
+ "orphans": orphans,
+ "orphan_count": len(orphans),
+ "domain_stats": dict(domain_stats),
+ "most_connected": [(t, n["total_links"]) for t, n in most_connected],
+ "notes": notes,
+ "links_from": {k: list(v) for k, v in links_from.items()},
+ "links_to": {k: list(v) for k, v in links_to.items()},
+ }
+
+
+def format_report(stats: dict) -> str:
+ """Format analysis as readable report."""
+ lines = [
+ "# Vault Graph Analysis",
+ "",
+ "## Overview",
+ "",
+ f"- **Total notes:** {stats['total_notes']}",
+ f"- **Total links:** {stats['total_links']}",
+ f"- **Orphan notes:** {stats['orphan_count']}",
+ "",
+ ]
+
+ # Most connected
+ if stats["most_connected"]:
+ lines.append("## Most Connected Notes")
+ lines.append("")
+ for title, count in stats["most_connected"][:5]:
+ lines.append(f"- [[{title}]] ({count} links)")
+ lines.append("")
+
+ # Domain stats
+ lines.append("## Domain Statistics")
+ lines.append("")
+ lines.append("| Domain | Notes | Avg Links |")
+ lines.append("|--------|-------|-----------|")
+ for domain, data in sorted(stats["domain_stats"].items()):
+ avg = data.get("avg_links", 0)
+ lines.append(f"| {domain}/ | {data['count']} | {avg:.1f} |")
+ lines.append("")
+
+ # Orphans
+ if stats["orphans"]:
+ lines.append("## Orphan Notes (need links)")
+ lines.append("")
+ for title in stats["orphans"][:20]:
+ note = stats["notes"][title]
+ lines.append(f"- [[{title}]] ({note['domain']}/)")
+ if len(stats["orphans"]) > 20:
+ lines.append(f"- ... and {len(stats['orphans']) - 20} more")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def format_html(stats: dict) -> str:
+ """Format analysis as Telegram HTML."""
+ orphan_count = stats["orphan_count"]
+ orphan_emoji = "⚠️" if orphan_count > 10 else "✅"
+
+ lines = [
+ f"📊 <b>Vault Graph Analysis</b>",
+ "",
+ f"<b>📝 Total notes:</b> {stats['total_notes']}",
+ f"<b>🔗 Total links:</b> {stats['total_links']}",
+ f"<b>{orphan_emoji} Orphan notes:</b> {orphan_count}",
+ "",
+ ]
+
+ # Most connected
+ if stats["most_connected"]:
+ lines.append("<b>🏆 Most connected:</b>")
+ for title, count in stats["most_connected"][:3]:
+ lines.append(f"• [[{title}]] ({count})")
+ lines.append("")
+
+ # Weakest domain
+ weakest = min(
+ stats["domain_stats"].items(),
+ key=lambda x: x[1].get("avg_links", 0)
+ )
+ lines.append(f"<b>⚡ Weakest domain:</b> {weakest[0]}/ (avg {weakest[1].get('avg_links', 0):.1f} links)")
+
+ # Orphan preview
+ if stats["orphans"]:
+ lines.append("")
+ lines.append("<b>📋 Sample orphans:</b>")
+ for title in stats["orphans"][:5]:
+ lines.append(f"• {title}")
+
+ return "\n".join(lines)
+
+
+def main():
+ if len(sys.argv) > 1:
+ vault_path = Path(sys.argv[1])
+ else:
+ # Default: assume script is in vault/.claude/skills/graph-builder/scripts/
+ vault_path = Path(__file__).parent.parent.parent.parent.parent
+
+ if not vault_path.exists():
+ print(f"Error: Vault path not found: {vault_path}", file=sys.stderr)
+ sys.exit(1)
+
+ stats = analyze_vault(vault_path)
+
+ # Output format based on args
+ if "--html" in sys.argv:
+ print(format_html(stats))
+ elif "--json" in sys.argv:
+ import json
+ print(json.dumps(stats, indent=2))
+ else:
+ print(format_report(stats))
+
+
+if __name__ == "__main__":
+ main()