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!: autograph replaces agent-memory/graph-builder/vault-health in the pipeline
smixsd069a36e2212
diff --git a/README.md b/README.mdindex ef23f3e..58184f5 100644--- a/README.md+++ b/README.md@@ -76,7 +76,7 @@ The archive tier is the interesting one. Occasionally, the agent pulls a randomOver time, note systems rot. Links break. Files become orphans. Tags diverge. You end up with a graveyard of markdown files that nobody, including you, can navigate.-The vault-health system runs automatically:+The vault health engine (autograph) runs automatically:- Scores your vault on a 100-point scale- Finds orphan notes (no links in or out) and suggests connections@@ -197,23 +197,20 @@ vault/## Skills-The agent has four built-in skills:+The agent has two built-in skills:| Skill | What it does ||-------|-------------|| **dbrain-processor** | Classifies entries, saves notes |-| **agent-memory** | Ebbinghaus decay engine - remembers, forgets, recalls |-| **vault-health** | Scores vault health, fixes links, generates MOCs |-| **graph-builder** | Maps relationships between notes, finds clusters |+| **autograph** | Typed vault engine: Ebbinghaus decay, graph health, MOCs, schema-as-code, dedup |-Want just the memory engine? See [agent-memory-skill](https://github.com/smixs/agent-memory-skill) - works standalone, no dependencies.+Want just the memory engine? See [autograph](https://github.com/smixs/autograph) - works standalone on any Obsidian vault, no dependencies.## Configuration| File | What it controls ||------|-----------------|| `.env` | API tokens (copy from `.env.example`) |-| `.memory-config.json` | How fast memories decay, tier boundaries || `vault/.claude/CLAUDE.md` | Agent personality and rules |All secrets stay in `.env`, which is gitignored. Don't commit tokens.diff --git a/README.ru.md b/README.ru.mdindex 1438190..fa0260e 100644--- a/README.ru.md+++ b/README.ru.md@@ -200,18 +200,15 @@ vault/| Навык | Что делает ||-------|-----------|| **dbrain-processor** | Классифицирует записи, создаёт задачи, сохраняет заметки |-| **agent-memory** | Движок памяти Эббингауза - помнит, забывает, вспоминает |-| **vault-health** | Оценка здоровья, починка ссылок, генерация MOC |-| **graph-builder** | Карта связей между заметками, поиск кластеров |+| **autograph** | Типизированный движок хранилища: память Эббингауза, здоровье графа, MOC, schema-as-code, дедуп |-Нужен только движок памяти? Смотри [agent-memory-skill](https://github.com/smixs/agent-memory-skill) - работает отдельно, без зависимостей.+Нужен только движок памяти? Смотри [autograph](https://github.com/smixs/autograph) - работает на любом Obsidian-хранилище, без зависимостей.## Конфигурация| Файл | За что отвечает ||------|----------------|| `.env` | API-токены (скопируй из `.env.example`) |-| `.memory-config.json` | Скорость угасания памяти, границы уровней || `mcp-config.json` | Подключения к внешним инструментам || `vault/.claude/CLAUDE.md` | Личность и правила агента |diff --git a/deploy/brain-system.md b/deploy/brain-system.mdindex 2c4f797..24512cc 100644--- a/deploy/brain-system.md+++ b/deploy/brain-system.md@@ -39,7 +39,7 @@ emit the closing `<<<E:ID>>>` marker:- Append a short entry to `vault/.session/handoff.md`: what was done, keydecisions, and the next step.- Update `vault/MEMORY.md` only on a genuinely new decision, preference, or- fact via the agent-memory card format.+ fact via the autograph card format.## Bootstrap (on a fresh session)diff --git a/scripts/process.sh b/scripts/process.shindex b2a22f6..9b7b48a 100755--- a/scripts/process.sh+++ b/scripts/process.sh@@ -47,7 +47,7 @@ if [ "$DAILY_SIZE" -lt 50 ]; then# Still rebuild graph and commitcd "$VAULT_DIR"- uv run .claude/skills/graph-builder/scripts/analyze.py || echo "Graph rebuild failed (non-critical)"+ uv run .claude/skills/autograph/scripts/graph.py health . || echo "Graph rebuild failed (non-critical)"cd "$PROJECT_DIR"git add -A@@ -93,11 +93,11 @@ REPORT_CLEAN=$(echo "$REPORT" | sed '/<!--/,/-->/d')# Rebuild vault graph (keeps structure up to date)echo "=== Rebuilding vault graph ==="cd "$VAULT_DIR"-uv run .claude/skills/graph-builder/scripts/analyze.py || echo "Graph rebuild failed (non-critical)"+uv run .claude/skills/autograph/scripts/graph.py health . || echo "Graph rebuild failed (non-critical)"# Memory decay (update relevance scores and tiers)echo "=== Memory decay ==="-uv run .claude/skills/agent-memory/scripts/memory-engine.py decay . || echo "Memory decay failed (non-critical)"+uv run .claude/skills/autograph/scripts/engine.py decay . || echo "Memory decay failed (non-critical)"cd "$PROJECT_DIR"# Git commitdiff --git a/vault/.claude/CLAUDE.md b/vault/.claude/CLAUDE.mdindex 849c7a6..b0ef51e 100644--- a/vault/.claude/CLAUDE.md+++ b/vault/.claude/CLAUDE.md@@ -7,11 +7,10 @@ Voice-first personal assistant for capturing thoughts and managing tasks via Tel**Before doing anything else, read these files in order:**1. `vault/MEMORY.md` — curated long-term memory (preferences, decisions, context)-2. `vault/.memory-config.json` — memory decay configuration-3. `vault/daily/YYYY-MM-DD.md` — today's entries-4. `vault/daily/YYYY-MM-DD.md` — yesterday's entries (for continuity)-5. `vault/goals/3-weekly.md` — this week's ONE Big Thing-6. `vault/.session/handoff.md` — previous session context (if exists)+2. `vault/daily/YYYY-MM-DD.md` — today's entries+3. `vault/daily/YYYY-MM-DD.md` — yesterday's entries (for continuity)+4. `vault/goals/3-weekly.md` — this week's ONE Big Thing+5. `vault/.session/handoff.md` — previous session context (if exists)**Don't ask permission, just do it.** This ensures context continuity across sessions.@@ -120,11 +119,11 @@ Run daily processing via `/process` command or automatically at 21:00.Each phase = fresh Claude context for better quality.-## Card Template (agent-memory)+## Card Template (autograph)-**Skill:** `.claude/skills/agent-memory/SKILL.md`+**Skill:** `.claude/skills/autograph/SKILL.md`-All new vault cards follow the agent-memory template:+All new vault cards follow the autograph template:```yaml---@@ -149,37 +148,28 @@ tier: active- `tags` — REQUIRED. 2-5 tags, lowercase, hyphen-separated- `status` ≠ `tier`: status = business status, tier = memory (automatic)- One fact = one place (DRY). References via [[wikilinks]]-- Decay engine: `uv run .claude/skills/agent-memory/scripts/memory-engine.py decay .`+- Decay engine: `uv run .claude/skills/autograph/scripts/engine.py decay .`## Skills & References| Skill | Purpose ||-------|---------|| `dbrain-processor` | Main daily processing (3-phase pipeline) |-| `graph-builder` | Vault link analysis and building |-| `vault-health` | Health scoring, MOC generation, link repair |-| `agent-memory` | Card template, decay engine, tiered search |+| `autograph` | Typed vault engine: schema enforcement, graph health, decay, MOC, dedup |- **Processing:** `.claude/skills/dbrain-processor/SKILL.md`-- **Graph Builder:** `.claude/skills/graph-builder/SKILL.md`-- **Vault Health:** `.claude/skills/vault-health/SKILL.md`-- **Agent Memory:** `.claude/skills/agent-memory/SKILL.md`+- **Autograph:** `.claude/skills/autograph/SKILL.md`- **Rules:** `.claude/rules/` (daily, thoughts, goals, obsidian-markdown, weekly-reflection)- **Docs:** `.claude/docs/`-## Graph Builder+## Vault Graph (autograph)**Purpose:** Analysis and maintenance of vault link structure.-**Architecture:**-1. `scripts/analyze.py` — deterministic vault traversal-2. `scripts/add_links.py` — batch link addition-3. Agent — semantic links for orphan files-**Usage:**```bash# Analyze vault-uv run vault/.claude/skills/graph-builder/scripts/analyze.py+uv run vault/.claude/skills/autograph/scripts/graph.py health vault# Resultvault/.graph/vault-graph.json # JSON graph with stats@@ -197,8 +187,6 @@ vault/.graph/report.md # Human-readable report| Agent | Purpose ||-------|---------|-| `weekly-digest` | Weekly review with goal progress |-| `goal-aligner` | Check task-goal alignment || `note-organizer` | Organize vault, fix links || `inbox-processor` | GTD-style inbox processing |@@ -224,9 +212,6 @@ Reports use Telegram HTML:| Command | Action ||---------|--------|| `/process` | Run daily processing |-| `/do` | Execute arbitrary request |-| `/weekly` | Generate weekly digest |-| `/align` | Check goal alignment || `/organize` | Organize vault || `/graph` | Analyze vault links |diff --git a/vault/.claude/skills/agent-memory/SKILL.md b/vault/.claude/skills/agent-memory/SKILL.mddeleted file mode 100644index 9fc2973..0000000--- a/vault/.claude/skills/agent-memory/SKILL.md+++ /dev/null@@ -1,206 +0,0 @@-----type: note-description: >--last_accessed: 2026-02-26-relevance: 1.0-tier: active-name: agent-memory-Use when: (1) setting up memory for a new agent, (2) diagnosing memory bloat or context-Triggers: "memory management", "organize vault", "memory decay", "forgetting curve",------# Agent Memory Management--Memory system with automatic decay, tiered search, and creative recall.-Works with any directory of markdown files.--## Quick Start--### 1. Scan existing files-```bash-python3 scripts/memory-engine.py scan <directory>-```-Reports: file count, YAML coverage, size, recommendations.--### 2. Bootstrap YAML frontmatter-```bash-python3 scripts/memory-engine.py init <directory> [--dry-run]-```-Adds `relevance`, `last_accessed`, `tier` to files missing frontmatter.-Infers `type` from directory path. Infers dates from YAML fields, git log, or file mtime.--### 3. Run decay-```bash-python3 scripts/memory-engine.py decay <directory> [--dry-run]-```-Updates all cards: recalculates relevance scores and reassigns tiers.-Schedule daily via cron for automatic forgetting.--### 4. Touch on read-```bash-python3 scripts/memory-engine.py touch <filepath>-```-Resets card to active (relevance=1.0). Call this when reading a card to answer a question.--### 5. Creative recall-```bash-python3 scripts/memory-engine.py creative <N> <directory>-```-Random sample from cold/archive tiers. Read these cards and look for unexpected connections.--### 6. Health check-```bash-python3 scripts/memory-engine.py stats <directory>-```-Shows tier distribution, context budget, stale card count.--## Core Concepts--### Three-Layer Architecture--| Layer | What | Size Target | Loaded |-|-------|------|-------------|--------|-| Hot context | State file (volatile focus, blockers) | <4KB | Every turn |-| Searchable vault | Cards with YAML, one per entity | Unlimited | On demand |-| Archive | Old logs, completed work | Unlimited | Deep/creative only |--**Rule:** Each fact lives in ONE place. If it's in a card, don't also put it in the state file.-See [references/architecture.md](references/architecture.md) for full design rationale.--### Forgetting Curve--Cards have `relevance: 0.0-1.0` that decays linearly over time:-- Day 0: 1.0 (just accessed)-- Day 7: 0.90 → tier: active-- Day 21: 0.69 → tier: warm-- Day 33: 0.50 → tier: cold-- Day 60+: 0.10 (floor) → tier: archive--`core` tier is manual-only — for identity, security, pricing. Never auto-demoted.--### Tier-Aware Search--| Mode | Tiers searched | When |-|------|---------------|------|-| heartbeat | core + active | Quick checks, monitoring |-| normal | active + warm | Most questions |-| deep | all tiers | Strategy, OSINT, complex analysis |-| creative | random cold+archive | Brainstorming, ideation |--See [references/search-protocols.md](references/search-protocols.md) for detailed protocols.--### YAML Frontmatter--Minimum required fields (managed by engine):-```yaml-----relevance: 0.85-last_accessed: 2026-02-25-tier: active-----```--See [references/yaml-schema.md](references/yaml-schema.md) for full schema with domain-specific fields.--## Daily Files (Episodic Memory)--Daily files (`memory/YYYY-MM-DD.md`) are the agent's episodic memory — what happened each day.-They follow the same decay system as vault cards. **Never delete them.**--### Lifecycle--```-Day 0: Created (end of day cron or manual) → tier: active, relevance: 1.0-Day 1-7: Auto-loaded at session start (today+yesterday) → tier: active-Day 8-21: Searchable but not auto-loaded → tier: warm-Day 22-60: Deep search only → tier: cold-Day 60+: Creative mode or explicit recall → tier: archive-```--### YAML Frontmatter for Daily Files--Add to each daily file (engine handles this via `init` or `decay`):-```yaml-----type: daily-date: 2026-02-18-relevance: 0.76-last_accessed: 2026-02-18-tier: warm-----```--### Session Loading Protocol--At session start, load only active-tier daily files:-```-1. Read today's daily file (if exists)-2. Read yesterday's daily file (if exists)-3. Stop. Don't load older files.-```--For questions about the past ("what happened last week?"), search warm/cold tier dailies on demand.--### Why Never Delete--1. **Disk cost ≈ zero.** 30 daily files ≈ 300KB. Irrelevant savings.-2. **Context is lost forever.** A knowledge graph captures entities but not reasoning, tone, or "why."-3. **Semantic search works on old files.** A query about "Red Bull tender" finds the relevant daily file regardless of age.-4. **Creative mode surfaces old context.** Forgotten daily entries become unexpected inspiration.-5. **Re-reading from source (Telegram, email) is expensive.** 100+ messages per day × API calls × LLM summarization > keeping a 10KB file.--### Compression (Optional)--If daily files grow large (>20KB), compress old ones instead of deleting:-1. Extract key decisions, contacts, and outcomes into vault cards-2. Trim the daily file to a 20-line summary-3. Keep the summary with its YAML frontmatter intact--This preserves searchability while reducing storage. But even without compression, a year of daily files is ~4MB — negligible.--## Configuration--Generate default config:-```bash-python3 scripts/memory-engine.py config <directory>-```--Creates `.memory-config.json`:-```json-{- "tiers": {"active": 7, "warm": 21, "cold": 60},- "decay_rate": 0.015,- "relevance_floor": 0.1,- "skip_patterns": ["_index.md"],- "type_inference": {"crm/": "crm", "leads/": "lead"},- "use_git_dates": true-}-```--Adjust tier thresholds and decay rate to match your domain's natural rhythm.-Fast-moving domains (sales): tighter thresholds (active=3, warm=10, cold=30).-Slow domains (research): wider thresholds (active=14, warm=45, cold=120).--## Cron Integration--Add decay to daily maintenance (OpenClaw example):-```json-{- "name": "memory-decay",- "schedule": {"kind": "cron", "expr": "0 22 * * *", "tz": "UTC"},- "payload": {"kind": "agentTurn", "message": "Run: python3 scripts/memory-engine.py decay vault/crm/"}-}-```--## Anti-Patterns--| Don't | Do Instead |-|-------|------------|-| Load all contacts into state file | Keep them in vault cards, search on demand |-| Create "knowledge graph" that duplicates vault | Vault IS the graph. Use index files for navigation |-| Store same fact in 3 files | One card per entity, reference via links |-| Delete old daily files to "save space" | Keep all dailies, let tier decay handle visibility |-| Auto-load all daily files at session start | Load only today + yesterday; search older on demand |-| Search all 500 cards for every question | Check index first, filter by tier, then search |-| Touch every card during bulk operations | Only touch on meaningful read/update |-| Build elaborate review systems | Let decay handle it — if you don't use it, it fades |diff --git a/vault/.claude/skills/agent-memory/references/architecture.md b/vault/.claude/skills/agent-memory/references/architecture.mddeleted file mode 100644index c5125ab..0000000--- a/vault/.claude/skills/agent-memory/references/architecture.md+++ /dev/null@@ -1,198 +0,0 @@-----type: note-title: Memory Architecture-last_accessed: 2026-02-26-relevance: 1.0-tier: active-----# Memory Architecture--## The Problem--AI agents forget everything between sessions. Common solutions (dump everything into context, vector-search everything) create bloat and noise. Human memory works differently: it has layers, it decays, and it surprises you with random connections.--## Design Principles--### Single Source of Truth (DRY)-Each fact lives in ONE place. If a contact exists in a CRM card, don't also list them in a "key contacts" section of your state file. Instead, reference them: `see vault/crm/alice.md`.--**Violation test:** Search for any person/project name. If it appears in 3+ files with substantive detail, you have a DRY violation.--### Context is a Shared Resource (KISS)-Every byte loaded per turn costs tokens. An agent loading 40KB of context files is burning ~10,000 tokens before the conversation starts. Measure your context budget:-- State file (volatile): target <4KB-- Config files: target <15KB total-- Per-turn overhead = sum of all always-loaded files--### Build Only What You Use (YAGNI)-Don't create "knowledge graphs," "daily digests," or "weekly reviews" unless you actively query them. If a cron job generates a report nobody reads, it's waste.--## Three-Layer Architecture--```-Layer 1: HOT CONTEXT (always loaded, <4KB)- └── State file — volatile: active focus, blockers, reminders- NOT: contacts, history, reference, tools--Layer 2: SEARCHABLE VAULT (on-demand, unlimited)- └── Cards with YAML frontmatter — one file per entity- Searched via: semantic search, grep, graph traversal- Organized by: domain directories + index files (MOC)--Layer 3: ARCHIVE (deep search only)- └── Old daily logs, completed projects, cold contacts- Still searchable but excluded from default queries-```--### Layer 1: Hot Context--This is what's loaded every turn. Must be ruthlessly slim.--**Include:** Current week's focus, active blockers, 3-5 pending items, security rules, navigation hints.--**Exclude:** Contact lists (use vault), tool docs (separate file), event history (daily files), anything searchable.--**Audit:** If your state file exceeds 80 lines, something belongs in Layer 2.--### Layer 2: Searchable Vault--One markdown file per entity (person, project, company, idea). YAML frontmatter enables filtering and automation.--**Directory structure:**-```-vault/-├── crm/ # contacts and companies-│ ├── clients/-│ ├── leads/-│ └── personal/-├── projects/ # active and past projects-├── MOC/ # Maps of Content (index files)-└── .graph/ # computed graph data-```--**Why one file per entity:** Enables granular decay, individual relevance scoring, and precise search results. A single "contacts.md" with 200 entries can't decay — the whole file is either loaded or not.--### Layer 2b: Daily Files (Episodic Memory)--Daily logs (`memory/YYYY-MM-DD.md`) sit between vault and archive. They capture the raw narrative of each day — conversations, decisions, reasoning, context that doesn't fit neatly into entity cards.--**Never delete daily files.** The decay system handles visibility:-- Active (0-7 days): loaded at session start-- Warm (8-21 days): searchable, not auto-loaded-- Cold (22-60 days): deep search only-- Archive (60+): creative mode, explicit queries--**Why keep everything:**-- Disk: 365 daily files ≈ 4MB. Irrelevant cost.-- Context: knowledge graphs capture entities but lose reasoning and tone.-- Search: semantic search finds old dailies just as well as new ones.-- Source rebuild: re-reading 100+ Telegram messages is far more expensive than keeping a 10KB summary.--**Compression:** If a daily file exceeds 20KB, extract key facts into vault cards and trim the daily to a 20-line summary. Keep the YAML frontmatter intact.--### Layer 3: Archive--One-off analysis reports. Completed project retrospectives. Generated artifacts that served a temporary purpose. These are still searchable but excluded from default queries. Daily files are NOT archive — they stay in `memory/` with tier-based visibility.--## Forgetting Curve--Inspired by Ebbinghaus (1885): memory strength decays over time without reinforcement.--### Relevance Score--Each card has `relevance: 0.0-1.0` in its frontmatter. Decays linearly:--```-relevance = max(floor, 1.0 - days_since_access × rate)--Default: rate=0.015, floor=0.1-→ After 7 days: 0.90-→ After 21 days: 0.69-→ After 33 days: 0.50-→ After 60 days: 0.10 (floor)-```--### Tier Assignment--Based on days since `last_accessed`:--| Tier | Days | Description |-|------|------|-------------|-| core | manual | Never auto-assigned. Identity, security, pricing. |-| active | 0-7 | Hot context. Searched in all modes. |-| warm | 8-21 | Default search radius. Gradually fading. |-| cold | 22-60 | Deep search only. Mostly forgotten. |-| archive | 60+ | Creative mode or explicit recall only. |--### Touch Protocol--When an agent reads or references a card, it should reset the card:-```bash-python3 memory-engine.py touch <filepath>-```-This sets `last_accessed` to today, `relevance` to 1.0, and `tier` to active.--**When to touch:**-- Agent reads card content to answer a question-- Agent updates card with new information-- User explicitly mentions the entity--**When NOT to touch:**-- Card appears in search results but isn't opened-- Automated scan (decay script itself)-- Bulk operations--## Search Protocols--Different tasks need different search depths:--### Heartbeat Mode (fast checks)-Search: core + active only.-Use for: quick status checks, routine monitoring, simple questions.-Cost: minimal — only hot cards in scope.--### Normal Mode (default)-Search: core + active + warm.-Use for: most questions, task execution, lookups.-Cost: moderate — includes fading but recent cards.--### Deep Mode (complex tasks)-Search: all tiers.-Use for: strategy, OSINT, complex analysis, "find everything about X."-Cost: high — full vault scan.--### Creative Mode (divergent thinking)-Method: random sample from cold + archive tiers.-Use for: brainstorming, finding unexpected connections, "what if" scenarios.-Not semantic search — deliberately random to surface forgotten associations.--```bash-python3 memory-engine.py creative 5 vault/-```--## Multi-Agent Shared Memory--When multiple agents share a vault:--1. **Shared YAML schema** — all agents use same frontmatter fields-2. **Each agent touches on read** — keeps decay accurate across agents-3. **One vault, one truth** — don't fork the vault per agent-4. **Conflict resolution** — last write wins for metadata; append-only for history sections--## Context Budget Calculator--Measure your actual per-turn cost:--```-Always-loaded files:- STATE.md _____ bytes- CONFIG.md _____ bytes- IDENTITY.md _____ bytes- RULES.md _____ bytes- ─────────────────────────- Total context: _____ bytes ÷ 4 ≈ _____ tokens--Target: <25KB (6,000 tokens) for always-loaded context-```--Every 1KB saved = ~250 tokens freed per turn for actual conversation.diff --git a/vault/.claude/skills/agent-memory/references/search-protocols.md b/vault/.claude/skills/agent-memory/references/search-protocols.mddeleted file mode 100644index 95eef61..0000000--- a/vault/.claude/skills/agent-memory/references/search-protocols.md+++ /dev/null@@ -1,125 +0,0 @@-----type: note-title: Search Protocols-last_accessed: 2026-02-26-relevance: 1.0-tier: active-----# Search Protocols--## Protocol Selection--Before searching, classify the task:--| Signal | Mode | Search Radius |-|--------|------|---------------|-| Quick status check, monitoring | heartbeat | core + active |-| Normal question, lookup | normal | active + warm |-| "Find everything about X" | deep | all tiers |-| Strategy, OSINT, complex analysis | deep | all tiers |-| Brainstorm, "what if", ideation | creative | random from cold+archive |--## Search Order (All Modes)--1. **Index files first** — MOC or `_index.md` files are pre-built navigation. Check them before searching.-2. **Follow links** — If an index points to `[[crm/acme]]`, read the card directly. Don't search for "Acme."-3. **Semantic search** — Only when indexes don't cover the query.-4. **Grep** — Last resort for exact strings, IDs, phone numbers.--## Tier Filtering--### Pre-filter with grep-```bash-# Find all active cards-grep -rl "^tier: active" vault/crm/--# Find all cold+ cards for deep search-grep -rl "^tier: \(cold\|archive\)" vault/crm/--# Find high-relevance cards-grep -l "^relevance: 0\.9" vault/crm/-```--### Combine with semantic search-1. Grep for tier → get file list-2. Read relevant files → answer question--This is cheaper than searching all 400+ cards semantically.--## Heartbeat Protocol--Heartbeats are frequent, automated checks. Minimize cost:--1. Read state file (always loaded)-2. Check only `core` + `active` tier cards matching current projects-3. Skip warm/cold/archive entirely-4. Total reads: 0-5 files per heartbeat--## Normal Protocol--Default for user questions:--1. Check index/MOC for direct link-2. If not found: semantic search with default radius (active + warm)-3. Read top 3-5 results-4. Touch any card you read: `memory-engine.py touch <file>`--## Deep Protocol--For complex, multi-step analysis:--1. Check indexes-2. Semantic search across ALL tiers (no filtering)-3. Read all relevant results (up to 10-15 files)-4. Cross-reference cards for connections-5. Touch all read cards--## Creative Protocol--Deliberately non-directed. Goal: surface unexpected connections.--```bash-python3 memory-engine.py creative 5 vault/-```--1. Get 5 random cards from cold/archive-2. Read each one-3. For each card, ask: "How could this connect to my current task?"-4. If a connection exists → touch the card (promotes it back to active)-5. If no connection → leave it (continues to decay)--### When to use creative mode-- Stuck on a problem-- Looking for new business angles-- User says "brainstorm" or "what if"-- Exploring forgotten knowledge-- Weekly reflection sessions--### What makes it work-Human creativity often comes from random associations — shower thoughts, dreams, serendipitous encounters. Creative mode simulates this by pulling forgotten cards back into working memory. The randomness is the feature, not a bug.--## Touch Discipline--Touching a card resets its decay. Over-touching defeats the purpose.--**Touch when:**-- You read the card's content to answer a question-- You update the card with new information-- User explicitly discusses the entity--**Don't touch when:**-- Card appears in search results but you didn't open it-- Running automated scans or reports-- Bulk migration or formatting changes-- Card mentioned in passing but not substantively used--## Cost Awareness--| Mode | Typical reads | Token cost |-|------|---------------|------------|-| Heartbeat | 0-5 files | ~2K tokens |-| Normal | 3-8 files | ~5K tokens |-| Deep | 10-20 files | ~15K tokens |-| Creative | 5 files | ~3K tokens |--Optimize by reading index files first — they're cheap navigation that prevents expensive full-text searches.diff --git a/vault/.claude/skills/agent-memory/references/yaml-schema.md b/vault/.claude/skills/agent-memory/references/yaml-schema.mddeleted file mode 100644index 0efab89..0000000--- a/vault/.claude/skills/agent-memory/references/yaml-schema.md+++ /dev/null@@ -1,189 +0,0 @@-----type: note-title: YAML Frontmatter Schema-last_accessed: 2026-02-26-relevance: 1.0-tier: active-----# YAML Frontmatter Schema--## Canonical Schema (all card types)--Every card MUST have this structure. Fields marked (auto) are managed by memory-engine.py.-Fields marked (required) must be written by the agent when creating a card.--```yaml-----# ── identity ──-type: crm # (required) crm | lead | contact | project | personal | daily | note-description: >- # (required) One-line summary. What is this card about?- Key client in [industry], active deal $XXK, [project description]--# ── classification ──-tags: [fmcg, active-deal, uz] # (required) 2-5 freeform tags for grep filtering-status: active # (required) universal: active|draft|pending|done|inactive; CRM-only: prospect|negotiation|won|lost-industry: FMCG # (optional) For CRM/leads-region: UZ # (optional) ISO country codes-source: referral # (optional) How this entity entered the system-priority: High # (optional) High | Medium | Low--# ── ownership ──-owner: [Your Name] # (optional) Who owns this relationship-responsible: [Your Name] # (optional) Who is doing the work--# ── dates ──-created: 2026-01-15 # (recommended) When card was first created-updated: 2026-02-20 # (recommended) When content was last meaningfully changed--# ── deal tracking ──-deal_status: negotiation # (optional) For active deals-deal_deadline: 2026-03-15 # (optional) Deal close date--# ── memory system (auto) ──-last_accessed: 2026-02-25 # (auto) When card was last read/touched-relevance: 0.85 # (auto) 0.0-1.0, decays over time-tier: active # (auto) core | active | warm | cold | archive-----```--## Required Fields Explained--### `description` (string, one line)-The single most important field for search quality. Write a concise summary that answers:-"If someone searches for this entity, what should they see in results?"--Good: `"Event Specialist, [Company] [Country], tender 2026"`-Bad: `"контакт"` (too vague)-Bad: (empty — defeats the purpose of the entire system)--### `tags` (list, 2-5 items)-Cross-cutting labels for fast grep filtering. Use lowercase, hyphens.-```yaml-tags: [hot-lead, ai-training, enterprise, follow-up]-```-Search: `grep -rl "hot-lead" vault/crm/`--### `type` (enum)-| Type | When |-|------|------|-| crm | Existing client/company |-| lead | Potential client |-| contact | Person (not a lead/client) |-| project | Active or past project |-| personal | Family, friends |-| daily | Daily log file |-| note | Everything else |--### `status` (enum, normalized)-Domain-specific lifecycle. NOT the same as `tier` (which is memory-system lifecycle).--**Universal (all card types):**--| Status | Meaning |-|--------|---------|-| `active` | Currently relevant, in use, engaged |-| `draft` | Work in progress, not finalized |-| `pending` | Waiting for external input or decision |-| `done` | Completed, kept for reference |-| `inactive` | Was active, went quiet or outdated |--**CRM-specific (only for type: crm, lead, crm-lead, client):**--| Status | Meaning |-|--------|---------|-| `prospect` | Identified lead, no deep engagement yet |-| `negotiation` | Proposal/KP sent, in talks |-| `won` | Deal closed positively |-| `lost` | Rejected, didn't pursue, conflict |--**ONLY these 9 values.** No Russian, no mixed case, no free-text.--Typical lifecycle by type:-- **crm/lead:** prospect → active → negotiation → won/lost-- **project:** draft → active → done-- **contact:** active → inactive-- **note/knowledge:** draft → active → inactive (outdated)-- **personal:** active → inactive-- **daily:** no status needed (has `date` field)--When in doubt: CRM → `prospect`, everything else → `active`.--## Memory System Fields (auto-managed)--### `relevance` (float, 0.0-1.0)-Computed by decay engine. Do not manually edit unless marking as `core`.-- 1.0 = just accessed-- 0.5 = ~33 days old-- 0.1 = floor (60+ days)--### `tier` (enum)-Computed by decay engine based on `last_accessed`.-- `core` — only manually assigned, never auto-demoted. Use for: identity, security rules, pricing.-- `active` — 0-7 days since access. Searched in all modes.-- `warm` — 8-21 days. Searched in normal+ modes.-- `cold` — 22-60 days. Deep search only.-- `archive` — 60+ days. Creative mode or explicit queries.--### `last_accessed` (ISO date)-Updated by `touch` command (graduated: +1 tier per touch).--## Agent Protocol for New Cards--When creating ANY new card:-1. ALWAYS include: `type`, `description`, `tags`, `status`-2. Write `description` as if it's a search result snippet — concise, informative-3. Add 2-5 `tags` that cross-cut directory structure-4. Run `memory-engine.py touch <file>` after creation-5. The engine will auto-add `relevance`, `last_accessed`, `tier` on next decay run--## Field Semantics--### `relevance` (float, 0.0-1.0)-Computed by decay engine. Do not manually edit unless marking as `core`.-- 1.0 = just accessed-- 0.5 = ~33 days old-- 0.1 = floor (60+ days)--### `tier` (enum)-Computed by decay engine based on `last_accessed`.-- `core` — only manually assigned, never auto-demoted. Use for: identity, security rules, pricing, critical reference.-- `active` — 0-7 days since access. Searched in all modes.-- `warm` — 8-21 days. Searched in normal+ modes.-- `cold` — 22-60 days. Deep search only.-- `archive` — 60+ days. Creative mode or explicit queries.--### `last_accessed` (ISO date)-Updated by `touch` command when agent reads the card. Also updated by decay engine on first run (inferred from `updated`, `created`, git log, or file mtime).--### `type` (string)-Auto-inferred from directory path if not present. Configurable via `type_inference` in `.memory-config.json`.--### `tags` (list)-Freeform. Useful for cross-cutting concerns that don't fit directory structure.-```yaml-tags: [hot-lead, ai-training, enterprise, follow-up]-```-Search: `grep -rl "hot-lead" vault/crm/`--## Configuration--Type inference mapping in `.memory-config.json`:-```json-{- "type_inference": {- "crm/clients/": "crm",- "crm/leads/": "lead",- "crm/personal/": "personal",- "projects/": "project"- }-}-```--When `memory-engine.py init` encounters a file without `type`, it checks the file path against these patterns.--## Frontmatter Tips--1. **Don't duplicate content.** If the H1 heading says "# Acme Corp", you don't need `title: Acme Corp` — the engine infers it.-2. **Tags > nested directories.** A flat `crm/` with tags is more flexible than `crm/hot/enterprise/ai/`.-3. **Status is domain-specific.** The memory system uses `tier` for lifecycle; `status` is for your business logic (active/won/lost/churned).-4. **`updated` vs `last_accessed`**: `updated` = when content changed; `last_accessed` = when anyone read it. Both matter for decay; the engine uses whichever is most recent.diff --git a/vault/.claude/skills/agent-memory/scripts/memory-engine.py b/vault/.claude/skills/agent-memory/scripts/memory-engine.pydeleted file mode 100644index 6251022..0000000--- a/vault/.claude/skills/agent-memory/scripts/memory-engine.py+++ /dev/null@@ -1,645 +0,0 @@-#!/usr/bin/env python3-"""-memory-engine.py — Universal memory management for AI agents.--Implements Ebbinghaus-inspired forgetting curve with tiered recall.-Works with any directory of markdown files.--Commands:- scan [dir] Analyze files, report stats (no changes)- init [dir] Add YAML frontmatter to files missing it- decay [dir] Update relevance scores and tiers- touch <file> Reset file to active (on read/use)- creative <N> [dir] Random N cards from cold/archive tiers- stats [dir] Show tier distribution and health metrics--Options:- --config <path> Config JSON (default: .memory-config.json in target dir)- --dry-run Preview changes without writing- --verbose Show per-file details--Config (.memory-config.json):-{- "tiers": {- "active": 7, // days threshold- "warm": 21,- "cold": 60- // beyond cold = archive- },- "decay_rate": 0.015, // relevance loss per day (linear)- "relevance_floor": 0.1, // minimum relevance- "skip_patterns": ["_index.md", "MOC-*"],- "type_inference": {- "crm/": "crm",- "leads/": "lead",- "personal/": "personal"- },- "use_git_dates": true-}-"""--import os-import re-import sys-import json-import random-import subprocess-from datetime import datetime, date-from pathlib import Path-from typing import Optional--# ─── defaults ───────────────────────────────────────────────────--DEFAULT_CONFIG = {- "tiers": {"active": 7, "warm": 21, "cold": 60},- "decay_rate": 0.015,- "relevance_floor": 0.1,- "skip_patterns": ["_index.md"],- "type_inference": {},- "use_git_dates": True,-}--TODAY = date.today()--# ─── YAML frontmatter parsing ──────────────────────────────────--def parse_frontmatter(content: str) -> tuple[dict, str, bool]:- """Parse YAML frontmatter. Returns (fields, body, had_yaml)."""- if content.startswith("---\n"):- end = content.find("\n---\n", 4)- if end != -1:- yaml_block = content[4:end]- body = content[end + 5:]- fields = {}- for line in yaml_block.split("\n"):- if ":" in line:- key, _, val = line.partition(":")- fields[key.strip()] = val.strip()- return fields, body, True- return {}, content, False---def build_frontmatter(fields: dict, field_order: list[str] | None = None) -> str:- """Build YAML frontmatter from dict, preserving field order."""- if field_order is None:- field_order = [- "type", "title", "description", "tags",- "industry", "source", "priority", "status", "region",- "owner", "responsible", "domain", "related", "client",- "deal_status", "deal_deadline", "deadline",- "created", "updated", "last_accessed", "relevance", "tier",- ]- lines = []- used = set()- for key in field_order:- if key in fields:- lines.append(f"{key}: {fields[key]}")- used.add(key)- for key, val in fields.items():- if key not in used:- lines.append(f"{key}: {val}")- return "---\n" + "\n".join(lines) + "\n---\n"---# ─── date resolution ───────────────────────────────────────────--def get_git_date(filepath: Path) -> date | None:- """Last git commit date for file."""- try:- result = subprocess.run(- ["git", "log", "-1", "--format=%aI", "--", str(filepath)],- capture_output=True, text=True,- cwd=filepath.parent, timeout=5,- )- if result.returncode == 0 and result.stdout.strip():- return date.fromisoformat(result.stdout.strip()[:10])- except Exception:- pass- return None---def get_best_date(fields: dict, filepath: Path, use_git: bool = True) -> date:- """Most recent date from YAML fields, git history, or file mtime."""- candidates = []- for field in ["last_accessed", "updated", "created"]:- val = fields.get(field, "")- try:- candidates.append(date.fromisoformat(val[:10]))- except (ValueError, IndexError):- continue- if use_git:- git_date = get_git_date(filepath)- if git_date:- candidates.append(git_date)- if not candidates:- mtime = os.path.getmtime(filepath)- candidates.append(date.fromtimestamp(mtime))- return max(candidates)---# ─── core logic ─────────────────────────────────────────────────--def calc_relevance(days: int, rate: float, floor: float) -> float:- """Linear decay with floor."""- return round(max(floor, 1.0 - days * rate), 2)---def calc_tier(days: int, tiers: dict, current_tier: str = "") -> str:- """Assign tier based on days since last access."""- if current_tier == "core":- return "core" # never auto-demote core- sorted_tiers = sorted(tiers.items(), key=lambda x: x[1])- for tier_name, threshold in sorted_tiers:- if days <= threshold:- return tier_name- return "archive"---def infer_type(filepath: Path, type_map: dict) -> str:- """Infer card type from path using configurable mapping."""- path_str = str(filepath)- for pattern, card_type in type_map.items():- if pattern in path_str:- return card_type- return "note"---def should_skip(filepath: Path, patterns: list[str]) -> bool:- """Check if file matches skip patterns."""- import fnmatch- name = filepath.name- for pattern in patterns:- if fnmatch.fnmatch(name, pattern):- return True- return False---def infer_title(body: str) -> str:- """Extract title from first H1 heading."""- for line in body.split("\n")[:10]:- if line.startswith("# "):- return line[2:].strip()- return ""---# ─── config ─────────────────────────────────────────────────────--def load_config(target_dir: Path, config_path: str | None = None) -> dict:- """Load config from file or return defaults."""- if config_path:- p = Path(config_path)- else:- p = target_dir / ".memory-config.json"- if p.exists():- with open(p) as f:- user = json.load(f)- # Merge with defaults- config = {**DEFAULT_CONFIG, **user}- config["tiers"] = {**DEFAULT_CONFIG["tiers"], **user.get("tiers", {})}- return config- return DEFAULT_CONFIG.copy()---def save_default_config(target_dir: Path):- """Write default config file."""- p = target_dir / ".memory-config.json"- with open(p, "w") as f:- json.dump(DEFAULT_CONFIG, f, indent=2)- print(f" wrote default config: {p}")---# ─── commands ───────────────────────────────────────────────────--def find_cards(target_dir: Path, config: dict) -> list[Path]:- """Find all markdown files, respecting skip patterns."""- cards = sorted(target_dir.rglob("*.md"))- return [c for c in cards if c.exists() and not c.is_symlink() and not should_skip(c, config["skip_patterns"])]---def cmd_scan(target_dir: Path, config: dict, verbose: bool = False):- """Analyze files without changes."""- cards = find_cards(target_dir, config)- with_yaml = 0- without_yaml = 0- has_relevance = 0- has_tier = 0- total_bytes = 0-- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- total_bytes += len(content.encode("utf-8"))- fields, body, had_yaml = parse_frontmatter(content)- if had_yaml:- with_yaml += 1- else:- without_yaml += 1- if "relevance" in fields:- has_relevance += 1- if "tier" in fields:- has_tier += 1- if verbose and not had_yaml:- print(f" no yaml: {card.relative_to(target_dir)}")-- print(f"\n scan results for {target_dir}:")- print(f" total files: {len(cards)}")- print(f" with yaml: {with_yaml}")- print(f" without yaml: {without_yaml}")- print(f" has relevance: {has_relevance}")- print(f" has tier: {has_tier}")- print(f" total size: {total_bytes / 1024:.0f} KB")- print(f" avg file size: {total_bytes / max(len(cards), 1) / 1024:.1f} KB")-- if without_yaml:- print(f"\n → run 'init' to add YAML frontmatter to {without_yaml} files")- if not has_relevance:- print(f" → run 'decay' to add relevance scores and tiers")---def cmd_init(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):- """Add YAML frontmatter to files missing it."""- cards = find_cards(target_dir, config)- added = 0-- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- fields, body, had_yaml = parse_frontmatter(content)- if had_yaml:- continue-- # Create minimal frontmatter- new_fields = {- "type": infer_type(card, config["type_inference"]),- }- title = infer_title(body)- if title:- new_fields["title"] = title-- ref_date = get_best_date({}, card, config["use_git_dates"])- new_fields["last_accessed"] = ref_date.isoformat()- days = max(0, (TODAY - ref_date).days)- new_fields["relevance"] = str(calc_relevance(days, config["decay_rate"], config["relevance_floor"]))- new_fields["tier"] = calc_tier(days, config["tiers"])-- new_content = build_frontmatter(new_fields) + body- if not dry_run:- card.write_text(new_content, encoding="utf-8")- added += 1- if verbose:- print(f" {'[dry] ' if dry_run else ''}init: {card.relative_to(target_dir)} → {new_fields['tier']}")-- print(f"\n {'DRY RUN — ' if dry_run else ''}init results:")- print(f" files processed: {len(cards)}")- print(f" frontmatter added: {added}")---def cmd_decay(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):- """Update relevance and tiers based on time decay."""- cards = find_cards(target_dir, config)- results = []-- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- fields, body, had_yaml = parse_frontmatter(content)-- ref_date = get_best_date(fields, card, config["use_git_dates"])- days = max(0, (TODAY - ref_date).days)-- old_tier = fields.get("tier", "")- new_relevance = calc_relevance(days, config["decay_rate"], config["relevance_floor"])- new_tier = calc_tier(days, config["tiers"], old_tier)-- if "last_accessed" not in fields:- fields["last_accessed"] = ref_date.isoformat()- if "type" not in fields:- fields["type"] = infer_type(card, config["type_inference"])-- fields["relevance"] = str(new_relevance)- fields["tier"] = new_tier-- new_content = build_frontmatter(fields) + body- changed = new_content != content-- if changed and not dry_run:- card.write_text(new_content, encoding="utf-8")-- results.append({- "path": str(card.relative_to(target_dir)),- "days": days,- "relevance": new_relevance,- "tier": new_tier,- "changed": changed,- })-- if verbose and changed:- print(f" {'[dry] ' if dry_run else ''}{card.relative_to(target_dir)}: {old_tier or '?'}→{new_tier} r={new_relevance}")-- # Stats- tiers = {}- changed_count = sum(1 for r in results if r["changed"])- for r in results:- tiers[r["tier"]] = tiers.get(r["tier"], 0) + 1- avg_rel = sum(r["relevance"] for r in results) / max(len(results), 1)-- print(f"\n {'DRY RUN — ' if dry_run else ''}decay results:")- print(f" total: {len(results)}, changed: {changed_count}")- print(f" avg relevance: {avg_rel:.2f}")- for tier in ["core", "active", "warm", "cold", "archive"]:- count = tiers.get(tier, 0)- bar = "█" * (count // 3)- if count:- print(f" {tier:8s}: {count:4d} {bar}")---def cmd_touch(filepath: str, config: dict):- """Promote a file one tier up (graduated recall).-- archive → cold → warm → active → active (refresh)- Each touch promotes one level, not straight to top.- Natural spaced repetition: multiple reads = stronger memory.- """- p = Path(filepath)- if not p.exists():- print(f" error: {filepath} not found")- sys.exit(1)-- content = p.read_text(encoding="utf-8", errors="replace")- fields, body, had_yaml = parse_frontmatter(content)-- if fields.get("tier") == "core":- fields["last_accessed"] = TODAY.isoformat()- fields["relevance"] = "1.0"- new_content = build_frontmatter(fields) + body- p.write_text(new_content, encoding="utf-8")- print(f" touched: {filepath} → core (refreshed)")- return-- tiers_cfg = config["tiers"]- # Promotion targets: set last_accessed to midpoint of next-higher tier- # archive → cold: midpoint of cold range- # cold → warm: midpoint of warm range- # warm → active: midpoint of active range- # active → active: today (refresh)- cold_threshold = tiers_cfg.get("cold", 60)- warm_threshold = tiers_cfg.get("warm", 21)- active_threshold = tiers_cfg.get("active", 7)-- current_tier = fields.get("tier", "archive")- if current_tier == "archive":- # Promote to cold: set last_accessed to midpoint of cold range- target_days = (warm_threshold + cold_threshold) // 2- new_tier = "cold"- elif current_tier == "cold":- # Promote to warm: midpoint of warm range- target_days = (active_threshold + warm_threshold) // 2- new_tier = "warm"- elif current_tier == "warm":- # Promote to active: midpoint of active range- target_days = active_threshold // 2- new_tier = "active"- else:- # Already active: refresh to today- target_days = 0- new_tier = "active"-- from datetime import timedelta- new_date = TODAY - timedelta(days=target_days)- new_relevance = calc_relevance(target_days, config["decay_rate"], config["relevance_floor"])-- fields["last_accessed"] = new_date.isoformat()- fields["relevance"] = str(new_relevance)- fields["tier"] = new_tier-- new_content = build_frontmatter(fields) + body- p.write_text(new_content, encoding="utf-8")- print(f" touched: {filepath} → {current_tier}→{new_tier}, relevance={new_relevance}")---def cmd_creative(n: int, target_dir: Path, config: dict):- """Random sample from cold/archive tiers for divergent thinking."""- cards = find_cards(target_dir, config)- cold_cards = []-- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- fields, body, had_yaml = parse_frontmatter(content)- tier = fields.get("tier", "")- if tier in ("cold", "archive", "warm"):- title = fields.get("title", "") or infer_title(body)- cold_cards.append({- "path": str(card.relative_to(target_dir)),- "tier": tier,- "relevance": fields.get("relevance", "?"),- "title": title,- "last_accessed": fields.get("last_accessed", "?"),- })-- if not cold_cards:- print(" no cold/archive cards found — memory is too fresh")- return-- sample = random.sample(cold_cards, min(n, len(cold_cards)))- print(f"\n 🎲 creative recall — {len(sample)} random cards:")- for card in sample:- print(f" [{card['tier']}] {card['title'] or card['path']}")- print(f" {card['path']} (r={card['relevance']}, last={card['last_accessed']})")- print(f"\n read these cards and look for unexpected connections to your current task")---def cmd_daily(target_dir: Path, config: dict, dry_run: bool = False, verbose: bool = False):- """Bootstrap and decay daily files (YYYY-MM-DD.md pattern)."""- date_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}\.md$")- daily_files = sorted(- f for f in target_dir.rglob("*.md")- if date_pattern.match(f.name)- )-- if not daily_files:- print(f" no daily files (YYYY-MM-DD.md) found in {target_dir}")- return-- results = []- for f in daily_files:- content = f.read_text(encoding="utf-8", errors="replace")- fields, body, had_yaml = parse_frontmatter(content)-- # Extract date from filename- file_date = date.fromisoformat(f.stem)- days = max(0, (TODAY - file_date).days)-- # Use file_date as reference (not git/mtime — daily files are date-intrinsic)- la = fields.get("last_accessed", "")- try:- last_acc = date.fromisoformat(la[:10])- # Use most recent of: file_date, last_accessed- ref_days = max(0, (TODAY - max(file_date, last_acc)).days)- except (ValueError, IndexError):- ref_days = days-- new_relevance = calc_relevance(ref_days, config["decay_rate"], config["relevance_floor"])- old_tier = fields.get("tier", "")- new_tier = calc_tier(ref_days, config["tiers"], old_tier)-- fields["type"] = "daily"- fields["date"] = file_date.isoformat()- if "last_accessed" not in fields:- fields["last_accessed"] = file_date.isoformat()- fields["relevance"] = str(new_relevance)- fields["tier"] = new_tier-- new_content = build_frontmatter(fields) + body- changed = new_content != content-- if changed and not dry_run:- f.write_text(new_content, encoding="utf-8")-- results.append({- "file": f.name,- "date": file_date.isoformat(),- "days": ref_days,- "relevance": new_relevance,- "tier": new_tier,- "changed": changed,- })-- if verbose:- print(f" {'[dry] ' if dry_run else ''}{f.name}: {old_tier or '?'}→{new_tier} r={new_relevance} ({ref_days}d)")-- # Summary- tiers = {}- for r in results:- tiers[r["tier"]] = tiers.get(r["tier"], 0) + 1- changed_count = sum(1 for r in results if r["changed"])-- print(f"\n {'DRY RUN — ' if dry_run else ''}daily results:")- print(f" files: {len(results)}, changed: {changed_count}")- for tier in ["active", "warm", "cold", "archive"]:- count = tiers.get(tier, 0)- if count:- dates = [r["date"] for r in results if r["tier"] == tier]- print(f" {tier:8s}: {count:3d} ({dates[0]}..{dates[-1]})")---def cmd_stats(target_dir: Path, config: dict):- """Show comprehensive memory health stats."""- cards = find_cards(target_dir, config)- tiers = {}- total_bytes = 0- stale_count = 0- no_yaml = 0-- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- total_bytes += len(content.encode("utf-8"))- fields, body, had_yaml = parse_frontmatter(content)- if not had_yaml:- no_yaml += 1- tier = fields.get("tier", "unknown")- tiers[tier] = tiers.get(tier, 0) + 1- try:- la = date.fromisoformat(fields.get("last_accessed", "")[:10])- if (TODAY - la).days > 90:- stale_count += 1- except (ValueError, IndexError):- pass-- print(f"\n memory health — {target_dir}")- print(f" {'─' * 40}")- print(f" total cards: {len(cards)}")- print(f" total size: {total_bytes / 1024:.0f} KB")- print(f" without yaml: {no_yaml}")- print(f" stale (>90 days): {stale_count}")- print(f" {'─' * 40}")- print(f" tier distribution:")- for tier in ["core", "active", "warm", "cold", "archive", "unknown"]:- count = tiers.get(tier, 0)- if count:- pct = count / len(cards) * 100- bar = "█" * int(pct / 2)- print(f" {tier:8s}: {count:4d} ({pct:4.1f}%) {bar}")-- # Context budget estimate (assuming ~4 chars per token)- active_bytes = 0- for card in cards:- content = card.read_text(encoding="utf-8", errors="replace")- fields, _, _ = parse_frontmatter(content)- if fields.get("tier") in ("core", "active"):- active_bytes += len(content.encode("utf-8"))- print(f" {'─' * 40}")- print(f" active context: {active_bytes / 1024:.0f} KB (~{active_bytes // 4:,} tokens)")- print(f" total context: {total_bytes / 1024:.0f} KB (~{total_bytes // 4:,} tokens)")---# ─── main ───────────────────────────────────────────────────────--def main():- args = sys.argv[1:]- if not args or args[0] in ("-h", "--help"):- print(__doc__)- sys.exit(0)-- cmd = args[0]- dry_run = "--dry-run" in args- verbose = "--verbose" in args-- # Find config path- config_path = None- if "--config" in args:- idx = args.index("--config")- config_path = args[idx + 1] if idx + 1 < len(args) else None-- # Find target directory (first non-flag argument after command)- target = None- for a in args[1:]:- if not a.startswith("-") and a != config_path:- target = a- break-- if cmd == "touch":- if not target:- print(" error: touch requires a file path")- sys.exit(1)- config = load_config(Path(target).parent, config_path)- cmd_touch(target, config)- return-- if cmd == "creative":- n = 5- creative_dir = None- for a in args[1:]:- if not a.startswith("-"):- try:- n = int(a)- except ValueError:- creative_dir = a- target_dir = Path(creative_dir) if creative_dir else Path(".")- config = load_config(target_dir, config_path)- cmd_creative(n, target_dir, config)- return-- target_dir = Path(target) if target else Path(".")- if not target_dir.is_dir():- print(f" error: {target_dir} is not a directory")- sys.exit(1)-- config = load_config(target_dir, config_path)-- if cmd == "scan":- cmd_scan(target_dir, config, verbose)- elif cmd == "init":- cmd_init(target_dir, config, dry_run, verbose)- elif cmd == "decay":- cmd_decay(target_dir, config, dry_run, verbose)- elif cmd == "daily":- cmd_daily(target_dir, config, dry_run, verbose)- elif cmd == "stats":- cmd_stats(target_dir, config)- elif cmd == "config":- save_default_config(target_dir)- else:- print(f" unknown command: {cmd}")- print(" commands: scan, init, decay, daily, touch, creative, stats, config")- sys.exit(1)---if __name__ == "__main__":- main()diff --git a/vault/.claude/skills/autograph/SKILL.md b/vault/.claude/skills/autograph/SKILL.mdindex 4d8759d..308f543 100644--- a/vault/.claude/skills/autograph/SKILL.md+++ b/vault/.claude/skills/autograph/SKILL.md@@ -7,7 +7,6 @@ description: >-a vault, fixing wikilinks, finding orphans or backlinks, extracting entities fromdaily files, or touching/promoting cards.Do NOT use for content generation or non-vault file operations.- For quick health checks without schema enforcement, prefer vault-health skill.---# autograph — typed vault enginediff --git a/vault/.claude/skills/dbrain-processor/SKILL.md b/vault/.claude/skills/dbrain-processor/SKILL.mdindex 67a9c4f..fedea9c 100644--- a/vault/.claude/skills/dbrain-processor/SKILL.md+++ b/vault/.claude/skills/dbrain-processor/SKILL.md@@ -2,7 +2,7 @@type: notedescription: Personal assistant for processing daily voice/text entries from Telegram. Classifies content, saves thoughts to Obsidian with wiki-links, generates HTML reports. Integrates Your Business context (clients, projects, CRM). Triggers on /process command or daily 21:00 cron.name: dbrain-processor-depends_on: [graph-builder, agent-memory, vault-health]+depends_on: [autograph]---# d-brain Processor@@ -556,4 +556,4 @@ grep -l "priority: High" business/crm/## Relevant Skills-- [[vault/.claude/skills/graph-builder/SKILL|graph-builder]] — Vault graph analysis+- [[vault/.claude/skills/autograph/SKILL|autograph]] — Typed vault engine: graph, decay, MOC, dedupdiff --git a/vault/.claude/skills/graph-builder/SKILL.md b/vault/.claude/skills/graph-builder/SKILL.mddeleted file mode 100644index 3dc5fd6..0000000--- a/vault/.claude/skills/graph-builder/SKILL.md+++ /dev/null@@ -1,210 +0,0 @@-----name: graph-builder-description: Analyze and build knowledge graph links in Obsidian vault. Runs a deterministic script for analysis, then the agent adds semantic links to orphan files. Three domains: Personal, Business, Projects.-allowed-tools: Bash(uv run:*), Bash(rg:*), Read, Edit-depends_on: []------# Graph Builder--Analyze vault link structure and build meaningful connections between notes.--## Architecture--```-+------------------------------------------+-| 1. SCRIPT analyze.py (deterministic) |-| -> vault-graph.json + report.md |-+-----------------+------------------------+- |- v-+------------------------------------------+-| 2. AGENT (you) |-| -> orphan analysis |-| -> semantic links |-| -> frontmatter updates |-| -> HTML report |-+------------------------------------------+-```--## Trigger--- `/graph` -- manual run-- After `dbrain-processor` in chain (optional)-- Weekly: full rebuild-------## STEP 1: Run the script--```bash-uv run vault/.claude/skills/graph-builder/scripts/analyze.py-```--**Script does:**-1. Traverses all .md files in vault/-2. Parses frontmatter-3. Extracts wiki-links `[[path]]` and `[[path|alias]]`-4. Determines domain (business, projects, personal)-5. Finds orphan files (no links)-6. Finds broken links-7. Generates `vault/.graph/vault-graph.json`-8. Generates `vault/.graph/report.md`--**CRITICAL:** Always run the script first! It provides up-to-date data.-------## STEP 2: Read script output--Read `vault/.graph/vault-graph.json`:--```json-{- "stats": {- "total_files": 331,- "orphan_files": 147,- "broken_links": 167- },- "orphans": ["path/to/file.md", ...],- "broken_links": [{"from": "...", "to": "..."}, ...]-}-```-------## STEP 3: Analyze orphan files--For each orphan file (start with **non-daily** files):--1. **Read the file content**-2. **Find potential links:**- - Company mentions -> `business/crm/{company}.md`- - People mentions -> search in contacts/- - Tags -> files with matching tags- - Dates -> daily/ for that day- - Topics -> thoughts/learnings/, MOC/--3. **Suggest links** -- add to frontmatter `related: []`--### Link search patterns--| Mention | Link |-|---------|------|-| Acme Corp, Acme | `[[business/crm/acme-corp]]` |-| PhoneBrand | `[[business/crm/phone-brand]]` |-| TechCo | `[[business/crm/tech-co]]` |-| SchoolCo | `[[projects/leads/school-co]]` |-| AutoDealer | `[[projects/leads/auto-dealer]]` |-| AI, Claude, GPT | thoughts/learnings/ with AI topic |-------## STEP 4: Update frontmatter--**Link format in frontmatter:**--```yaml-----type: learning-domain: personal-tags: [ai, marketing]-related:- - "[[business/crm/acme-corp]]"- - "[[projects/leads/school-co]]"- - "[[thoughts/learnings/agent-memory-system]]"-----```--**Rules:**-- Only add real links (file exists)-- Do not duplicate existing links-- Maximum 5-7 links per file-- Use `"[[path]]"` format with quotes-------## STEP 5: Update MOC (if needed)--Check MOC files:-- `MOC/MOC-learnings.md` -- add new learnings-- `MOC/MOC-projects.md` -- create if missing-------## STEP 6: HTML report--**Return RAW HTML for Telegram:**--<b>Graph Builder Report</b>--<b>Analyzed:</b>-- Files: {total_files}-- Links: {total_links}-- Orphans: {orphan_files}-- Broken links: {broken_links}--<b>Business:</b> {files} files, {links} links-<b>Projects:</b> {files} files, {links} links-<b>Personal:</b> {files} files, {links} links--<b>Links added:</b> {count}-- {file1} -> {file2}-- {file3} -> {file4}--<b>Needs attention:</b>-- {broken_count} broken links-- {orphan_count} orphan files--<i>Details: vault/.graph/report.md</i>-------## Three domains--### Personal-- `thoughts/` -- learnings, ideas, reflections-- `goals/` -- yearly, monthly, weekly-- `daily/` -- raw entries-- **Hub:** `MEMORY.md`--### Business-- `business/crm/` -- clients + deals (N files)-- `business/network/` -- org structure-- **Hub:** `business/_index.md`--### Projects-- `projects/clients/` -- project clients-- `projects/leads/` -- leads-- **Hub:** `projects/_index.md`-------## Orphan processing priority--1. **business/crm/** -- business-critical, many orphans-2. **thoughts/learnings/** -- valuable knowledge-3. **projects/** -- active projects-4. **daily/** -- old entries (low priority)-------## Do not--- Do not change file content (only frontmatter)-- Do not add links to non-existent files-- Do not process files in .obsidian/, attachments/, backup/-- Do not create new files without reason-------## References--- `references/domains.md` -- domain details-- `references/entities.md` -- entity patterns-- `references/frontmatter.md` -- frontmatter schema--## Relevant Skills--- [[vault/.claude/skills/vault-health/SKILL|vault-health]] -- Health scoring, MOC generation, link repair (depends on this skill)-- [[vault/.claude/skills/dbrain-processor/SKILL|dbrain-processor]] -- Daily entry processingdiff --git a/vault/.claude/skills/graph-builder/references/domains.md b/vault/.claude/skills/graph-builder/references/domains.mddeleted file mode 100644index 0052055..0000000--- a/vault/.claude/skills/graph-builder/references/domains.md+++ /dev/null@@ -1,123 +0,0 @@-# Domains--Three knowledge organization domains in the vault.--## Personal--**Path:** `thoughts/`, `goals/`, `daily/`, `MOC/`, `MEMORY.md`--**Content:**-- Personal thoughts and reflections-- Goals (yearly -> monthly -> weekly)-- Daily entries-- Learnings and ideas--**Hub:** `MEMORY.md` -- central context--**Frontmatter:**-```yaml-domain: personal-type: learning | reflection | idea | project-```-------## Business--**Path:** `business/`--**Structure:**-```-business/-+-- _index.md # Entry point, dataview queries-+-- crm/ # Clients + deals-| +-- acme-corp.md-| +-- client-b.md-| +-- ...-+-- network/ # Org structure (Your Holding)-| +-- founders.md-| +-- partner-a.md-| +-- partner-b.md-+-- events/ # Events-```--**Hub:** `business/_index.md`--**Frontmatter (CRM):**-```yaml-domain: business-type: crm-industry: FMCG | Electronics | Banks | Pharma | Retail-priority: High | Mid | Low-status: Active | Prospect | Dormant | Declined-region: UZ | KZ | BY-owner: [Your Name] | [Team Member]-deal_status: In progress | Tender | Proposal sent-deal_deadline: YYYY-MM-DD-```--**Key clients:**-- Client-A (FMCG, High, Active)-- Client-B (Electronics, High, Active)-- Client-C (Electronics, Mid, Active)-- Client-D (FMCG, Mid, Prospect)-------## Projects--**Path:** `projects/`--**Structure:**-```-projects/-+-- _index.md # Entry point-+-- clients/ # Project clients-| +-- client-a.md-| +-- client-b.md-| +-- client-c.md-| +-- client-d.md-+-- leads/ # Leads- +-- lead-a.md- +-- lead-b.md-```--**Hub:** `projects/_index.md`--**Frontmatter:**-```yaml-domain: projects-type: client | lead-company: Name-industry: Auto | IT | Retail | Education-status: APPROVED | Proposal sent | Hot | Cold-responsible: Name-```--**Difference from Business:**-- Business = main business (agency, services)-- Projects = personal side projects (consulting, training)-------## Cross-domain links--| Link | Example |-|------|---------|-| Projects -> Business | `lead-a` -> `partner-b` (partner) |-| Personal -> Business | `learning` -> `acme-corp` (case from practice) |-| Personal -> Projects | `learning` -> `client-a` (insight from training) |-| Business -> Contacts | `acme-corp` -> contacts (contacts) |-------## Determining domain by path--```python-def get_domain(path: Path) -> str:- if "business" in path.parts:- return "business"- elif "projects" in path.parts:- return "projects"- return "personal"-```diff --git a/vault/.claude/skills/graph-builder/references/entities.md b/vault/.claude/skills/graph-builder/references/entities.mddeleted file mode 100644index 09cca3e..0000000--- a/vault/.claude/skills/graph-builder/references/entities.md+++ /dev/null@@ -1,157 +0,0 @@-# Entity Extraction Patterns--Patterns for finding entities in text.--## Companies (Business CRM)--### Exact matches--| Pattern | File |-|---------|------|-| Client-A, ClientA | `business/crm/client-a.md` |-| Client-B | `business/crm/client-b.md` |-| Client-C | `business/crm/client-c.md` |-| Client-D | `business/crm/client-d.md` |-| Client-E | `business/crm/client-e.md` |-| Client-F | `business/crm/client-f.md` |-| Client-G | `business/crm/client-g.md` |-| Client-H | `business/crm/client-h.md` |-| Client-I | `business/crm/client-i.md` |-| Client-J | `business/crm/client-j.md` |--### Regex for companies--```python-COMPANY_PATTERNS = [- r'\b(Client-A|ClientA)\b',- r'\b(Client-B)\b',- r'\b(Client-C)\b',- r'\b(Client-D)\b',- r'\b(Client-E)\b',- r'\bClient-F\b',- r'\b(Client-G)\b',- r'\bClient-H\b',- r'\bClient-I\b',-]-```-------## Companies (Projects)--| Pattern | File |-|---------|------|-| Project-Client-A | `projects/clients/project-client-a.md` |-| Project-Client-B | `projects/clients/project-client-b.md` |-| Project-Client-C | `projects/clients/project-client-c.md` |-| Project-Client-D | `projects/clients/project-client-d.md` |-| Lead-A | `projects/leads/lead-a.md` |-| Lead-B | `projects/leads/lead-b.md` |-------## People--### Name format--```python-# Names in your language-LOCAL_NAME = r'[A-Z][a-z]+\s+[A-Z][a-z]+'-# Examples: [First Name] [Last Name]--# English names-ENGLISH_NAME = r'[A-Z][a-z]+\s+[A-Z][a-z]+'-# Examples: [First Name] [Last Name]-```--### Telegram handles--```python-TELEGRAM_HANDLE = r'@([a-zA-Z0-9_]+)'-# Examples: @username1, @username2, @username3-```-------## Projects--### Project patterns--```python-PROJECT_PATTERNS = [- r'project\s+([A-Za-z0-9\s]+)',- r'(?:NCP|SMM|BTL|ATL)\s+([A-Za-z]+)',- r'tender\s+([A-Za-z]+)',-]-```--### Active projects--| Mention | Link |-|---------|------|-| Client-A Campaign | `business/crm/client-a.md` |-| Client-B SMM | `business/crm/client-b.md` |-| Client-C Project | `business/crm/client-c.md` |-------## Topics (for learnings)--| Keywords | Links to |-|----------|----------|-| Claude, AI agent, LLM | `thoughts/learnings/` with AI |-| Second Brain, Obsidian, PKM | Methodology |-| Zettelkasten, graph | Knowledge organization |-| Prompt, prompt engineering | AI techniques |-| Marketing, SMM, content | Business |-------## Finding file for entity--```python-def find_file_for_entity(entity: str, vault_path: Path) -> Path | None:- """Find file for an entity."""-- # Normalize: Client-A -> client-a- slug = entity.lower().replace(" ", "-")-- # Search in CRM- crm_path = vault_path / "business" / "crm" / f"{slug}.md"- if crm_path.exists():- return crm_path-- # Search in Projects- for subdir in ["clients", "leads"]:- path = vault_path / "projects" / subdir / f"{slug}.md"- if path.exists():- return path-- # Fuzzy search by filename- for f in vault_path.rglob("*.md"):- if slug in f.stem.lower():- return f-- return None-```-------## Link normalization--```python-def normalize_link(link: str) -> str:- """Normalize wiki-link."""-- # Remove section: [[file#section]] -> file- link = link.split("#")[0]-- # Remove alias: [[file|alias]] -> file- link = link.split("|")[0]-- # Add .md if missing- if not link.endswith(".md"):- link = link + ".md"-- return link-```diff --git a/vault/.claude/skills/graph-builder/references/frontmatter.md b/vault/.claude/skills/graph-builder/references/frontmatter.mddeleted file mode 100644index eab5a9a..0000000--- a/vault/.claude/skills/graph-builder/references/frontmatter.md+++ /dev/null@@ -1,252 +0,0 @@-# Frontmatter Schema--YAML frontmatter schema for vault files.--## Basic schema (all files)--```yaml-----type: string # Record type (see below)-domain: string # business | projects | personal-description: string # Retrieval filter ~150 chars (NOT summary -- adds scope/mechanism/implication beyond title)-tags: [string] # Tags for categorization-related: [string] # Wiki-links to related files-created: date # Creation date (YYYY-MM-DD)-updated: date # Update date-----```--### Description field--**NOT a summary** -- description adds information BEYOND the title, does not repeat it.-This is a **retrieval filter**: the agent reads title + description and decides whether to open the file.--**Rules:**-- ~150 characters max-- Adds scope, mechanism or implication-- Does NOT repeat the title-- Specifics > abstractions--**Examples:**--```yaml-# CRM (title = acme-corp.md):-description: "Major FMCG client, Project $XXK active deal, promo codes in progress"--# Thought (title = 2026-02-05-hormonal-agent-algorithm.md):-description: "4 hormones as sine waves + noise -> mood -> intentions. Gives agent free will."--# Learning (title = 2026-01-30-session-persistence.md):-description: "JSONL append-only files for interaction history. Pattern from Clawdbot."-```-------## Record types--### Personal domain--| type | Folder | Description |-|------|--------|-------------|-| learning | thoughts/learnings/ | Knowledge, discoveries, TIL |-| idea | thoughts/ideas/ | Ideas, concepts |-| reflection | thoughts/reflections/ | Reflections, conclusions |-| project | thoughts/projects/ | Project notes |--### Business domain--| type | Folder | Description |-|------|--------|-------------|-| crm | business/crm/ | Client + deals |-| network | business/network/ | Org structure |-| event | business/events/ | Events |--### Projects domain--| type | Folder | Description |-|------|--------|-------------|-| client | projects/clients/ | Project client |-| lead | projects/leads/ | Lead |-------## CRM Schema (business/crm/)--```yaml-----type: crm-domain: business-description: string # Retrieval filter: key client context (~150 chars)-industry: FMCG | Electronics | Banks | Pharma | Retail | Auto | IT | Telecom-priority: High | Mid | Low-status: Active | Prospect | Dormant | Declined-region: UZ | KZ | BY | Global-owner: [Your Name] | [Team Member]-responsible: string # Responsible person on client side--# Active deal (if any)-deal_status: In progress | Tender | Proposal sent | Meeting held-deal_deadline: YYYY-MM-DD--# Links-related:- - "[[thoughts/learnings/...]]"--updated: YYYY-MM-DD-----```--**Example:**--```yaml-----type: crm-domain: business-industry: FMCG-priority: High-status: Active-region: UZ, KZ-owner: [Your Name]-deal_status: In progress-deal_deadline: 2026-02-09-updated: 2026-01-29-----```-------## Learning Schema (thoughts/learnings/)--```yaml-----type: learning-domain: personal-description: string # Retrieval filter: key insight (~150 chars)-tags: [ai, marketing, automation, ...]-source: daily/YYYY-MM-DD.md | URL | @mention-related:- - "[[business/crm/acme-corp]]"- - "[[projects/leads/lead-a]]"-created: YYYY-MM-DD-----```--**Example:**--```yaml-----type: learning-domain: personal-tags: [ai, marketing, panel]-source: event-related:- - "[[projects/leads/lead-a]]"- - "[[business/network/partner-a]]"-created: 2026-01-27-----```-------## Projects Client Schema--```yaml-----type: client-domain: projects-description: string # Retrieval filter: client type and status (~150 chars)-company: string-industry: Auto | IT | Retail | Pharma | Education | Finance-region: BY | UZ | KZ | RU-status: APPROVED | Proposal sent | In progress | Completed-responsible: string-budget: string # Optional-related:- - "[[thoughts/learnings/...]]"-updated: YYYY-MM-DD-----```-------## Projects Lead Schema--```yaml-----type: lead-domain: projects-description: string # Retrieval filter: who and why (~150 chars)-company: string-industry: Education | IT | ...-region: UZ | ...-status: Hot | Warm | Cold | Contacted | Proposal sent-source: string # Where lead came from-responsible: string-next_action: string # Next step-related: []-updated: YYYY-MM-DD-----```-------## Related format--**Correct:**--```yaml-related:- - "[[business/crm/acme-corp]]"- - "[[thoughts/learnings/agent-memory-system]]"-```--**Incorrect:**--```yaml-# Without quotes (may break YAML)-related:- - [[business/crm/acme-corp]]--# With alias in frontmatter (redundant)-related:- - "[[business/crm/acme-corp|Acme Corp]]"-```-------## Adding links by agent--When updating frontmatter:--1. **Read** existing frontmatter-2. **Get** current `related: []`-3. **Add** new links (no duplicates)-4. **Verify** that files exist-5. **Write** updated frontmatter--```python-def add_related(content: str, new_links: list[str]) -> str:- """Add links to frontmatter."""-- # Parse frontmatter- match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)- if not match:- return content-- fm = yaml.safe_load(match.group(1)) or {}-- # Get current links- existing = set(fm.get("related", []))-- # Add new (format with quotes)- for link in new_links:- formatted = f'[[{link}]]' if not link.startswith('[[') else link- existing.add(formatted)-- # Update- fm["related"] = sorted(list(existing))-- # Write- new_fm = yaml.dump(fm, allow_unicode=True, default_flow_style=False)- return f"---\n{new_fm}---\n" + content[match.end():]-```diff --git a/vault/.claude/skills/graph-builder/scripts/add_links.py b/vault/.claude/skills/graph-builder/scripts/add_links.pydeleted file mode 100644index 2a2669a..0000000--- a/vault/.claude/skills/graph-builder/scripts/add_links.py+++ /dev/null@@ -1,247 +0,0 @@-#!/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.pydeleted file mode 100644index d85bb8f..0000000--- a/vault/.claude/skills/graph-builder/scripts/analyze.py+++ /dev/null@@ -1,219 +0,0 @@-#!/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()diff --git a/vault/.claude/skills/vault-health/SKILL.md b/vault/.claude/skills/vault-health/SKILL.mddeleted file mode 100644index d1da7f9..0000000--- a/vault/.claude/skills/vault-health/SKILL.md+++ /dev/null@@ -1,249 +0,0 @@-----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.mddeleted file mode 100644index 789a5e4..0000000--- a/vault/.claude/skills/vault-health/references/arscontexta-patterns.md+++ /dev/null@@ -1,105 +0,0 @@-----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.pydeleted file mode 100644index 8d61fde..0000000--- a/vault/.claude/skills/vault-health/scripts/add_descriptions.py+++ /dev/null@@ -1,318 +0,0 @@-#!/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.shdeleted file mode 100755index ce02961..0000000--- a/vault/.claude/skills/vault-health/scripts/backlinks.sh+++ /dev/null@@ -1,20 +0,0 @@-#!/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.pydeleted file mode 100644index 4ccddda..0000000--- a/vault/.claude/skills/vault-health/scripts/connect_orphans.py+++ /dev/null@@ -1,169 +0,0 @@-#!/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.pydeleted file mode 100644index 90a092e..0000000--- a/vault/.claude/skills/vault-health/scripts/fix_links.py+++ /dev/null@@ -1,393 +0,0 @@-#!/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.pydeleted file mode 100644index af9d1cc..0000000--- a/vault/.claude/skills/vault-health/scripts/generate_moc.py+++ /dev/null@@ -1,534 +0,0 @@-#!/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()diff --git a/vault/MEMORY.md b/vault/MEMORY.mdindex a057735..a359c63 100644--- a/vault/MEMORY.md+++ b/vault/MEMORY.md@@ -1,6 +1,6 @@# Long-term Memory-Curated knowledge that persists across sessions. Part of the 3-layer memory architecture (hot context → searchable vault → archive). See `.claude/skills/agent-memory/SKILL.md` for details.+Curated knowledge that persists across sessions. Part of the 3-layer memory architecture (hot context → searchable vault → archive). See `.claude/skills/autograph/SKILL.md` for details.## User Profile