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.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
feat: add vault-health skill — health scoring, MOC generation, link repair
smixsbc5608f20c2f
diff --git a/vault/.claude/skills/vault-health/SKILL.md b/vault/.claude/skills/vault-health/SKILL.mdnew file mode 100644index 0000000..d1da7f9--- /dev/null+++ b/vault/.claude/skills/vault-health/SKILL.md@@ -0,0 +1,249 @@+---+type: note+description: "Vault health monitoring, MOC generation, link repair, and system evolution. Use this skill when checking vault quality metrics, regenerating MOC indexes, fixing broken links, finding backlinks, or triggering weekly system reflections. Also use it when the user mentions health score, link density, orphans, dead-ends, or description coverage."+name: vault-health+depends_on: [graph-builder]+---++# Vault Health++Monitoring and improving knowledge graph health. Built on patterns from [arscontexta](https://github.com/agenticnotetaking/arscontexta) — derivation engine for Claude Code.++## Origin++Skill based on arscontexta analysis (Heinrich's derivation engine, 249 research claims).++Key adopted patterns:+- **Health scoring** — composite metric for quantitative vault assessment+- **Explicit wikilinks in MOC** — instead of dataview (invisible to agents)+- **Operational learning loop** — observations → patterns → improvements+- **Typed relationships** — links with context phrases, not bare `related:[]`+- **Description as retrieval filter** — progressive disclosure for agents++---++## Quick Start++```bash+# Full diagnostics (health score, orphans, broken links, dead-ends)+uv run vault/.claude/skills/graph-builder/scripts/analyze.py++# Regenerate MOC with explicit wikilinks+uv run vault/.claude/skills/vault-health/scripts/generate_moc.py++# Find who links to a file+bash vault/.claude/skills/vault-health/scripts/backlinks.sh "business/crm/acme-corp"++# Find and fix broken links (dry run)+uv run vault/.claude/skills/vault-health/scripts/fix_links.py++# Apply fixes+uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply+```++---++## Health Score++Composite metric in analyze.py. Formula:++```+health_score = 100+ - (orphan_ratio × 30) # orphans = knowledge loss+ - (broken_ratio × 30) # broken links = fragmentation+ - max(0, (3 - avg_links) × 15) # target: 3+ links/file+ - ((1 - desc_ratio) × 10) # description coverage+```++### Metrics and targets++| Metric | Target | How to improve |+|--------|--------|----------------|+| Health Score | >80 | All other metrics |+| Avg links/file | >3.0 | generate_moc.py, typed relationships |+| Broken links | <50 | fix_links.py, manual review |+| Orphans | <30 | graph-builder orphan resolution |+| Dead-ends | <100 | Add backlinks to CRM |+| Desc coverage | >50% | Add description to frontmatter |++### Trend tracking++History stored in `.graph/health-history.json` (up to 90 entries). Each analyze.py run adds a data point.++```bash+# View trend+cat vault/.graph/health-history.json | python3 -c "+import json, sys+data = json.load(sys.stdin)+for d in data[-10:]:+ print(f\"{d['date']}: {d['health_score']}/100 | links: {d['total_links']} | broken: {d['broken_links']}\")+"+```++---++## MOC Generation++`generate_moc.py` creates Maps of Content with **explicit wikilinks and context phrases** (arscontexta pattern). Dataview queries preserved at end of files.++### What it generates++**MOC-business.md:**+- Active Deals (with deadline and deal value)+- High Priority clients+- Grouping by industry (FMCG, Banks, Retail, ...)+- Within industry: Active first, then Prospect++**MOC-projects.md:**+- Hot/Active leads+- Clients+- Projects, Resources++### Wikilink format++```markdown+- [[business/crm/acme-corp\|Acme Corp]] — Active, p1, Project $XXK, deadline YYYY-MM-DD+```++Each link contains: status, priority, deal info, region, deadline — agent sees context without opening file.++### When to run++- After adding new CRM files+- After updating status/deal_status in CRM+- Recommended: weekly or when changes in `business/crm/` / `projects/`++---++## Link Repair++### fix_links.py++Finds broken links and suggests fixes via fuzzy stem matching.++**Strategies:**+1. **Trailing backslash** — Obsidian table escaping artifact (`\|`)+2. **Wrong prefix** — `crm/company` → `business/crm/company`+3. **Stem match** — `old-name` → finds `new-name.md` by stem match++**Exclusions:** backup directories, attachment embeds, directory links.++```bash+# Dry run — shows suggestions+uv run vault/.claude/skills/vault-health/scripts/fix_links.py++# Apply+uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply+```++### backlinks.sh++Find files linking TO specified file (incoming links).++```bash+# Who links to Acme Corp?+bash vault/.claude/skills/vault-health/scripts/backlinks.sh "business/crm/acme-corp"++# Who links to MEMORY.md?+bash vault/.claude/skills/vault-health/scripts/backlinks.sh "MEMORY"+```++### Dead-end detection++Dead-end = file with outgoing links but no incoming (knows about others, but nobody knows about it). Detected by analyze.py, output in report.md.++---++## Weekly Reflection++Operational learning loop: observations → patterns → proposals.++### Trigger++- Every Sunday+- When observations in `.session/handoff.md` reach ≥10++### Process++1. Read `.session/handoff.md` → collect `## Observations`+2. Read `.graph/health-history.json` → week's trend+3. Group observations by type (friction/pattern/idea)+4. Find recurring patterns (>2 occurrences)+5. Propose concrete improvements (file + change)+6. Write reflection file+7. Clear processed observations from handoff.md++### Output++```+thoughts/reflections/YYYY-WNN-system-reflection.md+```++Detailed template: `.claude/rules/weekly-reflection.md`++### Observation format++In `.session/handoff.md`, section `## Observations`:++```markdown+- [friction] 2026-02-19: mcp-cli timeout 3x — retry saved, -60 sec+- [pattern] 2026-02-19: 65 "broken links" were attachment embeds+- [idea] 2026-02-19: generate_moc.py in process.sh chain+```++Types: `friction` (something broke/slow), `pattern` (recurring), `idea` (improvement).++---++## Typed Relationships++When adding links between files, use context phrases (arscontexta pattern):++| Type | When | Example |+|------|------|---------|+| **extends** | Develops an idea | `[[note]] — extends: deepens analysis` |+| **context** | Background info | `[[note]] — context: meeting where discussed` |+| **supports** | Supports a goal | `[[goal]] — supports: annual target` |+| **contradicts** | Contradicts | `[[note]] — contradicts: different approach` |+| **enables** | Makes possible | `[[tool]] — enables: workflow` |+| **requires** | Dependency | `[[resource]] — requires: API key` |++---++## Description Guidelines++Description = retrieval filter, NOT summary. Adds information BEYOND title.++```yaml+# WRONG (repeats title):+# title: "Acme Corp"+description: "Company Acme Corp"++# RIGHT (adds retrieval info):+# title: "Acme Corp"+description: "Key client in [industry], active deal $XXK, [project] in progress"+```++Target: ~150 chars. Scope, mechanism, implication — not retelling.++---++## Automation in process.sh++analyze.py runs **automatically** every day through `scripts/process.sh`:+- If daily is empty → graph-only rebuild+- After full processing → final rebuild++generate_moc.py, fix_links.py, backlinks.sh — manual run as needed.++---++## References++- `references/arscontexta-patterns.md` — patterns from arscontexta, adapted for agent-second-brain+- `.claude/rules/weekly-reflection.md` — template for weekly reflections++## Relevant Skills++- [[vault/.claude/skills/graph-builder/SKILL|graph-builder]] — core graph analysis (analyze.py)+- [[vault/.claude/skills/dbrain-processor/SKILL|dbrain-processor]] — daily processing pipelinediff --git a/vault/.claude/skills/vault-health/references/arscontexta-patterns.md b/vault/.claude/skills/vault-health/references/arscontexta-patterns.mdnew file mode 100644index 0000000..789a5e4--- /dev/null+++ b/vault/.claude/skills/vault-health/references/arscontexta-patterns.md@@ -0,0 +1,105 @@+---+type: note+title: Arscontexta Patterns for dbrain+last_accessed: 2026-02-19+relevance: 0.91+tier: active+---+# Arscontexta Patterns for dbrain++Паттерны из [arscontexta](https://github.com/agenticnotetaking/arscontexta), адаптированные для dbrain vault.++## Source++arscontexta — derivation engine для Claude Code (Heinrich). 249 research claims из cognitive science, network theory, Zettelkasten, agent architecture. Каждое архитектурное решение трейсится к конкретному claim.++## Adopted Patterns++### 1. Health Scoring (quantitative vault assessment)++**Claim:** Системы без метрик деградируют незаметно.++**Реализация:** `analyze.py` → `health_score` → `health-history.json`++Формула: 100 - orphan_penalty(30) - broken_penalty(30) - density_penalty(15) - desc_penalty(10)++### 2. Phase Isolation (fresh context per phase)++**Claim:** `[[LLM attention degrades as context fills]]`++**Реализация:** 3-phase pipeline в process.sh:+- CAPTURE: classify entries → JSON (minimal context)+- EXECUTE: create tasks, save thoughts → JSON (MCP tools)+- REFLECT: generate report, update MEMORY (read-only)++JSON handoff между фазами. Fallback на монолит при ошибке.++### 3. Operational Learning Loop (observations → improvements)++**Claim:** `[[operational-learning-loop]]` (INVARIANT primitive в arscontexta)++**Реализация:**+- `handoff.md` → `## Observations` (friction/pattern/idea)+- dbrain-processor Step 11: автоматический capture+- Weekly reflection: анализ observations → proposals++### 4. Description as Retrieval Filter++**Claim:** `[[descriptions are retrieval filters not summaries]]`++**Реализация:** `description: string` в frontmatter schema. Adds scope/mechanism beyond title. ~150 chars.++### 5. Prose-as-Title (claims, not labels)++**Claim:** `[[note titles should function as APIs enabling sentence transclusion]]`++**Реализация:** Для thoughts/ (не CRM): title = specific claim.+Test: `Since [[title]], ...` reads naturally.++### 6. Explicit Wikilinks in MOC++**Claim:** MOC должен быть видим для agents и graph analysis, не только для Obsidian renderer.++**Реализация:** `generate_moc.py` — 286 explicit wikilinks с context phrases.+Dataview сохранён для Obsidian UX.++### 7. Typed Relationships++**Claim:** `related:[]` без контекста = бесполезно. Нужен тип связи.++**Реализация:** 6 типов: extends, context, supports, contradicts, enables, requires.++### 8. Orient Phase (OODA loop)++**Claim:** Не тратить ресурсы на обработку пустого.++**Реализация:** Pre-flight checks в process.sh: daily exists, size > 50 bytes, handoff exists, graph freshness.++## Consciously NOT Adopted++| Pattern | Why not |+|---------|---------|+| Three-space restructure (self/notes/ops) | dbrain already has functional equivalent |+| Full 6Rs pipeline | 6 Claude calls too expensive for automated daily pipeline |+| PostToolUse hooks (schema validation) | analyze.py on rebuild sufficient for 655 files |+| Per-claim task queue (ops/queue/) | Todoist is our task manager |+| Semantic search (qmd MCP) | Hub navigation + rg sufficient at current scale |+| Personality layer | Not needed for automated processor |+| Derivation manifest | System grown organically, not derived |++## 8 Architectural Dimensions++arscontexta projects each system onto 8 axes. dbrain position:++| Axis | dbrain | Notes |+|------|--------|-------|+| Granularity | Mixed | CRM=entity (coarse), thoughts=atomic |+| Organization | Hierarchical | 3 domains with _index.md hubs |+| Linking | Explicit | Wikilinks |+| Processing | Medium | 3 phases (not 6Rs) |+| Navigation | Medium | MOC + _index hubs |+| Maintenance | Automated | systemd timer |+| Schema | Dense | 3 typed schemas (CRM, Learning, Aimasters) |+| Automation | Convention + script | No hooks, process.sh + analyze.py |++Key constraint: Atomic granularity REQUIRES explicit linking + deep navigation. Our mixed approach (CRM coarse + thoughts atomic) = conscious trade-off, compensated by hub navigation.diff --git a/vault/.claude/skills/vault-health/scripts/add_descriptions.py b/vault/.claude/skills/vault-health/scripts/add_descriptions.pynew file mode 100644index 0000000..8d61fde--- /dev/null+++ b/vault/.claude/skills/vault-health/scripts/add_descriptions.py@@ -0,0 +1,318 @@+#!/usr/bin/env python3+"""+Add description field to frontmatter of vault files.++Strategy by file type:+- CRM files: "{title} — {type}, {industry}, {status}, {deal_status}"+- Thoughts: first non-empty paragraph after frontmatter, truncated to 150 chars+- MOC: "Map of Content: {topic}, N entries"+- Goals: from first paragraph+- Summaries: "Weekly summary for {week}"+- Other: first paragraph, truncated to 150 chars++Skips:+- daily/ files (don't need descriptions per convention)+- Files that already have description field++Usage:+ uv run vault/.claude/skills/vault-health/scripts/add_descriptions.py # dry-run+ uv run vault/.claude/skills/vault-health/scripts/add_descriptions.py --apply # apply+"""++import json+import re+import sys+from pathlib import Path++SCRIPT_DIR = Path(__file__).parent+VAULT_PATH = SCRIPT_DIR.parents[3]+GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"++IGNORE_DIRS = {".obsidian", "attachments", ".git", ".graph", ".claude", ".trash"}+IGNORE_PATTERNS = {"backup", ".backup", "archive"}+++def load_graph():+ if not GRAPH_PATH.exists():+ print("Error: vault-graph.json not found. Run analyze.py first.")+ sys.exit(1)+ return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))+++def parse_frontmatter(content: str) -> dict[str, str]:+ """Extract YAML frontmatter as simple key-value pairs."""+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if not match:+ return {}+ fm = {}+ for line in match.group(1).split("\n"):+ if ":" in line and not line.strip().startswith("-") and not line.strip().startswith("#"):+ key, _, value = line.partition(":")+ key = key.strip()+ value = value.strip().strip('"').strip("'")+ if key and value and not value.startswith("[") and not value.startswith("{"):+ fm[key] = value+ return fm+++def get_body_after_frontmatter(content: str) -> str:+ """Get content after frontmatter."""+ match = re.match(r"^---\n.*?\n---\n?", content, re.DOTALL)+ if match:+ return content[match.end():]+ return content+++def extract_first_paragraph(body: str) -> str:+ """Extract first non-empty, non-heading paragraph from body."""+ lines = body.split("\n")+ paragraph_lines = []+ in_paragraph = False++ for line in lines:+ stripped = line.strip()++ # Skip empty lines before paragraph starts+ if not stripped and not in_paragraph:+ continue++ # Skip headings, callouts, code blocks, links-only lines+ if stripped.startswith(("#", ">", "```", "---", "| ", "- [[", "![")):+ if in_paragraph:+ break+ continue++ if stripped:+ in_paragraph = True+ paragraph_lines.append(stripped)+ elif in_paragraph:+ break++ text = " ".join(paragraph_lines)+ # Remove wikilinks: [[path|text]] → text, [[path]] → path+ text = re.sub(r"\[\[([^\]|]+)\|([^\]]+)\]\]", r"\2", text)+ text = re.sub(r"\[\[([^\]]+)\]\]", r"\1", text)+ # Remove markdown formatting+ text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)+ text = re.sub(r"\*([^*]+)\*", r"\1", text)+ text = re.sub(r"`([^`]+)`", r"\1", text)+ return text.strip()+++def truncate(text: str, max_len: int = 150) -> str:+ """Truncate text to max_len on word boundary."""+ if len(text) <= max_len:+ return text+ truncated = text[:max_len]+ # Find last space+ last_space = truncated.rfind(" ")+ if last_space > max_len // 2:+ truncated = truncated[:last_space]+ return truncated.rstrip(".,;: ") + "..."+++def generate_description(rel_path: str, content: str, fm: dict) -> str | None:+ """Generate a description for a file based on its type and content."""++ # CRM files (business/crm/, projects/crm/)+ if any(rel_path.startswith(p) for p in ("business/crm/", "projects/crm/")):+ # Extract title from H1 or filename+ title_match = re.search(r"^# (.+)$", content, re.MULTILINE)+ title = title_match.group(1).strip() if title_match else Path(rel_path).stem.replace("-", " ").title()++ parts = []+ if fm.get("type"):+ parts.append(fm["type"])+ if fm.get("industry"):+ parts.append(fm["industry"])+ if fm.get("status"):+ parts.append(fm["status"])+ if fm.get("deal_status"):+ parts.append(fm["deal_status"])+ if fm.get("region"):+ parts.append(fm["region"])++ if parts:+ return truncate(f"{title} — {', '.join(parts)}")+ return truncate(f"{title} — CRM record")++ # Projects files+ if rel_path.startswith("projects/"):+ title_match = re.search(r"^# (.+)$", content, re.MULTILINE)+ title = title_match.group(1).strip() if title_match else Path(rel_path).stem.replace("-", " ").title()++ parts = []+ if fm.get("type"):+ parts.append(fm["type"])+ if fm.get("industry"):+ parts.append(fm["industry"])+ if fm.get("status"):+ parts.append(fm["status"])+ if parts:+ return truncate(f"{title} — {', '.join(parts)}")++ body = get_body_after_frontmatter(content)+ para = extract_first_paragraph(body)+ if para:+ return truncate(para)+ return truncate(f"{title} — Projects")++ # MOC files+ if rel_path.startswith("MOC/"):+ topic = Path(rel_path).stem.removeprefix("MOC-").replace("-", " ").title()+ link_count = content.count("[[")+ return f"Map of Content: {topic}, {link_count} entries"++ # Thoughts+ if rel_path.startswith("thoughts/"):+ body = get_body_after_frontmatter(content)+ para = extract_first_paragraph(body)+ if para:+ return truncate(para)+ # Fallback: use filename+ stem = Path(rel_path).stem+ # Remove date prefix if present+ stem = re.sub(r"^\d{4}-\d{2}-\d{2}-", "", stem)+ return stem.replace("-", " ").capitalize()++ # Goals+ if rel_path.startswith("goals/"):+ body = get_body_after_frontmatter(content)+ para = extract_first_paragraph(body)+ if para:+ return truncate(para)+ return f"Goal: {Path(rel_path).stem.replace('-', ' ')}"++ # Summaries+ if rel_path.startswith("summaries/"):+ stem = Path(rel_path).stem+ week_match = re.search(r"(\d{4}-W\d{2})", stem)+ if week_match:+ return f"Weekly summary for {week_match.group(1)}"+ return f"Summary: {stem.replace('-', ' ')}"++ # Contacts+ if rel_path.startswith("contacts/"):+ body = get_body_after_frontmatter(content)+ para = extract_first_paragraph(body)+ if para:+ return truncate(para)+ return f"Contacts: {Path(rel_path).stem.replace('-', ' ')}"++ # _index files+ if Path(rel_path).stem == "_index":+ parent = Path(rel_path).parent.name+ return f"Index and entry point for {parent}"++ # MEMORY.md+ if Path(rel_path).name == "MEMORY.md":+ return "Long-term memory and key decisions"++ # Default: first paragraph+ body = get_body_after_frontmatter(content)+ para = extract_first_paragraph(body)+ if para:+ return truncate(para)++ return None+++def add_description_to_frontmatter(content: str, description: str) -> str:+ """Add description field to frontmatter."""+ # Escape quotes in description+ safe_desc = description.replace('"', '\\"')++ if content.startswith("---\n"):+ match = re.match(r"^(---\n)(.*?)(\n---)", content, re.DOTALL)+ if match:+ before = match.group(1)+ fm_body = match.group(2)+ after = match.group(3)+ rest = content[match.end():]+ return f'{before}description: "{safe_desc}"\n{fm_body}{after}{rest}'+ else:+ # Create minimal frontmatter+ return f'---\ndescription: "{safe_desc}"\n---\n{content}'++ return content+++def main():+ apply = "--apply" in sys.argv++ graph = load_graph()+ nodes = graph.get("nodes", {})++ # Get all non-daily files+ all_files = [+ f for f in VAULT_PATH.rglob("*.md")+ if not any(d in f.parts for d in IGNORE_DIRS)+ and not any(p in str(f) for p in IGNORE_PATTERNS)+ ]++ print(f"Total markdown files: {len(all_files)}")+ print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")+ print()++ added = 0+ skipped_daily = 0+ already_has = 0+ no_description = 0+ errors = 0++ for file_path in sorted(all_files):+ rel_path = str(file_path.relative_to(VAULT_PATH))++ # Skip daily files+ if rel_path.startswith("daily/"):+ skipped_daily += 1+ continue++ try:+ content = file_path.read_text(encoding="utf-8")+ except Exception:+ errors += 1+ continue++ # Check if already has description+ fm = parse_frontmatter(content)+ if fm.get("description"):+ already_has += 1+ continue++ # Also check raw frontmatter for description: field+ fm_match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if fm_match and "description:" in fm_match.group(1):+ already_has += 1+ continue++ description = generate_description(rel_path, content, fm)+ if not description:+ no_description += 1+ if "--verbose" in sys.argv:+ print(f" NO DESC: {rel_path}")+ continue++ print(f" {rel_path}: \"{description[:80]}{'...' if len(description) > 80 else ''}\"")+ added += 1++ if apply:+ new_content = add_description_to_frontmatter(content, description)+ file_path.write_text(new_content, encoding="utf-8")++ non_daily = len(all_files) - skipped_daily+ coverage = (already_has + added) / max(non_daily, 1) * 100++ print(f"\n{'='*50}")+ print(f"Non-daily files: {non_daily}")+ print(f"Already had description: {already_has}")+ print(f"Descriptions added: {added}")+ print(f"Could not generate: {no_description}")+ print(f"Errors: {errors}")+ print(f"Projected coverage: {coverage:.1f}%")+ if apply:+ print(f"Files modified: {added}")+++if __name__ == "__main__":+ main()diff --git a/vault/.claude/skills/vault-health/scripts/backlinks.sh b/vault/.claude/skills/vault-health/scripts/backlinks.shnew file mode 100755index 0000000..ce02961--- /dev/null+++ b/vault/.claude/skills/vault-health/scripts/backlinks.sh@@ -0,0 +1,20 @@+#!/bin/bash+# Find all files that link to a given target+# Usage: bash backlinks.sh "business/crm/acme-corp"+# bash backlinks.sh "thoughts/ideas/sample-idea"++set -e++VAULT_DIR="$(cd "$(dirname "$0")/../../.." && pwd)"+TARGET="${1%.md}"++if [ -z "$TARGET" ]; then+ echo "Usage: backlinks.sh <note-path>"+ echo "Example: backlinks.sh business/crm/acme-corp"+ exit 1+fi++# Search for wikilinks to target (with or without .md, with or without alias)+rg -l "\[\[$TARGET" "$VAULT_DIR" --glob '*.md' 2>/dev/null | \+ sed "s|$VAULT_DIR/||" | \+ sortdiff --git a/vault/.claude/skills/vault-health/scripts/connect_orphans.py b/vault/.claude/skills/vault-health/scripts/connect_orphans.pynew file mode 100644index 0000000..4ccddda--- /dev/null+++ b/vault/.claude/skills/vault-health/scripts/connect_orphans.py@@ -0,0 +1,169 @@+#!/usr/bin/env python3+"""+Connect orphan and weakly-connected files by adding related links to hub files.++Strategy:+- business/crm/* → related: ["[[business/_index]]"]+- projects/crm/* → related: ["[[projects/_index]]"]+- daily/* (old) → skip (expected orphans)+- templates/* → skip+- projects/* → related: ["[[projects/_index]]"]+- business/* → related: ["[[business/_index]]"]+- thoughts/* → related: ["[[MEMORY]]"]+- Other → related: ["[[MEMORY]]"]++Also processes weakly_connected files (total_links < 2) with same logic.++Usage:+ uv run vault/.claude/skills/vault-health/scripts/connect_orphans.py # dry-run+ uv run vault/.claude/skills/vault-health/scripts/connect_orphans.py --apply # apply+"""++import json+import re+import sys+from pathlib import Path++SCRIPT_DIR = Path(__file__).parent+VAULT_PATH = SCRIPT_DIR.parents[3]+GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"++# Hub mapping by path prefix+HUB_MAP = [+ ("business/crm/", '[[business/_index]]'),+ ("projects/crm/", '[[projects/_index]]'),+ ("business/network/", '[[business/_index]]'),+ ("business/events/", '[[business/_index]]'),+ ("business/", '[[business/_index]]'),+ ("projects/clients/", '[[projects/_index]]'),+ ("projects/leads/", '[[projects/_index]]'),+ ("projects/", '[[projects/_index]]'),+ ("thoughts/", '[[MEMORY]]'),+ ("goals/", '[[MEMORY]]'),+ ("contacts/", '[[MEMORY]]'),+ ("MOC/", '[[MEMORY]]'),+ ("summaries/", '[[MEMORY]]'),+ (".session/", '[[MEMORY]]'),+]++SKIP_PREFIXES = ("daily/", "templates/", ".claude/", ".graph/")+++def load_graph():+ if not GRAPH_PATH.exists():+ print("Error: vault-graph.json not found. Run analyze.py first.")+ sys.exit(1)+ return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))+++def get_hub_for_path(rel_path: str) -> str | None:+ """Determine the hub link for a given file path."""+ if any(rel_path.startswith(p) for p in SKIP_PREFIXES):+ return None+ for prefix, hub in HUB_MAP:+ if rel_path.startswith(prefix):+ return hub+ return '[[MEMORY]]'+++def has_frontmatter(content: str) -> bool:+ """Check if content has YAML frontmatter."""+ return content.startswith("---\n")+++def has_related_field(content: str) -> bool:+ """Check if frontmatter already has a related field."""+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if match:+ return "related:" in match.group(1)+ return False+++def has_description_field(content: str) -> bool:+ """Check if frontmatter already has a description field."""+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if match:+ return "description:" in match.group(1)+ return False+++def add_related_to_frontmatter(content: str, hub_link: str) -> str:+ """Add related field to existing frontmatter or create new frontmatter."""+ if has_related_field(content):+ return content # Already has related++ if has_frontmatter(content):+ # Insert related before closing ---+ match = re.match(r"^(---\n)(.*?)(\n---)", content, re.DOTALL)+ if match:+ before = match.group(1)+ fm_body = match.group(2)+ after = match.group(3)+ rest = content[match.end():]+ return f"{before}{fm_body}\nrelated:\n - \"{hub_link}\"{after}{rest}"+ else:+ # Create minimal frontmatter+ return f"---\nrelated:\n - \"{hub_link}\"\n---\n{content}"++ return content+++def main():+ apply = "--apply" in sys.argv++ graph = load_graph()+ orphans = graph.get("orphans", [])+ weakly_connected = graph.get("weakly_connected", [])++ # Combine: orphans + weakly_connected for maximum link density improvement+ targets = set(orphans + weakly_connected)++ print(f"Orphans: {len(orphans)}")+ print(f"Weakly connected: {len(weakly_connected)}")+ print(f"Total targets: {len(targets)}")+ print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")+ print()++ connected = 0+ skipped = 0+ already_has = 0+ errors = 0++ for rel_path in sorted(targets):+ hub_link = get_hub_for_path(rel_path)+ if hub_link is None:+ skipped += 1+ continue++ file_path = VAULT_PATH / rel_path+ if not file_path.exists():+ errors += 1+ print(f" MISSING: {rel_path}")+ continue++ content = file_path.read_text(encoding="utf-8")++ if has_related_field(content):+ already_has += 1+ continue++ new_content = add_related_to_frontmatter(content, hub_link)++ if new_content != content:+ tag = "ORPHAN" if rel_path in orphans else "WEAK"+ print(f" [{tag}] {rel_path} → {hub_link}")+ connected += 1+ if apply:+ file_path.write_text(new_content, encoding="utf-8")++ print(f"\n{'='*50}")+ print(f"Connected: {connected}")+ print(f"Skipped (daily/template/internal): {skipped}")+ print(f"Already has related: {already_has}")+ print(f"Missing files: {errors}")+ if apply:+ print(f"Files modified: {connected}")+++if __name__ == "__main__":+ main()diff --git a/vault/.claude/skills/vault-health/scripts/fix_links.py b/vault/.claude/skills/vault-health/scripts/fix_links.pynew file mode 100644index 0000000..90a092e--- /dev/null+++ b/vault/.claude/skills/vault-health/scripts/fix_links.py@@ -0,0 +1,393 @@+#!/usr/bin/env python3+"""+Fix broken wiki-links in vault using pattern matching and heuristics.++Patterns handled:+1. Trailing backslash: [[business/crm/acme-corp]] with trailing backslash → clean+2. Wrong prefix: [[crm/projects/X]] → [[projects/clients/X]] or [[projects/leads/X]]+3. Stem match: [[acme-corp]] → [[business/crm/acme-corp]] (when unique match exists)+4. CRM sub-project → parent: [[business/crm/client-a-smm]] → [[business/crm/client-a]]+5. business/projects/ → parent CRM: [[business/projects/brand-x-campaign-2026]] → [[business/crm/brand-x]]+6. Plaintext company names (self-refs): [[Acme]] inside acme.md → remove wikilink+7. Goals aliases: [[3-weekly-2026-W05]] → remove+8. Internal paths (.claude/, vault/, scripts/): [[.claude/CLAUDE]] → `code ref`+9. Stub/concept links: [[craftsmanship]], [[ai-philosophy]] → plain text+10. Misc: attachments, meals.md, etc. → remove wikilink++Usage:+ uv run vault/.claude/skills/vault-health/scripts/fix_links.py # dry-run+ uv run vault/.claude/skills/vault-health/scripts/fix_links.py --apply # apply fixes+"""++import json+import re+import sys+from pathlib import Path+from collections import defaultdict++SCRIPT_DIR = Path(__file__).parent+VAULT_PATH = SCRIPT_DIR.parents[3]+GRAPH_PATH = VAULT_PATH / ".graph" / "vault-graph.json"++IGNORE_DIRS = {".obsidian", "attachments", ".git", ".graph", ".claude", ".trash"}+EXCLUDE_PATTERNS = {"backup", ".backup", "business.backup"}++# Pattern A: CRM sub-project → parent CRM file+CRM_PARENT_MAP = {+ "client-a-smm": "client-a",+ "brand-x-meals-ncp": "brand-x",+ "brand-x-smm-region": "brand-x",+ "client-b-smm": "client-b",+ "client-c-wh": "client-c",+ "client-d-smm": "client-d",+ "client-e-influencers": "client-e",+ "techco-region": "techco",+ "brand-x-sub-smm": "brand-x",+ "brand-x-snacks-2026": "brand-x",+ "techco-eats-city": None, # no parent — remove link+ "techco-eats-tc": None, # no parent — remove link+ "brand-y": "brand-y-campaign",+}++# Pattern B: business/projects/ → parent CRM+PROJECT_CLIENT_MAP = {+ "brand-x-meals-ncp-2026": "brand-x",+ "client-a-smm-strategy-2026": "client-a",+ "client-a-smm": "client-a",+ "client-c-wellness": "client-c",+ "client-f-budget-2026": "client-f",+ "automaker-a-strategy-2026": "automaker-a",+ "client-d-smm-tender": "client-d",+ "automaker-b-bot-smm": "automaker-b",+ "client-b-baby-2026": "client-b",+ "brand-x-snacks-2026": "brand-x",+ "fmcg-co-region-rfi": "fmcg-co",+ "automaker-c-smm-tender": "automaker-c",+ "tobacco-co-hr-brand": "tobacco-co",+ "retailer-a-comstrat": "retailer-a",+}++# Pattern F: Stub/concept links that won't become files → remove wikilink+STUB_LINKS = {+ "craftsmanship", "ai-philosophy", "quality", "second-brain", "telegram-bot",+ "note", "title", "frontend-design", "accessibility", "vault-processor",+ "wikilinks", "sample-stub-link",+}++# Direct replacements for known mismatches+DIRECT_REPLACE_MAP = {+ "business/network/partner-alias": "business/network/partner-full-name",+ "thoughts/ideas/sample-algorithm": "thoughts/ideas/2026-02-05-sample-agent-algorithm",+}++# Pattern F extended: Long sentence-links from external sources+SENTENCE_LINK_PREFIXES = [+ "LLM attention degrades",+ "fresh context per task",+ "note titles should function",+ "Agent Memory System",+ "AI agents need layered memory",+]+++def load_graph():+ """Load vault-graph.json."""+ if not GRAPH_PATH.exists():+ print("Error: vault-graph.json not found. Run analyze.py first.")+ sys.exit(1)+ return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))+++def build_stem_index():+ """Build index: stem → [full_paths]."""+ index = defaultdict(list)+ md_files = [+ f for f in VAULT_PATH.rglob("*.md")+ if not any(d in f.parts for d in IGNORE_DIRS)+ and not any(p in str(f) for p in EXCLUDE_PATTERNS)+ ]+ for f in md_files:+ rel = str(f.relative_to(VAULT_PATH))+ stem = f.stem+ index[stem].append(rel)+ # Also index by path without .md+ index[rel.removesuffix(".md")].append(rel)+ return index+++def find_crm_file(client_name: str) -> str | None:+ """Find CRM file for a client name in business/crm/."""+ for prefix in ["business/crm/"]:+ candidate = VAULT_PATH / f"{prefix}{client_name}.md"+ if candidate.exists():+ return f"{prefix}{client_name}"+ return None+++def suggest_fix(broken_from: str, broken_to: str, stem_index: dict) -> tuple[str | None, str]:+ """Suggest a fix for a broken link target.++ Returns (suggestion, action) where action is:+ - 'replace': replace the wikilink target+ - 'remove': remove the wikilink, keep display text+ - 'none': no fix found+ """+ target = broken_to++ # Direct replacement map (known mismatches)+ if target in DIRECT_REPLACE_MAP:+ replacement = DIRECT_REPLACE_MAP[target]+ # Verify the target file exists+ if (VAULT_PATH / f"{replacement}.md").exists():+ return replacement, "replace"++ # Pattern 1: Trailing backslash+ if target.endswith("\\"):+ clean = target.rstrip("\\")+ if clean in stem_index:+ return clean, "replace"+ if clean + ".md" in stem_index:+ return clean, "replace"+ stem = Path(clean).stem+ if stem in stem_index and len(stem_index[stem]) == 1:+ return stem_index[stem][0].removesuffix(".md"), "replace"++ # Pattern 2: Wrong prefix (crm/projects/X → projects/clients/X or projects/leads/X)+ if target.startswith("crm/projects/"):+ name = target.removeprefix("crm/projects/").rstrip("\\")+ for prefix in ["projects/clients/", "projects/leads/"]:+ candidate = prefix + name+ if candidate in stem_index or candidate + ".md" in stem_index:+ return candidate, "replace"++ # Pattern A: CRM sub-project → parent+ for crm_prefix in ["business/crm/"]:+ if target.startswith(crm_prefix):+ sub_name = target.removeprefix(crm_prefix)+ if sub_name in CRM_PARENT_MAP:+ parent = CRM_PARENT_MAP[sub_name]+ if parent is None:+ return None, "remove"+ parent_path = find_crm_file(parent)+ if parent_path:+ return parent_path, "replace"++ # Pattern B: business/projects/ → parent CRM+ if target.startswith("business/projects/"):+ project_name = target.removeprefix("business/projects/")+ if project_name in PROJECT_CLIENT_MAP:+ client = PROJECT_CLIENT_MAP[project_name]+ parent_path = find_crm_file(client)+ if parent_path:+ return parent_path, "replace"++ # Pattern C: Plaintext company names (self-references inside CRM files)+ # e.g. business/crm/acme-corp.md has [[Acme Corp]] — remove the wikilink+ if not "/" in target and target[0:1].isupper() and broken_from.startswith(("business/crm/", "projects/crm/")):+ return None, "remove"++ # Pattern D: Goals aliases (3-weekly-2026-W05 etc.)+ if re.match(r"3-weekly-2026-W\d+", target):+ return None, "remove"++ # Pattern E: Internal paths (.claude/, vault/, scripts/, ~/)+ if any(target.startswith(p) for p in [".claude/", "vault/", "scripts/", "../", "~/"]):+ return None, "remove"++ # Pattern F: Stub/concept links+ if target in STUB_LINKS:+ return None, "remove"++ # Pattern F extended: Sentence-links from external sources+ for prefix in SENTENCE_LINK_PREFIXES:+ if target.startswith(prefix):+ return None, "remove"++ # Pattern G: Known unmatchable files → remove+ known_removable = {+ "contacts/partner-org.json", "meals.md", "brand-x-tasks-handoff.md",+ "thoughts/reflections/2026-01-03-data-backup",+ "2026-01-05-project-ssr-migration",+ }+ if target in known_removable:+ return None, "remove"++ # Attachments → remove wikilink (they're embeds, not graph nodes)+ if target.startswith("attachments/"):+ return None, "remove"++ # thoughts/ references that don't exist → check if stem exists+ if target.startswith("thoughts/"):+ stem = Path(target).stem+ if stem in stem_index and len(stem_index[stem]) == 1:+ return stem_index[stem][0].removesuffix(".md"), "replace"++ # Pattern 3: Stem-only match (e.g. "acme-corp" → "business/crm/acme-corp")+ stem = Path(target.rstrip("\\")).stem+ if stem in stem_index:+ matches = stem_index[stem]+ if len(matches) == 1:+ return matches[0].removesuffix(".md"), "replace"++ # Projects paths that might resolve differently+ if target.startswith("projects/"):+ stem = Path(target).stem+ if stem in stem_index and len(stem_index[stem]) == 1:+ return stem_index[stem][0].removesuffix(".md"), "replace"++ # business/network/ that doesn't exist+ if target.startswith("business/network/"):+ stem = Path(target).stem+ if stem in stem_index and len(stem_index[stem]) == 1:+ return stem_index[stem][0].removesuffix(".md"), "replace"++ # Final fallback: if the link has a path (contains /) and target doesn't exist → remove+ # This catches remaining broken paths like projects/leads/contact-name, etc.+ if "/" in target:+ target_path = VAULT_PATH / f"{target}.md"+ if not target_path.exists():+ return None, "remove"++ return None, "none"+++def apply_replace(file_path: Path, old_link: str, new_link: str) -> bool:+ """Replace broken link target in file."""+ content = file_path.read_text(encoding="utf-8")++ # Match [[old_link]], [[old_link|alias]], [[old_link#section]], [[old_link\|alias]] (table-escaped)+ escaped = re.escape(old_link)+ pattern = rf"\[\[{escaped}(\\?[|\]#])"+ replacement = f"[[{new_link}\\1"++ new_content = re.sub(pattern, replacement, content)++ if new_content != content:+ file_path.write_text(new_content, encoding="utf-8")+ return True+ return False+++def apply_remove(file_path: Path, old_link: str) -> bool:+ """Remove wikilink, keeping display text or link target as plain text."""+ content = file_path.read_text(encoding="utf-8")++ escaped = re.escape(old_link)++ # [[old_link|Display Text]] → Display Text+ pattern_with_alias = rf"\[\[{escaped}\|([^\]]+)\]\]"+ new_content = re.sub(pattern_with_alias, r"\1", content)++ if new_content != content:+ file_path.write_text(new_content, encoding="utf-8")+ return True++ # [[old_link]] → old_link (just the text)+ # For paths, use just the stem; for names, use as-is+ if "/" in old_link:+ display = Path(old_link).stem.replace("-", " ").title()+ else:+ display = old_link++ pattern_plain = rf"\[\[{escaped}\]\]"+ new_content = re.sub(pattern_plain, display, content)++ if new_content != content:+ file_path.write_text(new_content, encoding="utf-8")+ return True++ return False+++def main():+ apply = "--apply" in sys.argv++ graph = load_graph()+ broken_links = graph.get("broken_links", [])+ stem_index = build_stem_index()++ print(f"Broken links: {len(broken_links)}")+ print(f"Mode: {'APPLY' if apply else 'DRY-RUN'}")+ print()++ # Group by source file+ by_source = defaultdict(list)+ for bl in broken_links:+ by_source[bl["from"]].append(bl["to"])++ replacements = []+ removals = []+ unfixable = []++ for source, targets in sorted(by_source.items()):+ for target in targets:+ suggestion, action = suggest_fix(source, target, stem_index)+ if action == "replace" and suggestion:+ replacements.append((source, target, suggestion))+ elif action == "remove":+ removals.append((source, target))+ else:+ unfixable.append((source, target))++ # Deduplicate+ seen = set()+ unique_replacements = []+ for src, old, new in replacements:+ key = (src, old, new)+ if key not in seen:+ seen.add(key)+ unique_replacements.append((src, old, new))+ replacements = unique_replacements++ seen_removals = set()+ unique_removals = []+ for src, old in removals:+ key = (src, old)+ if key not in seen_removals:+ seen_removals.add(key)+ unique_removals.append((src, old))+ removals = unique_removals++ print(f"Replacements: {len(replacements)}")+ print(f"Removals: {len(removals)}")+ print(f"Unfixable: {len(unfixable)}")+ print()++ if replacements:+ print("=== REPLACEMENTS ===")+ applied = 0+ for src, old, new in replacements:+ print(f" {src}: [[{old}]] → [[{new}]]")+ if apply:+ src_path = VAULT_PATH / src+ if src_path.exists() and apply_replace(src_path, old, new):+ applied += 1+ if apply:+ print(f"\nApplied: {applied}/{len(replacements)} replacements")++ if removals:+ print("\n=== REMOVALS (wikilink → plain text) ===")+ removed = 0+ for src, old in removals:+ print(f" {src}: [[{old}]] → plain text")+ if apply:+ src_path = VAULT_PATH / src+ if src_path.exists() and apply_remove(src_path, old):+ removed += 1+ if apply:+ print(f"\nRemoved: {removed}/{len(removals)} wikilinks")++ if unfixable:+ print("\n=== UNFIXABLE (manual review needed) ===")+ for src, target in unfixable:+ print(f" {src} → {target}")++ # Summary+ total_fixed = len(replacements) + len(removals)+ print(f"\n{'='*50}")+ print(f"Total fixable: {total_fixed}/{len(broken_links)}")+ print(f"Unfixable: {len(unfixable)}")+++if __name__ == "__main__":+ main()diff --git a/vault/.claude/skills/vault-health/scripts/generate_moc.py b/vault/.claude/skills/vault-health/scripts/generate_moc.pynew file mode 100644index 0000000..af9d1cc--- /dev/null+++ b/vault/.claude/skills/vault-health/scripts/generate_moc.py@@ -0,0 +1,534 @@+#!/usr/bin/env python3+"""+Generate explicit-wikilinks MOC files for Business and Projects.++Reads CRM/client/lead files, extracts frontmatter, groups by industry,+and generates MOC markdown with explicit wikilinks:+ - [[business/crm/acme-corp|Acme Corp]] — Active, High priority, POST-LAUNCH deal++Output:+ - vault/MOC/MOC-business.md — Business CRM Map of Content+ - vault/MOC/MOC-projects.md — Projects Map of Content++Usage:+ uv run vault/.claude/skills/graph-builder/scripts/generate_moc.py+"""++import re+from pathlib import Path+from collections import defaultdict+from datetime import datetime++# Paths+SCRIPT_DIR = Path(__file__).parent+VAULT_PATH = SCRIPT_DIR.parents[3] # vault/.claude/skills/graph-builder/scripts -> vault+MOC_DIR = VAULT_PATH / "MOC"+BUSINESS_CRM_DIR = VAULT_PATH / "business" / "crm"+PROJECTS_DIR = VAULT_PATH / "projects"+++def parse_frontmatter(content: str) -> dict[str, str]:+ """Extract YAML frontmatter as simple key-value pairs."""+ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if not match:+ return {}+ fm = {}+ for line in match.group(1).split("\n"):+ if ":" in line and not line.strip().startswith("-") and not line.strip().startswith("#"):+ key, _, value = line.partition(":")+ key = key.strip()+ value = value.strip().strip('"').strip("'")+ if key and value and not value.startswith("[") and not value.startswith("{"):+ fm[key] = value+ return fm+++def extract_title(content: str) -> str | None:+ """Extract first H1 heading from markdown content."""+ match = re.search(r"^# (.+)$", content, re.MULTILINE)+ if match:+ return match.group(1).strip()+ return None+++def build_context_phrase(fm: dict[str, str]) -> str:+ """Build a context phrase from frontmatter fields.++ Pattern: status, priority, deal_status, region+ Example: "Active, High priority, POST-LAUNCH deal"+ """+ parts = []++ status = fm.get("status", "")+ if status:+ parts.append(status)++ priority = fm.get("priority", "")+ if priority:+ parts.append(f"{priority} priority")++ deal_status = fm.get("deal_status", "")+ if deal_status:+ parts.append(f"{deal_status} deal")++ region = fm.get("region", "")+ if region:+ parts.append(region)++ return ", ".join(parts)+++def relative_path(file_path: Path) -> str:+ """Get vault-relative path without .md extension."""+ rel = file_path.relative_to(VAULT_PATH)+ return str(rel).removesuffix(".md")+++def generate_business_moc() -> str:+ """Generate MOC-business.md content with explicit wikilinks grouped by industry."""++ # Collect all CRM files+ records: list[dict] = []+ for md_file in sorted(BUSINESS_CRM_DIR.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)++ records.append({+ "path": rel,+ "title": title,+ "industry": fm.get("industry", "Unknown"),+ "status": fm.get("status", ""),+ "priority": fm.get("priority", ""),+ "deal_status": fm.get("deal_status", ""),+ "region": fm.get("region", ""),+ "updated": fm.get("updated", ""),+ "fm": fm,+ })++ # Group by industry+ by_industry: dict[str, list[dict]] = defaultdict(list)+ for rec in records:+ by_industry[rec["industry"]].append(rec)++ # Sort industries by count (descending), then alphabetically+ sorted_industries = sorted(+ by_industry.keys(),+ key=lambda ind: (-len(by_industry[ind]), ind),+ )++ # Count active deals and high priority+ active_deals = [r for r in records if r["deal_status"] and r["deal_status"] not in ("StandBy", "Отказано")]+ high_priority = [r for r in records if r["priority"] == "High"]++ now = datetime.now().strftime("%Y-%m-%d")++ lines = [+ "# MOC - Business",+ "",+ "> Map of Content for Business CRM data",+ f"> Generated: {now} | {len(records)} records, {len(active_deals)} active deals, {len(high_priority)} high priority",+ "",+ "[[business/_index|Business Data Overview]]",+ "",+ "---",+ "",+ ]++ # Active Deals section (explicit wikilinks)+ if active_deals:+ lines.append(f"## Active Deals ({len(active_deals)})")+ lines.append("")+ # Sort by deal_deadline if available, then by title+ for rec in sorted(active_deals, key=lambda r: (r.get("fm", {}).get("deal_deadline", "9999"), r["title"])):+ ctx = build_context_phrase(rec["fm"])+ deadline = rec["fm"].get("deal_deadline", "")+ deadline_str = f", deadline {deadline}" if deadline else ""+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}{deadline_str}")+ lines.append("")+ lines.append("---")+ lines.append("")++ # High Priority section (explicit wikilinks)+ if high_priority:+ lines.append(f"## High Priority ({len(high_priority)})")+ lines.append("")+ for rec in sorted(high_priority, key=lambda r: (r["industry"], r["title"])):+ ctx = build_context_phrase(rec["fm"])+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")+ lines.append("")+ lines.append("---")+ lines.append("")++ # By Industry sections+ lines.append("## By Industry")+ lines.append("")++ for industry in sorted_industries:+ industry_records = by_industry[industry]+ lines.append(f"### {industry} ({len(industry_records)})")+ lines.append("")++ # Sort: active/in-work first, then by title+ def sort_key(r: dict) -> tuple:+ status_order = 0+ s = r["status"].lower()+ if s in ("active", "в работе"):+ status_order = 0+ elif "tender" in s or "negotiation" in s:+ status_order = 1+ elif s == "prospect":+ status_order = 2+ else:+ status_order = 3+ return (status_order, r["title"])++ for rec in sorted(industry_records, key=sort_key):+ ctx = build_context_phrase(rec["fm"])+ if ctx:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Dataview blocks (preserved at the end)+ lines.extend([+ "---",+ "",+ "## Dataview: Active Deals",+ "",+ "```dataview",+ 'TABLE deal_status as "Status", deal_deadline as "Deadline", industry',+ 'FROM "business/crm"',+ 'WHERE deal_status != null AND deal_status != "StandBy" AND deal_status != "Отказано"',+ "SORT deal_deadline ASC",+ "LIMIT 15",+ "```",+ "",+ "## Dataview: High Priority",+ "",+ "```dataview",+ "TABLE industry, status, deal_status",+ 'FROM "business/crm"',+ 'WHERE priority = "High"',+ "SORT deal_status DESC",+ "LIMIT 20",+ "```",+ "",+ "## Dataview: By Industry",+ "",+ "```dataview",+ "TABLE WITHOUT ID",+ ' industry as "Industry",',+ ' length(rows) as "Count"',+ 'FROM "business/crm"',+ "GROUP BY industry",+ "SORT length(rows) DESC",+ "```",+ "",+ "## Dataview: By Status",+ "",+ "```dataview",+ "TABLE WITHOUT ID",+ ' status as "Status",',+ ' length(rows) as "Count"',+ 'FROM "business/crm"',+ "GROUP BY status",+ "SORT length(rows) DESC",+ "```",+ "",+ "## Dataview: Recently Updated",+ "",+ "```dataview",+ "TABLE industry, status, priority",+ 'FROM "business/crm"',+ "SORT file.mtime DESC",+ "LIMIT 20",+ "```",+ "",+ ])++ return "\n".join(lines)+++def generate_projects_moc() -> str:+ """Generate MOC-projects.md with explicit wikilinks."""++ now = datetime.now().strftime("%Y-%m-%d")++ # Collect clients+ clients: list[dict] = []+ clients_dir = PROJECTS_DIR / "clients"+ if clients_dir.exists():+ for md_file in sorted(clients_dir.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ clients.append({+ "path": rel,+ "title": title,+ "industry": fm.get("industry", "Unknown"),+ "status": fm.get("status", ""),+ "region": fm.get("region", ""),+ "company": fm.get("company", title),+ "fm": fm,+ })++ # Collect leads+ leads: list[dict] = []+ leads_dir = PROJECTS_DIR / "leads"+ if leads_dir.exists():+ for md_file in sorted(leads_dir.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ leads.append({+ "path": rel,+ "title": title,+ "industry": fm.get("industry", "Unknown"),+ "status": fm.get("status", ""),+ "company": fm.get("company", title),+ "potential": fm.get("potential", ""),+ "region": fm.get("region", ""),+ "fm": fm,+ })++ # Collect projects+ projects: list[dict] = []+ projects_dir = PROJECTS_DIR / "projects"+ if projects_dir.exists():+ for md_file in sorted(projects_dir.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ projects.append({+ "path": rel,+ "title": title,+ "status": fm.get("status", ""),+ "fm": fm,+ })++ # Collect standalone files (resources, reports, etc.)+ standalone: list[dict] = []+ for md_file in sorted(PROJECTS_DIR.glob("*.md")):+ if md_file.name == "_index.md":+ continue+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ standalone.append({+ "path": rel,+ "title": title,+ "fm": fm,+ })++ # Collect events+ events: list[dict] = []+ events_dir = PROJECTS_DIR / "events"+ if events_dir.exists():+ for md_file in sorted(events_dir.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ events.append({+ "path": rel,+ "title": title,+ "status": fm.get("status", ""),+ "fm": fm,+ })++ # Collect reports+ reports: list[dict] = []+ reports_dir = PROJECTS_DIR / "reports"+ if reports_dir.exists():+ for md_file in sorted(reports_dir.glob("*.md")):+ content = md_file.read_text(encoding="utf-8")+ fm = parse_frontmatter(content)+ title = extract_title(content) or md_file.stem.replace("-", " ").title()+ rel = relative_path(md_file)+ reports.append({+ "path": rel,+ "title": title,+ "fm": fm,+ })++ total = len(clients) + len(leads) + len(projects) + len(standalone) + len(events) + len(reports)++ lines = [+ "# MOC - Projects",+ "",+ "> Map of Content for Projects",+ f"> Generated: {now} | {len(clients)} clients, {len(leads)} leads, {len(projects)} projects",+ "",+ "[[projects/_index|Projects Overview]]",+ "",+ "---",+ "",+ ]++ # Clients+ if clients:+ lines.append(f"## Clients ({len(clients)})")+ lines.append("")+ for rec in sorted(clients, key=lambda r: r["title"]):+ parts = []+ if rec["status"]:+ parts.append(rec["status"])+ if rec["industry"] and rec["industry"] != "Unknown":+ parts.append(rec["industry"])+ if rec["region"]:+ parts.append(rec["region"])+ ctx = ", ".join(parts)+ if ctx:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Leads+ if leads:+ # Split into hot/active and others+ hot_leads = [l for l in leads if l["status"].lower() in ("hot", "qualified", "follow-up sent", "proposal sent")]+ other_leads = [l for l in leads if l not in hot_leads]++ lines.append(f"## Leads ({len(leads)})")+ lines.append("")++ if hot_leads:+ lines.append("### Hot / Active")+ lines.append("")+ for rec in sorted(hot_leads, key=lambda r: r["title"]):+ parts = []+ if rec["status"]:+ parts.append(rec["status"])+ if rec["company"] and rec["company"] != rec["title"]:+ parts.append(rec["company"])+ if rec["potential"]:+ parts.append(rec["potential"])+ if rec["region"]:+ parts.append(rec["region"])+ ctx = ", ".join(parts)+ if ctx:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ if other_leads:+ lines.append("### Other Leads")+ lines.append("")+ for rec in sorted(other_leads, key=lambda r: r["title"]):+ parts = []+ if rec["status"]:+ parts.append(rec["status"])+ if rec["company"] and rec["company"] != rec["title"]:+ parts.append(rec["company"])+ if rec["potential"]:+ parts.append(rec["potential"])+ if rec["region"]:+ parts.append(rec["region"])+ ctx = ", ".join(parts)+ if ctx:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {ctx}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Projects+ if projects:+ lines.append(f"## Projects ({len(projects)})")+ lines.append("")+ for rec in sorted(projects, key=lambda r: r["title"]):+ status = rec["status"]+ if status:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {status}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Events+ if events:+ lines.append(f"## Events ({len(events)})")+ lines.append("")+ for rec in sorted(events, key=lambda r: r["path"]):+ status = rec["status"]+ if status:+ lines.append(f"- [[{rec['path']}|{rec['title']}]] — {status}")+ else:+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Reports+ if reports:+ lines.append(f"## Reports ({len(reports)})")+ lines.append("")+ for rec in sorted(reports, key=lambda r: r["path"]):+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Standalone files+ if standalone:+ lines.append(f"## Resources ({len(standalone)})")+ lines.append("")+ for rec in sorted(standalone, key=lambda r: r["title"]):+ lines.append(f"- [[{rec['path']}|{rec['title']}]]")+ lines.append("")++ # Dataview blocks (preserved)+ lines.extend([+ "---",+ "",+ "## Dataview: Leads",+ "",+ "```dataview",+ "TABLE company, industry, status, responsible",+ 'FROM "projects/leads"',+ "SORT updated DESC",+ "```",+ "",+ "## Dataview: Clients",+ "",+ "```dataview",+ "TABLE company, industry, status",+ 'FROM "projects/clients"',+ "SORT updated DESC",+ "```",+ "",+ ])++ return "\n".join(lines)+++def main():+ """Generate both MOC files."""+ MOC_DIR.mkdir(exist_ok=True)++ # Generate Business MOC+ biz_content = generate_business_moc()+ biz_path = MOC_DIR / "MOC-business.md"+ biz_path.write_text(biz_content, encoding="utf-8")+ print(f"Generated: {biz_path.relative_to(VAULT_PATH)}")++ # Generate Projects MOC+ proj_content = generate_projects_moc()+ proj_path = MOC_DIR / "MOC-projects.md"+ proj_path.write_text(proj_content, encoding="utf-8")+ print(f"Generated: {proj_path.relative_to(VAULT_PATH)}")++ # Stats+ biz_links = biz_content.count("[[")+ proj_links = proj_content.count("[[")+ print(f"\nStats:")+ print(f" Business: {biz_links} wikilinks")+ print(f" Projects: {proj_links} wikilinks")+ print(f" Total: {biz_links + proj_links} explicit wikilinks")+++if __name__ == "__main__":+ main()