⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
docs: Add architecture sections to all Kai bundle packs
Daniel Miesslercb7b302edeb3
diff --git a/Packs/kai-history-system.md b/Packs/kai-history-system.mdindex a9df2e31..484f8d02 100644--- a/Packs/kai-history-system.md+++ b/Packs/kai-history-system.md@@ -146,6 +146,178 @@ $PAI_DIR/Documentation is a byproduct, not a task. By instrumenting the work itself, you get perfect records without any effort. The history system sees everything because it's wired into the event stream.+---++## Architecture: The Special Sauce++The history system's power comes from its **automatic categorization pipeline** - a multi-layered architecture that captures, analyzes, and routes every piece of work to the right location without any manual intervention.++```+┌─────────────────────────────────────────────────────────────────────────┐+│ HISTORY SYSTEM ARCHITECTURE │+├─────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 1: Event Capture │ │+│ │ capture-all-events.ts hooks into EVERY Claude Code event │ │+│ │ PreToolUse │ PostToolUse │ Stop │ SubagentStop │ SessionEnd │ │+│ └──────────────────────────────┬──────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 2: Raw Storage │ │+│ │ Every event → JSONL file with full payload │ │+│ │ raw-outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl │ │+│ └──────────────────────────────┬──────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 3: Content Analysis │ │+│ │ Hooks analyze response content for category indicators │ │+│ │ "problem + solved + root cause" → LEARNING │ │+│ │ "completed + deployed" → SESSION │ │+│ └──────────────────────────────┬──────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 4: Agent Type Routing │ │+│ │ SubagentStop routes by agent type automatically │ │+│ │ researcher/intern → research/ │ │+│ │ architect → decisions/ │ │+│ │ engineer/designer → execution/features/ │ │+│ └──────────────────────────────┬──────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 5: Organized Storage │ │+│ │ Markdown files with YAML frontmatter in categorized dirs │ │+│ │ learnings/ │ research/ │ decisions/ │ sessions/ │ execution/ │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────┘+```++### How Data Flows Through the System++**Example: You debug a tricky auth bug with a researcher agent**++```+1. You ask Claude to investigate the auth bug+ │+ ▼+2. Claude spawns a researcher agent (Task tool)+ │+ ├──► PreToolUse event captured to raw-outputs/+ │+ ▼+3. Researcher agent investigates, finds root cause+ │+ ▼+4. Agent completes with: "🎯 COMPLETED: Found root cause - JWT tokens not refreshing"+ │+ ├──► SubagentStop fires+ │+ ▼+5. subagent-stop-hook.ts:+ a) Extracts completion message+ b) Detects agent_type = "researcher"+ c) Routes to research/YYYY-MM/+ │+ ▼+6. Main Claude fixes the bug based on research+ │+ ▼+7. Claude responds with "fixed", "root cause", "solved" in message+ │+ ├──► Stop fires+ │+ ▼+8. stop-hook.ts:+ a) Analyzes content for learning indicators+ b) Detects 3+ learning keywords+ c) Routes to learnings/YYYY-MM/+ │+ ▼+9. Result: TWO history entries automatically created:+ - research/2025-12/..._AGENT-researcher_RESEARCH_jwt-token-issue.md+ - learnings/2025-12/..._LEARNING_jwt-refresh-fix.md+```++### Why This Architecture Matters++**1. Zero Manual Effort**+- No "save this" commands needed+- No copy-paste to documentation+- Work normally; history captures itself++**2. Automatic Categorization**+- Content analysis detects learnings vs sessions+- Agent type determines output location+- Never manually file anything++**3. Complete Audit Trail**+- Raw JSONL captures EVERYTHING (even things not categorized)+- Can replay/analyze any session retroactively+- Nothing lost, ever++**4. Queryable Structure**+- Consistent file naming: `TIMESTAMP_TYPE_description.md`+- Time-based directories: `YYYY-MM/`+- Standard Unix tools work: `grep -r "authentication" history/`++**5. Agent Awareness**+- Each spawned agent's output is captured separately+- Agent type informs categorization+- Parallel work doesn't get lost or merged++### The Categorization Logic (Deep Dive)++**Learning Detection (stop-hook.ts):**+```+Contains 2+ of these indicators:+ problem, solved, discovered, fixed, learned, realized,+ figured out, root cause, debugging, issue was, turned out,+ mistake, error, bug, solution++YES → learnings/+NO → sessions/+```++**Agent Routing (subagent-stop-hook.ts):**+```+Agent Type → Output Directory+─────────────────────────────────────+*researcher, intern → research/+architect → decisions/+engineer, designer → execution/features/+```++### What Problems This Architecture Prevents++| Problem | How History Solves It |+|---------|----------------------|+| "What did we work on last week?" | `ls history/sessions/2025-01/` |+| "Why did we choose that architecture?" | `grep -l "architecture" history/decisions/` |+| "I fixed this bug before, what was the fix?" | `grep -r "auth" history/learnings/` |+| "What did that researcher agent find?" | Automatically in `history/research/` |+| "Can we audit what happened?" | Complete JSONL in `raw-outputs/` |++### The Fundamental Insight++**Naive approach:** Ask the AI to "remember" or manually save important things+- Requires explicit action (never happens)+- AI memory is session-scoped (resets on restart)+- No searchable archive++**History approach:** Instrument the event stream, capture automatically+- Zero effort (hooks run silently)+- Permanent markdown files (never lost)+- Searchable with grep/ls++The history system transforms ephemeral AI interactions into **permanent, searchable institutional memory**. Every debugging session, every research finding, every architectural decision - captured automatically, categorized intelligently, queryable forever.++---+## Why This Is DifferentThis sounds similar to ChatGPT's Memory feature or vector databases like Pinecone, which also preserve context. What makes this approach different?diff --git a/Packs/kai-hook-system.md b/Packs/kai-hook-system.mdindex d7f7efeb..92a30107 100644--- a/Packs/kai-hook-system.md+++ b/Packs/kai-hook-system.md@@ -118,6 +118,140 @@ $PAI_DIR/Hooks are middleware for your AI. They sit between Claude Code's event system and your custom logic. By instrumenting the event stream, you gain complete visibility and control over your AI's operations.+---++## Architecture: The Special Sauce++The hook system's power comes from its **event-driven middleware pattern** - a layered architecture that intercepts, processes, and extends every AI operation without modifying Claude Code itself.++```+┌─────────────────────────────────────────────────────────────────────────┐+│ HOOK SYSTEM ARCHITECTURE │+├─────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌──────────────┐ │+│ │ Claude Code │ ──► Events fire at every operation │+│ └──────┬───────┘ │+│ │ │+│ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 1: Event Stream │ │+│ │ SessionStart ─► PreToolUse ─► PostToolUse ─► Stop ─► SessionEnd │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 2: Hook Registry │ │+│ │ settings.json defines which hooks fire on which events │ │+│ │ Matchers filter by tool name (Bash, Edit, *) or context │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 3: Hook Implementations │ │+│ │ TypeScript files that process events and take actions │ │+│ │ security-validator.ts │ initialize-session.ts │ update-tabs.ts │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 4: Shared Libraries │ │+│ │ Common utilities: observability.ts, prosody-enhancer.ts │ │+│ │ Fail-safe patterns, logging, integration helpers │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ LAYER 5: External Integrations │ │+│ │ Observability dashboards, voice servers, notification systems │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────┘+```++### How Data Flows Through the System++**Example: User runs `rm -rf important/`**++```+1. Claude Code invokes Bash tool+ │+ ▼+2. PreToolUse event fires with payload:+ { tool_name: "Bash", tool_input: { command: "rm -rf important/" } }+ │+ ▼+3. settings.json routes to security-validator.ts (matcher: "Bash")+ │+ ▼+4. Hook receives JSON via stdin, pattern-matches against attack tiers+ │+ ▼+5. MATCH: Catastrophic deletion pattern detected+ │+ ▼+6. Hook exits with code 2 (BLOCK) + outputs warning message+ │+ ▼+7. Claude Code sees exit 2, BLOCKS the command+ │+ ▼+8. User sees: "🚨 BLOCKED: Catastrophic deletion detected"+```++### Why This Architecture Matters++**1. Separation of Concerns**+- Event stream (Claude Code) is separate from hook logic (your code)+- Registration (settings.json) is separate from implementation (.ts files)+- Each hook does one thing well (UNIX philosophy)++**2. Fail-Safe by Design**+- Hooks NEVER crash Claude Code (exit 0 on errors)+- External integrations fail silently (observability down? keep working)+- Fast execution (milliseconds, not seconds)++**3. Composable Pipeline**+- Multiple hooks can chain on the same event+- Each hook processes independently+- Order defined in settings.json++**4. Deterministic Behavior**+- Same event + same hook = same outcome+- Pattern matching is explicit, not fuzzy+- Exit codes have precise meanings (0=allow, 2=block)++**5. Zero-Overhead Extensibility**+- Add new hooks without modifying existing ones+- Add new event handlers without touching Claude Code+- Shared libraries reduce duplication++### What Problems This Architecture Prevents++| Problem | How Hooks Solve It |+|---------|-------------------|+| Dangerous commands execute | PreToolUse validates before execution |+| Sessions start cold | SessionStart injects context automatically |+| Work disappears | Stop/SubagentStop capture everything |+| No visibility into operations | PostToolUse logs to observability |+| UI doesn't show context | UserPromptSubmit updates tab titles |++### The Fundamental Insight++**Naive approach:** Build safety/automation INTO the AI prompts+- Fragile (prompts can be ignored)+- Inconsistent (varies by session)+- Invisible (no audit trail)++**Hook approach:** Build safety/automation AROUND the AI as middleware+- Robust (code can't be prompt-injected)+- Consistent (same code runs every time)+- Observable (events logged, actions traced)++The hook system transforms Claude Code from a standalone tool into an **observable, controllable, extensible infrastructure**. Every operation can be validated, logged, modified, or blocked. This is the foundation that enables all other PAI capabilities.++---+## Why This Is DifferentThis sounds similar to Claude Code's built-in hooks in settings.json, which also intercept events. What makes this approach different?diff --git a/Packs/kai-identity.md b/Packs/kai-identity.mdindex 3c023f5c..c11170e0 100644--- a/Packs/kai-identity.md+++ b/Packs/kai-identity.md@@ -166,6 +166,241 @@ System prompts define behavior but lack structure. They're free-form text that v---+## Architecture: The Special Sauce++The Kai Identity Pack uses a **5-layer constitutional identity framework** that transforms generic AI behavior into consistent, personality-driven collaboration with voice integration:++```+┌──────────────────────────────────────────────────────────────────┐+│ CONSTITUTIONAL IDENTITY FRAMEWORK │+├──────────────────────────────────────────────────────────────────┤+│ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 1. CONSTITUTIONAL FOUNDATION Non-negotiable principles │ │+│ │ 14 Founding Principles Permission to fail │ │+│ │ Security protocols Prompt injection defense │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 2. PERSONALITY CALIBRATION Numeric trait precision │ │+│ │ humor: 60/100 excitement: 60/100 │ │+│ │ curiosity: 90/100 precision: 95/100 │ │+│ │ professionalism: 75/100 directness: 80/100 │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 3. RESPONSE FORMAT Mandatory structure │ │+│ │ 📋 SUMMARY 📁 CAPTURE │ │+│ │ 🔍 ANALYSIS ➡️ NEXT │ │+│ │ ⚡ ACTIONS / ✅ RESULTS 📖 STORY EXPLANATION │ │+│ │ 📊 STATUS 🎯 COMPLETED │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 4. VOICE INTEGRATION Speech output extraction │ │+│ │ 🎯 COMPLETED line → stop-hook extracts │ │+│ │ 📁 CAPTURE section → history system stores │ │+│ │ Prosody markers preserved → TTS renders naturally │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 5. IDENTITY OUTPUT First-person behavior │ │+│ │ "I can help" not Consistent personality │ │+│ │ "the assistant can" across all responses │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │+└──────────────────────────────────────────────────────────────────┘+```++### How Data Flows Through the System++**Concrete example:** User asks to fix a bug:++```+User Request: "Fix the auth bug in login.ts"+ │+ ▼+ ┌─────────────────────────────────────┐+ │ CONSTITUTIONAL CHECK │+ │ • Security protocols: OK │+ │ • Not external command: OK │+ │ • Within permissions: OK │+ └─────────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────────────────┐+ │ PERSONALITY APPLICATION │+ │ • Excitement: 60/100 → measured │+ │ • Precision: 95/100 → exact │+ │ • Directness: 80/100 → clear │+ │ │+ │ Voice: Like colleague sharing │+ │ discovery, not excessive │+ └─────────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────────────────┐+ │ FORMAT GENERATION │+ │ │+ │ 📋 SUMMARY: Fixed auth timeout │+ │ 🔍 ANALYSIS: Token refresh logic │+ │ was checking wrong expiry field │+ │ ⚡ ACTIONS: Updated checkToken() │+ │ ✅ RESULTS: Tests pass, auth works │+ │ 📊 STATUS: Ready for review │+ │ 📁 CAPTURE: Auth uses JWT with │+ │ 15-min refresh window │+ │ ➡️ NEXT: Add integration tests │+ │ 📖 STORY EXPLANATION: │+ │ 1. Found token expiry bug │+ │ 2. Wrong field was checked │+ │ ... (8 points total) │+ │ 🎯 COMPLETED: Fixed auth timeout │+ │ by correcting token expiry │+ │ check │+ └─────────────────────────────────────┘+ │+ ┌───────────────────┴───────────────────┐+ │ │+ ▼ ▼+ ┌─────────────────────┐ ┌─────────────────────┐+ │ VOICE EXTRACTION │ │ HISTORY CAPTURE │+ │ │ │ │+ │ stop-hook reads: │ │ history-hook saves │+ │ "Fixed auth │ │ 📁 CAPTURE to │+ │ timeout by │ │ learnings/ │+ │ correcting token │ │ │+ │ expiry check" │ │ Key: "Auth uses │+ │ │ │ JWT with 15-min │+ │ → ElevenLabs TTS │ │ refresh window" │+ │ → Audio output │ │ │+ └─────────────────────┘ └─────────────────────┘+```++### Why This Architecture Matters++1. **Constitutional Foundation**: Before any response, core principles are checked. This prevents prompt injection, enforces security protocols, and ensures consistent behavior. The AI can't be tricked into violating its constitution.++2. **Numeric Precision**: Instead of vague "be enthusiastic," we specify `excitement: 60/100`. This calibration is reproducible. Different users can share personality configs. Models interpret numbers more consistently than adjectives.++3. **Mandatory Format = Integration Points**: The emoji sections aren't decoration—they're API contracts:+ - 🎯 COMPLETED → Voice system extracts this for speech+ - 📁 CAPTURE → History system stores this for learning+ - 📖 STORY EXPLANATION → Forces narrative thinking, better outputs++4. **First-Person Voice**: "I can help" vs "the assistant can help" transforms interaction. The AI becomes a collaborator, not a tool. This affects how users communicate back—partnership instead of command.++5. **Composable Integration**: Each layer connects to infrastructure:+ - Format → Voice hooks extract 🎯 COMPLETED+ - Format → History hooks capture 📁 CAPTURE+ - Personality → Prosody enhancement matches calibration+ - Constitution → Security hooks enforce boundaries++### The Personality Calibration Deep Dive++Why numeric precision matters:++```+CALIBRATION PRECISION COMPARISON+─────────────────────────────────────────────────────────────────++Vague Instruction: "Be helpful but not too enthusiastic"++ Problem: What is "too enthusiastic"? Depends on:+ - Model interpretation (varies by version)+ - Context (varies by conversation)+ - User expectation (varies by person)++ Result: Inconsistent behavior between sessions+++Numeric Calibration: excitement: 60/100+ precision: 95/100+ directness: 80/100++ Clear meaning:+ - 60/100 = measured enthusiasm (not 20 = reserved, not 90 = effusive)+ - 95/100 = extremely precise technical details+ - 80/100 = clear and direct without being blunt++ Result: Reproducible personality across:+ - Different sessions+ - Different users (with same config)+ - Different models (calibration transfers)+++EXAMPLE OUTPUT COMPARISON:++@ excitement: 30/100: "I've identified the issue. The token+ validation logic has a bug on line 47."++@ excitement: 60/100: "Found it! The token validation had a+ subtle bug—line 47 was checking the+ wrong expiry field."++@ excitement: 90/100: "YES! I found the bug! This is actually+ really interesting—the token validation+ on line 47 was checking the completely+ wrong field! 🎉"+```++### What Problems This Architecture Prevents++| Problem | Without Identity Pack | With Identity Pack |+|---------|----------------------|-------------------|+| **Inconsistent tone** | Different sessions feel like different AIs | Same calibrated personality every time |+| **Unparseable output** | Free-form text, can't extract for voice | Mandatory format with extraction points |+| **Silent voice** | No standard line to speak | 🎯 COMPLETED always present for TTS |+| **Lost context** | Valuable insights vanish after session | 📁 CAPTURE feeds history system |+| **Vague personality** | "Be helpful" means different things | Numeric precision: excitement=60/100 |+| **Third-person distance** | "The assistant recommends..." | First-person: "I recommend..." |+| **No guardrails** | Can be tricked into violations | Constitutional layer enforces boundaries |+| **Generic feel** | Interchangeable with any AI | Specific, recognizable collaborator |++### The Fundamental Insight++**Naive approach:** Give the AI instructions about how to behave.++```+System Prompt: "You are a helpful assistant. Be professional+ but friendly. Provide clear responses."++ ↓++Output: Variable formatting, inconsistent tone,+ no integration points, generic responses+```++**Identity pack approach:** Build a constitutional framework that defines WHO the AI is, with integration points to other systems.++```+Identity Framework:++┌─ Constitution: Principles that can't be violated+│+├─ Calibration: personality = { excitement: 60, precision: 95, ... }+│+├─ Format: Mandatory structure with extraction points+│ ├── 🎯 COMPLETED → Voice speaks this+│ └── 📁 CAPTURE → History stores this+│+└─ Voice: First-person ("I") not third-person ("the assistant")++ ↓++Output: Consistent personality, parseable format,+ voice integration, history capture,+ feels like specific collaborator+```++The difference: System prompts describe behavior. Identity frameworks define an entity with constitutional principles, calibrated personality, and integration contracts with other infrastructure.++---+## Installation### Prerequisitesdiff --git a/Packs/kai-voice-system.md b/Packs/kai-voice-system.mdindex 73edecbb..fa919831 100644--- a/Packs/kai-voice-system.md+++ b/Packs/kai-voice-system.md@@ -140,6 +140,178 @@ Basic TTS reads everything literally—code blocks, markdown syntax, technical a---+## Architecture: The Special Sauce++The Kai Voice System uses a **5-layer prosody enhancement pipeline** that transforms raw AI text into natural speech with emotional intelligence and personality-driven delivery:++```+┌──────────────────────────────────────────────────────────────────┐+│ PROSODY ENHANCEMENT PIPELINE │+├──────────────────────────────────────────────────────────────────┤+│ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 1. TEXT EXTRACTION Raw completion message │ │+│ │ 🎯 COMPLETED: "fixed the authentication bug" │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 2. CONTEXT ANALYSIS Detect emotional patterns │ │+│ │ Pattern: "fixed" → success emotion detected │ │+│ │ Output: [✨ success] fixed the auth... │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 3. PERSONALITY PROSODY Agent-specific speech patterns │ │+│ │ Agent: "engineer" → wise-leader archetype │ │+│ │ Output: [✨ success] **fixed** the... │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 4. SPEECH CLEANING Remove non-spoken artifacts │ │+│ │ Strip: ```code```, Preserve: **, ..., -- │ │+│ │ stray emoji (prosody markers) │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────────────────────────────────────────┐ │+│ │ 5. VOICE DELIVERY Personality → Voice ID routing │ │+│ │ Agent: "engineer" → ELEVENLABS_VOICE_ENGINEER │ │+│ │ Settings: stability=0.72, rate=212wpm │ │+│ │ → POST to voice server → ElevenLabs TTS → Audio output │ │+│ └────────────────────────────────────────────────────────────┘ │+│ │+└──────────────────────────────────────────────────────────────────┘+```++### How Data Flows Through the System++**Concrete example:** A background research agent completes a task:++```+Raw Output: "📋 SUMMARY: Analyzed competitor+ ...+ 🎯 COMPLETED: [AGENT:Researcher]+ Found 3 critical market gaps"++ │+ ┌──────────────────────────────────┼──────────────────────────────────┐+ │ │ │+ ▼ ▼ ▼+┌──────────┐ ┌──────────────┐ ┌──────────┐+│ Extract │ │ Detect │ │ Lookup │+│ COMPLETED│ │ agent type: │ │ voice: │+│ line │ │ "researcher" │ │ Analyst │+└──────────┘ └──────────────┘ └──────────┘+ │ │ │+ │ │ │+ └──────────────────────────────────┼──────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────────────────┐+ │ CONTEXT ANALYSIS │+ │ Pattern: "Found 3" + "gaps" │+ │ → [💡 insight] emotion detected │+ └─────────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────────────────┐+ │ PERSONALITY PROSODY │+ │ Analyst archetype: emphasize │+ │ findings → **Found** 3 critical... │+ └─────────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────────────────┐+ │ VOICE DELIVERY │+ │ POST to localhost:8888/notify │+ │ { │+ │ title: "Researcher", │+ │ message: "[💡 insight] Researcher│+ │ completed **Found** 3 critical │+ │ market gaps", │+ │ voice_id: "VOICE_RESEARCHER", │+ │ voice_enabled: true │+ │ } │+ └─────────────────────────────────────┘+ │+ ▼+ ┌─────────────────────────┐+ │ ELEVENLABS TTS │+ │ stability: 0.64 │+ │ rate: 229 wpm │+ │ → Audio plays through │+ │ speakers │+ └─────────────────────────┘+```++### Why This Architecture Matters++1. **Emotional Intelligence**: The system doesn't just read text—it understands context. "Fixed the bug" becomes `[✨ success]` with emphasis. "CRITICAL error" becomes `[🚨 urgent]` with urgency markers.++2. **Personality-Specific Delivery**: Each agent type has distinct prosody patterns. Enthusiast agents get `!` endings and `...` pauses. Wise-leader agents get em-dashes (`--`) for thoughtful breaks. Same message, different delivery.++3. **Speech-First Cleaning**: The system knows what to speak and what to skip. Code blocks become "code block", inline code is stripped, but prosody markers (`**bold**`, `...`) are preserved for TTS emphasis.++4. **Graceful Degradation**: If the voice server is offline, hooks exit silently with code 0. No errors, no interruptions. Voice is an enhancement, not a dependency.++5. **Voice Routing Abstraction**: Agent types map to voice IDs via environment variables. Change voices by updating config, not code. Add new agents without touching existing hooks.++### The Emotional Detection Deep Dive++The prosody enhancer scans for patterns that indicate emotional context:++```+DETECTION PRIORITY (checked in order):+─────────────────────────────────────────+1. urgent → "critical", "broken", "failing" → [🚨 urgent]+2. debugging → "bug", "error", "tracking" → [🐛 debugging]+3. insight → "wait", "aha", "I see" → [💡 insight]+4. celebration→ "finally", "phew", "we did it" → [🎉 celebration]+5. excited → "breakthrough", "discovered" → [💥 excited]+6. investigating → "analyzing", "examining" → [🔍 investigating]+7. progress → "phase complete", "moving to" → [📈 progress]+8. success → "completed", "fixed", "deployed" → [✨ success]+9. caution → "warning", "careful", "partial" → [⚠️ caution]+```++If a message already has a marker (e.g., `[✨ success]`), detection is skipped to avoid double-marking.++### What Problems This Architecture Prevents++| Problem | Without Voice System | With Voice System |+|---------|---------------------|-------------------|+| **Missing completions** | Task finishes while you're in another window—you don't know | Hear announcement immediately |+| **Robotic TTS** | Basic TTS reads code blocks character-by-character | Intelligent cleaning summarizes code as "code block" |+| **No personality** | All agents sound the same | Each agent type has distinct voice and prosody |+| **Context-free delivery** | "Fixed the bug" sounds same as "CRITICAL error" | Emotional markers adjust tone automatically |+| **Server dependency** | TTS failure breaks the workflow | Graceful degradation—silent but functional |+| **Hardcoded voices** | Changing voices requires code changes | Environment variables abstract voice IDs |++### The Fundamental Insight++**Naive approach:** Read text aloud with basic TTS.++```+AI Output → say "completed fixing the authentication bug" → Robotic monotone+```++**Voice system approach:** Build a prosody enhancement pipeline that transforms text into emotionally-intelligent speech.++```+AI Output → Extract COMPLETED → Detect "fixed" = success+ → Add [✨ success] marker+ → Apply engineer prosody (em-dashes, emphasis on actions)+ → Route to engineer voice ID (stability: 0.72, rate: 212wpm)+ → POST to voice server → ElevenLabs TTS → Natural speech+```++The difference: Basic TTS treats AI output as text to read. The voice system treats AI output as information to communicate—with appropriate emotion, personality, and delivery.++---+## Installation### Prerequisites